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"
23 #include "wx/object.h"
24 #include "wx/string.h"
27 #include "wx/module.h"
32 #include "wx/sckaddr.h"
33 #include "wx/socket.h"
34 #include "wx/mac/carbon/private.h"
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
41 #define HAVE_INET_ATON
43 // DLL options compatibility check:
46 WX_CHECK_BUILD_OPTIONS("wxNet")
50 #define MAX_DISCARD_SIZE (10 * 1024)
52 #ifndef INVALID_SOCKET
53 #define INVALID_SOCKET -1
56 // what to do within waits: we have 2 cases: from the main thread itself we
57 // have to call wxYield() to let the events (including the GUI events and the
58 // low-level (not wxWidgets) events from GSocket) be processed. From another
59 // thread it is enough to just call wxThread::Yield() which will give away the
60 // rest of our time slice: the explanation is that the events will be processed
61 // by the main thread anyhow, without calling wxYield(), but we don't want to
62 // eat the CPU time uselessly while sitting in the loop waiting for the data
64 #define PROCESS_EVENTS() \
66 if ( wxThread::IsMain() ) \
71 #else // !wxUSE_THREADS
72 #define PROCESS_EVENTS() wxYield()
73 #endif // wxUSE_THREADS/!wxUSE_THREADS
75 #define wxTRACE_Socket _T("wxSocket")
78 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
79 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
80 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
81 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
82 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
84 // --------------------------------------------------------------------------
86 // --------------------------------------------------------------------------
88 class wxSocketState
: public wxObject
91 wxSocketFlags m_flags
;
92 wxSocketEventFlags m_eventmask
;
97 wxSocketState() : wxObject() {}
99 DECLARE_NO_COPY_CLASS(wxSocketState
)
104 CFSocketNativeHandle m_fd
;
107 GSocketError m_error
;
114 unsigned long m_timeout
;
117 GSocketEventFlags m_detected
;
118 GSocketCallback m_cbacks
[GSOCK_MAX_EVENT
];
119 char *m_data
[GSOCK_MAX_EVENT
];
121 CFSocketRef m_cfSocket
;
122 CFRunLoopSourceRef m_runLoopSource
;
123 CFReadStreamRef m_readStream
;
124 CFWriteStreamRef m_writeStream
;
129 struct sockaddr
*m_addr
;
132 GAddressType m_family
;
135 GSocketError m_error
;
139 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
140 CFDataRef address
, const void* data
, void* info
) ;
141 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
) ;
142 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
) ;
144 // ==========================================================================
146 // ==========================================================================
148 // --------------------------------------------------------------------------
149 // Initialization and shutdown
150 // --------------------------------------------------------------------------
152 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
153 // to m_countInit with a crit section
154 size_t wxSocketBase::m_countInit
= 0;
156 bool wxSocketBase::IsInitialized()
158 return m_countInit
> 0;
161 bool wxSocketBase::Initialize()
163 if ( !m_countInit
++ )
166 wxAppTraits
*traits
= wxAppConsole::GetInstance() ?
167 wxAppConsole::GetInstance()->GetTraits() : NULL
;
168 GSocketGUIFunctionsTable
*functions
=
169 traits
? traits
->GetSocketGUIFunctionsTable() : NULL
;
170 GSocket_SetGUIFunctions(functions
);
172 if ( !GSocket_Init() )
184 void wxSocketBase::Shutdown()
186 // we should be initialized
187 wxASSERT_MSG( m_countInit
, wxT("extra call to Shutdown()") );
188 if ( !--m_countInit
)
196 // --------------------------------------------------------------------------
198 // --------------------------------------------------------------------------
200 void wxSocketBase::Init()
203 m_type
= wxSOCKET_UNINIT
;
214 m_beingDeleted
= false;
228 if ( !IsInitialized() )
230 // this Initialize() will be undone by wxSocketModule::OnExit(), all the
231 // other calls to it should be matched by a call to Shutdown()
236 wxSocketBase::wxSocketBase()
241 wxSocketBase::wxSocketBase( wxSocketFlags flags
, wxSocketType type
)
249 wxSocketBase::~wxSocketBase()
251 // Just in case the app called Destroy() *and* then deleted
252 // the socket immediately: don't leave dangling pointers.
253 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
255 traits
->RemoveFromPendingDelete(this);
257 // Shutdown and close the socket
261 // Destroy the GSocket object
264 GSocket_destroy(m_socket
);
267 // Free the pushback buffer
272 bool wxSocketBase::Destroy()
274 // Delayed destruction: the socket will be deleted during the next
275 // idle loop iteration. This ensures that all pending events have
277 m_beingDeleted
= true;
279 // Shutdown and close the socket
282 // Supress events from now on
285 // schedule this object for deletion
286 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
289 // let the traits object decide what to do with us
290 traits
->ScheduleForDestroy(this);
292 else // no app or no traits
294 // in wxBase we might have no app object at all, don't leak memory
301 // --------------------------------------------------------------------------
303 // --------------------------------------------------------------------------
305 // The following IO operations update m_error and m_lcount:
306 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
308 // TODO: Should Connect, Accept and AcceptWith update m_error?
310 bool wxSocketBase::Close()
312 // Interrupt pending waits
316 GSocket_Shutdown(m_socket
);
319 m_establishing
= false;
324 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
329 m_lcount
= _Read(buffer
, nbytes
);
331 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
332 if (m_flags
& wxSOCKET_WAITALL
)
333 m_error
= (m_lcount
!= nbytes
);
335 m_error
= (m_lcount
== 0);
337 // Allow read events from now on
343 wxUint32
wxSocketBase::_Read(void* buffer
, wxUint32 nbytes
)
347 // Try the pushback buffer first
348 total
= GetPushback(buffer
, nbytes
, false);
350 buffer
= (char *)buffer
+ total
;
352 // Return now in one of the following cases:
353 // - the socket is invalid,
354 // - we got all the data,
355 // - we got *some* data and we are not using wxSOCKET_WAITALL.
358 ((total
!= 0) && !(m_flags
& wxSOCKET_WAITALL
)) )
361 // Possible combinations (they are checked in this order)
363 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
369 if (m_flags
& wxSOCKET_NOWAIT
)
371 GSocket_SetNonBlocking(m_socket
, 1);
372 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
373 GSocket_SetNonBlocking(m_socket
, 0);
384 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForRead() )
387 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
393 buffer
= (char *)buffer
+ ret
;
396 // If we got here and wxSOCKET_WAITALL is not set, we can leave
397 // now. Otherwise, wait until we recv all the data or until there
400 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
407 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
409 wxUint32 len
, len2
, sig
, total
;
414 unsigned char sig
[4];
415 unsigned char len
[4];
425 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
427 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
430 sig
= (wxUint32
)msg
.sig
[0];
431 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
432 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
433 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
435 if (sig
!= 0xfeeddead)
437 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
441 len
= (wxUint32
)msg
.len
[0];
442 len
|= (wxUint32
)(msg
.len
[1] << 8);
443 len
|= (wxUint32
)(msg
.len
[2] << 16);
444 len
|= (wxUint32
)(msg
.len
[3] << 24);
454 // Don't attemp to read if the msg was zero bytes long.
457 total
= _Read(buffer
, len
);
464 char *discard_buffer
= new char[MAX_DISCARD_SIZE
];
467 // NOTE: discarded bytes don't add to m_lcount.
470 discard_len
= ((len2
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE
: len2
);
471 discard_len
= _Read(discard_buffer
, (wxUint32
)discard_len
);
472 len2
-= (wxUint32
)discard_len
;
474 while ((discard_len
> 0) && len2
);
476 delete [] discard_buffer
;
481 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
484 sig
= (wxUint32
)msg
.sig
[0];
485 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
486 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
487 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
489 if (sig
!= 0xdeadfeed)
491 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
507 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
512 m_lcount
= _Read(buffer
, nbytes
);
513 Pushback(buffer
, m_lcount
);
515 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
516 if (m_flags
& wxSOCKET_WAITALL
)
517 m_error
= (m_lcount
!= nbytes
);
519 m_error
= (m_lcount
== 0);
521 // Allow read events again
527 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
532 m_lcount
= _Write(buffer
, nbytes
);
534 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
535 if (m_flags
& wxSOCKET_WAITALL
)
536 m_error
= (m_lcount
!= nbytes
);
538 m_error
= (m_lcount
== 0);
540 // Allow write events again
546 wxUint32
wxSocketBase::_Write(const void *buffer
, wxUint32 nbytes
)
550 // If the socket is invalid or parameters are ill, return immediately
551 if (!m_socket
|| !buffer
|| !nbytes
)
554 // Possible combinations (they are checked in this order)
556 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
561 if (m_flags
& wxSOCKET_NOWAIT
)
563 GSocket_SetNonBlocking(m_socket
, 1);
564 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
565 GSocket_SetNonBlocking(m_socket
, 0);
576 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForWrite() )
579 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
585 buffer
= (const char *)buffer
+ ret
;
588 // If we got here and wxSOCKET_WAITALL is not set, we can leave
589 // now. Otherwise, wait until we send all the data or until there
592 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
599 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
605 unsigned char sig
[4];
606 unsigned char len
[4];
615 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
617 msg
.sig
[0] = (unsigned char) 0xad;
618 msg
.sig
[1] = (unsigned char) 0xde;
619 msg
.sig
[2] = (unsigned char) 0xed;
620 msg
.sig
[3] = (unsigned char) 0xfe;
622 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
623 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
624 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
625 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
627 if (_Write(&msg
, sizeof(msg
)) < sizeof(msg
))
630 total
= _Write(buffer
, nbytes
);
635 msg
.sig
[0] = (unsigned char) 0xed;
636 msg
.sig
[1] = (unsigned char) 0xfe;
637 msg
.sig
[2] = (unsigned char) 0xad;
638 msg
.sig
[3] = (unsigned char) 0xde;
639 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
641 if ((_Write(&msg
, sizeof(msg
))) < sizeof(msg
))
655 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
658 Pushback(buffer
, nbytes
);
666 wxSocketBase
& wxSocketBase::Discard()
668 char *buffer
= new char[MAX_DISCARD_SIZE
];
675 SetFlags(wxSOCKET_NOWAIT
);
679 ret
= _Read(buffer
, MAX_DISCARD_SIZE
);
682 while (ret
== MAX_DISCARD_SIZE
);
688 // Allow read events again
694 // --------------------------------------------------------------------------
696 // --------------------------------------------------------------------------
698 // All Wait functions poll the socket using GSocket_Select() to
699 // check for the specified combination of conditions, until one
700 // of these conditions become true, an error occurs, or the
701 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
702 // this won't block the GUI.
704 bool wxSocketBase::_Wait(long seconds
,
706 wxSocketEventFlags flags
)
708 GSocketEventFlags result
;
711 // Set this to true to interrupt ongoing waits
714 // Check for valid socket
718 // Check for valid timeout value.
720 timeout
= seconds
* 1000 + milliseconds
;
722 timeout
= m_timeout
* 1000;
724 #if !defined(wxUSE_GUI) || !wxUSE_GUI
725 GSocket_SetTimeout(m_socket
, timeout
);
728 // Wait in an active polling loop.
730 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
731 // hurt. It has to be here because the (GSocket) event might arrive
732 // a bit delayed, and it has to be in OnRequest as well because we
733 // don't know whether the Wait functions are being used.
735 // Do this at least once (important if timeout == 0, when
736 // we are just polling). Also, if just polling, do not yield.
743 result
= GSocket_Select(m_socket
, flags
| GSOCK_LOST_FLAG
);
745 // Incoming connection (server) or connection established (client)
746 if (result
& GSOCK_CONNECTION_FLAG
)
749 m_establishing
= false;
754 // Data available or output buffer ready
755 if ((result
& GSOCK_INPUT_FLAG
) || (result
& GSOCK_OUTPUT_FLAG
))
761 if (result
& GSOCK_LOST_FLAG
)
764 m_establishing
= false;
766 return (flags
& GSOCK_LOST_FLAG
) != 0;
770 if ((!timeout
) || (chrono
.Time() > timeout
) || (m_interrupt
))
779 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
781 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
783 GSOCK_CONNECTION_FLAG
|
787 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
789 // Check pushback buffer before entering _Wait
793 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
794 // _Wait becuase of the semantics of WaitForRead: a return
795 // value of true means that a GSocket_Read call will return
796 // immediately, not that there is actually data to read.
798 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
| GSOCK_LOST_FLAG
);
801 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
803 return _Wait(seconds
, milliseconds
, GSOCK_OUTPUT_FLAG
);
806 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
808 return _Wait(seconds
, milliseconds
, GSOCK_LOST_FLAG
);
811 // --------------------------------------------------------------------------
813 // --------------------------------------------------------------------------
816 // Get local or peer address
819 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
826 peer
= GSocket_GetPeer(m_socket
);
828 // copying a null address would just trigger an assert anyway
833 addr_man
.SetAddress(peer
);
834 GAddress_destroy(peer
);
839 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
847 local
= GSocket_GetLocal(m_socket
);
848 addr_man
.SetAddress(local
);
849 GAddress_destroy(local
);
856 // Save and restore socket state
859 void wxSocketBase::SaveState()
861 wxSocketState
*state
;
863 state
= new wxSocketState();
865 state
->m_flags
= m_flags
;
866 state
->m_notify
= m_notify
;
867 state
->m_eventmask
= m_eventmask
;
868 state
->m_clientData
= m_clientData
;
870 m_states
.Append(state
);
873 void wxSocketBase::RestoreState()
875 wxList::compatibility_iterator node
;
876 wxSocketState
*state
;
878 node
= m_states
.GetLast();
882 state
= (wxSocketState
*)node
->GetData();
884 m_flags
= state
->m_flags
;
885 m_notify
= state
->m_notify
;
886 m_eventmask
= state
->m_eventmask
;
887 m_clientData
= state
->m_clientData
;
889 m_states
.Erase(node
);
897 void wxSocketBase::SetTimeout(long seconds
)
903 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
907 void wxSocketBase::SetFlags(wxSocketFlags flags
)
913 // --------------------------------------------------------------------------
915 // --------------------------------------------------------------------------
917 // A note on how events are processed, which is probably the most
918 // difficult thing to get working right while keeping the same API
919 // and functionality for all platforms.
921 // When GSocket detects an event, it calls wx_socket_callback, which in
922 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
923 // object. OnRequest does some housekeeping, and if the event is to be
924 // propagated to the user, it creates a new wxSocketEvent object and
925 // posts it. The event is not processed immediately, but delayed with
926 // AddPendingEvent instead. This is necessary in order to decouple the
927 // event processing from wx_socket_callback; otherwise, subsequent IO
928 // calls made from the user event handler would fail, as gtk callbacks
929 // are not reentrant.
931 // Note that, unlike events, user callbacks (now deprecated) are _not_
932 // decoupled from wx_socket_callback and thus they suffer from a variety
933 // of problems. Avoid them where possible and use events instead.
936 void LINKAGEMODE
wx_socket_callback(GSocket
* WXUNUSED(socket
),
937 GSocketEvent notification
,
940 wxSocketBase
*sckobj
= (wxSocketBase
*)cdata
;
942 sckobj
->OnRequest((wxSocketNotify
) notification
);
945 void wxSocketBase::OnRequest(wxSocketNotify notification
)
947 // NOTE: We duplicate some of the code in _Wait, but this doesn't
948 // hurt. It has to be here because the (GSocket) event might arrive
949 // a bit delayed, and it has to be in _Wait as well because we don't
950 // know whether the Wait functions are being used.
952 switch (notification
)
954 case wxSOCKET_CONNECTION
:
955 m_establishing
= false;
959 // If we are in the middle of a R/W operation, do not
960 // propagate events to users. Also, filter 'late' events
961 // which are no longer valid.
964 if (m_reading
|| !GSocket_Select(m_socket
, GSOCK_INPUT_FLAG
))
968 case wxSOCKET_OUTPUT
:
969 if (m_writing
|| !GSocket_Select(m_socket
, GSOCK_OUTPUT_FLAG
))
975 m_establishing
= false;
982 // Schedule the event
984 wxSocketEventFlags flag
= 0;
986 switch (notification
)
989 flag
= GSOCK_INPUT_FLAG
;
993 flag
= GSOCK_OUTPUT_FLAG
;
996 case GSOCK_CONNECTION
:
997 flag
= GSOCK_CONNECTION_FLAG
;
1001 flag
= GSOCK_LOST_FLAG
;
1005 wxLogWarning( wxT("wxSocket: unknown event!") );
1009 if (((m_eventmask
& flag
) == flag
) && m_notify
)
1013 wxSocketEvent
event(m_id
);
1014 event
.m_event
= notification
;
1015 event
.m_clientData
= m_clientData
;
1016 event
.SetEventObject(this);
1018 m_handler
->AddPendingEvent(event
);
1023 void wxSocketBase::Notify(bool notify
)
1028 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1030 m_eventmask
= flags
;
1033 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1035 m_handler
= &handler
;
1039 // --------------------------------------------------------------------------
1041 // --------------------------------------------------------------------------
1043 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1048 if (m_unread
== NULL
)
1049 m_unread
= malloc(size
);
1054 tmp
= malloc(m_unrd_size
+ size
);
1055 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1061 m_unrd_size
+= size
;
1063 memcpy(m_unread
, buffer
, size
);
1066 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1071 if (size
> (m_unrd_size
-m_unrd_cur
))
1072 size
= m_unrd_size
-m_unrd_cur
;
1074 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1079 if (m_unrd_size
== m_unrd_cur
)
1092 // ==========================================================================
1094 // ==========================================================================
1096 // --------------------------------------------------------------------------
1098 // --------------------------------------------------------------------------
1100 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1101 wxSocketFlags flags
)
1102 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1104 wxLogTrace( wxTRACE_Socket
, wxT("Opening wxSocketServer") );
1106 m_socket
= GSocket_new();
1110 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_new failed") );
1114 // Setup the socket as server
1117 GSocket_SetLocal(m_socket
, addr_man
.GetAddress());
1118 if (GSocket_SetServer(m_socket
) != GSOCK_NOERROR
)
1120 GSocket_destroy(m_socket
);
1123 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_SetServer failed") );
1127 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1128 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1129 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1130 wx_socket_callback
, (char *)this);
1134 // --------------------------------------------------------------------------
1136 // --------------------------------------------------------------------------
1138 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1140 GSocket
*child_socket
;
1145 // If wait == false, then the call should be nonblocking.
1146 // When we are finished, we put the socket to blocking mode
1151 GSocket_SetNonBlocking(m_socket
, 1);
1153 child_socket
= GSocket_WaitConnection(m_socket
);
1156 GSocket_SetNonBlocking(m_socket
, 0);
1161 sock
.m_type
= wxSOCKET_BASE
;
1162 sock
.m_socket
= child_socket
;
1163 sock
.m_connected
= true;
1165 GSocket_SetTimeout(sock
.m_socket
, sock
.m_timeout
* 1000);
1166 GSocket_SetCallback(sock
.m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1167 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1168 wx_socket_callback
, (char *)&sock
);
1174 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1176 wxSocketBase
* sock
= new wxSocketBase();
1178 sock
->SetFlags(m_flags
);
1180 if (!AcceptWith(*sock
, wait
))
1189 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1191 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
);
1194 // ==========================================================================
1196 // ==========================================================================
1198 // --------------------------------------------------------------------------
1200 // --------------------------------------------------------------------------
1202 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1203 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1207 wxSocketClient::~wxSocketClient()
1211 // --------------------------------------------------------------------------
1213 // --------------------------------------------------------------------------
1215 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1221 // Shutdown and destroy the socket
1223 GSocket_destroy(m_socket
);
1226 m_socket
= GSocket_new();
1227 m_connected
= false;
1228 m_establishing
= false;
1233 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1234 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1235 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1236 wx_socket_callback
, (char *)this);
1238 // If wait == false, then the call should be nonblocking.
1239 // When we are finished, we put the socket to blocking mode
1243 GSocket_SetNonBlocking(m_socket
, 1);
1245 GSocket_SetPeer(m_socket
, addr_man
.GetAddress());
1246 err
= GSocket_Connect(m_socket
, GSOCK_STREAMED
);
1249 GSocket_SetNonBlocking(m_socket
, 0);
1251 if (err
!= GSOCK_NOERROR
)
1253 if (err
== GSOCK_WOULDBLOCK
)
1254 m_establishing
= true;
1263 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1265 if (m_connected
) // Already connected
1268 if (!m_establishing
|| !m_socket
) // No connection in progress
1271 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
| GSOCK_LOST_FLAG
);
1274 // ==========================================================================
1276 // ==========================================================================
1278 /* NOTE: experimental stuff - might change */
1280 wxDatagramSocket::wxDatagramSocket( wxSockAddress
& addr
,
1281 wxSocketFlags flags
)
1282 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1285 // Create the socket
1286 m_socket
= GSocket_new();
1291 // Setup the socket as non connection oriented
1292 GSocket_SetLocal(m_socket
, addr
.GetAddress());
1293 if( GSocket_SetNonOriented(m_socket
) != GSOCK_NOERROR
)
1295 GSocket_destroy(m_socket
);
1300 // Initialize all stuff
1301 m_connected
= false;
1302 m_establishing
= false;
1303 GSocket_SetTimeout( m_socket
, m_timeout
);
1304 GSocket_SetCallback( m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1305 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1306 wx_socket_callback
, (char*)this );
1310 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1319 wxDatagramSocket
& wxDatagramSocket::SendTo( wxSockAddress
& addr
,
1323 GSocket_SetPeer(m_socket
, addr
.GetAddress());
1329 * -------------------------------------------------------------------------
1331 * -------------------------------------------------------------------------
1334 /* CHECK_ADDRESS verifies that the current address family is either
1335 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1336 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1337 * an appropiate error code.
1339 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1341 #define CHECK_ADDRESS(address, family) \
1343 if (address->m_family == GSOCK_NOFAMILY) \
1344 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1345 return address->m_error; \
1346 if (address->m_family != GSOCK_##family) \
1348 address->m_error = GSOCK_INVADDR; \
1349 return GSOCK_INVADDR; \
1353 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1355 if (address->m_family == GSOCK_NOFAMILY) \
1356 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1358 if (address->m_family != GSOCK_##family) \
1360 address->m_error = GSOCK_INVADDR; \
1366 GAddress
*GAddress_new(void)
1370 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1373 address
->m_family
= GSOCK_NOFAMILY
;
1374 address
->m_addr
= NULL
;
1380 GAddress
*GAddress_copy(GAddress
*address
)
1384 assert(address
!= NULL
);
1386 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1389 memcpy(addr2
, address
, sizeof(GAddress
));
1391 if (address
->m_addr
&& address
->m_len
> 0)
1393 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1394 if (addr2
->m_addr
== NULL
)
1400 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1406 void GAddress_destroy(GAddress
*address
)
1408 assert( address
!= NULL
);
1410 if (address
->m_addr
)
1411 free(address
->m_addr
);
1416 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1418 assert(address
!= NULL
);
1420 address
->m_family
= type
;
1423 GAddressType
GAddress_GetFamily(GAddress
*address
)
1425 assert( address
!= NULL
);
1427 return address
->m_family
;
1430 GSocketError
_GAddress_translate_from(GAddress
*address
,
1431 struct sockaddr
*addr
, int len
)
1433 address
->m_realfamily
= addr
->sa_family
;
1434 switch (addr
->sa_family
)
1437 address
->m_family
= GSOCK_INET
;
1441 address
->m_family
= GSOCK_UNIX
;
1446 address
->m_family
= GSOCK_INET6
;
1452 address
->m_error
= GSOCK_INVOP
;
1457 if (address
->m_addr
)
1458 free(address
->m_addr
);
1460 address
->m_len
= len
;
1461 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1463 if (address
->m_addr
== NULL
)
1465 address
->m_error
= GSOCK_MEMERR
;
1466 return GSOCK_MEMERR
;
1469 memcpy(address
->m_addr
, addr
, len
);
1471 return GSOCK_NOERROR
;
1474 GSocketError
_GAddress_translate_to(GAddress
*address
,
1475 struct sockaddr
**addr
, int *len
)
1477 if (!address
->m_addr
)
1479 address
->m_error
= GSOCK_INVADDR
;
1480 return GSOCK_INVADDR
;
1483 *len
= address
->m_len
;
1484 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1487 address
->m_error
= GSOCK_MEMERR
;
1488 return GSOCK_MEMERR
;
1491 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1492 return GSOCK_NOERROR
;
1496 * -------------------------------------------------------------------------
1497 * Internet address family
1498 * -------------------------------------------------------------------------
1501 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1503 address
->m_len
= sizeof(struct sockaddr_in
);
1504 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1505 if (address
->m_addr
== NULL
)
1507 address
->m_error
= GSOCK_MEMERR
;
1508 return GSOCK_MEMERR
;
1511 memset( address
->m_addr
, 0 , address
->m_len
) ;
1512 address
->m_family
= GSOCK_INET
;
1513 address
->m_realfamily
= PF_INET
;
1514 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1515 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1517 return GSOCK_NOERROR
;
1520 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1523 struct in_addr
*addr
;
1525 assert( address
!= NULL
);
1526 CHECK_ADDRESS( address
, INET
);
1528 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1530 // If it is a numeric host name, convert it now
1531 #if defined(HAVE_INET_ATON)
1532 if (inet_aton(hostname
, addr
) == 0)
1534 #elif defined(HAVE_INET_ADDR)
1535 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1538 // Use gethostbyname by default
1540 int val
= 1; // VA doesn't like constants in conditional expressions
1545 struct in_addr
*array_addr
;
1547 // It is a real name, we solve it
1548 if ((he
= gethostbyname(hostname
)) == NULL
)
1550 // Reset to invalid address
1551 addr
->s_addr
= INADDR_NONE
;
1552 address
->m_error
= GSOCK_NOHOST
;
1553 return GSOCK_NOHOST
;
1555 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1556 addr
->s_addr
= array_addr
[0].s_addr
;
1559 return GSOCK_NOERROR
;
1562 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1564 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1567 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1568 unsigned long hostaddr
)
1570 struct in_addr
*addr
;
1572 assert( address
!= NULL
);
1573 CHECK_ADDRESS( address
, INET
);
1575 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1576 addr
->s_addr
= htonl(hostaddr
) ;
1578 return GSOCK_NOERROR
;
1581 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1582 const char *protocol
)
1585 struct sockaddr_in
*addr
;
1587 assert( address
!= NULL
);
1588 CHECK_ADDRESS( address
, INET
);
1592 address
->m_error
= GSOCK_INVPORT
;
1593 return GSOCK_INVPORT
;
1596 se
= getservbyname(port
, protocol
);
1599 // the cast to int suppresses compiler warnings
1600 // about subscript having the type char
1601 if (isdigit((int)port
[0]))
1605 port_int
= atoi(port
);
1606 addr
= (struct sockaddr_in
*)address
->m_addr
;
1607 addr
->sin_port
= htons(port_int
);
1608 return GSOCK_NOERROR
;
1611 address
->m_error
= GSOCK_INVPORT
;
1612 return GSOCK_INVPORT
;
1615 addr
= (struct sockaddr_in
*)address
->m_addr
;
1616 addr
->sin_port
= se
->s_port
;
1618 return GSOCK_NOERROR
;
1621 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1623 struct sockaddr_in
*addr
;
1625 assert( address
!= NULL
);
1626 CHECK_ADDRESS( address
, INET
);
1628 addr
= (struct sockaddr_in
*)address
->m_addr
;
1629 addr
->sin_port
= htons(port
);
1631 return GSOCK_NOERROR
;
1634 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1638 struct sockaddr_in
*addr
;
1640 assert( address
!= NULL
);
1641 CHECK_ADDRESS( address
, INET
);
1643 addr
= (struct sockaddr_in
*)address
->m_addr
;
1644 addr_buf
= (char *)&(addr
->sin_addr
);
1646 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1649 address
->m_error
= GSOCK_NOHOST
;
1650 return GSOCK_NOHOST
;
1653 strncpy(hostname
, he
->h_name
, sbuf
);
1655 return GSOCK_NOERROR
;
1658 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1660 struct sockaddr_in
*addr
;
1662 assert( address
!= NULL
);
1663 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1665 addr
= (struct sockaddr_in
*)address
->m_addr
;
1667 return ntohl(addr
->sin_addr
.s_addr
) ;
1670 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1672 struct sockaddr_in
*addr
;
1674 assert( address
!= NULL
);
1675 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1677 addr
= (struct sockaddr_in
*)address
->m_addr
;
1679 return ntohs(addr
->sin_port
);
1683 * -------------------------------------------------------------------------
1684 * Unix address family
1685 * -------------------------------------------------------------------------
1688 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1690 address
->m_len
= sizeof(struct sockaddr_un
);
1691 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1692 if (address
->m_addr
== NULL
)
1694 address
->m_error
= GSOCK_MEMERR
;
1695 return GSOCK_MEMERR
;
1698 address
->m_family
= GSOCK_UNIX
;
1699 address
->m_realfamily
= PF_UNIX
;
1700 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1701 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1703 return GSOCK_NOERROR
;
1706 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1708 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1710 struct sockaddr_un
*addr
;
1712 assert( address
!= NULL
);
1713 CHECK_ADDRESS( address
, UNIX
);
1715 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1716 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1717 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1719 return GSOCK_NOERROR
;
1722 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1724 struct sockaddr_un
*addr
;
1726 assert( address
!= NULL
);
1727 CHECK_ADDRESS( address
, UNIX
);
1729 addr
= (struct sockaddr_un
*)address
->m_addr
;
1731 strncpy(path
, addr
->sun_path
, sbuf
);
1733 return GSOCK_NOERROR
;
1736 /* Address handling */
1738 /* GSocket_SetLocal:
1742 * Set or get the local or peer address for this socket. The 'set'
1743 * functions return GSOCK_NOERROR on success, an error code otherwise.
1744 * The 'get' functions return a pointer to a GAddress object on success,
1745 * or NULL otherwise, in which case they set the error code of the
1746 * corresponding GSocket.
1749 * GSOCK_INVSOCK - the socket is not valid.
1750 * GSOCK_INVADDR - the address is not valid.
1753 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
1755 assert( socket
!= NULL
);
1757 // the socket must be initialized, or it must be a server
1758 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
1760 socket
->m_error
= GSOCK_INVSOCK
;
1761 return GSOCK_INVSOCK
;
1765 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1767 socket
->m_error
= GSOCK_INVADDR
;
1768 return GSOCK_INVADDR
;
1771 if (socket
->m_local
)
1772 GAddress_destroy(socket
->m_local
);
1774 socket
->m_local
= GAddress_copy(address
);
1776 return GSOCK_NOERROR
;
1779 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
1781 assert(socket
!= NULL
);
1784 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1786 socket
->m_error
= GSOCK_INVADDR
;
1787 return GSOCK_INVADDR
;
1791 GAddress_destroy(socket
->m_peer
);
1793 socket
->m_peer
= GAddress_copy(address
);
1795 return GSOCK_NOERROR
;
1798 GAddress
*GSocket_GetLocal(GSocket
*socket
)
1801 struct sockaddr addr
;
1802 socklen_t size
= sizeof(addr
);
1805 assert( socket
!= NULL
);
1807 // try to get it from the m_local var first
1808 if (socket
->m_local
)
1809 return GAddress_copy(socket
->m_local
);
1811 // else, if the socket is initialized, try getsockname
1812 if (socket
->m_fd
== INVALID_SOCKET
)
1814 socket
->m_error
= GSOCK_INVSOCK
;
1818 if (getsockname(socket
->m_fd
, &addr
, (socklen_t
*) &size
) < 0)
1820 socket
->m_error
= GSOCK_IOERR
;
1824 // got a valid address from getsockname, create a GAddress object
1825 address
= GAddress_new();
1826 if (address
== NULL
)
1828 socket
->m_error
= GSOCK_MEMERR
;
1832 err
= _GAddress_translate_from(address
, &addr
, size
);
1833 if (err
!= GSOCK_NOERROR
)
1835 GAddress_destroy(address
);
1836 socket
->m_error
= err
;
1843 GAddress
*GSocket_GetPeer(GSocket
*socket
)
1845 assert(socket
!= NULL
);
1847 // try to get it from the m_peer var
1849 return GAddress_copy(socket
->m_peer
);
1855 GSocket
*GSocket_new(void)
1858 socket
= (GSocket
*)malloc(sizeof(GSocket
));
1863 socket
->m_fd
= INVALID_SOCKET
;
1865 for (int i
=0;i
<GSOCK_MAX_EVENT
;i
++)
1867 socket
->m_cbacks
[i
] = NULL
;
1870 socket
->m_detected
= 0;
1872 socket
->m_local
= NULL
;
1873 socket
->m_peer
= NULL
;
1874 socket
->m_error
= GSOCK_NOERROR
;
1876 socket
->m_non_blocking
= false ;
1877 socket
->m_stream
= true;
1878 // socket->m_oriented = true;
1879 socket
->m_server
= false;
1880 socket
->m_establishing
= false;
1881 socket
->m_timeout
= 10 * 60 * 1000;
1882 // 10 minutes * 60 sec * 1000 millisec
1884 socket
->m_cfSocket
= NULL
;
1885 socket
->m_runLoopSource
= NULL
;
1886 socket
->m_readStream
= NULL
;
1887 socket
->m_writeStream
= NULL
;
1892 void GSocket_close(GSocket
*socket
)
1894 if ( socket
->m_cfSocket
!= NULL
)
1896 if ( socket
->m_readStream
)
1898 CFReadStreamClose(socket
->m_readStream
);
1899 CFRelease( socket
->m_readStream
) ;
1900 socket
->m_readStream
= NULL
;
1903 if ( socket
->m_writeStream
)
1905 CFWriteStreamClose(socket
->m_writeStream
);
1906 CFRelease( socket
->m_writeStream
) ;
1907 socket
->m_writeStream
= NULL
;
1910 CFSocketInvalidate( socket
->m_cfSocket
) ;
1911 CFRelease( socket
->m_cfSocket
) ;
1912 socket
->m_cfSocket
= NULL
;
1913 socket
->m_fd
= INVALID_SOCKET
;
1917 void GSocket_Shutdown(GSocket
*socket
)
1919 GSocket_close( socket
);
1921 // Disable GUI callbacks
1922 for (int evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
1923 socket
->m_cbacks
[evt
] = NULL
;
1925 socket
->m_detected
= GSOCK_LOST_FLAG
;
1928 void GSocket_destroy(GSocket
*socket
)
1930 assert( socket
!= NULL
);
1932 // Check that the socket is really shut down
1933 if (socket
->m_fd
!= INVALID_SOCKET
)
1934 GSocket_Shutdown(socket
);
1936 // Destroy private addresses
1937 if (socket
->m_local
)
1938 GAddress_destroy(socket
->m_local
);
1941 GAddress_destroy(socket
->m_peer
);
1943 // Destroy the socket itself
1947 GSocketError
GSocket_Connect(GSocket
*socket
, GSocketStream stream
)
1949 assert( socket
!= NULL
);
1951 if (socket
->m_fd
!= INVALID_SOCKET
)
1953 socket
->m_error
= GSOCK_INVSOCK
;
1954 return GSOCK_INVSOCK
;
1957 if (!socket
->m_peer
)
1959 socket
->m_error
= GSOCK_INVADDR
;
1960 return GSOCK_INVADDR
;
1963 // Streamed or dgram socket?
1964 socket
->m_stream
= (stream
== GSOCK_STREAMED
);
1965 socket
->m_oriented
= true;
1966 socket
->m_server
= false;
1967 socket
->m_establishing
= false;
1969 GSocketError returnErr
= GSOCK_NOERROR
;
1972 CFAllocatorRef alloc
= kCFAllocatorDefault
;
1973 CFSocketContext ctx
;
1974 memset( &ctx
, 0 , sizeof( ctx
) ) ;
1976 socket
->m_cfSocket
= CFSocketCreate( alloc
, socket
->m_peer
->m_realfamily
,
1977 stream
== GSOCK_STREAMED
? SOCK_STREAM
: SOCK_DGRAM
, 0 ,
1978 kCFSocketReadCallBack
| kCFSocketWriteCallBack
| kCFSocketConnectCallBack
, wxMacCFSocketCallback
, &ctx
) ;
1979 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
1981 socket
->m_fd
= CFSocketGetNative( socket
->m_cfSocket
) ;
1983 CFStreamCreatePairWithSocket ( alloc
, socket
->m_fd
, &socket
->m_readStream
, &socket
->m_writeStream
);
1984 if ((socket
->m_readStream
== NULL
) || (socket
->m_writeStream
== NULL
))
1986 GSocket_close(socket
);
1987 socket
->m_error
= GSOCK_IOERR
;
1991 if ( !CFReadStreamOpen( socket
->m_readStream
) || !CFWriteStreamOpen( socket
->m_writeStream
) )
1993 GSocket_close(socket
);
1994 socket
->m_error
= GSOCK_IOERR
;
1998 CFRunLoopSourceRef rls
= CFSocketCreateRunLoopSource(alloc
, socket
->m_cfSocket
, 0);
1999 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls
, kCFRunLoopCommonModes
);
2002 CFDataRef address
= CFDataCreateWithBytesNoCopy(alloc
, (const UInt8
*) socket
->m_peer
->m_addr
, socket
->m_peer
->m_len
, kCFAllocatorNull
);
2004 return GSOCK_MEMERR
;
2006 err
= CFSocketConnectToAddress( socket
->m_cfSocket
, address
, socket
->m_non_blocking
? -1 : socket
->m_timeout
/ 1000 ) ;
2009 if (err
!= kCFSocketSuccess
)
2011 if ( err
== kCFSocketTimeout
)
2013 GSocket_close(socket
);
2014 socket
->m_error
= GSOCK_TIMEDOUT
;
2015 return GSOCK_TIMEDOUT
;
2018 // we don't know whether a connect in progress will be issued like this
2019 if ( err
!= kCFSocketTimeout
&& socket
->m_non_blocking
)
2021 socket
->m_establishing
= true;
2022 socket
->m_error
= GSOCK_WOULDBLOCK
;
2023 return GSOCK_WOULDBLOCK
;
2026 GSocket_close(socket
);
2027 socket
->m_error
= GSOCK_IOERR
;
2031 return GSOCK_NOERROR
;
2036 /* GSocket_SetNonBlocking:
2037 * Sets the socket to non-blocking mode.
2038 * All IO calls will return immediately.
2040 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
2042 assert( socket
!= NULL
);
2044 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2046 socket
->m_non_blocking
= non_block
;
2050 * GSocket_SetTimeout:
2051 * Sets the timeout for blocking calls. Time is expressed in
2054 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
2056 assert( socket
!= NULL
);
2058 socket
->m_timeout
= millisec
;
2061 /* GSocket_GetError:
2062 * Returns the last error which occurred for this socket. Note that successful
2063 * operations do not clear this back to GSOCK_NOERROR, so use it only
2066 GSocketError
GSocket_GetError(GSocket
*socket
)
2068 assert( socket
!= NULL
);
2070 return socket
->m_error
;
2076 * There is data to be read in the input buffer. If, after a read
2077 * operation, there is still data available, the callback function will
2080 * The socket is available for writing. That is, the next write call
2081 * won't block. This event is generated only once, when the connection is
2082 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2083 * when the output buffer empties again. This means that the app should
2084 * assume that it can write since the first OUTPUT event, and no more
2085 * OUTPUT events will be generated unless an error occurs.
2087 * Connection successfully established, for client sockets, or incoming
2088 * client connection, for server sockets. Wait for this event (also watch
2089 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2091 * The connection is lost (or a connection request failed); this could
2092 * be due to a failure, or due to the peer closing it gracefully.
2095 /* GSocket_SetCallback:
2096 * Enables the callbacks specified by 'flags'. Note that 'flags'
2097 * may be a combination of flags OR'ed toghether, so the same
2098 * callback function can be made to accept different events.
2099 * The callback function must have the following prototype:
2101 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2103 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
2104 GSocketCallback callback
, char *cdata
)
2108 assert( socket
!= NULL
);
2110 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2112 if ((flags
& (1 << count
)) != 0)
2114 socket
->m_cbacks
[count
] = callback
;
2115 socket
->m_data
[count
] = cdata
;
2120 /* GSocket_UnsetCallback:
2121 * Disables all callbacks specified by 'flags', which may be a
2122 * combination of flags OR'ed toghether.
2124 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
2128 assert(socket
!= NULL
);
2130 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2132 if ((flags
& (1 << count
)) != 0)
2134 socket
->m_cbacks
[count
] = NULL
;
2135 socket
->m_data
[count
] = NULL
;
2141 #define CALL_CALLBACK(socket, event) { \
2142 _GSocket_Disable(socket, event); \
2143 if (socket->m_cbacks[event]) \
2144 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2147 void _GSocket_Install_Callback(GSocket
*socket
, GSocketEvent event
)
2152 case GSOCK_CONNECTION
:
2153 if (socket
->m_server
)
2154 c
= kCFSocketReadCallBack
;
2156 c
= kCFSocketConnectCallBack
;
2161 c
= kCFSocketReadCallBack
;
2165 c
= kCFSocketWriteCallBack
;
2172 CFSocketEnableCallBacks(socket
->m_cfSocket
, c
);
2175 void _GSocket_Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
2180 case GSOCK_CONNECTION
:
2181 if (socket
->m_server
)
2182 c
= kCFSocketReadCallBack
;
2184 c
= kCFSocketConnectCallBack
;
2189 c
= kCFSocketReadCallBack
;
2193 c
= kCFSocketWriteCallBack
;
2201 CFSocketDisableCallBacks(socket
->m_cfSocket
, c
);
2204 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
2206 socket
->m_detected
&= ~(1 << event
);
2207 _GSocket_Install_Callback(socket
, event
);
2210 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
2212 socket
->m_detected
|= (1 << event
);
2213 _GSocket_Uninstall_Callback(socket
, event
);
2216 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
2217 CFDataRef address
, const void* data
, void* info
)
2219 GSocket
* socket
= (GSocket
*)info
;
2221 switch (callbackType
)
2223 case kCFSocketConnectCallBack
:
2226 SInt32 error
= *((SInt32
*)data
) ;
2227 CALL_CALLBACK( socket
, GSOCK_LOST
) ;
2228 GSocket_Shutdown(socket
);
2232 CALL_CALLBACK( socket
, GSOCK_CONNECTION
) ;
2236 case kCFSocketReadCallBack
:
2237 CALL_CALLBACK( socket
, GSOCK_INPUT
) ;
2240 case kCFSocketWriteCallBack
:
2241 CALL_CALLBACK( socket
, GSOCK_OUTPUT
) ;
2245 break; // We shouldn't get here.
2249 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
2253 assert(socket
!= NULL
);
2254 // if ( !CFReadStreamHasBytesAvailable() )
2255 ret
= CFReadStreamRead( socket
->m_readStream
, (UInt8
*) buffer
, size
) ;
2260 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
2264 assert(socket
!= NULL
);
2265 ret
= CFWriteStreamWrite( socket
->m_writeStream
, (UInt8
*) buffer
, size
) ;
2270 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
2272 assert( socket
!= NULL
);
2274 return flags
& socket
->m_detected
;
2277 // ==========================================================================
2279 // ==========================================================================
2281 class wxSocketModule
: public wxModule
2284 virtual bool OnInit()
2286 // wxSocketBase will call GSocket_Init() itself when/if needed
2290 virtual void OnExit()
2292 if ( wxSocketBase::IsInitialized() )
2293 wxSocketBase::Shutdown();
2297 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2300 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)