1 /////////////////////////////////////////////////////////////////////////////
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 // ==========================================================================
14 // ==========================================================================
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
26 #include "wx/apptrait.h"
28 #include "wx/object.h"
29 #include "wx/string.h"
32 #include "wx/module.h"
37 #include "wx/sckaddr.h"
38 #include "wx/socket.h"
39 #include "wx/mac/carbon/private.h"
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
46 #define HAVE_INET_ATON
48 // DLL options compatibility check:
50 WX_CHECK_BUILD_OPTIONS("wxNet")
52 // --------------------------------------------------------------------------
53 // macros and constants
54 // --------------------------------------------------------------------------
57 #define MAX_DISCARD_SIZE (10 * 1024)
59 #ifndef INVALID_SOCKET
60 #define INVALID_SOCKET -1
63 // what to do within waits: we have 2 cases: from the main thread itself we
64 // have to call wxYield() to let the events (including the GUI events and the
65 // low-level (not wxWidgets) events from GSocket) be processed. From another
66 // thread it is enough to just call wxThread::Yield() which will give away the
67 // rest of our time slice: the explanation is that the events will be processed
68 // by the main thread anyhow, without calling wxYield(), but we don't want to
69 // eat the CPU time uselessly while sitting in the loop waiting for the data
71 #define PROCESS_EVENTS() \
73 if ( wxThread::IsMain() ) \
78 #else // !wxUSE_THREADS
79 #define PROCESS_EVENTS() wxYield()
80 #endif // wxUSE_THREADS/!wxUSE_THREADS
82 #define wxTRACE_Socket _T("wxSocket")
84 // --------------------------------------------------------------------------
86 // --------------------------------------------------------------------------
88 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
89 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
90 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
91 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
92 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
94 // --------------------------------------------------------------------------
96 // --------------------------------------------------------------------------
98 class wxSocketState
: public wxObject
101 wxSocketFlags m_flags
;
102 wxSocketEventFlags m_eventmask
;
107 wxSocketState() : wxObject() {}
109 DECLARE_NO_COPY_CLASS(wxSocketState
)
114 CFSocketNativeHandle m_fd
;
117 GSocketError m_error
;
124 unsigned long m_timeout
;
128 GSocketEventFlags m_detected
;
129 GSocketCallback m_cbacks
[GSOCK_MAX_EVENT
];
130 char *m_data
[GSOCK_MAX_EVENT
];
132 CFSocketRef m_cfSocket
;
133 CFRunLoopSourceRef m_runLoopSource
;
134 CFReadStreamRef m_readStream
;
135 CFWriteStreamRef m_writeStream
;
140 struct sockaddr
*m_addr
;
143 GAddressType m_family
;
146 GSocketError m_error
;
150 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
151 CFDataRef address
, const void* data
, void* info
) ;
152 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
) ;
153 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
) ;
155 // ==========================================================================
157 // ==========================================================================
159 // --------------------------------------------------------------------------
160 // Initialization and shutdown
161 // --------------------------------------------------------------------------
163 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
164 // to m_countInit with a crit section
165 size_t wxSocketBase::m_countInit
= 0;
167 bool wxSocketBase::IsInitialized()
169 return m_countInit
> 0;
172 bool wxSocketBase::Initialize()
174 if ( !m_countInit
++ )
177 wxAppTraits
*traits
= wxAppConsole::GetInstance() ?
178 wxAppConsole::GetInstance()->GetTraits() : NULL
;
179 GSocketGUIFunctionsTable
*functions
=
180 traits
? traits
->GetSocketGUIFunctionsTable() : NULL
;
181 GSocket_SetGUIFunctions(functions
);
183 if ( !GSocket_Init() )
195 void wxSocketBase::Shutdown()
197 // we should be initialized
198 wxASSERT_MSG( m_countInit
, _T("extra call to Shutdown()") );
199 if ( !--m_countInit
)
207 // --------------------------------------------------------------------------
209 // --------------------------------------------------------------------------
211 void wxSocketBase::Init()
214 m_type
= wxSOCKET_UNINIT
;
225 m_beingDeleted
= FALSE
;
239 if ( !IsInitialized() )
241 // this Initialize() will be undone by wxSocketModule::OnExit(), all the
242 // other calls to it should be matched by a call to Shutdown()
247 wxSocketBase::wxSocketBase()
252 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
260 wxSocketBase::~wxSocketBase()
262 // Just in case the app called Destroy() *and* then deleted
263 // the socket immediately: don't leave dangling pointers.
264 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
266 traits
->RemoveFromPendingDelete(this);
268 // Shutdown and close the socket
272 // Destroy the GSocket object
275 GSocket_destroy(m_socket
);
278 // Free the pushback buffer
283 bool wxSocketBase::Destroy()
285 // Delayed destruction: the socket will be deleted during the next
286 // idle loop iteration. This ensures that all pending events have
288 m_beingDeleted
= TRUE
;
290 // Shutdown and close the socket
293 // Supress events from now on
296 // schedule this object for deletion
297 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
300 // let the traits object decide what to do with us
301 traits
->ScheduleForDestroy(this);
303 else // no app or no traits
305 // in wxBase we might have no app object at all, don't leak memory
312 // --------------------------------------------------------------------------
314 // --------------------------------------------------------------------------
316 // The following IO operations update m_error and m_lcount:
317 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
319 // TODO: Should Connect, Accept and AcceptWith update m_error?
321 bool wxSocketBase::Close()
323 // Interrupt pending waits
328 GSocket_Shutdown(m_socket
);
332 m_establishing
= FALSE
;
336 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
341 m_lcount
= _Read(buffer
, nbytes
);
343 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
344 if (m_flags
& wxSOCKET_WAITALL
)
345 m_error
= (m_lcount
!= nbytes
);
347 m_error
= (m_lcount
== 0);
349 // Allow read events from now on
355 wxUint32
wxSocketBase::_Read(void* buffer
, wxUint32 nbytes
)
359 // Try the pushback buffer first
360 total
= GetPushback(buffer
, nbytes
, FALSE
);
362 buffer
= (char *)buffer
+ total
;
364 // Return now in one of the following cases:
365 // - the socket is invalid,
366 // - we got all the data,
367 // - we got *some* data and we are not using wxSOCKET_WAITALL.
370 ((total
!= 0) && !(m_flags
& wxSOCKET_WAITALL
)) )
373 // Possible combinations (they are checked in this order)
375 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
381 if (m_flags
& wxSOCKET_NOWAIT
)
383 GSocket_SetNonBlocking(m_socket
, 1);
384 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
385 GSocket_SetNonBlocking(m_socket
, 0);
396 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForRead() )
399 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
405 buffer
= (char *)buffer
+ ret
;
408 // If we got here and wxSOCKET_WAITALL is not set, we can leave
409 // now. Otherwise, wait until we recv all the data or until there
412 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
419 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
421 wxUint32 len
, len2
, sig
, total
;
426 unsigned char sig
[4];
427 unsigned char len
[4];
436 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
438 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
441 sig
= (wxUint32
)msg
.sig
[0];
442 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
443 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
444 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
446 if (sig
!= 0xfeeddead)
448 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
452 len
= (wxUint32
)msg
.len
[0];
453 len
|= (wxUint32
)(msg
.len
[1] << 8);
454 len
|= (wxUint32
)(msg
.len
[2] << 16);
455 len
|= (wxUint32
)(msg
.len
[3] << 24);
465 // Don't attemp to read if the msg was zero bytes long.
468 total
= _Read(buffer
, len
);
475 char *discard_buffer
= new char[MAX_DISCARD_SIZE
];
478 // NOTE: discarded bytes don't add to m_lcount.
481 discard_len
= ((len2
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE
: len2
);
482 discard_len
= _Read(discard_buffer
, (wxUint32
)discard_len
);
483 len2
-= (wxUint32
)discard_len
;
485 while ((discard_len
> 0) && len2
);
487 delete [] discard_buffer
;
492 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
495 sig
= (wxUint32
)msg
.sig
[0];
496 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
497 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
498 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
500 if (sig
!= 0xdeadfeed)
502 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
518 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
523 m_lcount
= _Read(buffer
, nbytes
);
524 Pushback(buffer
, m_lcount
);
526 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
527 if (m_flags
& wxSOCKET_WAITALL
)
528 m_error
= (m_lcount
!= nbytes
);
530 m_error
= (m_lcount
== 0);
532 // Allow read events again
538 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
543 m_lcount
= _Write(buffer
, nbytes
);
545 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
546 if (m_flags
& wxSOCKET_WAITALL
)
547 m_error
= (m_lcount
!= nbytes
);
549 m_error
= (m_lcount
== 0);
551 // Allow write events again
557 wxUint32
wxSocketBase::_Write(const void *buffer
, wxUint32 nbytes
)
561 // If the socket is invalid or parameters are ill, return immediately
562 if (!m_socket
|| !buffer
|| !nbytes
)
565 // Possible combinations (they are checked in this order)
567 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
572 if (m_flags
& wxSOCKET_NOWAIT
)
574 GSocket_SetNonBlocking(m_socket
, 1);
575 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
576 GSocket_SetNonBlocking(m_socket
, 0);
587 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForWrite() )
590 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
596 buffer
= (const char *)buffer
+ ret
;
599 // If we got here and wxSOCKET_WAITALL is not set, we can leave
600 // now. Otherwise, wait until we send all the data or until there
603 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
610 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
616 unsigned char sig
[4];
617 unsigned char len
[4];
625 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
627 msg
.sig
[0] = (unsigned char) 0xad;
628 msg
.sig
[1] = (unsigned char) 0xde;
629 msg
.sig
[2] = (unsigned char) 0xed;
630 msg
.sig
[3] = (unsigned char) 0xfe;
632 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
633 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
634 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
635 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
637 if (_Write(&msg
, sizeof(msg
)) < sizeof(msg
))
640 total
= _Write(buffer
, nbytes
);
645 msg
.sig
[0] = (unsigned char) 0xed;
646 msg
.sig
[1] = (unsigned char) 0xfe;
647 msg
.sig
[2] = (unsigned char) 0xad;
648 msg
.sig
[3] = (unsigned char) 0xde;
649 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
651 if ((_Write(&msg
, sizeof(msg
))) < sizeof(msg
))
665 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
668 Pushback(buffer
, nbytes
);
676 wxSocketBase
& wxSocketBase::Discard()
678 char *buffer
= new char[MAX_DISCARD_SIZE
];
685 SetFlags(wxSOCKET_NOWAIT
);
689 ret
= _Read(buffer
, MAX_DISCARD_SIZE
);
692 while (ret
== MAX_DISCARD_SIZE
);
698 // Allow read events again
704 // --------------------------------------------------------------------------
706 // --------------------------------------------------------------------------
708 // All Wait functions poll the socket using GSocket_Select() to
709 // check for the specified combination of conditions, until one
710 // of these conditions become true, an error occurs, or the
711 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
712 // this won't block the GUI.
714 bool wxSocketBase::_Wait(long seconds
,
716 wxSocketEventFlags flags
)
719 GSocketEventFlags result
;
722 // Set this to TRUE to interrupt ongoing waits
725 // Check for valid socket
729 // Check for valid timeout value.
731 timeout
= seconds
* 1000 + milliseconds
;
733 timeout
= m_timeout
* 1000;
735 #if !defined(wxUSE_GUI) || !wxUSE_GUI
736 GSocket_SetTimeout(m_socket
, timeout
);
739 // Wait in an active polling loop.
741 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
742 // hurt. It has to be here because the (GSocket) event might arrive
743 // a bit delayed, and it has to be in OnRequest as well because we
744 // don't know whether the Wait functions are being used.
746 // Do this at least once (important if timeout == 0, when
747 // we are just polling). Also, if just polling, do not yield.
754 result
= GSocket_Select(m_socket
, flags
| GSOCK_LOST_FLAG
);
756 // Incoming connection (server) or connection established (client)
757 if (result
& GSOCK_CONNECTION_FLAG
)
760 m_establishing
= FALSE
;
764 // Data available or output buffer ready
765 if ((result
& GSOCK_INPUT_FLAG
) || (result
& GSOCK_OUTPUT_FLAG
))
771 if (result
& GSOCK_LOST_FLAG
)
774 m_establishing
= FALSE
;
775 return (flags
& GSOCK_LOST_FLAG
) != 0;
779 if ((!timeout
) || (chrono
.Time() > timeout
) || (m_interrupt
))
788 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
790 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
792 GSOCK_CONNECTION_FLAG
|
796 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
798 // Check pushback buffer before entering _Wait
802 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
803 // _Wait becuase of the semantics of WaitForRead: a return
804 // value of TRUE means that a GSocket_Read call will return
805 // immediately, not that there is actually data to read.
807 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
811 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
813 return _Wait(seconds
, milliseconds
, GSOCK_OUTPUT_FLAG
);
816 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
818 return _Wait(seconds
, milliseconds
, GSOCK_LOST_FLAG
);
821 // --------------------------------------------------------------------------
823 // --------------------------------------------------------------------------
826 // Get local or peer address
829 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
836 peer
= GSocket_GetPeer(m_socket
);
838 // copying a null address would just trigger an assert anyway
843 addr_man
.SetAddress(peer
);
844 GAddress_destroy(peer
);
849 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
857 local
= GSocket_GetLocal(m_socket
);
858 addr_man
.SetAddress(local
);
859 GAddress_destroy(local
);
865 // Save and restore socket state
868 void wxSocketBase::SaveState()
870 wxSocketState
*state
;
872 state
= new wxSocketState();
874 state
->m_flags
= m_flags
;
875 state
->m_notify
= m_notify
;
876 state
->m_eventmask
= m_eventmask
;
877 state
->m_clientData
= m_clientData
;
879 m_states
.Append(state
);
882 void wxSocketBase::RestoreState()
884 wxList::compatibility_iterator node
;
885 wxSocketState
*state
;
887 node
= m_states
.GetLast();
891 state
= (wxSocketState
*)node
->GetData();
893 m_flags
= state
->m_flags
;
894 m_notify
= state
->m_notify
;
895 m_eventmask
= state
->m_eventmask
;
896 m_clientData
= state
->m_clientData
;
898 m_states
.Erase(node
);
906 void wxSocketBase::SetTimeout(long seconds
)
912 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
916 void wxSocketBase::SetFlags(wxSocketFlags flags
)
922 // --------------------------------------------------------------------------
924 // --------------------------------------------------------------------------
926 // A note on how events are processed, which is probably the most
927 // difficult thing to get working right while keeping the same API
928 // and functionality for all platforms.
930 // When GSocket detects an event, it calls wx_socket_callback, which in
931 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
932 // object. OnRequest does some housekeeping, and if the event is to be
933 // propagated to the user, it creates a new wxSocketEvent object and
934 // posts it. The event is not processed immediately, but delayed with
935 // AddPendingEvent instead. This is necessary in order to decouple the
936 // event processing from wx_socket_callback; otherwise, subsequent IO
937 // calls made from the user event handler would fail, as gtk callbacks
938 // are not reentrant.
940 // Note that, unlike events, user callbacks (now deprecated) are _not_
941 // decoupled from wx_socket_callback and thus they suffer from a variety
942 // of problems. Avoid them where possible and use events instead.
945 void LINKAGEMODE
wx_socket_callback(GSocket
* WXUNUSED(socket
),
946 GSocketEvent notification
,
949 wxSocketBase
*sckobj
= (wxSocketBase
*)cdata
;
951 sckobj
->OnRequest((wxSocketNotify
) notification
);
954 void wxSocketBase::OnRequest(wxSocketNotify notification
)
956 // NOTE: We duplicate some of the code in _Wait, but this doesn't
957 // hurt. It has to be here because the (GSocket) event might arrive
958 // a bit delayed, and it has to be in _Wait as well because we don't
959 // know whether the Wait functions are being used.
963 case wxSOCKET_CONNECTION
:
964 m_establishing
= FALSE
;
968 // If we are in the middle of a R/W operation, do not
969 // propagate events to users. Also, filter 'late' events
970 // which are no longer valid.
973 if (m_reading
|| !GSocket_Select(m_socket
, GSOCK_INPUT_FLAG
))
977 case wxSOCKET_OUTPUT
:
978 if (m_writing
|| !GSocket_Select(m_socket
, GSOCK_OUTPUT_FLAG
))
984 m_establishing
= FALSE
;
991 // Schedule the event
993 wxSocketEventFlags flag
= 0;
995 switch (notification
)
997 case GSOCK_INPUT
: flag
= GSOCK_INPUT_FLAG
; break;
998 case GSOCK_OUTPUT
: flag
= GSOCK_OUTPUT_FLAG
; break;
999 case GSOCK_CONNECTION
: flag
= GSOCK_CONNECTION_FLAG
; break;
1000 case GSOCK_LOST
: flag
= GSOCK_LOST_FLAG
; break;
1002 wxLogWarning(_("wxSocket: unknown event!."));
1006 if (((m_eventmask
& flag
) == flag
) && m_notify
)
1010 wxSocketEvent
event(m_id
);
1011 event
.m_event
= notification
;
1012 event
.m_clientData
= m_clientData
;
1013 event
.SetEventObject(this);
1015 m_handler
->AddPendingEvent(event
);
1020 void wxSocketBase::Notify(bool notify
)
1025 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1027 m_eventmask
= flags
;
1030 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1032 m_handler
= &handler
;
1036 // --------------------------------------------------------------------------
1038 // --------------------------------------------------------------------------
1040 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1044 if (m_unread
== NULL
)
1045 m_unread
= malloc(size
);
1050 tmp
= malloc(m_unrd_size
+ size
);
1051 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1057 m_unrd_size
+= size
;
1059 memcpy(m_unread
, buffer
, size
);
1062 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1067 if (size
> (m_unrd_size
-m_unrd_cur
))
1068 size
= m_unrd_size
-m_unrd_cur
;
1070 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1075 if (m_unrd_size
== m_unrd_cur
)
1088 // ==========================================================================
1090 // ==========================================================================
1092 // --------------------------------------------------------------------------
1094 // --------------------------------------------------------------------------
1096 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1097 wxSocketFlags flags
)
1098 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1100 wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") );
1102 m_socket
= GSocket_new();
1106 wxLogTrace( wxTRACE_Socket
, _T("*** GSocket_new failed") );
1110 // Setup the socket as server
1113 GSocket_SetLocal(m_socket
, addr_man
.GetAddress());
1114 if (GSocket_SetServer(m_socket
) != GSOCK_NOERROR
)
1116 GSocket_destroy(m_socket
);
1119 wxLogTrace( wxTRACE_Socket
, _T("*** GSocket_SetServer failed") );
1123 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1124 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1125 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1126 wx_socket_callback
, (char *)this);
1130 // --------------------------------------------------------------------------
1132 // --------------------------------------------------------------------------
1134 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1136 GSocket
*child_socket
;
1141 // If wait == FALSE, then the call should be nonblocking.
1142 // When we are finished, we put the socket to blocking mode
1147 GSocket_SetNonBlocking(m_socket
, 1);
1149 child_socket
= GSocket_WaitConnection(m_socket
);
1152 GSocket_SetNonBlocking(m_socket
, 0);
1157 sock
.m_type
= wxSOCKET_BASE
;
1158 sock
.m_socket
= child_socket
;
1159 sock
.m_connected
= TRUE
;
1161 GSocket_SetTimeout(sock
.m_socket
, sock
.m_timeout
* 1000);
1162 GSocket_SetCallback(sock
.m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1163 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1164 wx_socket_callback
, (char *)&sock
);
1169 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1171 wxSocketBase
* sock
= new wxSocketBase();
1173 sock
->SetFlags(m_flags
);
1175 if (!AcceptWith(*sock
, wait
))
1184 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1186 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
);
1189 // ==========================================================================
1191 // ==========================================================================
1193 // --------------------------------------------------------------------------
1195 // --------------------------------------------------------------------------
1197 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1198 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1202 wxSocketClient::~wxSocketClient()
1206 // --------------------------------------------------------------------------
1208 // --------------------------------------------------------------------------
1210 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1216 // Shutdown and destroy the socket
1218 GSocket_destroy(m_socket
);
1221 m_socket
= GSocket_new();
1222 m_connected
= FALSE
;
1223 m_establishing
= FALSE
;
1228 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1229 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1230 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1231 wx_socket_callback
, (char *)this);
1233 // If wait == FALSE, then the call should be nonblocking.
1234 // When we are finished, we put the socket to blocking mode
1238 GSocket_SetNonBlocking(m_socket
, 1);
1240 GSocket_SetPeer(m_socket
, addr_man
.GetAddress());
1241 err
= GSocket_Connect(m_socket
, GSOCK_STREAMED
);
1244 GSocket_SetNonBlocking(m_socket
, 0);
1246 if (err
!= GSOCK_NOERROR
)
1248 if (err
== GSOCK_WOULDBLOCK
)
1249 m_establishing
= TRUE
;
1258 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1260 if (m_connected
) // Already connected
1263 if (!m_establishing
|| !m_socket
) // No connection in progress
1266 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
|
1270 // ==========================================================================
1272 // ==========================================================================
1274 /* NOTE: experimental stuff - might change */
1276 wxDatagramSocket::wxDatagramSocket( wxSockAddress
& addr
,
1277 wxSocketFlags flags
)
1278 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1281 // Create the socket
1282 m_socket
= GSocket_new();
1287 // Setup the socket as non connection oriented
1288 GSocket_SetLocal(m_socket
, addr
.GetAddress());
1289 if( GSocket_SetNonOriented(m_socket
) != GSOCK_NOERROR
)
1291 GSocket_destroy(m_socket
);
1296 // Initialize all stuff
1297 m_connected
= FALSE
;
1298 m_establishing
= FALSE
;
1299 GSocket_SetTimeout( m_socket
, m_timeout
);
1300 GSocket_SetCallback( m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1301 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1302 wx_socket_callback
, (char*)this );
1306 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1315 wxDatagramSocket
& wxDatagramSocket::SendTo( wxSockAddress
& addr
,
1319 GSocket_SetPeer(m_socket
, addr
.GetAddress());
1325 * -------------------------------------------------------------------------
1327 * -------------------------------------------------------------------------
1330 /* CHECK_ADDRESS verifies that the current address family is either
1331 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1332 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1333 * an appropiate error code.
1335 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1337 #define CHECK_ADDRESS(address, family) \
1339 if (address->m_family == GSOCK_NOFAMILY) \
1340 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1341 return address->m_error; \
1342 if (address->m_family != GSOCK_##family) \
1344 address->m_error = GSOCK_INVADDR; \
1345 return GSOCK_INVADDR; \
1349 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1351 if (address->m_family == GSOCK_NOFAMILY) \
1352 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1354 if (address->m_family != GSOCK_##family) \
1356 address->m_error = GSOCK_INVADDR; \
1362 GAddress
*GAddress_new(void)
1366 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1369 address
->m_family
= GSOCK_NOFAMILY
;
1370 address
->m_addr
= NULL
;
1376 GAddress
*GAddress_copy(GAddress
*address
)
1380 assert(address
!= NULL
);
1382 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1385 memcpy(addr2
, address
, sizeof(GAddress
));
1387 if (address
->m_addr
&& address
->m_len
> 0)
1389 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1390 if (addr2
->m_addr
== NULL
)
1395 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1401 void GAddress_destroy(GAddress
*address
)
1403 assert(address
!= NULL
);
1405 if (address
->m_addr
)
1406 free(address
->m_addr
);
1411 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1413 assert(address
!= NULL
);
1415 address
->m_family
= type
;
1418 GAddressType
GAddress_GetFamily(GAddress
*address
)
1420 assert(address
!= NULL
);
1422 return address
->m_family
;
1425 GSocketError
_GAddress_translate_from(GAddress
*address
,
1426 struct sockaddr
*addr
, int len
)
1428 address
->m_realfamily
= addr
->sa_family
;
1429 switch (addr
->sa_family
)
1432 address
->m_family
= GSOCK_INET
;
1435 address
->m_family
= GSOCK_UNIX
;
1439 address
->m_family
= GSOCK_INET6
;
1444 address
->m_error
= GSOCK_INVOP
;
1449 if (address
->m_addr
)
1450 free(address
->m_addr
);
1452 address
->m_len
= len
;
1453 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1455 if (address
->m_addr
== NULL
)
1457 address
->m_error
= GSOCK_MEMERR
;
1458 return GSOCK_MEMERR
;
1460 memcpy(address
->m_addr
, addr
, len
);
1462 return GSOCK_NOERROR
;
1465 GSocketError
_GAddress_translate_to(GAddress
*address
,
1466 struct sockaddr
**addr
, int *len
)
1468 if (!address
->m_addr
)
1470 address
->m_error
= GSOCK_INVADDR
;
1471 return GSOCK_INVADDR
;
1474 *len
= address
->m_len
;
1475 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1478 address
->m_error
= GSOCK_MEMERR
;
1479 return GSOCK_MEMERR
;
1482 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1483 return GSOCK_NOERROR
;
1487 * -------------------------------------------------------------------------
1488 * Internet address family
1489 * -------------------------------------------------------------------------
1492 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1494 address
->m_len
= sizeof(struct sockaddr_in
);
1495 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1496 if (address
->m_addr
== NULL
)
1498 address
->m_error
= GSOCK_MEMERR
;
1499 return GSOCK_MEMERR
;
1502 memset( address
->m_addr
, 0 , address
->m_len
) ;
1503 address
->m_family
= GSOCK_INET
;
1504 address
->m_realfamily
= PF_INET
;
1505 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1506 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1508 return GSOCK_NOERROR
;
1511 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1514 struct in_addr
*addr
;
1516 assert(address
!= NULL
);
1518 CHECK_ADDRESS(address
, INET
);
1520 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1522 /* If it is a numeric host name, convert it now */
1523 #if defined(HAVE_INET_ATON)
1524 if (inet_aton(hostname
, addr
) == 0)
1526 #elif defined(HAVE_INET_ADDR)
1527 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1530 /* Use gethostbyname by default */
1532 int val
= 1; /* VA doesn't like constants in conditional expressions */
1537 struct in_addr
*array_addr
;
1539 /* It is a real name, we solve it */
1540 if ((he
= gethostbyname(hostname
)) == NULL
)
1542 /* Reset to invalid address */
1543 addr
->s_addr
= INADDR_NONE
;
1544 address
->m_error
= GSOCK_NOHOST
;
1545 return GSOCK_NOHOST
;
1547 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1548 addr
->s_addr
= array_addr
[0].s_addr
;
1550 return GSOCK_NOERROR
;
1553 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1555 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1558 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1559 unsigned long hostaddr
)
1561 struct in_addr
*addr
;
1563 assert(address
!= NULL
);
1565 CHECK_ADDRESS(address
, INET
);
1567 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1568 addr
->s_addr
= htonl(hostaddr
) ;
1570 return GSOCK_NOERROR
;
1573 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1574 const char *protocol
)
1577 struct sockaddr_in
*addr
;
1579 assert(address
!= NULL
);
1580 CHECK_ADDRESS(address
, INET
);
1584 address
->m_error
= GSOCK_INVPORT
;
1585 return GSOCK_INVPORT
;
1588 se
= getservbyname(port
, protocol
);
1591 /* the cast to int suppresses compiler warnings about subscript having the
1593 if (isdigit((int)port
[0]))
1597 port_int
= atoi(port
);
1598 addr
= (struct sockaddr_in
*)address
->m_addr
;
1599 addr
->sin_port
= htons(port_int
);
1600 return GSOCK_NOERROR
;
1603 address
->m_error
= GSOCK_INVPORT
;
1604 return GSOCK_INVPORT
;
1607 addr
= (struct sockaddr_in
*)address
->m_addr
;
1608 addr
->sin_port
= se
->s_port
;
1610 return GSOCK_NOERROR
;
1613 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1615 struct sockaddr_in
*addr
;
1617 assert(address
!= NULL
);
1618 CHECK_ADDRESS(address
, INET
);
1620 addr
= (struct sockaddr_in
*)address
->m_addr
;
1621 addr
->sin_port
= htons(port
);
1623 return GSOCK_NOERROR
;
1626 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1630 struct sockaddr_in
*addr
;
1632 assert(address
!= NULL
);
1633 CHECK_ADDRESS(address
, INET
);
1635 addr
= (struct sockaddr_in
*)address
->m_addr
;
1636 addr_buf
= (char *)&(addr
->sin_addr
);
1638 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1641 address
->m_error
= GSOCK_NOHOST
;
1642 return GSOCK_NOHOST
;
1645 strncpy(hostname
, he
->h_name
, sbuf
);
1647 return GSOCK_NOERROR
;
1650 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1652 struct sockaddr_in
*addr
;
1654 assert(address
!= NULL
);
1655 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1657 addr
= (struct sockaddr_in
*)address
->m_addr
;
1659 return ntohl(addr
->sin_addr
.s_addr
) ;
1662 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1664 struct sockaddr_in
*addr
;
1666 assert(address
!= NULL
);
1667 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1669 addr
= (struct sockaddr_in
*)address
->m_addr
;
1670 return ntohs(addr
->sin_port
);
1674 * -------------------------------------------------------------------------
1675 * Unix address family
1676 * -------------------------------------------------------------------------
1679 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1681 address
->m_len
= sizeof(struct sockaddr_un
);
1682 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1683 if (address
->m_addr
== NULL
)
1685 address
->m_error
= GSOCK_MEMERR
;
1686 return GSOCK_MEMERR
;
1689 address
->m_family
= GSOCK_UNIX
;
1690 address
->m_realfamily
= PF_UNIX
;
1691 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1692 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1694 return GSOCK_NOERROR
;
1697 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1699 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1701 struct sockaddr_un
*addr
;
1703 assert(address
!= NULL
);
1705 CHECK_ADDRESS(address
, UNIX
);
1707 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1708 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1709 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1711 return GSOCK_NOERROR
;
1714 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1716 struct sockaddr_un
*addr
;
1718 assert(address
!= NULL
);
1719 CHECK_ADDRESS(address
, UNIX
);
1721 addr
= (struct sockaddr_un
*)address
->m_addr
;
1723 strncpy(path
, addr
->sun_path
, sbuf
);
1725 return GSOCK_NOERROR
;
1728 /* Address handling */
1730 /* GSocket_SetLocal:
1734 * Set or get the local or peer address for this socket. The 'set'
1735 * functions return GSOCK_NOERROR on success, an error code otherwise.
1736 * The 'get' functions return a pointer to a GAddress object on success,
1737 * or NULL otherwise, in which case they set the error code of the
1738 * corresponding GSocket.
1741 * GSOCK_INVSOCK - the socket is not valid.
1742 * GSOCK_INVADDR - the address is not valid.
1745 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
1747 assert(socket
!= NULL
);
1749 /* the socket must be initialized, or it must be a server */
1750 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
1752 socket
->m_error
= GSOCK_INVSOCK
;
1753 return GSOCK_INVSOCK
;
1757 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1759 socket
->m_error
= GSOCK_INVADDR
;
1760 return GSOCK_INVADDR
;
1763 if (socket
->m_local
)
1764 GAddress_destroy(socket
->m_local
);
1766 socket
->m_local
= GAddress_copy(address
);
1768 return GSOCK_NOERROR
;
1771 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
1773 assert(socket
!= NULL
);
1776 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1778 socket
->m_error
= GSOCK_INVADDR
;
1779 return GSOCK_INVADDR
;
1783 GAddress_destroy(socket
->m_peer
);
1785 socket
->m_peer
= GAddress_copy(address
);
1787 return GSOCK_NOERROR
;
1790 GAddress
*GSocket_GetLocal(GSocket
*socket
)
1793 struct sockaddr addr
;
1794 socklen_t size
= sizeof(addr
);
1797 assert(socket
!= NULL
);
1799 /* try to get it from the m_local var first */
1800 if (socket
->m_local
)
1801 return GAddress_copy(socket
->m_local
);
1803 /* else, if the socket is initialized, try getsockname */
1804 if (socket
->m_fd
== INVALID_SOCKET
)
1806 socket
->m_error
= GSOCK_INVSOCK
;
1810 if (getsockname(socket
->m_fd
, &addr
, (socklen_t
*) &size
) < 0)
1812 socket
->m_error
= GSOCK_IOERR
;
1816 /* got a valid address from getsockname, create a GAddress object */
1817 address
= GAddress_new();
1818 if (address
== NULL
)
1820 socket
->m_error
= GSOCK_MEMERR
;
1824 err
= _GAddress_translate_from(address
, &addr
, size
);
1825 if (err
!= GSOCK_NOERROR
)
1827 GAddress_destroy(address
);
1828 socket
->m_error
= err
;
1835 GAddress
*GSocket_GetPeer(GSocket
*socket
)
1837 assert(socket
!= NULL
);
1839 /* try to get it from the m_peer var */
1841 return GAddress_copy(socket
->m_peer
);
1851 GSocket
*GSocket_new(void)
1854 socket
= (GSocket
*)malloc(sizeof(GSocket
));
1859 socket
->m_fd
= INVALID_SOCKET
;
1861 for (int i
=0;i
<GSOCK_MAX_EVENT
;i
++)
1863 socket
->m_cbacks
[i
] = NULL
;
1865 socket
->m_detected
= 0;
1867 socket
->m_local
= NULL
;
1868 socket
->m_peer
= NULL
;
1869 socket
->m_error
= GSOCK_NOERROR
;
1871 socket
->m_non_blocking
= FALSE
;
1872 socket
->m_stream
= TRUE
;
1873 // socket->m_oriented = TRUE;
1874 socket
->m_server
= FALSE
;
1875 socket
->m_establishing
= FALSE
;
1876 socket
->m_timeout
= 10*60*1000;
1877 /* 10 minutes * 60 sec * 1000 millisec */
1879 socket
->m_cfSocket
= NULL
;
1880 socket
->m_runLoopSource
= NULL
;
1881 socket
->m_readStream
= NULL
;
1882 socket
->m_writeStream
= NULL
;
1887 void GSocket_close(GSocket
*socket
)
1889 if ( socket
->m_cfSocket
!= NULL
)
1891 if ( socket
->m_readStream
)
1893 CFReadStreamClose(socket
->m_readStream
);
1894 CFRelease( socket
->m_readStream
) ;
1895 socket
->m_readStream
= NULL
;
1897 if ( socket
->m_writeStream
)
1899 CFWriteStreamClose(socket
->m_writeStream
);
1900 CFRelease( socket
->m_writeStream
) ;
1901 socket
->m_writeStream
= NULL
;
1904 CFSocketInvalidate( socket
->m_cfSocket
) ;
1905 CFRelease( socket
->m_cfSocket
) ;
1906 socket
->m_cfSocket
= NULL
;
1907 socket
->m_fd
= INVALID_SOCKET
;
1911 void GSocket_Shutdown(GSocket
*socket
)
1913 GSocket_close( socket
) ;
1915 /* Disable GUI callbacks */
1916 for (int evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
1917 socket
->m_cbacks
[evt
] = NULL
;
1919 socket
->m_detected
= GSOCK_LOST_FLAG
;
1922 void GSocket_destroy(GSocket
*socket
)
1924 assert(socket
!= NULL
);
1926 /* Check that the socket is really shutdowned */
1927 if (socket
->m_fd
!= INVALID_SOCKET
)
1928 GSocket_Shutdown(socket
);
1930 /* Destroy private addresses */
1931 if (socket
->m_local
)
1932 GAddress_destroy(socket
->m_local
);
1935 GAddress_destroy(socket
->m_peer
);
1937 /* Destroy the socket itself */
1941 GSocketError
GSocket_Connect(GSocket
*socket
, GSocketStream stream
)
1943 assert(socket
!= NULL
);
1945 if (socket
->m_fd
!= INVALID_SOCKET
)
1947 socket
->m_error
= GSOCK_INVSOCK
;
1948 return GSOCK_INVSOCK
;
1951 if (!socket
->m_peer
)
1953 socket
->m_error
= GSOCK_INVADDR
;
1954 return GSOCK_INVADDR
;
1957 /* Streamed or dgram socket? */
1958 socket
->m_stream
= (stream
== GSOCK_STREAMED
);
1959 socket
->m_oriented
= TRUE
;
1960 socket
->m_server
= FALSE
;
1961 socket
->m_establishing
= FALSE
;
1963 GSocketError returnErr
= GSOCK_NOERROR
;
1966 CFAllocatorRef alloc
= kCFAllocatorDefault
;
1967 CFSocketContext ctx
;
1968 memset( &ctx
, 0 , sizeof( ctx
) ) ;
1970 socket
->m_cfSocket
= CFSocketCreate( alloc
, socket
->m_peer
->m_realfamily
,
1971 stream
== GSOCK_STREAMED
? SOCK_STREAM
: SOCK_DGRAM
, 0 ,
1972 kCFSocketReadCallBack
| kCFSocketWriteCallBack
| kCFSocketConnectCallBack
, wxMacCFSocketCallback
, &ctx
) ;
1973 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
1975 socket
->m_fd
= CFSocketGetNative( socket
->m_cfSocket
) ;
1977 CFStreamCreatePairWithSocket ( alloc
, socket
->m_fd
, &socket
->m_readStream
, &socket
->m_writeStream
);
1978 if ((socket
->m_readStream
== NULL
) || (socket
->m_writeStream
== NULL
))
1980 GSocket_close(socket
);
1981 socket
->m_error
= GSOCK_IOERR
;
1985 if ( !CFReadStreamOpen( socket
->m_readStream
) || !CFWriteStreamOpen( socket
->m_writeStream
) )
1987 GSocket_close(socket
);
1988 socket
->m_error
= GSOCK_IOERR
;
1992 CFRunLoopSourceRef rls
= CFSocketCreateRunLoopSource(alloc
, socket
->m_cfSocket
, 0);
1993 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls
, kCFRunLoopCommonModes
);
1996 CFDataRef address
= CFDataCreateWithBytesNoCopy(alloc
, (const UInt8
*) socket
->m_peer
->m_addr
, socket
->m_peer
->m_len
, kCFAllocatorNull
);
1998 return GSOCK_MEMERR
;
2000 err
= CFSocketConnectToAddress( socket
->m_cfSocket
, address
, socket
->m_non_blocking
? -1 : socket
->m_timeout
/ 1000 ) ;
2003 if (err
!= kCFSocketSuccess
)
2005 if ( err
== kCFSocketTimeout
)
2007 GSocket_close(socket
);
2008 socket
->m_error
= GSOCK_TIMEDOUT
;
2009 return GSOCK_TIMEDOUT
;
2011 // we don't know whether a connect in progress will be issued like this
2012 if ( err
!= kCFSocketTimeout
&& socket
->m_non_blocking
)
2014 socket
->m_establishing
= TRUE
;
2015 socket
->m_error
= GSOCK_WOULDBLOCK
;
2016 return GSOCK_WOULDBLOCK
;
2019 GSocket_close(socket
);
2020 socket
->m_error
= GSOCK_IOERR
;
2024 return GSOCK_NOERROR
;
2029 /* GSocket_SetNonBlocking:
2030 * Sets the socket to non-blocking mode. All IO calls will return
2033 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
2035 assert(socket
!= NULL
);
2037 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2039 socket
->m_non_blocking
= non_block
;
2042 /* GSocket_SetTimeout:
2043 * Sets the timeout for blocking calls. Time is expressed in
2046 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
2048 assert(socket
!= NULL
);
2050 socket
->m_timeout
= millisec
;
2053 /* GSocket_GetError:
2054 * Returns the last error which occurred for this socket. Note that successful
2055 * operations do not clear this back to GSOCK_NOERROR, so use it only
2058 GSocketError
GSocket_GetError(GSocket
*socket
)
2060 assert(socket
!= NULL
);
2062 return socket
->m_error
;
2068 * There is data to be read in the input buffer. If, after a read
2069 * operation, there is still data available, the callback function will
2072 * The socket is available for writing. That is, the next write call
2073 * won't block. This event is generated only once, when the connection is
2074 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2075 * when the output buffer empties again. This means that the app should
2076 * assume that it can write since the first OUTPUT event, and no more
2077 * OUTPUT events will be generated unless an error occurs.
2079 * Connection successfully established, for client sockets, or incoming
2080 * client connection, for server sockets. Wait for this event (also watch
2081 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2083 * The connection is lost (or a connection request failed); this could
2084 * be due to a failure, or due to the peer closing it gracefully.
2087 /* GSocket_SetCallback:
2088 * Enables the callbacks specified by 'flags'. Note that 'flags'
2089 * may be a combination of flags OR'ed toghether, so the same
2090 * callback function can be made to accept different events.
2091 * The callback function must have the following prototype:
2093 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2095 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
2096 GSocketCallback callback
, char *cdata
)
2100 assert(socket
!= NULL
);
2102 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2104 if ((flags
& (1 << count
)) != 0)
2106 socket
->m_cbacks
[count
] = callback
;
2107 socket
->m_data
[count
] = cdata
;
2112 /* GSocket_UnsetCallback:
2113 * Disables all callbacks specified by 'flags', which may be a
2114 * combination of flags OR'ed toghether.
2116 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
2120 assert(socket
!= NULL
);
2122 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2124 if ((flags
& (1 << count
)) != 0)
2126 socket
->m_cbacks
[count
] = NULL
;
2127 socket
->m_data
[count
] = NULL
;
2133 #define CALL_CALLBACK(socket, event) { \
2134 _GSocket_Disable(socket, event); \
2135 if (socket->m_cbacks[event]) \
2136 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2139 void _GSocket_Install_Callback(GSocket
*socket
, GSocketEvent event
)
2144 case GSOCK_CONNECTION
:
2145 if(socket
->m_server
)
2146 c
= kCFSocketReadCallBack
;
2148 c
= kCFSocketConnectCallBack
;
2152 c
= kCFSocketReadCallBack
;
2155 c
= kCFSocketWriteCallBack
;
2160 CFSocketEnableCallBacks(socket
->m_cfSocket
, c
);
2163 void _GSocket_Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
2168 case GSOCK_CONNECTION
:
2169 if(socket
->m_server
)
2170 c
= kCFSocketReadCallBack
;
2172 c
= kCFSocketConnectCallBack
;
2176 c
= kCFSocketReadCallBack
;
2179 c
= kCFSocketWriteCallBack
;
2184 CFSocketDisableCallBacks(socket
->m_cfSocket
, c
);
2187 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
2189 socket
->m_detected
&= ~(1 << event
);
2190 _GSocket_Install_Callback(socket
, event
);
2193 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
2195 socket
->m_detected
|= (1 << event
);
2196 _GSocket_Uninstall_Callback(socket
, event
);
2199 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
2200 CFDataRef address
, const void* data
, void* info
)
2202 GSocket
* socket
= (GSocket
*)info
;
2204 switch (callbackType
)
2206 case kCFSocketConnectCallBack
:
2209 SInt32 error
= *((SInt32
*)data
) ;
2210 CALL_CALLBACK( socket
, GSOCK_LOST
) ;
2211 GSocket_Shutdown(socket
);
2215 CALL_CALLBACK( socket
, GSOCK_CONNECTION
) ;
2218 case kCFSocketReadCallBack
:
2219 CALL_CALLBACK( socket
, GSOCK_INPUT
) ;
2221 case kCFSocketWriteCallBack
:
2222 CALL_CALLBACK( socket
, GSOCK_OUTPUT
) ;
2225 break; /* We shouldn't get here. */
2229 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
2233 assert(socket
!= NULL
);
2234 // if ( !CFReadStreamHasBytesAvailable() )
2235 ret
= CFReadStreamRead( socket
->m_readStream
, (UInt8
*) buffer
, size
) ;
2240 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
2244 assert(socket
!= NULL
);
2245 ret
= CFWriteStreamWrite( socket
->m_writeStream
, (UInt8
*) buffer
, size
) ;
2249 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
2251 assert(socket
!= NULL
);
2252 return flags
& socket
->m_detected
;
2255 // ==========================================================================
2257 // ==========================================================================
2259 class wxSocketModule
: public wxModule
2262 virtual bool OnInit()
2264 // wxSocketBase will call GSocket_Init() itself when/if needed
2268 virtual void OnExit()
2270 if ( wxSocketBase::IsInitialized() )
2271 wxSocketBase::Shutdown();
2275 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2278 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)