1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/cfsocket.cpp
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
6 // Copyright: (C) 1999-1997, Guilhem Lavaux
7 // (C) 2000-1999, Guillermo Rodriguez Garcia
9 // License: see wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
21 #include "wx/apptrait.h"
22 #include "wx/object.h"
23 #include "wx/string.h"
26 #include "wx/module.h"
31 #include "wx/sckaddr.h"
32 #include "wx/socket.h"
33 #include "wx/mac/carbon/private.h"
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
40 #define HAVE_INET_ATON
42 // DLL options compatibility check:
45 WX_CHECK_BUILD_OPTIONS("wxNet")
49 #define MAX_DISCARD_SIZE (10 * 1024)
51 #ifndef INVALID_SOCKET
52 #define INVALID_SOCKET -1
55 // what to do within waits: we have 2 cases: from the main thread itself we
56 // have to call wxYield() to let the events (including the GUI events and the
57 // low-level (not wxWidgets) events from GSocket) be processed. From another
58 // thread it is enough to just call wxThread::Yield() which will give away the
59 // rest of our time slice: the explanation is that the events will be processed
60 // by the main thread anyhow, without calling wxYield(), but we don't want to
61 // eat the CPU time uselessly while sitting in the loop waiting for the data
63 #define PROCESS_EVENTS() \
65 if ( wxThread::IsMain() ) \
70 #else // !wxUSE_THREADS
71 #define PROCESS_EVENTS() wxYield()
72 #endif // wxUSE_THREADS/!wxUSE_THREADS
74 #define wxTRACE_Socket _T("wxSocket")
77 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
78 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
79 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
80 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
81 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
83 // --------------------------------------------------------------------------
85 // --------------------------------------------------------------------------
87 class wxSocketState
: public wxObject
90 wxSocketFlags m_flags
;
91 wxSocketEventFlags m_eventmask
;
96 wxSocketState() : wxObject() {}
98 DECLARE_NO_COPY_CLASS(wxSocketState
)
103 CFSocketNativeHandle m_fd
;
106 GSocketError m_error
;
113 unsigned long m_timeout
;
116 GSocketEventFlags m_detected
;
117 GSocketCallback m_cbacks
[GSOCK_MAX_EVENT
];
118 char *m_data
[GSOCK_MAX_EVENT
];
120 CFSocketRef m_cfSocket
;
121 CFRunLoopSourceRef m_runLoopSource
;
122 CFReadStreamRef m_readStream
;
123 CFWriteStreamRef m_writeStream
;
128 struct sockaddr
*m_addr
;
131 GAddressType m_family
;
134 GSocketError m_error
;
138 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
139 CFDataRef address
, const void* data
, void* info
) ;
140 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
) ;
141 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
) ;
143 // ==========================================================================
145 // ==========================================================================
147 // --------------------------------------------------------------------------
148 // Initialization and shutdown
149 // --------------------------------------------------------------------------
151 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
152 // to m_countInit with a crit section
153 size_t wxSocketBase::m_countInit
= 0;
155 bool wxSocketBase::IsInitialized()
157 return m_countInit
> 0;
160 bool wxSocketBase::Initialize()
162 if ( !m_countInit
++ )
165 wxAppTraits
*traits
= wxAppConsole::GetInstance() ?
166 wxAppConsole::GetInstance()->GetTraits() : NULL
;
167 GSocketGUIFunctionsTable
*functions
=
168 traits
? traits
->GetSocketGUIFunctionsTable() : NULL
;
169 GSocket_SetGUIFunctions(functions
);
171 if ( !GSocket_Init() )
183 void wxSocketBase::Shutdown()
185 // we should be initialized
186 wxASSERT_MSG( m_countInit
, wxT("extra call to Shutdown()") );
187 if ( !--m_countInit
)
195 // --------------------------------------------------------------------------
197 // --------------------------------------------------------------------------
199 void wxSocketBase::Init()
202 m_type
= wxSOCKET_UNINIT
;
213 m_beingDeleted
= false;
227 if ( !IsInitialized() )
229 // this Initialize() will be undone by wxSocketModule::OnExit(), all the
230 // other calls to it should be matched by a call to Shutdown()
235 wxSocketBase::wxSocketBase()
240 wxSocketBase::wxSocketBase( wxSocketFlags flags
, wxSocketType type
)
248 wxSocketBase::~wxSocketBase()
250 // Just in case the app called Destroy() *and* then deleted
251 // the socket immediately: don't leave dangling pointers.
252 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
254 traits
->RemoveFromPendingDelete(this);
256 // Shutdown and close the socket
260 // Destroy the GSocket object
263 GSocket_destroy(m_socket
);
266 // Free the pushback buffer
271 bool wxSocketBase::Destroy()
273 // Delayed destruction: the socket will be deleted during the next
274 // idle loop iteration. This ensures that all pending events have
276 m_beingDeleted
= true;
278 // Shutdown and close the socket
281 // Supress events from now on
284 // schedule this object for deletion
285 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
288 // let the traits object decide what to do with us
289 traits
->ScheduleForDestroy(this);
291 else // no app or no traits
293 // in wxBase we might have no app object at all, don't leak memory
300 // --------------------------------------------------------------------------
302 // --------------------------------------------------------------------------
304 // The following IO operations update m_error and m_lcount:
305 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
307 // TODO: Should Connect, Accept and AcceptWith update m_error?
309 bool wxSocketBase::Close()
311 // Interrupt pending waits
315 GSocket_Shutdown(m_socket
);
318 m_establishing
= false;
323 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
328 m_lcount
= _Read(buffer
, nbytes
);
330 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
331 if (m_flags
& wxSOCKET_WAITALL
)
332 m_error
= (m_lcount
!= nbytes
);
334 m_error
= (m_lcount
== 0);
336 // Allow read events from now on
342 wxUint32
wxSocketBase::_Read(void* buffer
, wxUint32 nbytes
)
346 // Try the pushback buffer first
347 total
= GetPushback(buffer
, nbytes
, false);
349 buffer
= (char *)buffer
+ total
;
351 // Return now in one of the following cases:
352 // - the socket is invalid,
353 // - we got all the data,
354 // - we got *some* data and we are not using wxSOCKET_WAITALL.
357 ((total
!= 0) && !(m_flags
& wxSOCKET_WAITALL
)) )
360 // Possible combinations (they are checked in this order)
362 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
368 if (m_flags
& wxSOCKET_NOWAIT
)
370 GSocket_SetNonBlocking(m_socket
, 1);
371 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
372 GSocket_SetNonBlocking(m_socket
, 0);
383 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForRead() )
386 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
392 buffer
= (char *)buffer
+ ret
;
395 // If we got here and wxSOCKET_WAITALL is not set, we can leave
396 // now. Otherwise, wait until we recv all the data or until there
399 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
406 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
408 wxUint32 len
, len2
, sig
, total
;
413 unsigned char sig
[4];
414 unsigned char len
[4];
424 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
426 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
429 sig
= (wxUint32
)msg
.sig
[0];
430 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
431 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
432 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
434 if (sig
!= 0xfeeddead)
436 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
440 len
= (wxUint32
)msg
.len
[0];
441 len
|= (wxUint32
)(msg
.len
[1] << 8);
442 len
|= (wxUint32
)(msg
.len
[2] << 16);
443 len
|= (wxUint32
)(msg
.len
[3] << 24);
453 // Don't attemp to read if the msg was zero bytes long.
456 total
= _Read(buffer
, len
);
463 char *discard_buffer
= new char[MAX_DISCARD_SIZE
];
466 // NOTE: discarded bytes don't add to m_lcount.
469 discard_len
= ((len2
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE
: len2
);
470 discard_len
= _Read(discard_buffer
, (wxUint32
)discard_len
);
471 len2
-= (wxUint32
)discard_len
;
473 while ((discard_len
> 0) && len2
);
475 delete [] discard_buffer
;
480 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
483 sig
= (wxUint32
)msg
.sig
[0];
484 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
485 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
486 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
488 if (sig
!= 0xdeadfeed)
490 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
506 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
511 m_lcount
= _Read(buffer
, nbytes
);
512 Pushback(buffer
, m_lcount
);
514 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
515 if (m_flags
& wxSOCKET_WAITALL
)
516 m_error
= (m_lcount
!= nbytes
);
518 m_error
= (m_lcount
== 0);
520 // Allow read events again
526 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
531 m_lcount
= _Write(buffer
, nbytes
);
533 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
534 if (m_flags
& wxSOCKET_WAITALL
)
535 m_error
= (m_lcount
!= nbytes
);
537 m_error
= (m_lcount
== 0);
539 // Allow write events again
545 wxUint32
wxSocketBase::_Write(const void *buffer
, wxUint32 nbytes
)
549 // If the socket is invalid or parameters are ill, return immediately
550 if (!m_socket
|| !buffer
|| !nbytes
)
553 // Possible combinations (they are checked in this order)
555 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
560 if (m_flags
& wxSOCKET_NOWAIT
)
562 GSocket_SetNonBlocking(m_socket
, 1);
563 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
564 GSocket_SetNonBlocking(m_socket
, 0);
575 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForWrite() )
578 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
584 buffer
= (const char *)buffer
+ ret
;
587 // If we got here and wxSOCKET_WAITALL is not set, we can leave
588 // now. Otherwise, wait until we send all the data or until there
591 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
598 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
604 unsigned char sig
[4];
605 unsigned char len
[4];
614 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
616 msg
.sig
[0] = (unsigned char) 0xad;
617 msg
.sig
[1] = (unsigned char) 0xde;
618 msg
.sig
[2] = (unsigned char) 0xed;
619 msg
.sig
[3] = (unsigned char) 0xfe;
621 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
622 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
623 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
624 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
626 if (_Write(&msg
, sizeof(msg
)) < sizeof(msg
))
629 total
= _Write(buffer
, nbytes
);
634 msg
.sig
[0] = (unsigned char) 0xed;
635 msg
.sig
[1] = (unsigned char) 0xfe;
636 msg
.sig
[2] = (unsigned char) 0xad;
637 msg
.sig
[3] = (unsigned char) 0xde;
638 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
640 if ((_Write(&msg
, sizeof(msg
))) < sizeof(msg
))
654 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
657 Pushback(buffer
, nbytes
);
665 wxSocketBase
& wxSocketBase::Discard()
667 char *buffer
= new char[MAX_DISCARD_SIZE
];
674 SetFlags(wxSOCKET_NOWAIT
);
678 ret
= _Read(buffer
, MAX_DISCARD_SIZE
);
681 while (ret
== MAX_DISCARD_SIZE
);
687 // Allow read events again
693 // --------------------------------------------------------------------------
695 // --------------------------------------------------------------------------
697 // All Wait functions poll the socket using GSocket_Select() to
698 // check for the specified combination of conditions, until one
699 // of these conditions become true, an error occurs, or the
700 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
701 // this won't block the GUI.
703 bool wxSocketBase::_Wait(long seconds
,
705 wxSocketEventFlags flags
)
707 GSocketEventFlags result
;
710 // Set this to true to interrupt ongoing waits
713 // Check for valid socket
717 // Check for valid timeout value.
719 timeout
= seconds
* 1000 + milliseconds
;
721 timeout
= m_timeout
* 1000;
723 #if !defined(wxUSE_GUI) || !wxUSE_GUI
724 GSocket_SetTimeout(m_socket
, timeout
);
727 // Wait in an active polling loop.
729 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
730 // hurt. It has to be here because the (GSocket) event might arrive
731 // a bit delayed, and it has to be in OnRequest as well because we
732 // don't know whether the Wait functions are being used.
734 // Do this at least once (important if timeout == 0, when
735 // we are just polling). Also, if just polling, do not yield.
742 result
= GSocket_Select(m_socket
, flags
| GSOCK_LOST_FLAG
);
744 // Incoming connection (server) or connection established (client)
745 if (result
& GSOCK_CONNECTION_FLAG
)
748 m_establishing
= false;
753 // Data available or output buffer ready
754 if ((result
& GSOCK_INPUT_FLAG
) || (result
& GSOCK_OUTPUT_FLAG
))
760 if (result
& GSOCK_LOST_FLAG
)
763 m_establishing
= false;
765 return (flags
& GSOCK_LOST_FLAG
) != 0;
769 if ((!timeout
) || (chrono
.Time() > timeout
) || (m_interrupt
))
778 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
780 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
782 GSOCK_CONNECTION_FLAG
|
786 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
788 // Check pushback buffer before entering _Wait
792 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
793 // _Wait becuase of the semantics of WaitForRead: a return
794 // value of true means that a GSocket_Read call will return
795 // immediately, not that there is actually data to read.
797 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
| GSOCK_LOST_FLAG
);
800 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
802 return _Wait(seconds
, milliseconds
, GSOCK_OUTPUT_FLAG
);
805 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
807 return _Wait(seconds
, milliseconds
, GSOCK_LOST_FLAG
);
810 // --------------------------------------------------------------------------
812 // --------------------------------------------------------------------------
815 // Get local or peer address
818 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
825 peer
= GSocket_GetPeer(m_socket
);
827 // copying a null address would just trigger an assert anyway
832 addr_man
.SetAddress(peer
);
833 GAddress_destroy(peer
);
838 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
846 local
= GSocket_GetLocal(m_socket
);
847 addr_man
.SetAddress(local
);
848 GAddress_destroy(local
);
855 // Save and restore socket state
858 void wxSocketBase::SaveState()
860 wxSocketState
*state
;
862 state
= new wxSocketState();
864 state
->m_flags
= m_flags
;
865 state
->m_notify
= m_notify
;
866 state
->m_eventmask
= m_eventmask
;
867 state
->m_clientData
= m_clientData
;
869 m_states
.Append(state
);
872 void wxSocketBase::RestoreState()
874 wxList::compatibility_iterator node
;
875 wxSocketState
*state
;
877 node
= m_states
.GetLast();
881 state
= (wxSocketState
*)node
->GetData();
883 m_flags
= state
->m_flags
;
884 m_notify
= state
->m_notify
;
885 m_eventmask
= state
->m_eventmask
;
886 m_clientData
= state
->m_clientData
;
888 m_states
.Erase(node
);
896 void wxSocketBase::SetTimeout(long seconds
)
902 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
906 void wxSocketBase::SetFlags(wxSocketFlags flags
)
912 // --------------------------------------------------------------------------
914 // --------------------------------------------------------------------------
916 // A note on how events are processed, which is probably the most
917 // difficult thing to get working right while keeping the same API
918 // and functionality for all platforms.
920 // When GSocket detects an event, it calls wx_socket_callback, which in
921 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
922 // object. OnRequest does some housekeeping, and if the event is to be
923 // propagated to the user, it creates a new wxSocketEvent object and
924 // posts it. The event is not processed immediately, but delayed with
925 // AddPendingEvent instead. This is necessary in order to decouple the
926 // event processing from wx_socket_callback; otherwise, subsequent IO
927 // calls made from the user event handler would fail, as gtk callbacks
928 // are not reentrant.
930 // Note that, unlike events, user callbacks (now deprecated) are _not_
931 // decoupled from wx_socket_callback and thus they suffer from a variety
932 // of problems. Avoid them where possible and use events instead.
935 void LINKAGEMODE
wx_socket_callback(GSocket
* WXUNUSED(socket
),
936 GSocketEvent notification
,
939 wxSocketBase
*sckobj
= (wxSocketBase
*)cdata
;
941 sckobj
->OnRequest((wxSocketNotify
) notification
);
944 void wxSocketBase::OnRequest(wxSocketNotify notification
)
946 // NOTE: We duplicate some of the code in _Wait, but this doesn't
947 // hurt. It has to be here because the (GSocket) event might arrive
948 // a bit delayed, and it has to be in _Wait as well because we don't
949 // know whether the Wait functions are being used.
951 switch (notification
)
953 case wxSOCKET_CONNECTION
:
954 m_establishing
= false;
958 // If we are in the middle of a R/W operation, do not
959 // propagate events to users. Also, filter 'late' events
960 // which are no longer valid.
963 if (m_reading
|| !GSocket_Select(m_socket
, GSOCK_INPUT_FLAG
))
967 case wxSOCKET_OUTPUT
:
968 if (m_writing
|| !GSocket_Select(m_socket
, GSOCK_OUTPUT_FLAG
))
974 m_establishing
= false;
981 // Schedule the event
983 wxSocketEventFlags flag
= 0;
985 switch (notification
)
988 flag
= GSOCK_INPUT_FLAG
;
992 flag
= GSOCK_OUTPUT_FLAG
;
995 case GSOCK_CONNECTION
:
996 flag
= GSOCK_CONNECTION_FLAG
;
1000 flag
= GSOCK_LOST_FLAG
;
1004 wxLogWarning( wxT("wxSocket: unknown event!") );
1008 if (((m_eventmask
& flag
) == flag
) && m_notify
)
1012 wxSocketEvent
event(m_id
);
1013 event
.m_event
= notification
;
1014 event
.m_clientData
= m_clientData
;
1015 event
.SetEventObject(this);
1017 m_handler
->AddPendingEvent(event
);
1022 void wxSocketBase::Notify(bool notify
)
1027 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1029 m_eventmask
= flags
;
1032 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1034 m_handler
= &handler
;
1038 // --------------------------------------------------------------------------
1040 // --------------------------------------------------------------------------
1042 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1047 if (m_unread
== NULL
)
1048 m_unread
= malloc(size
);
1053 tmp
= malloc(m_unrd_size
+ size
);
1054 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1060 m_unrd_size
+= size
;
1062 memcpy(m_unread
, buffer
, size
);
1065 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1070 if (size
> (m_unrd_size
-m_unrd_cur
))
1071 size
= m_unrd_size
-m_unrd_cur
;
1073 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1078 if (m_unrd_size
== m_unrd_cur
)
1091 // ==========================================================================
1093 // ==========================================================================
1095 // --------------------------------------------------------------------------
1097 // --------------------------------------------------------------------------
1099 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1100 wxSocketFlags flags
)
1101 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1103 wxLogTrace( wxTRACE_Socket
, wxT("Opening wxSocketServer") );
1105 m_socket
= GSocket_new();
1109 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_new failed") );
1113 // Setup the socket as server
1116 GSocket_SetLocal(m_socket
, addr_man
.GetAddress());
1117 if (GSocket_SetServer(m_socket
) != GSOCK_NOERROR
)
1119 GSocket_destroy(m_socket
);
1122 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_SetServer failed") );
1126 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1127 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1128 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1129 wx_socket_callback
, (char *)this);
1133 // --------------------------------------------------------------------------
1135 // --------------------------------------------------------------------------
1137 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1139 GSocket
*child_socket
;
1144 // If wait == false, then the call should be nonblocking.
1145 // When we are finished, we put the socket to blocking mode
1150 GSocket_SetNonBlocking(m_socket
, 1);
1152 child_socket
= GSocket_WaitConnection(m_socket
);
1155 GSocket_SetNonBlocking(m_socket
, 0);
1160 sock
.m_type
= wxSOCKET_BASE
;
1161 sock
.m_socket
= child_socket
;
1162 sock
.m_connected
= true;
1164 GSocket_SetTimeout(sock
.m_socket
, sock
.m_timeout
* 1000);
1165 GSocket_SetCallback(sock
.m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1166 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1167 wx_socket_callback
, (char *)&sock
);
1173 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1175 wxSocketBase
* sock
= new wxSocketBase();
1177 sock
->SetFlags(m_flags
);
1179 if (!AcceptWith(*sock
, wait
))
1188 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1190 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
);
1193 // ==========================================================================
1195 // ==========================================================================
1197 // --------------------------------------------------------------------------
1199 // --------------------------------------------------------------------------
1201 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1202 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1206 wxSocketClient::~wxSocketClient()
1210 // --------------------------------------------------------------------------
1212 // --------------------------------------------------------------------------
1214 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1220 // Shutdown and destroy the socket
1222 GSocket_destroy(m_socket
);
1225 m_socket
= GSocket_new();
1226 m_connected
= false;
1227 m_establishing
= false;
1232 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1233 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1234 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1235 wx_socket_callback
, (char *)this);
1237 // If wait == false, then the call should be nonblocking.
1238 // When we are finished, we put the socket to blocking mode
1242 GSocket_SetNonBlocking(m_socket
, 1);
1244 GSocket_SetPeer(m_socket
, addr_man
.GetAddress());
1245 err
= GSocket_Connect(m_socket
, GSOCK_STREAMED
);
1248 GSocket_SetNonBlocking(m_socket
, 0);
1250 if (err
!= GSOCK_NOERROR
)
1252 if (err
== GSOCK_WOULDBLOCK
)
1253 m_establishing
= true;
1262 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1264 if (m_connected
) // Already connected
1267 if (!m_establishing
|| !m_socket
) // No connection in progress
1270 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
| GSOCK_LOST_FLAG
);
1273 // ==========================================================================
1275 // ==========================================================================
1277 /* NOTE: experimental stuff - might change */
1279 wxDatagramSocket::wxDatagramSocket( wxSockAddress
& addr
,
1280 wxSocketFlags flags
)
1281 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1284 // Create the socket
1285 m_socket
= GSocket_new();
1290 // Setup the socket as non connection oriented
1291 GSocket_SetLocal(m_socket
, addr
.GetAddress());
1292 if( GSocket_SetNonOriented(m_socket
) != GSOCK_NOERROR
)
1294 GSocket_destroy(m_socket
);
1299 // Initialize all stuff
1300 m_connected
= false;
1301 m_establishing
= false;
1302 GSocket_SetTimeout( m_socket
, m_timeout
);
1303 GSocket_SetCallback( m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1304 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1305 wx_socket_callback
, (char*)this );
1309 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1318 wxDatagramSocket
& wxDatagramSocket::SendTo( wxSockAddress
& addr
,
1322 GSocket_SetPeer(m_socket
, addr
.GetAddress());
1328 * -------------------------------------------------------------------------
1330 * -------------------------------------------------------------------------
1333 /* CHECK_ADDRESS verifies that the current address family is either
1334 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1335 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1336 * an appropiate error code.
1338 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1340 #define CHECK_ADDRESS(address, family) \
1342 if (address->m_family == GSOCK_NOFAMILY) \
1343 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1344 return address->m_error; \
1345 if (address->m_family != GSOCK_##family) \
1347 address->m_error = GSOCK_INVADDR; \
1348 return GSOCK_INVADDR; \
1352 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1354 if (address->m_family == GSOCK_NOFAMILY) \
1355 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1357 if (address->m_family != GSOCK_##family) \
1359 address->m_error = GSOCK_INVADDR; \
1365 GAddress
*GAddress_new(void)
1369 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1372 address
->m_family
= GSOCK_NOFAMILY
;
1373 address
->m_addr
= NULL
;
1379 GAddress
*GAddress_copy(GAddress
*address
)
1383 assert(address
!= NULL
);
1385 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1388 memcpy(addr2
, address
, sizeof(GAddress
));
1390 if (address
->m_addr
&& address
->m_len
> 0)
1392 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1393 if (addr2
->m_addr
== NULL
)
1399 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1405 void GAddress_destroy(GAddress
*address
)
1407 assert( address
!= NULL
);
1409 if (address
->m_addr
)
1410 free(address
->m_addr
);
1415 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1417 assert(address
!= NULL
);
1419 address
->m_family
= type
;
1422 GAddressType
GAddress_GetFamily(GAddress
*address
)
1424 assert( address
!= NULL
);
1426 return address
->m_family
;
1429 GSocketError
_GAddress_translate_from(GAddress
*address
,
1430 struct sockaddr
*addr
, int len
)
1432 address
->m_realfamily
= addr
->sa_family
;
1433 switch (addr
->sa_family
)
1436 address
->m_family
= GSOCK_INET
;
1440 address
->m_family
= GSOCK_UNIX
;
1445 address
->m_family
= GSOCK_INET6
;
1451 address
->m_error
= GSOCK_INVOP
;
1456 if (address
->m_addr
)
1457 free(address
->m_addr
);
1459 address
->m_len
= len
;
1460 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1462 if (address
->m_addr
== NULL
)
1464 address
->m_error
= GSOCK_MEMERR
;
1465 return GSOCK_MEMERR
;
1468 memcpy(address
->m_addr
, addr
, len
);
1470 return GSOCK_NOERROR
;
1473 GSocketError
_GAddress_translate_to(GAddress
*address
,
1474 struct sockaddr
**addr
, int *len
)
1476 if (!address
->m_addr
)
1478 address
->m_error
= GSOCK_INVADDR
;
1479 return GSOCK_INVADDR
;
1482 *len
= address
->m_len
;
1483 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1486 address
->m_error
= GSOCK_MEMERR
;
1487 return GSOCK_MEMERR
;
1490 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1491 return GSOCK_NOERROR
;
1495 * -------------------------------------------------------------------------
1496 * Internet address family
1497 * -------------------------------------------------------------------------
1500 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1502 address
->m_len
= sizeof(struct sockaddr_in
);
1503 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1504 if (address
->m_addr
== NULL
)
1506 address
->m_error
= GSOCK_MEMERR
;
1507 return GSOCK_MEMERR
;
1510 memset( address
->m_addr
, 0 , address
->m_len
) ;
1511 address
->m_family
= GSOCK_INET
;
1512 address
->m_realfamily
= PF_INET
;
1513 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1514 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1516 return GSOCK_NOERROR
;
1519 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1522 struct in_addr
*addr
;
1524 assert( address
!= NULL
);
1525 CHECK_ADDRESS( address
, INET
);
1527 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1529 // If it is a numeric host name, convert it now
1530 #if defined(HAVE_INET_ATON)
1531 if (inet_aton(hostname
, addr
) == 0)
1533 #elif defined(HAVE_INET_ADDR)
1534 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1537 // Use gethostbyname by default
1539 int val
= 1; // VA doesn't like constants in conditional expressions
1544 struct in_addr
*array_addr
;
1546 // It is a real name, we solve it
1547 if ((he
= gethostbyname(hostname
)) == NULL
)
1549 // Reset to invalid address
1550 addr
->s_addr
= INADDR_NONE
;
1551 address
->m_error
= GSOCK_NOHOST
;
1552 return GSOCK_NOHOST
;
1554 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1555 addr
->s_addr
= array_addr
[0].s_addr
;
1558 return GSOCK_NOERROR
;
1561 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1563 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1566 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1567 unsigned long hostaddr
)
1569 struct in_addr
*addr
;
1571 assert( address
!= NULL
);
1572 CHECK_ADDRESS( address
, INET
);
1574 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1575 addr
->s_addr
= htonl(hostaddr
) ;
1577 return GSOCK_NOERROR
;
1580 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1581 const char *protocol
)
1584 struct sockaddr_in
*addr
;
1586 assert( address
!= NULL
);
1587 CHECK_ADDRESS( address
, INET
);
1591 address
->m_error
= GSOCK_INVPORT
;
1592 return GSOCK_INVPORT
;
1595 se
= getservbyname(port
, protocol
);
1598 // the cast to int suppresses compiler warnings
1599 // about subscript having the type char
1600 if (isdigit((int)port
[0]))
1604 port_int
= atoi(port
);
1605 addr
= (struct sockaddr_in
*)address
->m_addr
;
1606 addr
->sin_port
= htons(port_int
);
1607 return GSOCK_NOERROR
;
1610 address
->m_error
= GSOCK_INVPORT
;
1611 return GSOCK_INVPORT
;
1614 addr
= (struct sockaddr_in
*)address
->m_addr
;
1615 addr
->sin_port
= se
->s_port
;
1617 return GSOCK_NOERROR
;
1620 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1622 struct sockaddr_in
*addr
;
1624 assert( address
!= NULL
);
1625 CHECK_ADDRESS( address
, INET
);
1627 addr
= (struct sockaddr_in
*)address
->m_addr
;
1628 addr
->sin_port
= htons(port
);
1630 return GSOCK_NOERROR
;
1633 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1637 struct sockaddr_in
*addr
;
1639 assert( address
!= NULL
);
1640 CHECK_ADDRESS( address
, INET
);
1642 addr
= (struct sockaddr_in
*)address
->m_addr
;
1643 addr_buf
= (char *)&(addr
->sin_addr
);
1645 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1648 address
->m_error
= GSOCK_NOHOST
;
1649 return GSOCK_NOHOST
;
1652 strncpy(hostname
, he
->h_name
, sbuf
);
1654 return GSOCK_NOERROR
;
1657 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1659 struct sockaddr_in
*addr
;
1661 assert( address
!= NULL
);
1662 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1664 addr
= (struct sockaddr_in
*)address
->m_addr
;
1666 return ntohl(addr
->sin_addr
.s_addr
) ;
1669 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1671 struct sockaddr_in
*addr
;
1673 assert( address
!= NULL
);
1674 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1676 addr
= (struct sockaddr_in
*)address
->m_addr
;
1678 return ntohs(addr
->sin_port
);
1682 * -------------------------------------------------------------------------
1683 * Unix address family
1684 * -------------------------------------------------------------------------
1687 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1689 address
->m_len
= sizeof(struct sockaddr_un
);
1690 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1691 if (address
->m_addr
== NULL
)
1693 address
->m_error
= GSOCK_MEMERR
;
1694 return GSOCK_MEMERR
;
1697 address
->m_family
= GSOCK_UNIX
;
1698 address
->m_realfamily
= PF_UNIX
;
1699 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1700 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1702 return GSOCK_NOERROR
;
1705 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1707 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1709 struct sockaddr_un
*addr
;
1711 assert( address
!= NULL
);
1712 CHECK_ADDRESS( address
, UNIX
);
1714 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1715 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1716 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1718 return GSOCK_NOERROR
;
1721 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1723 struct sockaddr_un
*addr
;
1725 assert( address
!= NULL
);
1726 CHECK_ADDRESS( address
, UNIX
);
1728 addr
= (struct sockaddr_un
*)address
->m_addr
;
1730 strncpy(path
, addr
->sun_path
, sbuf
);
1732 return GSOCK_NOERROR
;
1735 /* Address handling */
1737 /* GSocket_SetLocal:
1741 * Set or get the local or peer address for this socket. The 'set'
1742 * functions return GSOCK_NOERROR on success, an error code otherwise.
1743 * The 'get' functions return a pointer to a GAddress object on success,
1744 * or NULL otherwise, in which case they set the error code of the
1745 * corresponding GSocket.
1748 * GSOCK_INVSOCK - the socket is not valid.
1749 * GSOCK_INVADDR - the address is not valid.
1752 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
1754 assert( socket
!= NULL
);
1756 // the socket must be initialized, or it must be a server
1757 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
1759 socket
->m_error
= GSOCK_INVSOCK
;
1760 return GSOCK_INVSOCK
;
1764 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1766 socket
->m_error
= GSOCK_INVADDR
;
1767 return GSOCK_INVADDR
;
1770 if (socket
->m_local
)
1771 GAddress_destroy(socket
->m_local
);
1773 socket
->m_local
= GAddress_copy(address
);
1775 return GSOCK_NOERROR
;
1778 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
1780 assert(socket
!= NULL
);
1783 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1785 socket
->m_error
= GSOCK_INVADDR
;
1786 return GSOCK_INVADDR
;
1790 GAddress_destroy(socket
->m_peer
);
1792 socket
->m_peer
= GAddress_copy(address
);
1794 return GSOCK_NOERROR
;
1797 GAddress
*GSocket_GetLocal(GSocket
*socket
)
1800 struct sockaddr addr
;
1801 socklen_t size
= sizeof(addr
);
1804 assert( socket
!= NULL
);
1806 // try to get it from the m_local var first
1807 if (socket
->m_local
)
1808 return GAddress_copy(socket
->m_local
);
1810 // else, if the socket is initialized, try getsockname
1811 if (socket
->m_fd
== INVALID_SOCKET
)
1813 socket
->m_error
= GSOCK_INVSOCK
;
1817 if (getsockname(socket
->m_fd
, &addr
, (socklen_t
*) &size
) < 0)
1819 socket
->m_error
= GSOCK_IOERR
;
1823 // got a valid address from getsockname, create a GAddress object
1824 address
= GAddress_new();
1825 if (address
== NULL
)
1827 socket
->m_error
= GSOCK_MEMERR
;
1831 err
= _GAddress_translate_from(address
, &addr
, size
);
1832 if (err
!= GSOCK_NOERROR
)
1834 GAddress_destroy(address
);
1835 socket
->m_error
= err
;
1842 GAddress
*GSocket_GetPeer(GSocket
*socket
)
1844 assert(socket
!= NULL
);
1846 // try to get it from the m_peer var
1848 return GAddress_copy(socket
->m_peer
);
1854 GSocket
*GSocket_new(void)
1857 socket
= (GSocket
*)malloc(sizeof(GSocket
));
1862 socket
->m_fd
= INVALID_SOCKET
;
1864 for (int i
=0;i
<GSOCK_MAX_EVENT
;i
++)
1866 socket
->m_cbacks
[i
] = NULL
;
1869 socket
->m_detected
= 0;
1871 socket
->m_local
= NULL
;
1872 socket
->m_peer
= NULL
;
1873 socket
->m_error
= GSOCK_NOERROR
;
1875 socket
->m_non_blocking
= false ;
1876 socket
->m_stream
= true;
1877 // socket->m_oriented = true;
1878 socket
->m_server
= false;
1879 socket
->m_establishing
= false;
1880 socket
->m_timeout
= 10 * 60 * 1000;
1881 // 10 minutes * 60 sec * 1000 millisec
1883 socket
->m_cfSocket
= NULL
;
1884 socket
->m_runLoopSource
= NULL
;
1885 socket
->m_readStream
= NULL
;
1886 socket
->m_writeStream
= NULL
;
1891 void GSocket_close(GSocket
*socket
)
1893 if ( socket
->m_cfSocket
!= NULL
)
1895 if ( socket
->m_readStream
)
1897 CFReadStreamClose(socket
->m_readStream
);
1898 CFRelease( socket
->m_readStream
) ;
1899 socket
->m_readStream
= NULL
;
1902 if ( socket
->m_writeStream
)
1904 CFWriteStreamClose(socket
->m_writeStream
);
1905 CFRelease( socket
->m_writeStream
) ;
1906 socket
->m_writeStream
= NULL
;
1909 CFSocketInvalidate( socket
->m_cfSocket
) ;
1910 CFRelease( socket
->m_cfSocket
) ;
1911 socket
->m_cfSocket
= NULL
;
1912 socket
->m_fd
= INVALID_SOCKET
;
1916 void GSocket_Shutdown(GSocket
*socket
)
1918 GSocket_close( socket
);
1920 // Disable GUI callbacks
1921 for (int evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
1922 socket
->m_cbacks
[evt
] = NULL
;
1924 socket
->m_detected
= GSOCK_LOST_FLAG
;
1927 void GSocket_destroy(GSocket
*socket
)
1929 assert( socket
!= NULL
);
1931 // Check that the socket is really shut down
1932 if (socket
->m_fd
!= INVALID_SOCKET
)
1933 GSocket_Shutdown(socket
);
1935 // Destroy private addresses
1936 if (socket
->m_local
)
1937 GAddress_destroy(socket
->m_local
);
1940 GAddress_destroy(socket
->m_peer
);
1942 // Destroy the socket itself
1946 GSocketError
GSocket_Connect(GSocket
*socket
, GSocketStream stream
)
1948 assert( socket
!= NULL
);
1950 if (socket
->m_fd
!= INVALID_SOCKET
)
1952 socket
->m_error
= GSOCK_INVSOCK
;
1953 return GSOCK_INVSOCK
;
1956 if (!socket
->m_peer
)
1958 socket
->m_error
= GSOCK_INVADDR
;
1959 return GSOCK_INVADDR
;
1962 // Streamed or dgram socket?
1963 socket
->m_stream
= (stream
== GSOCK_STREAMED
);
1964 socket
->m_oriented
= true;
1965 socket
->m_server
= false;
1966 socket
->m_establishing
= false;
1968 GSocketError returnErr
= GSOCK_NOERROR
;
1971 CFAllocatorRef alloc
= kCFAllocatorDefault
;
1972 CFSocketContext ctx
;
1973 memset( &ctx
, 0 , sizeof( ctx
) ) ;
1975 socket
->m_cfSocket
= CFSocketCreate( alloc
, socket
->m_peer
->m_realfamily
,
1976 stream
== GSOCK_STREAMED
? SOCK_STREAM
: SOCK_DGRAM
, 0 ,
1977 kCFSocketReadCallBack
| kCFSocketWriteCallBack
| kCFSocketConnectCallBack
, wxMacCFSocketCallback
, &ctx
) ;
1978 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
1980 socket
->m_fd
= CFSocketGetNative( socket
->m_cfSocket
) ;
1982 CFStreamCreatePairWithSocket ( alloc
, socket
->m_fd
, &socket
->m_readStream
, &socket
->m_writeStream
);
1983 if ((socket
->m_readStream
== NULL
) || (socket
->m_writeStream
== NULL
))
1985 GSocket_close(socket
);
1986 socket
->m_error
= GSOCK_IOERR
;
1990 if ( !CFReadStreamOpen( socket
->m_readStream
) || !CFWriteStreamOpen( socket
->m_writeStream
) )
1992 GSocket_close(socket
);
1993 socket
->m_error
= GSOCK_IOERR
;
1997 CFRunLoopSourceRef rls
= CFSocketCreateRunLoopSource(alloc
, socket
->m_cfSocket
, 0);
1998 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls
, kCFRunLoopCommonModes
);
2001 CFDataRef address
= CFDataCreateWithBytesNoCopy(alloc
, (const UInt8
*) socket
->m_peer
->m_addr
, socket
->m_peer
->m_len
, kCFAllocatorNull
);
2003 return GSOCK_MEMERR
;
2005 err
= CFSocketConnectToAddress( socket
->m_cfSocket
, address
, socket
->m_non_blocking
? -1 : socket
->m_timeout
/ 1000 ) ;
2008 if (err
!= kCFSocketSuccess
)
2010 if ( err
== kCFSocketTimeout
)
2012 GSocket_close(socket
);
2013 socket
->m_error
= GSOCK_TIMEDOUT
;
2014 return GSOCK_TIMEDOUT
;
2017 // we don't know whether a connect in progress will be issued like this
2018 if ( err
!= kCFSocketTimeout
&& socket
->m_non_blocking
)
2020 socket
->m_establishing
= true;
2021 socket
->m_error
= GSOCK_WOULDBLOCK
;
2022 return GSOCK_WOULDBLOCK
;
2025 GSocket_close(socket
);
2026 socket
->m_error
= GSOCK_IOERR
;
2030 return GSOCK_NOERROR
;
2035 /* GSocket_SetNonBlocking:
2036 * Sets the socket to non-blocking mode.
2037 * All IO calls will return immediately.
2039 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
2041 assert( socket
!= NULL
);
2043 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2045 socket
->m_non_blocking
= non_block
;
2049 * GSocket_SetTimeout:
2050 * Sets the timeout for blocking calls. Time is expressed in
2053 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
2055 assert( socket
!= NULL
);
2057 socket
->m_timeout
= millisec
;
2060 /* GSocket_GetError:
2061 * Returns the last error which occurred for this socket. Note that successful
2062 * operations do not clear this back to GSOCK_NOERROR, so use it only
2065 GSocketError
GSocket_GetError(GSocket
*socket
)
2067 assert( socket
!= NULL
);
2069 return socket
->m_error
;
2075 * There is data to be read in the input buffer. If, after a read
2076 * operation, there is still data available, the callback function will
2079 * The socket is available for writing. That is, the next write call
2080 * won't block. This event is generated only once, when the connection is
2081 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2082 * when the output buffer empties again. This means that the app should
2083 * assume that it can write since the first OUTPUT event, and no more
2084 * OUTPUT events will be generated unless an error occurs.
2086 * Connection successfully established, for client sockets, or incoming
2087 * client connection, for server sockets. Wait for this event (also watch
2088 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2090 * The connection is lost (or a connection request failed); this could
2091 * be due to a failure, or due to the peer closing it gracefully.
2094 /* GSocket_SetCallback:
2095 * Enables the callbacks specified by 'flags'. Note that 'flags'
2096 * may be a combination of flags OR'ed toghether, so the same
2097 * callback function can be made to accept different events.
2098 * The callback function must have the following prototype:
2100 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2102 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
2103 GSocketCallback callback
, char *cdata
)
2107 assert( socket
!= NULL
);
2109 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2111 if ((flags
& (1 << count
)) != 0)
2113 socket
->m_cbacks
[count
] = callback
;
2114 socket
->m_data
[count
] = cdata
;
2119 /* GSocket_UnsetCallback:
2120 * Disables all callbacks specified by 'flags', which may be a
2121 * combination of flags OR'ed toghether.
2123 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
2127 assert(socket
!= NULL
);
2129 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2131 if ((flags
& (1 << count
)) != 0)
2133 socket
->m_cbacks
[count
] = NULL
;
2134 socket
->m_data
[count
] = NULL
;
2140 #define CALL_CALLBACK(socket, event) { \
2141 _GSocket_Disable(socket, event); \
2142 if (socket->m_cbacks[event]) \
2143 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2146 void _GSocket_Install_Callback(GSocket
*socket
, GSocketEvent event
)
2151 case GSOCK_CONNECTION
:
2152 if (socket
->m_server
)
2153 c
= kCFSocketReadCallBack
;
2155 c
= kCFSocketConnectCallBack
;
2160 c
= kCFSocketReadCallBack
;
2164 c
= kCFSocketWriteCallBack
;
2171 CFSocketEnableCallBacks(socket
->m_cfSocket
, c
);
2174 void _GSocket_Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
2179 case GSOCK_CONNECTION
:
2180 if (socket
->m_server
)
2181 c
= kCFSocketReadCallBack
;
2183 c
= kCFSocketConnectCallBack
;
2188 c
= kCFSocketReadCallBack
;
2192 c
= kCFSocketWriteCallBack
;
2200 CFSocketDisableCallBacks(socket
->m_cfSocket
, c
);
2203 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
2205 socket
->m_detected
&= ~(1 << event
);
2206 _GSocket_Install_Callback(socket
, event
);
2209 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
2211 socket
->m_detected
|= (1 << event
);
2212 _GSocket_Uninstall_Callback(socket
, event
);
2215 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
2216 CFDataRef address
, const void* data
, void* info
)
2218 GSocket
* socket
= (GSocket
*)info
;
2220 switch (callbackType
)
2222 case kCFSocketConnectCallBack
:
2225 SInt32 error
= *((SInt32
*)data
) ;
2226 CALL_CALLBACK( socket
, GSOCK_LOST
) ;
2227 GSocket_Shutdown(socket
);
2231 CALL_CALLBACK( socket
, GSOCK_CONNECTION
) ;
2235 case kCFSocketReadCallBack
:
2236 CALL_CALLBACK( socket
, GSOCK_INPUT
) ;
2239 case kCFSocketWriteCallBack
:
2240 CALL_CALLBACK( socket
, GSOCK_OUTPUT
) ;
2244 break; // We shouldn't get here.
2248 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
2252 assert(socket
!= NULL
);
2253 // if ( !CFReadStreamHasBytesAvailable() )
2254 ret
= CFReadStreamRead( socket
->m_readStream
, (UInt8
*) buffer
, size
) ;
2259 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
2263 assert(socket
!= NULL
);
2264 ret
= CFWriteStreamWrite( socket
->m_writeStream
, (UInt8
*) buffer
, size
) ;
2269 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
2271 assert( socket
!= NULL
);
2273 return flags
& socket
->m_detected
;
2276 // ==========================================================================
2278 // ==========================================================================
2280 class wxSocketModule
: public wxModule
2283 virtual bool OnInit()
2285 // wxSocketBase will call GSocket_Init() itself when/if needed
2289 virtual void OnExit()
2291 if ( wxSocketBase::IsInitialized() )
2292 wxSocketBase::Shutdown();
2296 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2299 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)