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"
20 #include "wx/socket.h"
23 #include "wx/object.h"
24 #include "wx/string.h"
33 #include "wx/apptrait.h"
34 #include "wx/module.h"
36 #include "wx/sckaddr.h"
37 #include "wx/mac/carbon/private.h"
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
44 #define HAVE_INET_ATON
46 // DLL options compatibility check:
49 WX_CHECK_BUILD_OPTIONS("wxNet")
53 #define MAX_DISCARD_SIZE (10 * 1024)
55 #ifndef INVALID_SOCKET
56 #define INVALID_SOCKET -1
59 // what to do within waits: we have 2 cases: from the main thread itself we
60 // have to call wxYield() to let the events (including the GUI events and the
61 // low-level (not wxWidgets) events from GSocket) be processed. From another
62 // thread it is enough to just call wxThread::Yield() which will give away the
63 // rest of our time slice: the explanation is that the events will be processed
64 // by the main thread anyhow, without calling wxYield(), but we don't want to
65 // eat the CPU time uselessly while sitting in the loop waiting for the data
67 #define PROCESS_EVENTS() \
69 if ( wxThread::IsMain() ) \
74 #else // !wxUSE_THREADS
75 #define PROCESS_EVENTS() wxYield()
76 #endif // wxUSE_THREADS/!wxUSE_THREADS
78 #define wxTRACE_Socket _T("wxSocket")
81 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
82 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
83 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
84 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
85 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
87 // --------------------------------------------------------------------------
89 // --------------------------------------------------------------------------
91 class wxSocketState
: public wxObject
94 wxSocketFlags m_flags
;
95 wxSocketEventFlags m_eventmask
;
100 wxSocketState() : wxObject() {}
102 DECLARE_NO_COPY_CLASS(wxSocketState
)
107 CFSocketNativeHandle m_fd
;
110 GSocketError m_error
;
117 unsigned long m_timeout
;
120 GSocketEventFlags m_detected
;
121 GSocketCallback m_cbacks
[GSOCK_MAX_EVENT
];
122 char *m_data
[GSOCK_MAX_EVENT
];
124 CFSocketRef m_cfSocket
;
125 CFRunLoopSourceRef m_runLoopSource
;
126 CFReadStreamRef m_readStream
;
127 CFWriteStreamRef m_writeStream
;
132 struct sockaddr
*m_addr
;
135 GAddressType m_family
;
138 GSocketError m_error
;
142 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
143 CFDataRef address
, const void* data
, void* info
) ;
144 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
) ;
145 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
) ;
147 // ==========================================================================
149 // ==========================================================================
151 // --------------------------------------------------------------------------
152 // Initialization and shutdown
153 // --------------------------------------------------------------------------
155 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
156 // to m_countInit with a crit section
157 size_t wxSocketBase::m_countInit
= 0;
159 bool wxSocketBase::IsInitialized()
161 return m_countInit
> 0;
164 bool wxSocketBase::Initialize()
166 if ( !m_countInit
++ )
169 wxAppTraits
*traits
= wxAppConsole::GetInstance() ?
170 wxAppConsole::GetInstance()->GetTraits() : NULL
;
171 GSocketGUIFunctionsTable
*functions
=
172 traits
? traits
->GetSocketGUIFunctionsTable() : NULL
;
173 GSocket_SetGUIFunctions(functions
);
175 if ( !GSocket_Init() )
187 void wxSocketBase::Shutdown()
189 // we should be initialized
190 wxASSERT_MSG( m_countInit
, wxT("extra call to Shutdown()") );
191 if ( !--m_countInit
)
199 // --------------------------------------------------------------------------
201 // --------------------------------------------------------------------------
203 void wxSocketBase::Init()
206 m_type
= wxSOCKET_UNINIT
;
217 m_beingDeleted
= false;
231 if ( !IsInitialized() )
233 // this Initialize() will be undone by wxSocketModule::OnExit(), all the
234 // other calls to it should be matched by a call to Shutdown()
239 wxSocketBase::wxSocketBase()
244 wxSocketBase::wxSocketBase( wxSocketFlags flags
, wxSocketType type
)
252 wxSocketBase::~wxSocketBase()
254 // Just in case the app called Destroy() *and* then deleted
255 // the socket immediately: don't leave dangling pointers.
256 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
258 traits
->RemoveFromPendingDelete(this);
260 // Shutdown and close the socket
264 // Destroy the GSocket object
267 GSocket_destroy(m_socket
);
270 // Free the pushback buffer
275 bool wxSocketBase::Destroy()
277 // Delayed destruction: the socket will be deleted during the next
278 // idle loop iteration. This ensures that all pending events have
280 m_beingDeleted
= true;
282 // Shutdown and close the socket
285 // Supress events from now on
288 // schedule this object for deletion
289 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
292 // let the traits object decide what to do with us
293 traits
->ScheduleForDestroy(this);
295 else // no app or no traits
297 // in wxBase we might have no app object at all, don't leak memory
304 // --------------------------------------------------------------------------
306 // --------------------------------------------------------------------------
308 // The following IO operations update m_error and m_lcount:
309 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
311 // TODO: Should Connect, Accept and AcceptWith update m_error?
313 bool wxSocketBase::Close()
315 // Interrupt pending waits
319 GSocket_Shutdown(m_socket
);
322 m_establishing
= false;
327 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
332 m_lcount
= _Read(buffer
, nbytes
);
334 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
335 if (m_flags
& wxSOCKET_WAITALL
)
336 m_error
= (m_lcount
!= nbytes
);
338 m_error
= (m_lcount
== 0);
340 // Allow read events from now on
346 wxUint32
wxSocketBase::_Read(void* buffer
, wxUint32 nbytes
)
350 // Try the pushback buffer first
351 total
= GetPushback(buffer
, nbytes
, false);
353 buffer
= (char *)buffer
+ total
;
355 // Return now in one of the following cases:
356 // - the socket is invalid,
357 // - we got all the data,
358 // - we got *some* data and we are not using wxSOCKET_WAITALL.
361 ((total
!= 0) && !(m_flags
& wxSOCKET_WAITALL
)) )
364 // Possible combinations (they are checked in this order)
366 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
372 if (m_flags
& wxSOCKET_NOWAIT
)
374 GSocket_SetNonBlocking(m_socket
, 1);
375 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
376 GSocket_SetNonBlocking(m_socket
, 0);
387 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForRead() )
390 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
396 buffer
= (char *)buffer
+ ret
;
399 // If we got here and wxSOCKET_WAITALL is not set, we can leave
400 // now. Otherwise, wait until we recv all the data or until there
403 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
410 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
412 wxUint32 len
, len2
, sig
, total
;
417 unsigned char sig
[4];
418 unsigned char len
[4];
428 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
430 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
433 sig
= (wxUint32
)msg
.sig
[0];
434 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
435 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
436 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
438 if (sig
!= 0xfeeddead)
440 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
444 len
= (wxUint32
)msg
.len
[0];
445 len
|= (wxUint32
)(msg
.len
[1] << 8);
446 len
|= (wxUint32
)(msg
.len
[2] << 16);
447 len
|= (wxUint32
)(msg
.len
[3] << 24);
457 // Don't attemp to read if the msg was zero bytes long.
460 total
= _Read(buffer
, len
);
467 char *discard_buffer
= new char[MAX_DISCARD_SIZE
];
470 // NOTE: discarded bytes don't add to m_lcount.
473 discard_len
= ((len2
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE
: len2
);
474 discard_len
= _Read(discard_buffer
, (wxUint32
)discard_len
);
475 len2
-= (wxUint32
)discard_len
;
477 while ((discard_len
> 0) && len2
);
479 delete [] discard_buffer
;
484 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
487 sig
= (wxUint32
)msg
.sig
[0];
488 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
489 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
490 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
492 if (sig
!= 0xdeadfeed)
494 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
510 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
515 m_lcount
= _Read(buffer
, nbytes
);
516 Pushback(buffer
, m_lcount
);
518 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
519 if (m_flags
& wxSOCKET_WAITALL
)
520 m_error
= (m_lcount
!= nbytes
);
522 m_error
= (m_lcount
== 0);
524 // Allow read events again
530 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
535 m_lcount
= _Write(buffer
, nbytes
);
537 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
538 if (m_flags
& wxSOCKET_WAITALL
)
539 m_error
= (m_lcount
!= nbytes
);
541 m_error
= (m_lcount
== 0);
543 // Allow write events again
549 wxUint32
wxSocketBase::_Write(const void *buffer
, wxUint32 nbytes
)
553 // If the socket is invalid or parameters are ill, return immediately
554 if (!m_socket
|| !buffer
|| !nbytes
)
557 // Possible combinations (they are checked in this order)
559 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
564 if (m_flags
& wxSOCKET_NOWAIT
)
566 GSocket_SetNonBlocking(m_socket
, 1);
567 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
568 GSocket_SetNonBlocking(m_socket
, 0);
579 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForWrite() )
582 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
588 buffer
= (const char *)buffer
+ ret
;
591 // If we got here and wxSOCKET_WAITALL is not set, we can leave
592 // now. Otherwise, wait until we send all the data or until there
595 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
602 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
608 unsigned char sig
[4];
609 unsigned char len
[4];
618 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
620 msg
.sig
[0] = (unsigned char) 0xad;
621 msg
.sig
[1] = (unsigned char) 0xde;
622 msg
.sig
[2] = (unsigned char) 0xed;
623 msg
.sig
[3] = (unsigned char) 0xfe;
625 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
626 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
627 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
628 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
630 if (_Write(&msg
, sizeof(msg
)) < sizeof(msg
))
633 total
= _Write(buffer
, nbytes
);
638 msg
.sig
[0] = (unsigned char) 0xed;
639 msg
.sig
[1] = (unsigned char) 0xfe;
640 msg
.sig
[2] = (unsigned char) 0xad;
641 msg
.sig
[3] = (unsigned char) 0xde;
642 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
644 if ((_Write(&msg
, sizeof(msg
))) < sizeof(msg
))
658 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
661 Pushback(buffer
, nbytes
);
669 wxSocketBase
& wxSocketBase::Discard()
671 char *buffer
= new char[MAX_DISCARD_SIZE
];
678 SetFlags(wxSOCKET_NOWAIT
);
682 ret
= _Read(buffer
, MAX_DISCARD_SIZE
);
685 while (ret
== MAX_DISCARD_SIZE
);
691 // Allow read events again
697 // --------------------------------------------------------------------------
699 // --------------------------------------------------------------------------
701 // All Wait functions poll the socket using GSocket_Select() to
702 // check for the specified combination of conditions, until one
703 // of these conditions become true, an error occurs, or the
704 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
705 // this won't block the GUI.
707 bool wxSocketBase::_Wait(long seconds
,
709 wxSocketEventFlags flags
)
711 GSocketEventFlags result
;
714 // Set this to true to interrupt ongoing waits
717 // Check for valid socket
721 // Check for valid timeout value.
723 timeout
= seconds
* 1000 + milliseconds
;
725 timeout
= m_timeout
* 1000;
727 #if !defined(wxUSE_GUI) || !wxUSE_GUI
728 GSocket_SetTimeout(m_socket
, timeout
);
731 // Wait in an active polling loop.
733 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
734 // hurt. It has to be here because the (GSocket) event might arrive
735 // a bit delayed, and it has to be in OnRequest as well because we
736 // don't know whether the Wait functions are being used.
738 // Do this at least once (important if timeout == 0, when
739 // we are just polling). Also, if just polling, do not yield.
746 result
= GSocket_Select(m_socket
, flags
| GSOCK_LOST_FLAG
);
748 // Incoming connection (server) or connection established (client)
749 if (result
& GSOCK_CONNECTION_FLAG
)
752 m_establishing
= false;
757 // Data available or output buffer ready
758 if ((result
& GSOCK_INPUT_FLAG
) || (result
& GSOCK_OUTPUT_FLAG
))
764 if (result
& GSOCK_LOST_FLAG
)
767 m_establishing
= false;
769 return (flags
& GSOCK_LOST_FLAG
) != 0;
773 if ((!timeout
) || (chrono
.Time() > timeout
) || (m_interrupt
))
782 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
784 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
786 GSOCK_CONNECTION_FLAG
|
790 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
792 // Check pushback buffer before entering _Wait
796 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
797 // _Wait becuase of the semantics of WaitForRead: a return
798 // value of true means that a GSocket_Read call will return
799 // immediately, not that there is actually data to read.
801 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
| GSOCK_LOST_FLAG
);
804 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
806 return _Wait(seconds
, milliseconds
, GSOCK_OUTPUT_FLAG
);
809 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
811 return _Wait(seconds
, milliseconds
, GSOCK_LOST_FLAG
);
814 // --------------------------------------------------------------------------
816 // --------------------------------------------------------------------------
819 // Get local or peer address
822 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
829 peer
= GSocket_GetPeer(m_socket
);
831 // copying a null address would just trigger an assert anyway
836 addr_man
.SetAddress(peer
);
837 GAddress_destroy(peer
);
842 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
850 local
= GSocket_GetLocal(m_socket
);
851 addr_man
.SetAddress(local
);
852 GAddress_destroy(local
);
859 // Save and restore socket state
862 void wxSocketBase::SaveState()
864 wxSocketState
*state
;
866 state
= new wxSocketState();
868 state
->m_flags
= m_flags
;
869 state
->m_notify
= m_notify
;
870 state
->m_eventmask
= m_eventmask
;
871 state
->m_clientData
= m_clientData
;
873 m_states
.Append(state
);
876 void wxSocketBase::RestoreState()
878 wxList::compatibility_iterator node
;
879 wxSocketState
*state
;
881 node
= m_states
.GetLast();
885 state
= (wxSocketState
*)node
->GetData();
887 m_flags
= state
->m_flags
;
888 m_notify
= state
->m_notify
;
889 m_eventmask
= state
->m_eventmask
;
890 m_clientData
= state
->m_clientData
;
892 m_states
.Erase(node
);
900 void wxSocketBase::SetTimeout(long seconds
)
906 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
910 void wxSocketBase::SetFlags(wxSocketFlags flags
)
916 // --------------------------------------------------------------------------
918 // --------------------------------------------------------------------------
920 // A note on how events are processed, which is probably the most
921 // difficult thing to get working right while keeping the same API
922 // and functionality for all platforms.
924 // When GSocket detects an event, it calls wx_socket_callback, which in
925 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
926 // object. OnRequest does some housekeeping, and if the event is to be
927 // propagated to the user, it creates a new wxSocketEvent object and
928 // posts it. The event is not processed immediately, but delayed with
929 // AddPendingEvent instead. This is necessary in order to decouple the
930 // event processing from wx_socket_callback; otherwise, subsequent IO
931 // calls made from the user event handler would fail, as gtk callbacks
932 // are not reentrant.
934 // Note that, unlike events, user callbacks (now deprecated) are _not_
935 // decoupled from wx_socket_callback and thus they suffer from a variety
936 // of problems. Avoid them where possible and use events instead.
939 void LINKAGEMODE
wx_socket_callback(GSocket
* WXUNUSED(socket
),
940 GSocketEvent notification
,
943 wxSocketBase
*sckobj
= (wxSocketBase
*)cdata
;
945 sckobj
->OnRequest((wxSocketNotify
) notification
);
948 void wxSocketBase::OnRequest(wxSocketNotify notification
)
950 // NOTE: We duplicate some of the code in _Wait, but this doesn't
951 // hurt. It has to be here because the (GSocket) event might arrive
952 // a bit delayed, and it has to be in _Wait as well because we don't
953 // know whether the Wait functions are being used.
955 switch (notification
)
957 case wxSOCKET_CONNECTION
:
958 m_establishing
= false;
962 // If we are in the middle of a R/W operation, do not
963 // propagate events to users. Also, filter 'late' events
964 // which are no longer valid.
967 if (m_reading
|| !GSocket_Select(m_socket
, GSOCK_INPUT_FLAG
))
971 case wxSOCKET_OUTPUT
:
972 if (m_writing
|| !GSocket_Select(m_socket
, GSOCK_OUTPUT_FLAG
))
978 m_establishing
= false;
985 // Schedule the event
987 wxSocketEventFlags flag
= 0;
989 switch (notification
)
992 flag
= GSOCK_INPUT_FLAG
;
996 flag
= GSOCK_OUTPUT_FLAG
;
999 case GSOCK_CONNECTION
:
1000 flag
= GSOCK_CONNECTION_FLAG
;
1004 flag
= GSOCK_LOST_FLAG
;
1008 wxLogWarning( wxT("wxSocket: unknown event!") );
1012 if (((m_eventmask
& flag
) == flag
) && m_notify
)
1016 wxSocketEvent
event(m_id
);
1017 event
.m_event
= notification
;
1018 event
.m_clientData
= m_clientData
;
1019 event
.SetEventObject(this);
1021 m_handler
->AddPendingEvent(event
);
1026 void wxSocketBase::Notify(bool notify
)
1031 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1033 m_eventmask
= flags
;
1036 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1038 m_handler
= &handler
;
1042 // --------------------------------------------------------------------------
1044 // --------------------------------------------------------------------------
1046 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1051 if (m_unread
== NULL
)
1052 m_unread
= malloc(size
);
1057 tmp
= malloc(m_unrd_size
+ size
);
1058 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1064 m_unrd_size
+= size
;
1066 memcpy(m_unread
, buffer
, size
);
1069 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1074 if (size
> (m_unrd_size
-m_unrd_cur
))
1075 size
= m_unrd_size
-m_unrd_cur
;
1077 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1082 if (m_unrd_size
== m_unrd_cur
)
1095 // ==========================================================================
1097 // ==========================================================================
1099 // --------------------------------------------------------------------------
1101 // --------------------------------------------------------------------------
1103 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1104 wxSocketFlags flags
)
1105 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1107 wxLogTrace( wxTRACE_Socket
, wxT("Opening wxSocketServer") );
1109 m_socket
= GSocket_new();
1113 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_new failed") );
1117 // Setup the socket as server
1120 GSocket_SetLocal(m_socket
, addr_man
.GetAddress());
1121 if (GSocket_SetServer(m_socket
) != GSOCK_NOERROR
)
1123 GSocket_destroy(m_socket
);
1126 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_SetServer failed") );
1130 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1131 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1132 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1133 wx_socket_callback
, (char *)this);
1137 // --------------------------------------------------------------------------
1139 // --------------------------------------------------------------------------
1141 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1143 GSocket
*child_socket
;
1148 // If wait == false, then the call should be nonblocking.
1149 // When we are finished, we put the socket to blocking mode
1154 GSocket_SetNonBlocking(m_socket
, 1);
1156 child_socket
= GSocket_WaitConnection(m_socket
);
1159 GSocket_SetNonBlocking(m_socket
, 0);
1164 sock
.m_type
= wxSOCKET_BASE
;
1165 sock
.m_socket
= child_socket
;
1166 sock
.m_connected
= true;
1168 GSocket_SetTimeout(sock
.m_socket
, sock
.m_timeout
* 1000);
1169 GSocket_SetCallback(sock
.m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1170 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1171 wx_socket_callback
, (char *)&sock
);
1177 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1179 wxSocketBase
* sock
= new wxSocketBase();
1181 sock
->SetFlags(m_flags
);
1183 if (!AcceptWith(*sock
, wait
))
1192 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1194 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
);
1197 // ==========================================================================
1199 // ==========================================================================
1201 // --------------------------------------------------------------------------
1203 // --------------------------------------------------------------------------
1205 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1206 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1210 wxSocketClient::~wxSocketClient()
1214 // --------------------------------------------------------------------------
1216 // --------------------------------------------------------------------------
1218 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1224 // Shutdown and destroy the socket
1226 GSocket_destroy(m_socket
);
1229 m_socket
= GSocket_new();
1230 m_connected
= false;
1231 m_establishing
= false;
1236 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1237 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1238 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1239 wx_socket_callback
, (char *)this);
1241 // If wait == false, then the call should be nonblocking.
1242 // When we are finished, we put the socket to blocking mode
1246 GSocket_SetNonBlocking(m_socket
, 1);
1248 GSocket_SetPeer(m_socket
, addr_man
.GetAddress());
1249 err
= GSocket_Connect(m_socket
, GSOCK_STREAMED
);
1252 GSocket_SetNonBlocking(m_socket
, 0);
1254 if (err
!= GSOCK_NOERROR
)
1256 if (err
== GSOCK_WOULDBLOCK
)
1257 m_establishing
= true;
1266 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1268 if (m_connected
) // Already connected
1271 if (!m_establishing
|| !m_socket
) // No connection in progress
1274 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
| GSOCK_LOST_FLAG
);
1277 // ==========================================================================
1279 // ==========================================================================
1281 /* NOTE: experimental stuff - might change */
1283 wxDatagramSocket::wxDatagramSocket( wxSockAddress
& addr
,
1284 wxSocketFlags flags
)
1285 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1288 // Create the socket
1289 m_socket
= GSocket_new();
1294 // Setup the socket as non connection oriented
1295 GSocket_SetLocal(m_socket
, addr
.GetAddress());
1296 if( GSocket_SetNonOriented(m_socket
) != GSOCK_NOERROR
)
1298 GSocket_destroy(m_socket
);
1303 // Initialize all stuff
1304 m_connected
= false;
1305 m_establishing
= false;
1306 GSocket_SetTimeout( m_socket
, m_timeout
);
1307 GSocket_SetCallback( m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1308 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1309 wx_socket_callback
, (char*)this );
1313 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1322 wxDatagramSocket
& wxDatagramSocket::SendTo( wxSockAddress
& addr
,
1326 GSocket_SetPeer(m_socket
, addr
.GetAddress());
1332 * -------------------------------------------------------------------------
1334 * -------------------------------------------------------------------------
1337 /* CHECK_ADDRESS verifies that the current address family is either
1338 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1339 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1340 * an appropiate error code.
1342 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1344 #define CHECK_ADDRESS(address, family) \
1346 if (address->m_family == GSOCK_NOFAMILY) \
1347 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1348 return address->m_error; \
1349 if (address->m_family != GSOCK_##family) \
1351 address->m_error = GSOCK_INVADDR; \
1352 return GSOCK_INVADDR; \
1356 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1358 if (address->m_family == GSOCK_NOFAMILY) \
1359 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1361 if (address->m_family != GSOCK_##family) \
1363 address->m_error = GSOCK_INVADDR; \
1369 GAddress
*GAddress_new(void)
1373 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1376 address
->m_family
= GSOCK_NOFAMILY
;
1377 address
->m_addr
= NULL
;
1383 GAddress
*GAddress_copy(GAddress
*address
)
1387 assert(address
!= NULL
);
1389 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1392 memcpy(addr2
, address
, sizeof(GAddress
));
1394 if (address
->m_addr
&& address
->m_len
> 0)
1396 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1397 if (addr2
->m_addr
== NULL
)
1403 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1409 void GAddress_destroy(GAddress
*address
)
1411 assert( address
!= NULL
);
1413 if (address
->m_addr
)
1414 free(address
->m_addr
);
1419 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1421 assert(address
!= NULL
);
1423 address
->m_family
= type
;
1426 GAddressType
GAddress_GetFamily(GAddress
*address
)
1428 assert( address
!= NULL
);
1430 return address
->m_family
;
1433 GSocketError
_GAddress_translate_from(GAddress
*address
,
1434 struct sockaddr
*addr
, int len
)
1436 address
->m_realfamily
= addr
->sa_family
;
1437 switch (addr
->sa_family
)
1440 address
->m_family
= GSOCK_INET
;
1444 address
->m_family
= GSOCK_UNIX
;
1449 address
->m_family
= GSOCK_INET6
;
1455 address
->m_error
= GSOCK_INVOP
;
1460 if (address
->m_addr
)
1461 free(address
->m_addr
);
1463 address
->m_len
= len
;
1464 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1466 if (address
->m_addr
== NULL
)
1468 address
->m_error
= GSOCK_MEMERR
;
1469 return GSOCK_MEMERR
;
1472 memcpy(address
->m_addr
, addr
, len
);
1474 return GSOCK_NOERROR
;
1477 GSocketError
_GAddress_translate_to(GAddress
*address
,
1478 struct sockaddr
**addr
, int *len
)
1480 if (!address
->m_addr
)
1482 address
->m_error
= GSOCK_INVADDR
;
1483 return GSOCK_INVADDR
;
1486 *len
= address
->m_len
;
1487 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1490 address
->m_error
= GSOCK_MEMERR
;
1491 return GSOCK_MEMERR
;
1494 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1495 return GSOCK_NOERROR
;
1499 * -------------------------------------------------------------------------
1500 * Internet address family
1501 * -------------------------------------------------------------------------
1504 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1506 address
->m_len
= sizeof(struct sockaddr_in
);
1507 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1508 if (address
->m_addr
== NULL
)
1510 address
->m_error
= GSOCK_MEMERR
;
1511 return GSOCK_MEMERR
;
1514 memset( address
->m_addr
, 0 , address
->m_len
) ;
1515 address
->m_family
= GSOCK_INET
;
1516 address
->m_realfamily
= PF_INET
;
1517 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1518 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1520 return GSOCK_NOERROR
;
1523 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1526 struct in_addr
*addr
;
1528 assert( address
!= NULL
);
1529 CHECK_ADDRESS( address
, INET
);
1531 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1533 // If it is a numeric host name, convert it now
1534 #if defined(HAVE_INET_ATON)
1535 if (inet_aton(hostname
, addr
) == 0)
1537 #elif defined(HAVE_INET_ADDR)
1538 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1541 // Use gethostbyname by default
1543 int val
= 1; // VA doesn't like constants in conditional expressions
1548 struct in_addr
*array_addr
;
1550 // It is a real name, we solve it
1551 if ((he
= gethostbyname(hostname
)) == NULL
)
1553 // Reset to invalid address
1554 addr
->s_addr
= INADDR_NONE
;
1555 address
->m_error
= GSOCK_NOHOST
;
1556 return GSOCK_NOHOST
;
1558 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1559 addr
->s_addr
= array_addr
[0].s_addr
;
1562 return GSOCK_NOERROR
;
1565 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1567 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1570 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1571 unsigned long hostaddr
)
1573 struct in_addr
*addr
;
1575 assert( address
!= NULL
);
1576 CHECK_ADDRESS( address
, INET
);
1578 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1579 addr
->s_addr
= htonl(hostaddr
) ;
1581 return GSOCK_NOERROR
;
1584 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1585 const char *protocol
)
1588 struct sockaddr_in
*addr
;
1590 assert( address
!= NULL
);
1591 CHECK_ADDRESS( address
, INET
);
1595 address
->m_error
= GSOCK_INVPORT
;
1596 return GSOCK_INVPORT
;
1599 se
= getservbyname(port
, protocol
);
1602 // the cast to int suppresses compiler warnings
1603 // about subscript having the type char
1604 if (isdigit((int)port
[0]))
1608 port_int
= atoi(port
);
1609 addr
= (struct sockaddr_in
*)address
->m_addr
;
1610 addr
->sin_port
= htons(port_int
);
1611 return GSOCK_NOERROR
;
1614 address
->m_error
= GSOCK_INVPORT
;
1615 return GSOCK_INVPORT
;
1618 addr
= (struct sockaddr_in
*)address
->m_addr
;
1619 addr
->sin_port
= se
->s_port
;
1621 return GSOCK_NOERROR
;
1624 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1626 struct sockaddr_in
*addr
;
1628 assert( address
!= NULL
);
1629 CHECK_ADDRESS( address
, INET
);
1631 addr
= (struct sockaddr_in
*)address
->m_addr
;
1632 addr
->sin_port
= htons(port
);
1634 return GSOCK_NOERROR
;
1637 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1641 struct sockaddr_in
*addr
;
1643 assert( address
!= NULL
);
1644 CHECK_ADDRESS( address
, INET
);
1646 addr
= (struct sockaddr_in
*)address
->m_addr
;
1647 addr_buf
= (char *)&(addr
->sin_addr
);
1649 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1652 address
->m_error
= GSOCK_NOHOST
;
1653 return GSOCK_NOHOST
;
1656 strncpy(hostname
, he
->h_name
, sbuf
);
1658 return GSOCK_NOERROR
;
1661 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1663 struct sockaddr_in
*addr
;
1665 assert( address
!= NULL
);
1666 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1668 addr
= (struct sockaddr_in
*)address
->m_addr
;
1670 return ntohl(addr
->sin_addr
.s_addr
) ;
1673 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1675 struct sockaddr_in
*addr
;
1677 assert( address
!= NULL
);
1678 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1680 addr
= (struct sockaddr_in
*)address
->m_addr
;
1682 return ntohs(addr
->sin_port
);
1686 * -------------------------------------------------------------------------
1687 * Unix address family
1688 * -------------------------------------------------------------------------
1691 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1693 address
->m_len
= sizeof(struct sockaddr_un
);
1694 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1695 if (address
->m_addr
== NULL
)
1697 address
->m_error
= GSOCK_MEMERR
;
1698 return GSOCK_MEMERR
;
1701 address
->m_family
= GSOCK_UNIX
;
1702 address
->m_realfamily
= PF_UNIX
;
1703 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1704 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1706 return GSOCK_NOERROR
;
1709 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1711 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1713 struct sockaddr_un
*addr
;
1715 assert( address
!= NULL
);
1716 CHECK_ADDRESS( address
, UNIX
);
1718 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1719 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1720 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1722 return GSOCK_NOERROR
;
1725 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1727 struct sockaddr_un
*addr
;
1729 assert( address
!= NULL
);
1730 CHECK_ADDRESS( address
, UNIX
);
1732 addr
= (struct sockaddr_un
*)address
->m_addr
;
1734 strncpy(path
, addr
->sun_path
, sbuf
);
1736 return GSOCK_NOERROR
;
1739 /* Address handling */
1741 /* GSocket_SetLocal:
1745 * Set or get the local or peer address for this socket. The 'set'
1746 * functions return GSOCK_NOERROR on success, an error code otherwise.
1747 * The 'get' functions return a pointer to a GAddress object on success,
1748 * or NULL otherwise, in which case they set the error code of the
1749 * corresponding GSocket.
1752 * GSOCK_INVSOCK - the socket is not valid.
1753 * GSOCK_INVADDR - the address is not valid.
1756 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
1758 assert( socket
!= NULL
);
1760 // the socket must be initialized, or it must be a server
1761 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
1763 socket
->m_error
= GSOCK_INVSOCK
;
1764 return GSOCK_INVSOCK
;
1768 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1770 socket
->m_error
= GSOCK_INVADDR
;
1771 return GSOCK_INVADDR
;
1774 if (socket
->m_local
)
1775 GAddress_destroy(socket
->m_local
);
1777 socket
->m_local
= GAddress_copy(address
);
1779 return GSOCK_NOERROR
;
1782 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
1784 assert(socket
!= NULL
);
1787 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1789 socket
->m_error
= GSOCK_INVADDR
;
1790 return GSOCK_INVADDR
;
1794 GAddress_destroy(socket
->m_peer
);
1796 socket
->m_peer
= GAddress_copy(address
);
1798 return GSOCK_NOERROR
;
1801 GAddress
*GSocket_GetLocal(GSocket
*socket
)
1804 struct sockaddr addr
;
1805 socklen_t size
= sizeof(addr
);
1808 assert( socket
!= NULL
);
1810 // try to get it from the m_local var first
1811 if (socket
->m_local
)
1812 return GAddress_copy(socket
->m_local
);
1814 // else, if the socket is initialized, try getsockname
1815 if (socket
->m_fd
== INVALID_SOCKET
)
1817 socket
->m_error
= GSOCK_INVSOCK
;
1821 if (getsockname(socket
->m_fd
, &addr
, (socklen_t
*) &size
) < 0)
1823 socket
->m_error
= GSOCK_IOERR
;
1827 // got a valid address from getsockname, create a GAddress object
1828 address
= GAddress_new();
1829 if (address
== NULL
)
1831 socket
->m_error
= GSOCK_MEMERR
;
1835 err
= _GAddress_translate_from(address
, &addr
, size
);
1836 if (err
!= GSOCK_NOERROR
)
1838 GAddress_destroy(address
);
1839 socket
->m_error
= err
;
1846 GAddress
*GSocket_GetPeer(GSocket
*socket
)
1848 assert(socket
!= NULL
);
1850 // try to get it from the m_peer var
1852 return GAddress_copy(socket
->m_peer
);
1858 GSocket
*GSocket_new(void)
1861 socket
= (GSocket
*)malloc(sizeof(GSocket
));
1866 socket
->m_fd
= INVALID_SOCKET
;
1868 for (int i
=0;i
<GSOCK_MAX_EVENT
;i
++)
1870 socket
->m_cbacks
[i
] = NULL
;
1873 socket
->m_detected
= 0;
1875 socket
->m_local
= NULL
;
1876 socket
->m_peer
= NULL
;
1877 socket
->m_error
= GSOCK_NOERROR
;
1879 socket
->m_non_blocking
= false ;
1880 socket
->m_stream
= true;
1881 // socket->m_oriented = true;
1882 socket
->m_server
= false;
1883 socket
->m_establishing
= false;
1884 socket
->m_timeout
= 10 * 60 * 1000;
1885 // 10 minutes * 60 sec * 1000 millisec
1887 socket
->m_cfSocket
= NULL
;
1888 socket
->m_runLoopSource
= NULL
;
1889 socket
->m_readStream
= NULL
;
1890 socket
->m_writeStream
= NULL
;
1895 void GSocket_close(GSocket
*socket
)
1897 if ( socket
->m_cfSocket
!= NULL
)
1899 if ( socket
->m_readStream
)
1901 CFReadStreamClose(socket
->m_readStream
);
1902 CFRelease( socket
->m_readStream
) ;
1903 socket
->m_readStream
= NULL
;
1906 if ( socket
->m_writeStream
)
1908 CFWriteStreamClose(socket
->m_writeStream
);
1909 CFRelease( socket
->m_writeStream
) ;
1910 socket
->m_writeStream
= NULL
;
1913 CFSocketInvalidate( socket
->m_cfSocket
) ;
1914 CFRelease( socket
->m_cfSocket
) ;
1915 socket
->m_cfSocket
= NULL
;
1916 socket
->m_fd
= INVALID_SOCKET
;
1920 void GSocket_Shutdown(GSocket
*socket
)
1922 GSocket_close( socket
);
1924 // Disable GUI callbacks
1925 for (int evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
1926 socket
->m_cbacks
[evt
] = NULL
;
1928 socket
->m_detected
= GSOCK_LOST_FLAG
;
1931 void GSocket_destroy(GSocket
*socket
)
1933 assert( socket
!= NULL
);
1935 // Check that the socket is really shut down
1936 if (socket
->m_fd
!= INVALID_SOCKET
)
1937 GSocket_Shutdown(socket
);
1939 // Destroy private addresses
1940 if (socket
->m_local
)
1941 GAddress_destroy(socket
->m_local
);
1944 GAddress_destroy(socket
->m_peer
);
1946 // Destroy the socket itself
1950 GSocketError
GSocket_Connect(GSocket
*socket
, GSocketStream stream
)
1952 assert( socket
!= NULL
);
1954 if (socket
->m_fd
!= INVALID_SOCKET
)
1956 socket
->m_error
= GSOCK_INVSOCK
;
1957 return GSOCK_INVSOCK
;
1960 if (!socket
->m_peer
)
1962 socket
->m_error
= GSOCK_INVADDR
;
1963 return GSOCK_INVADDR
;
1966 // Streamed or dgram socket?
1967 socket
->m_stream
= (stream
== GSOCK_STREAMED
);
1968 socket
->m_oriented
= true;
1969 socket
->m_server
= false;
1970 socket
->m_establishing
= false;
1972 GSocketError returnErr
= GSOCK_NOERROR
;
1975 CFAllocatorRef alloc
= kCFAllocatorDefault
;
1976 CFSocketContext ctx
;
1977 memset( &ctx
, 0 , sizeof( ctx
) ) ;
1979 socket
->m_cfSocket
= CFSocketCreate( alloc
, socket
->m_peer
->m_realfamily
,
1980 stream
== GSOCK_STREAMED
? SOCK_STREAM
: SOCK_DGRAM
, 0 ,
1981 kCFSocketReadCallBack
| kCFSocketWriteCallBack
| kCFSocketConnectCallBack
, wxMacCFSocketCallback
, &ctx
) ;
1982 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
1984 socket
->m_fd
= CFSocketGetNative( socket
->m_cfSocket
) ;
1986 CFStreamCreatePairWithSocket ( alloc
, socket
->m_fd
, &socket
->m_readStream
, &socket
->m_writeStream
);
1987 if ((socket
->m_readStream
== NULL
) || (socket
->m_writeStream
== NULL
))
1989 GSocket_close(socket
);
1990 socket
->m_error
= GSOCK_IOERR
;
1994 if ( !CFReadStreamOpen( socket
->m_readStream
) || !CFWriteStreamOpen( socket
->m_writeStream
) )
1996 GSocket_close(socket
);
1997 socket
->m_error
= GSOCK_IOERR
;
2001 CFRunLoopSourceRef rls
= CFSocketCreateRunLoopSource(alloc
, socket
->m_cfSocket
, 0);
2002 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls
, kCFRunLoopCommonModes
);
2005 CFDataRef address
= CFDataCreateWithBytesNoCopy(alloc
, (const UInt8
*) socket
->m_peer
->m_addr
, socket
->m_peer
->m_len
, kCFAllocatorNull
);
2007 return GSOCK_MEMERR
;
2009 err
= CFSocketConnectToAddress( socket
->m_cfSocket
, address
, socket
->m_non_blocking
? -1 : socket
->m_timeout
/ 1000 ) ;
2012 if (err
!= kCFSocketSuccess
)
2014 if ( err
== kCFSocketTimeout
)
2016 GSocket_close(socket
);
2017 socket
->m_error
= GSOCK_TIMEDOUT
;
2018 return GSOCK_TIMEDOUT
;
2021 // we don't know whether a connect in progress will be issued like this
2022 if ( err
!= kCFSocketTimeout
&& socket
->m_non_blocking
)
2024 socket
->m_establishing
= true;
2025 socket
->m_error
= GSOCK_WOULDBLOCK
;
2026 return GSOCK_WOULDBLOCK
;
2029 GSocket_close(socket
);
2030 socket
->m_error
= GSOCK_IOERR
;
2034 return GSOCK_NOERROR
;
2039 /* GSocket_SetNonBlocking:
2040 * Sets the socket to non-blocking mode.
2041 * All IO calls will return immediately.
2043 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
2045 assert( socket
!= NULL
);
2047 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2049 socket
->m_non_blocking
= non_block
;
2053 * GSocket_SetTimeout:
2054 * Sets the timeout for blocking calls. Time is expressed in
2057 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
2059 assert( socket
!= NULL
);
2061 socket
->m_timeout
= millisec
;
2064 /* GSocket_GetError:
2065 * Returns the last error which occurred for this socket. Note that successful
2066 * operations do not clear this back to GSOCK_NOERROR, so use it only
2069 GSocketError
GSocket_GetError(GSocket
*socket
)
2071 assert( socket
!= NULL
);
2073 return socket
->m_error
;
2079 * There is data to be read in the input buffer. If, after a read
2080 * operation, there is still data available, the callback function will
2083 * The socket is available for writing. That is, the next write call
2084 * won't block. This event is generated only once, when the connection is
2085 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2086 * when the output buffer empties again. This means that the app should
2087 * assume that it can write since the first OUTPUT event, and no more
2088 * OUTPUT events will be generated unless an error occurs.
2090 * Connection successfully established, for client sockets, or incoming
2091 * client connection, for server sockets. Wait for this event (also watch
2092 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2094 * The connection is lost (or a connection request failed); this could
2095 * be due to a failure, or due to the peer closing it gracefully.
2098 /* GSocket_SetCallback:
2099 * Enables the callbacks specified by 'flags'. Note that 'flags'
2100 * may be a combination of flags OR'ed toghether, so the same
2101 * callback function can be made to accept different events.
2102 * The callback function must have the following prototype:
2104 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2106 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
2107 GSocketCallback callback
, char *cdata
)
2111 assert( socket
!= NULL
);
2113 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2115 if ((flags
& (1 << count
)) != 0)
2117 socket
->m_cbacks
[count
] = callback
;
2118 socket
->m_data
[count
] = cdata
;
2123 /* GSocket_UnsetCallback:
2124 * Disables all callbacks specified by 'flags', which may be a
2125 * combination of flags OR'ed toghether.
2127 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
2131 assert(socket
!= NULL
);
2133 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2135 if ((flags
& (1 << count
)) != 0)
2137 socket
->m_cbacks
[count
] = NULL
;
2138 socket
->m_data
[count
] = NULL
;
2144 #define CALL_CALLBACK(socket, event) { \
2145 _GSocket_Disable(socket, event); \
2146 if (socket->m_cbacks[event]) \
2147 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2150 void _GSocket_Install_Callback(GSocket
*socket
, GSocketEvent event
)
2155 case GSOCK_CONNECTION
:
2156 if (socket
->m_server
)
2157 c
= kCFSocketReadCallBack
;
2159 c
= kCFSocketConnectCallBack
;
2164 c
= kCFSocketReadCallBack
;
2168 c
= kCFSocketWriteCallBack
;
2175 CFSocketEnableCallBacks(socket
->m_cfSocket
, c
);
2178 void _GSocket_Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
2183 case GSOCK_CONNECTION
:
2184 if (socket
->m_server
)
2185 c
= kCFSocketReadCallBack
;
2187 c
= kCFSocketConnectCallBack
;
2192 c
= kCFSocketReadCallBack
;
2196 c
= kCFSocketWriteCallBack
;
2204 CFSocketDisableCallBacks(socket
->m_cfSocket
, c
);
2207 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
2209 socket
->m_detected
&= ~(1 << event
);
2210 _GSocket_Install_Callback(socket
, event
);
2213 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
2215 socket
->m_detected
|= (1 << event
);
2216 _GSocket_Uninstall_Callback(socket
, event
);
2219 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
2220 CFDataRef address
, const void* data
, void* info
)
2222 GSocket
* socket
= (GSocket
*)info
;
2224 switch (callbackType
)
2226 case kCFSocketConnectCallBack
:
2229 SInt32 error
= *((SInt32
*)data
) ;
2230 CALL_CALLBACK( socket
, GSOCK_LOST
) ;
2231 GSocket_Shutdown(socket
);
2235 CALL_CALLBACK( socket
, GSOCK_CONNECTION
) ;
2239 case kCFSocketReadCallBack
:
2240 CALL_CALLBACK( socket
, GSOCK_INPUT
) ;
2243 case kCFSocketWriteCallBack
:
2244 CALL_CALLBACK( socket
, GSOCK_OUTPUT
) ;
2248 break; // We shouldn't get here.
2252 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
2256 assert(socket
!= NULL
);
2257 // if ( !CFReadStreamHasBytesAvailable() )
2258 ret
= CFReadStreamRead( socket
->m_readStream
, (UInt8
*) buffer
, size
) ;
2263 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
2267 assert(socket
!= NULL
);
2268 ret
= CFWriteStreamWrite( socket
->m_writeStream
, (UInt8
*) buffer
, size
) ;
2273 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
2275 assert( socket
!= NULL
);
2277 return flags
& socket
->m_detected
;
2280 // ==========================================================================
2282 // ==========================================================================
2284 class wxSocketModule
: public wxModule
2287 virtual bool OnInit()
2289 // wxSocketBase will call GSocket_Init() itself when/if needed
2293 virtual void OnExit()
2295 if ( wxSocketBase::IsInitialized() )
2296 wxSocketBase::Shutdown();
2300 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2303 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)