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"
31 #include "wx/module.h"
34 #include "wx/apptrait.h"
36 #include "wx/sckaddr.h"
37 #include "wx/osx/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_SetBroadcastAddress(GAddress
*address
)
1567 return GAddress_INET_SetHostAddress(address
, INADDR_BROADCAST
);
1570 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1572 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1575 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1576 unsigned long hostaddr
)
1578 struct in_addr
*addr
;
1580 assert( address
!= NULL
);
1581 CHECK_ADDRESS( address
, INET
);
1583 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1584 addr
->s_addr
= htonl(hostaddr
) ;
1586 return GSOCK_NOERROR
;
1589 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1590 const char *protocol
)
1593 struct sockaddr_in
*addr
;
1595 assert( address
!= NULL
);
1596 CHECK_ADDRESS( address
, INET
);
1600 address
->m_error
= GSOCK_INVPORT
;
1601 return GSOCK_INVPORT
;
1604 se
= getservbyname(port
, protocol
);
1607 // the cast to int suppresses compiler warnings
1608 // about subscript having the type char
1609 if (isdigit((int)port
[0]))
1613 port_int
= atoi(port
);
1614 addr
= (struct sockaddr_in
*)address
->m_addr
;
1615 addr
->sin_port
= htons(port_int
);
1616 return GSOCK_NOERROR
;
1619 address
->m_error
= GSOCK_INVPORT
;
1620 return GSOCK_INVPORT
;
1623 addr
= (struct sockaddr_in
*)address
->m_addr
;
1624 addr
->sin_port
= se
->s_port
;
1626 return GSOCK_NOERROR
;
1629 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1631 struct sockaddr_in
*addr
;
1633 assert( address
!= NULL
);
1634 CHECK_ADDRESS( address
, INET
);
1636 addr
= (struct sockaddr_in
*)address
->m_addr
;
1637 addr
->sin_port
= htons(port
);
1639 return GSOCK_NOERROR
;
1642 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1646 struct sockaddr_in
*addr
;
1648 assert( address
!= NULL
);
1649 CHECK_ADDRESS( address
, INET
);
1651 addr
= (struct sockaddr_in
*)address
->m_addr
;
1652 addr_buf
= (char *)&(addr
->sin_addr
);
1654 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1657 address
->m_error
= GSOCK_NOHOST
;
1658 return GSOCK_NOHOST
;
1661 strncpy(hostname
, he
->h_name
, sbuf
);
1663 return GSOCK_NOERROR
;
1666 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1668 struct sockaddr_in
*addr
;
1670 assert( address
!= NULL
);
1671 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1673 addr
= (struct sockaddr_in
*)address
->m_addr
;
1675 return ntohl(addr
->sin_addr
.s_addr
) ;
1678 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1680 struct sockaddr_in
*addr
;
1682 assert( address
!= NULL
);
1683 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1685 addr
= (struct sockaddr_in
*)address
->m_addr
;
1687 return ntohs(addr
->sin_port
);
1691 * -------------------------------------------------------------------------
1692 * Unix address family
1693 * -------------------------------------------------------------------------
1696 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1698 address
->m_len
= sizeof(struct sockaddr_un
);
1699 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1700 if (address
->m_addr
== NULL
)
1702 address
->m_error
= GSOCK_MEMERR
;
1703 return GSOCK_MEMERR
;
1706 address
->m_family
= GSOCK_UNIX
;
1707 address
->m_realfamily
= PF_UNIX
;
1708 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1709 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1711 return GSOCK_NOERROR
;
1714 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1716 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1718 struct sockaddr_un
*addr
;
1720 assert( address
!= NULL
);
1721 CHECK_ADDRESS( address
, UNIX
);
1723 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1724 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1725 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1727 return GSOCK_NOERROR
;
1730 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1732 struct sockaddr_un
*addr
;
1734 assert( address
!= NULL
);
1735 CHECK_ADDRESS( address
, UNIX
);
1737 addr
= (struct sockaddr_un
*)address
->m_addr
;
1739 strncpy(path
, addr
->sun_path
, sbuf
);
1741 return GSOCK_NOERROR
;
1744 /* Address handling */
1746 /* GSocket_SetLocal:
1750 * Set or get the local or peer address for this socket. The 'set'
1751 * functions return GSOCK_NOERROR on success, an error code otherwise.
1752 * The 'get' functions return a pointer to a GAddress object on success,
1753 * or NULL otherwise, in which case they set the error code of the
1754 * corresponding GSocket.
1757 * GSOCK_INVSOCK - the socket is not valid.
1758 * GSOCK_INVADDR - the address is not valid.
1761 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
1763 assert( socket
!= NULL
);
1765 // the socket must be initialized, or it must be a server
1766 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
1768 socket
->m_error
= GSOCK_INVSOCK
;
1769 return GSOCK_INVSOCK
;
1773 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1775 socket
->m_error
= GSOCK_INVADDR
;
1776 return GSOCK_INVADDR
;
1779 if (socket
->m_local
)
1780 GAddress_destroy(socket
->m_local
);
1782 socket
->m_local
= GAddress_copy(address
);
1784 return GSOCK_NOERROR
;
1787 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
1789 assert(socket
!= NULL
);
1792 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1794 socket
->m_error
= GSOCK_INVADDR
;
1795 return GSOCK_INVADDR
;
1799 GAddress_destroy(socket
->m_peer
);
1801 socket
->m_peer
= GAddress_copy(address
);
1803 return GSOCK_NOERROR
;
1806 GAddress
*GSocket_GetLocal(GSocket
*socket
)
1809 struct sockaddr addr
;
1810 socklen_t size
= sizeof(addr
);
1813 assert( socket
!= NULL
);
1815 // try to get it from the m_local var first
1816 if (socket
->m_local
)
1817 return GAddress_copy(socket
->m_local
);
1819 // else, if the socket is initialized, try getsockname
1820 if (socket
->m_fd
== INVALID_SOCKET
)
1822 socket
->m_error
= GSOCK_INVSOCK
;
1826 if (getsockname(socket
->m_fd
, &addr
, (socklen_t
*) &size
) < 0)
1828 socket
->m_error
= GSOCK_IOERR
;
1832 // got a valid address from getsockname, create a GAddress object
1833 address
= GAddress_new();
1834 if (address
== NULL
)
1836 socket
->m_error
= GSOCK_MEMERR
;
1840 err
= _GAddress_translate_from(address
, &addr
, size
);
1841 if (err
!= GSOCK_NOERROR
)
1843 GAddress_destroy(address
);
1844 socket
->m_error
= err
;
1851 GAddress
*GSocket_GetPeer(GSocket
*socket
)
1853 assert(socket
!= NULL
);
1855 // try to get it from the m_peer var
1857 return GAddress_copy(socket
->m_peer
);
1863 GSocket
*GSocket_new(void)
1866 socket
= (GSocket
*)malloc(sizeof(GSocket
));
1871 socket
->m_fd
= INVALID_SOCKET
;
1873 for (int i
=0;i
<GSOCK_MAX_EVENT
;i
++)
1875 socket
->m_cbacks
[i
] = NULL
;
1878 socket
->m_detected
= 0;
1880 socket
->m_local
= NULL
;
1881 socket
->m_peer
= NULL
;
1882 socket
->m_error
= GSOCK_NOERROR
;
1884 socket
->m_non_blocking
= false ;
1885 socket
->m_stream
= true;
1886 // socket->m_oriented = true;
1887 socket
->m_server
= false;
1888 socket
->m_establishing
= false;
1889 socket
->m_timeout
= 10 * 60 * 1000;
1890 // 10 minutes * 60 sec * 1000 millisec
1892 socket
->m_cfSocket
= NULL
;
1893 socket
->m_runLoopSource
= NULL
;
1894 socket
->m_readStream
= NULL
;
1895 socket
->m_writeStream
= NULL
;
1900 void GSocket_close(GSocket
*socket
)
1902 if ( socket
->m_cfSocket
!= NULL
)
1904 if ( socket
->m_readStream
)
1906 CFReadStreamClose(socket
->m_readStream
);
1907 CFRelease( socket
->m_readStream
) ;
1908 socket
->m_readStream
= NULL
;
1911 if ( socket
->m_writeStream
)
1913 CFWriteStreamClose(socket
->m_writeStream
);
1914 CFRelease( socket
->m_writeStream
) ;
1915 socket
->m_writeStream
= NULL
;
1918 CFSocketInvalidate( socket
->m_cfSocket
) ;
1919 CFRelease( socket
->m_cfSocket
) ;
1920 socket
->m_cfSocket
= NULL
;
1921 socket
->m_fd
= INVALID_SOCKET
;
1925 void GSocket_Shutdown(GSocket
*socket
)
1927 GSocket_close( socket
);
1929 // Disable GUI callbacks
1930 for (int evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
1931 socket
->m_cbacks
[evt
] = NULL
;
1933 socket
->m_detected
= GSOCK_LOST_FLAG
;
1936 void GSocket_destroy(GSocket
*socket
)
1938 assert( socket
!= NULL
);
1940 // Check that the socket is really shut down
1941 if (socket
->m_fd
!= INVALID_SOCKET
)
1942 GSocket_Shutdown(socket
);
1944 // Destroy private addresses
1945 if (socket
->m_local
)
1946 GAddress_destroy(socket
->m_local
);
1949 GAddress_destroy(socket
->m_peer
);
1951 // Destroy the socket itself
1955 GSocketError
GSocket_Connect(GSocket
*socket
, GSocketStream stream
)
1957 assert( socket
!= NULL
);
1959 if (socket
->m_fd
!= INVALID_SOCKET
)
1961 socket
->m_error
= GSOCK_INVSOCK
;
1962 return GSOCK_INVSOCK
;
1965 if (!socket
->m_peer
)
1967 socket
->m_error
= GSOCK_INVADDR
;
1968 return GSOCK_INVADDR
;
1971 // Streamed or dgram socket?
1972 socket
->m_stream
= (stream
== GSOCK_STREAMED
);
1973 socket
->m_oriented
= true;
1974 socket
->m_server
= false;
1975 socket
->m_establishing
= false;
1977 GSocketError returnErr
= GSOCK_NOERROR
;
1980 CFAllocatorRef alloc
= kCFAllocatorDefault
;
1981 CFSocketContext ctx
;
1982 memset( &ctx
, 0 , sizeof( ctx
) ) ;
1984 socket
->m_cfSocket
= CFSocketCreate( alloc
, socket
->m_peer
->m_realfamily
,
1985 stream
== GSOCK_STREAMED
? SOCK_STREAM
: SOCK_DGRAM
, 0 ,
1986 kCFSocketReadCallBack
| kCFSocketWriteCallBack
| kCFSocketConnectCallBack
, wxMacCFSocketCallback
, &ctx
) ;
1987 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
1989 socket
->m_fd
= CFSocketGetNative( socket
->m_cfSocket
) ;
1991 CFStreamCreatePairWithSocket ( alloc
, socket
->m_fd
, &socket
->m_readStream
, &socket
->m_writeStream
);
1992 if ((socket
->m_readStream
== NULL
) || (socket
->m_writeStream
== NULL
))
1994 GSocket_close(socket
);
1995 socket
->m_error
= GSOCK_IOERR
;
1999 if ( !CFReadStreamOpen( socket
->m_readStream
) || !CFWriteStreamOpen( socket
->m_writeStream
) )
2001 GSocket_close(socket
);
2002 socket
->m_error
= GSOCK_IOERR
;
2006 CFRunLoopSourceRef rls
= CFSocketCreateRunLoopSource(alloc
, socket
->m_cfSocket
, 0);
2007 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls
, kCFRunLoopCommonModes
);
2010 CFDataRef address
= CFDataCreateWithBytesNoCopy(alloc
, (const UInt8
*) socket
->m_peer
->m_addr
, socket
->m_peer
->m_len
, kCFAllocatorNull
);
2012 return GSOCK_MEMERR
;
2014 err
= CFSocketConnectToAddress( socket
->m_cfSocket
, address
, socket
->m_non_blocking
? -1 : socket
->m_timeout
/ 1000 ) ;
2017 if (err
!= kCFSocketSuccess
)
2019 if ( err
== kCFSocketTimeout
)
2021 GSocket_close(socket
);
2022 socket
->m_error
= GSOCK_TIMEDOUT
;
2023 return GSOCK_TIMEDOUT
;
2026 // we don't know whether a connect in progress will be issued like this
2027 if ( err
!= kCFSocketTimeout
&& socket
->m_non_blocking
)
2029 socket
->m_establishing
= true;
2030 socket
->m_error
= GSOCK_WOULDBLOCK
;
2031 return GSOCK_WOULDBLOCK
;
2034 GSocket_close(socket
);
2035 socket
->m_error
= GSOCK_IOERR
;
2039 return GSOCK_NOERROR
;
2044 /* GSocket_SetNonBlocking:
2045 * Sets the socket to non-blocking mode.
2046 * All IO calls will return immediately.
2048 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
2050 assert( socket
!= NULL
);
2052 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2054 socket
->m_non_blocking
= non_block
;
2058 * GSocket_SetTimeout:
2059 * Sets the timeout for blocking calls. Time is expressed in
2062 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
2064 assert( socket
!= NULL
);
2066 socket
->m_timeout
= millisec
;
2069 /* GSocket_GetError:
2070 * Returns the last error which occurred for this socket. Note that successful
2071 * operations do not clear this back to GSOCK_NOERROR, so use it only
2074 GSocketError
GSocket_GetError(GSocket
*socket
)
2076 assert( socket
!= NULL
);
2078 return socket
->m_error
;
2084 * There is data to be read in the input buffer. If, after a read
2085 * operation, there is still data available, the callback function will
2088 * The socket is available for writing. That is, the next write call
2089 * won't block. This event is generated only once, when the connection is
2090 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2091 * when the output buffer empties again. This means that the app should
2092 * assume that it can write since the first OUTPUT event, and no more
2093 * OUTPUT events will be generated unless an error occurs.
2095 * Connection successfully established, for client sockets, or incoming
2096 * client connection, for server sockets. Wait for this event (also watch
2097 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2099 * The connection is lost (or a connection request failed); this could
2100 * be due to a failure, or due to the peer closing it gracefully.
2103 /* GSocket_SetCallback:
2104 * Enables the callbacks specified by 'flags'. Note that 'flags'
2105 * may be a combination of flags OR'ed toghether, so the same
2106 * callback function can be made to accept different events.
2107 * The callback function must have the following prototype:
2109 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2111 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
2112 GSocketCallback callback
, char *cdata
)
2116 assert( socket
!= NULL
);
2118 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2120 if ((flags
& (1 << count
)) != 0)
2122 socket
->m_cbacks
[count
] = callback
;
2123 socket
->m_data
[count
] = cdata
;
2128 /* GSocket_UnsetCallback:
2129 * Disables all callbacks specified by 'flags', which may be a
2130 * combination of flags OR'ed toghether.
2132 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
2136 assert(socket
!= NULL
);
2138 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2140 if ((flags
& (1 << count
)) != 0)
2142 socket
->m_cbacks
[count
] = NULL
;
2143 socket
->m_data
[count
] = NULL
;
2149 #define CALL_CALLBACK(socket, event) { \
2150 _GSocket_Disable(socket, event); \
2151 if (socket->m_cbacks[event]) \
2152 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2155 void _GSocket_Install_Callback(GSocket
*socket
, GSocketEvent event
)
2160 case GSOCK_CONNECTION
:
2161 if (socket
->m_server
)
2162 c
= kCFSocketReadCallBack
;
2164 c
= kCFSocketConnectCallBack
;
2169 c
= kCFSocketReadCallBack
;
2173 c
= kCFSocketWriteCallBack
;
2180 CFSocketEnableCallBacks(socket
->m_cfSocket
, c
);
2183 void _GSocket_Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
2188 case GSOCK_CONNECTION
:
2189 if (socket
->m_server
)
2190 c
= kCFSocketReadCallBack
;
2192 c
= kCFSocketConnectCallBack
;
2197 c
= kCFSocketReadCallBack
;
2201 c
= kCFSocketWriteCallBack
;
2209 CFSocketDisableCallBacks(socket
->m_cfSocket
, c
);
2212 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
2214 socket
->m_detected
&= ~(1 << event
);
2215 _GSocket_Install_Callback(socket
, event
);
2218 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
2220 socket
->m_detected
|= (1 << event
);
2221 _GSocket_Uninstall_Callback(socket
, event
);
2224 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
2225 CFDataRef address
, const void* data
, void* info
)
2227 GSocket
* socket
= (GSocket
*)info
;
2229 switch (callbackType
)
2231 case kCFSocketConnectCallBack
:
2234 SInt32 error
= *((SInt32
*)data
) ;
2235 CALL_CALLBACK( socket
, GSOCK_LOST
) ;
2236 GSocket_Shutdown(socket
);
2240 CALL_CALLBACK( socket
, GSOCK_CONNECTION
) ;
2244 case kCFSocketReadCallBack
:
2245 CALL_CALLBACK( socket
, GSOCK_INPUT
) ;
2248 case kCFSocketWriteCallBack
:
2249 CALL_CALLBACK( socket
, GSOCK_OUTPUT
) ;
2253 break; // We shouldn't get here.
2257 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
2261 assert(socket
!= NULL
);
2262 // if ( !CFReadStreamHasBytesAvailable() )
2263 ret
= CFReadStreamRead( socket
->m_readStream
, (UInt8
*) buffer
, size
) ;
2268 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
2272 assert(socket
!= NULL
);
2273 ret
= CFWriteStreamWrite( socket
->m_writeStream
, (UInt8
*) buffer
, size
) ;
2278 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
2280 assert( socket
!= NULL
);
2282 return flags
& socket
->m_detected
;
2285 // ==========================================================================
2287 // ==========================================================================
2289 class wxSocketModule
: public wxModule
2292 virtual bool OnInit()
2294 // wxSocketBase will call GSocket_Init() itself when/if needed
2298 virtual void OnExit()
2300 if ( wxSocketBase::IsInitialized() )
2301 wxSocketBase::Shutdown();
2305 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2308 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)