1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/cfsocket.cpp
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
6 // Copyright: (C) 1999-1997, Guilhem Lavaux
7 // (C) 2000-1999, Guillermo Rodriguez Garcia
9 // License: see wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
21 #include "wx/object.h"
25 #include "wx/apptrait.h"
26 #include "wx/string.h"
29 #include "wx/module.h"
34 #include "wx/sckaddr.h"
35 #include "wx/socket.h"
36 #include "wx/mac/carbon/private.h"
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
43 #define HAVE_INET_ATON
45 // DLL options compatibility check:
48 WX_CHECK_BUILD_OPTIONS("wxNet")
52 #define MAX_DISCARD_SIZE (10 * 1024)
54 #ifndef INVALID_SOCKET
55 #define INVALID_SOCKET -1
58 // what to do within waits: we have 2 cases: from the main thread itself we
59 // have to call wxYield() to let the events (including the GUI events and the
60 // low-level (not wxWidgets) events from GSocket) be processed. From another
61 // thread it is enough to just call wxThread::Yield() which will give away the
62 // rest of our time slice: the explanation is that the events will be processed
63 // by the main thread anyhow, without calling wxYield(), but we don't want to
64 // eat the CPU time uselessly while sitting in the loop waiting for the data
66 #define PROCESS_EVENTS() \
68 if ( wxThread::IsMain() ) \
73 #else // !wxUSE_THREADS
74 #define PROCESS_EVENTS() wxYield()
75 #endif // wxUSE_THREADS/!wxUSE_THREADS
77 #define wxTRACE_Socket _T("wxSocket")
80 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
81 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
82 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
83 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
84 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
86 // --------------------------------------------------------------------------
88 // --------------------------------------------------------------------------
90 class wxSocketState
: public wxObject
93 wxSocketFlags m_flags
;
94 wxSocketEventFlags m_eventmask
;
99 wxSocketState() : wxObject() {}
101 DECLARE_NO_COPY_CLASS(wxSocketState
)
106 CFSocketNativeHandle m_fd
;
109 GSocketError m_error
;
116 unsigned long m_timeout
;
119 GSocketEventFlags m_detected
;
120 GSocketCallback m_cbacks
[GSOCK_MAX_EVENT
];
121 char *m_data
[GSOCK_MAX_EVENT
];
123 CFSocketRef m_cfSocket
;
124 CFRunLoopSourceRef m_runLoopSource
;
125 CFReadStreamRef m_readStream
;
126 CFWriteStreamRef m_writeStream
;
131 struct sockaddr
*m_addr
;
134 GAddressType m_family
;
137 GSocketError m_error
;
141 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
142 CFDataRef address
, const void* data
, void* info
) ;
143 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
) ;
144 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
) ;
146 // ==========================================================================
148 // ==========================================================================
150 // --------------------------------------------------------------------------
151 // Initialization and shutdown
152 // --------------------------------------------------------------------------
154 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
155 // to m_countInit with a crit section
156 size_t wxSocketBase::m_countInit
= 0;
158 bool wxSocketBase::IsInitialized()
160 return m_countInit
> 0;
163 bool wxSocketBase::Initialize()
165 if ( !m_countInit
++ )
168 wxAppTraits
*traits
= wxAppConsole::GetInstance() ?
169 wxAppConsole::GetInstance()->GetTraits() : NULL
;
170 GSocketGUIFunctionsTable
*functions
=
171 traits
? traits
->GetSocketGUIFunctionsTable() : NULL
;
172 GSocket_SetGUIFunctions(functions
);
174 if ( !GSocket_Init() )
186 void wxSocketBase::Shutdown()
188 // we should be initialized
189 wxASSERT_MSG( m_countInit
, wxT("extra call to Shutdown()") );
190 if ( !--m_countInit
)
198 // --------------------------------------------------------------------------
200 // --------------------------------------------------------------------------
202 void wxSocketBase::Init()
205 m_type
= wxSOCKET_UNINIT
;
216 m_beingDeleted
= false;
230 if ( !IsInitialized() )
232 // this Initialize() will be undone by wxSocketModule::OnExit(), all the
233 // other calls to it should be matched by a call to Shutdown()
238 wxSocketBase::wxSocketBase()
243 wxSocketBase::wxSocketBase( wxSocketFlags flags
, wxSocketType type
)
251 wxSocketBase::~wxSocketBase()
253 // Just in case the app called Destroy() *and* then deleted
254 // the socket immediately: don't leave dangling pointers.
255 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
257 traits
->RemoveFromPendingDelete(this);
259 // Shutdown and close the socket
263 // Destroy the GSocket object
266 GSocket_destroy(m_socket
);
269 // Free the pushback buffer
274 bool wxSocketBase::Destroy()
276 // Delayed destruction: the socket will be deleted during the next
277 // idle loop iteration. This ensures that all pending events have
279 m_beingDeleted
= true;
281 // Shutdown and close the socket
284 // Supress events from now on
287 // schedule this object for deletion
288 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
291 // let the traits object decide what to do with us
292 traits
->ScheduleForDestroy(this);
294 else // no app or no traits
296 // in wxBase we might have no app object at all, don't leak memory
303 // --------------------------------------------------------------------------
305 // --------------------------------------------------------------------------
307 // The following IO operations update m_error and m_lcount:
308 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
310 // TODO: Should Connect, Accept and AcceptWith update m_error?
312 bool wxSocketBase::Close()
314 // Interrupt pending waits
318 GSocket_Shutdown(m_socket
);
321 m_establishing
= false;
326 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
331 m_lcount
= _Read(buffer
, nbytes
);
333 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
334 if (m_flags
& wxSOCKET_WAITALL
)
335 m_error
= (m_lcount
!= nbytes
);
337 m_error
= (m_lcount
== 0);
339 // Allow read events from now on
345 wxUint32
wxSocketBase::_Read(void* buffer
, wxUint32 nbytes
)
349 // Try the pushback buffer first
350 total
= GetPushback(buffer
, nbytes
, false);
352 buffer
= (char *)buffer
+ total
;
354 // Return now in one of the following cases:
355 // - the socket is invalid,
356 // - we got all the data,
357 // - we got *some* data and we are not using wxSOCKET_WAITALL.
360 ((total
!= 0) && !(m_flags
& wxSOCKET_WAITALL
)) )
363 // Possible combinations (they are checked in this order)
365 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
371 if (m_flags
& wxSOCKET_NOWAIT
)
373 GSocket_SetNonBlocking(m_socket
, 1);
374 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
375 GSocket_SetNonBlocking(m_socket
, 0);
386 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForRead() )
389 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
395 buffer
= (char *)buffer
+ ret
;
398 // If we got here and wxSOCKET_WAITALL is not set, we can leave
399 // now. Otherwise, wait until we recv all the data or until there
402 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
409 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
411 wxUint32 len
, len2
, sig
, total
;
416 unsigned char sig
[4];
417 unsigned char len
[4];
427 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
429 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
432 sig
= (wxUint32
)msg
.sig
[0];
433 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
434 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
435 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
437 if (sig
!= 0xfeeddead)
439 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
443 len
= (wxUint32
)msg
.len
[0];
444 len
|= (wxUint32
)(msg
.len
[1] << 8);
445 len
|= (wxUint32
)(msg
.len
[2] << 16);
446 len
|= (wxUint32
)(msg
.len
[3] << 24);
456 // Don't attemp to read if the msg was zero bytes long.
459 total
= _Read(buffer
, len
);
466 char *discard_buffer
= new char[MAX_DISCARD_SIZE
];
469 // NOTE: discarded bytes don't add to m_lcount.
472 discard_len
= ((len2
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE
: len2
);
473 discard_len
= _Read(discard_buffer
, (wxUint32
)discard_len
);
474 len2
-= (wxUint32
)discard_len
;
476 while ((discard_len
> 0) && len2
);
478 delete [] discard_buffer
;
483 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
486 sig
= (wxUint32
)msg
.sig
[0];
487 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
488 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
489 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
491 if (sig
!= 0xdeadfeed)
493 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
509 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
514 m_lcount
= _Read(buffer
, nbytes
);
515 Pushback(buffer
, m_lcount
);
517 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
518 if (m_flags
& wxSOCKET_WAITALL
)
519 m_error
= (m_lcount
!= nbytes
);
521 m_error
= (m_lcount
== 0);
523 // Allow read events again
529 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
534 m_lcount
= _Write(buffer
, nbytes
);
536 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
537 if (m_flags
& wxSOCKET_WAITALL
)
538 m_error
= (m_lcount
!= nbytes
);
540 m_error
= (m_lcount
== 0);
542 // Allow write events again
548 wxUint32
wxSocketBase::_Write(const void *buffer
, wxUint32 nbytes
)
552 // If the socket is invalid or parameters are ill, return immediately
553 if (!m_socket
|| !buffer
|| !nbytes
)
556 // Possible combinations (they are checked in this order)
558 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
563 if (m_flags
& wxSOCKET_NOWAIT
)
565 GSocket_SetNonBlocking(m_socket
, 1);
566 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
567 GSocket_SetNonBlocking(m_socket
, 0);
578 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForWrite() )
581 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
587 buffer
= (const char *)buffer
+ ret
;
590 // If we got here and wxSOCKET_WAITALL is not set, we can leave
591 // now. Otherwise, wait until we send all the data or until there
594 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
601 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
607 unsigned char sig
[4];
608 unsigned char len
[4];
617 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
619 msg
.sig
[0] = (unsigned char) 0xad;
620 msg
.sig
[1] = (unsigned char) 0xde;
621 msg
.sig
[2] = (unsigned char) 0xed;
622 msg
.sig
[3] = (unsigned char) 0xfe;
624 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
625 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
626 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
627 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
629 if (_Write(&msg
, sizeof(msg
)) < sizeof(msg
))
632 total
= _Write(buffer
, nbytes
);
637 msg
.sig
[0] = (unsigned char) 0xed;
638 msg
.sig
[1] = (unsigned char) 0xfe;
639 msg
.sig
[2] = (unsigned char) 0xad;
640 msg
.sig
[3] = (unsigned char) 0xde;
641 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
643 if ((_Write(&msg
, sizeof(msg
))) < sizeof(msg
))
657 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
660 Pushback(buffer
, nbytes
);
668 wxSocketBase
& wxSocketBase::Discard()
670 char *buffer
= new char[MAX_DISCARD_SIZE
];
677 SetFlags(wxSOCKET_NOWAIT
);
681 ret
= _Read(buffer
, MAX_DISCARD_SIZE
);
684 while (ret
== MAX_DISCARD_SIZE
);
690 // Allow read events again
696 // --------------------------------------------------------------------------
698 // --------------------------------------------------------------------------
700 // All Wait functions poll the socket using GSocket_Select() to
701 // check for the specified combination of conditions, until one
702 // of these conditions become true, an error occurs, or the
703 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
704 // this won't block the GUI.
706 bool wxSocketBase::_Wait(long seconds
,
708 wxSocketEventFlags flags
)
710 GSocketEventFlags result
;
713 // Set this to true to interrupt ongoing waits
716 // Check for valid socket
720 // Check for valid timeout value.
722 timeout
= seconds
* 1000 + milliseconds
;
724 timeout
= m_timeout
* 1000;
726 #if !defined(wxUSE_GUI) || !wxUSE_GUI
727 GSocket_SetTimeout(m_socket
, timeout
);
730 // Wait in an active polling loop.
732 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
733 // hurt. It has to be here because the (GSocket) event might arrive
734 // a bit delayed, and it has to be in OnRequest as well because we
735 // don't know whether the Wait functions are being used.
737 // Do this at least once (important if timeout == 0, when
738 // we are just polling). Also, if just polling, do not yield.
745 result
= GSocket_Select(m_socket
, flags
| GSOCK_LOST_FLAG
);
747 // Incoming connection (server) or connection established (client)
748 if (result
& GSOCK_CONNECTION_FLAG
)
751 m_establishing
= false;
756 // Data available or output buffer ready
757 if ((result
& GSOCK_INPUT_FLAG
) || (result
& GSOCK_OUTPUT_FLAG
))
763 if (result
& GSOCK_LOST_FLAG
)
766 m_establishing
= false;
768 return (flags
& GSOCK_LOST_FLAG
) != 0;
772 if ((!timeout
) || (chrono
.Time() > timeout
) || (m_interrupt
))
781 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
783 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
785 GSOCK_CONNECTION_FLAG
|
789 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
791 // Check pushback buffer before entering _Wait
795 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
796 // _Wait becuase of the semantics of WaitForRead: a return
797 // value of true means that a GSocket_Read call will return
798 // immediately, not that there is actually data to read.
800 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
| GSOCK_LOST_FLAG
);
803 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
805 return _Wait(seconds
, milliseconds
, GSOCK_OUTPUT_FLAG
);
808 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
810 return _Wait(seconds
, milliseconds
, GSOCK_LOST_FLAG
);
813 // --------------------------------------------------------------------------
815 // --------------------------------------------------------------------------
818 // Get local or peer address
821 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
828 peer
= GSocket_GetPeer(m_socket
);
830 // copying a null address would just trigger an assert anyway
835 addr_man
.SetAddress(peer
);
836 GAddress_destroy(peer
);
841 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
849 local
= GSocket_GetLocal(m_socket
);
850 addr_man
.SetAddress(local
);
851 GAddress_destroy(local
);
858 // Save and restore socket state
861 void wxSocketBase::SaveState()
863 wxSocketState
*state
;
865 state
= new wxSocketState();
867 state
->m_flags
= m_flags
;
868 state
->m_notify
= m_notify
;
869 state
->m_eventmask
= m_eventmask
;
870 state
->m_clientData
= m_clientData
;
872 m_states
.Append(state
);
875 void wxSocketBase::RestoreState()
877 wxList::compatibility_iterator node
;
878 wxSocketState
*state
;
880 node
= m_states
.GetLast();
884 state
= (wxSocketState
*)node
->GetData();
886 m_flags
= state
->m_flags
;
887 m_notify
= state
->m_notify
;
888 m_eventmask
= state
->m_eventmask
;
889 m_clientData
= state
->m_clientData
;
891 m_states
.Erase(node
);
899 void wxSocketBase::SetTimeout(long seconds
)
905 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
909 void wxSocketBase::SetFlags(wxSocketFlags flags
)
915 // --------------------------------------------------------------------------
917 // --------------------------------------------------------------------------
919 // A note on how events are processed, which is probably the most
920 // difficult thing to get working right while keeping the same API
921 // and functionality for all platforms.
923 // When GSocket detects an event, it calls wx_socket_callback, which in
924 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
925 // object. OnRequest does some housekeeping, and if the event is to be
926 // propagated to the user, it creates a new wxSocketEvent object and
927 // posts it. The event is not processed immediately, but delayed with
928 // AddPendingEvent instead. This is necessary in order to decouple the
929 // event processing from wx_socket_callback; otherwise, subsequent IO
930 // calls made from the user event handler would fail, as gtk callbacks
931 // are not reentrant.
933 // Note that, unlike events, user callbacks (now deprecated) are _not_
934 // decoupled from wx_socket_callback and thus they suffer from a variety
935 // of problems. Avoid them where possible and use events instead.
938 void LINKAGEMODE
wx_socket_callback(GSocket
* WXUNUSED(socket
),
939 GSocketEvent notification
,
942 wxSocketBase
*sckobj
= (wxSocketBase
*)cdata
;
944 sckobj
->OnRequest((wxSocketNotify
) notification
);
947 void wxSocketBase::OnRequest(wxSocketNotify notification
)
949 // NOTE: We duplicate some of the code in _Wait, but this doesn't
950 // hurt. It has to be here because the (GSocket) event might arrive
951 // a bit delayed, and it has to be in _Wait as well because we don't
952 // know whether the Wait functions are being used.
954 switch (notification
)
956 case wxSOCKET_CONNECTION
:
957 m_establishing
= false;
961 // If we are in the middle of a R/W operation, do not
962 // propagate events to users. Also, filter 'late' events
963 // which are no longer valid.
966 if (m_reading
|| !GSocket_Select(m_socket
, GSOCK_INPUT_FLAG
))
970 case wxSOCKET_OUTPUT
:
971 if (m_writing
|| !GSocket_Select(m_socket
, GSOCK_OUTPUT_FLAG
))
977 m_establishing
= false;
984 // Schedule the event
986 wxSocketEventFlags flag
= 0;
988 switch (notification
)
991 flag
= GSOCK_INPUT_FLAG
;
995 flag
= GSOCK_OUTPUT_FLAG
;
998 case GSOCK_CONNECTION
:
999 flag
= GSOCK_CONNECTION_FLAG
;
1003 flag
= GSOCK_LOST_FLAG
;
1007 wxLogWarning( wxT("wxSocket: unknown event!") );
1011 if (((m_eventmask
& flag
) == flag
) && m_notify
)
1015 wxSocketEvent
event(m_id
);
1016 event
.m_event
= notification
;
1017 event
.m_clientData
= m_clientData
;
1018 event
.SetEventObject(this);
1020 m_handler
->AddPendingEvent(event
);
1025 void wxSocketBase::Notify(bool notify
)
1030 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1032 m_eventmask
= flags
;
1035 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1037 m_handler
= &handler
;
1041 // --------------------------------------------------------------------------
1043 // --------------------------------------------------------------------------
1045 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1050 if (m_unread
== NULL
)
1051 m_unread
= malloc(size
);
1056 tmp
= malloc(m_unrd_size
+ size
);
1057 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1063 m_unrd_size
+= size
;
1065 memcpy(m_unread
, buffer
, size
);
1068 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1073 if (size
> (m_unrd_size
-m_unrd_cur
))
1074 size
= m_unrd_size
-m_unrd_cur
;
1076 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1081 if (m_unrd_size
== m_unrd_cur
)
1094 // ==========================================================================
1096 // ==========================================================================
1098 // --------------------------------------------------------------------------
1100 // --------------------------------------------------------------------------
1102 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1103 wxSocketFlags flags
)
1104 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1106 wxLogTrace( wxTRACE_Socket
, wxT("Opening wxSocketServer") );
1108 m_socket
= GSocket_new();
1112 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_new failed") );
1116 // Setup the socket as server
1119 GSocket_SetLocal(m_socket
, addr_man
.GetAddress());
1120 if (GSocket_SetServer(m_socket
) != GSOCK_NOERROR
)
1122 GSocket_destroy(m_socket
);
1125 wxLogTrace( wxTRACE_Socket
, wxT("*** GSocket_SetServer failed") );
1129 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1130 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1131 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1132 wx_socket_callback
, (char *)this);
1136 // --------------------------------------------------------------------------
1138 // --------------------------------------------------------------------------
1140 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1142 GSocket
*child_socket
;
1147 // If wait == false, then the call should be nonblocking.
1148 // When we are finished, we put the socket to blocking mode
1153 GSocket_SetNonBlocking(m_socket
, 1);
1155 child_socket
= GSocket_WaitConnection(m_socket
);
1158 GSocket_SetNonBlocking(m_socket
, 0);
1163 sock
.m_type
= wxSOCKET_BASE
;
1164 sock
.m_socket
= child_socket
;
1165 sock
.m_connected
= true;
1167 GSocket_SetTimeout(sock
.m_socket
, sock
.m_timeout
* 1000);
1168 GSocket_SetCallback(sock
.m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1169 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1170 wx_socket_callback
, (char *)&sock
);
1176 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1178 wxSocketBase
* sock
= new wxSocketBase();
1180 sock
->SetFlags(m_flags
);
1182 if (!AcceptWith(*sock
, wait
))
1191 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1193 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
);
1196 // ==========================================================================
1198 // ==========================================================================
1200 // --------------------------------------------------------------------------
1202 // --------------------------------------------------------------------------
1204 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1205 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1209 wxSocketClient::~wxSocketClient()
1213 // --------------------------------------------------------------------------
1215 // --------------------------------------------------------------------------
1217 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1223 // Shutdown and destroy the socket
1225 GSocket_destroy(m_socket
);
1228 m_socket
= GSocket_new();
1229 m_connected
= false;
1230 m_establishing
= false;
1235 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1236 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1237 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1238 wx_socket_callback
, (char *)this);
1240 // If wait == false, then the call should be nonblocking.
1241 // When we are finished, we put the socket to blocking mode
1245 GSocket_SetNonBlocking(m_socket
, 1);
1247 GSocket_SetPeer(m_socket
, addr_man
.GetAddress());
1248 err
= GSocket_Connect(m_socket
, GSOCK_STREAMED
);
1251 GSocket_SetNonBlocking(m_socket
, 0);
1253 if (err
!= GSOCK_NOERROR
)
1255 if (err
== GSOCK_WOULDBLOCK
)
1256 m_establishing
= true;
1265 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1267 if (m_connected
) // Already connected
1270 if (!m_establishing
|| !m_socket
) // No connection in progress
1273 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
| GSOCK_LOST_FLAG
);
1276 // ==========================================================================
1278 // ==========================================================================
1280 /* NOTE: experimental stuff - might change */
1282 wxDatagramSocket::wxDatagramSocket( wxSockAddress
& addr
,
1283 wxSocketFlags flags
)
1284 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1287 // Create the socket
1288 m_socket
= GSocket_new();
1293 // Setup the socket as non connection oriented
1294 GSocket_SetLocal(m_socket
, addr
.GetAddress());
1295 if( GSocket_SetNonOriented(m_socket
) != GSOCK_NOERROR
)
1297 GSocket_destroy(m_socket
);
1302 // Initialize all stuff
1303 m_connected
= false;
1304 m_establishing
= false;
1305 GSocket_SetTimeout( m_socket
, m_timeout
);
1306 GSocket_SetCallback( m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1307 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1308 wx_socket_callback
, (char*)this );
1312 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1321 wxDatagramSocket
& wxDatagramSocket::SendTo( wxSockAddress
& addr
,
1325 GSocket_SetPeer(m_socket
, addr
.GetAddress());
1331 * -------------------------------------------------------------------------
1333 * -------------------------------------------------------------------------
1336 /* CHECK_ADDRESS verifies that the current address family is either
1337 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1338 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1339 * an appropiate error code.
1341 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1343 #define CHECK_ADDRESS(address, family) \
1345 if (address->m_family == GSOCK_NOFAMILY) \
1346 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1347 return address->m_error; \
1348 if (address->m_family != GSOCK_##family) \
1350 address->m_error = GSOCK_INVADDR; \
1351 return GSOCK_INVADDR; \
1355 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1357 if (address->m_family == GSOCK_NOFAMILY) \
1358 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1360 if (address->m_family != GSOCK_##family) \
1362 address->m_error = GSOCK_INVADDR; \
1368 GAddress
*GAddress_new(void)
1372 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1375 address
->m_family
= GSOCK_NOFAMILY
;
1376 address
->m_addr
= NULL
;
1382 GAddress
*GAddress_copy(GAddress
*address
)
1386 assert(address
!= NULL
);
1388 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1391 memcpy(addr2
, address
, sizeof(GAddress
));
1393 if (address
->m_addr
&& address
->m_len
> 0)
1395 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1396 if (addr2
->m_addr
== NULL
)
1402 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1408 void GAddress_destroy(GAddress
*address
)
1410 assert( address
!= NULL
);
1412 if (address
->m_addr
)
1413 free(address
->m_addr
);
1418 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1420 assert(address
!= NULL
);
1422 address
->m_family
= type
;
1425 GAddressType
GAddress_GetFamily(GAddress
*address
)
1427 assert( address
!= NULL
);
1429 return address
->m_family
;
1432 GSocketError
_GAddress_translate_from(GAddress
*address
,
1433 struct sockaddr
*addr
, int len
)
1435 address
->m_realfamily
= addr
->sa_family
;
1436 switch (addr
->sa_family
)
1439 address
->m_family
= GSOCK_INET
;
1443 address
->m_family
= GSOCK_UNIX
;
1448 address
->m_family
= GSOCK_INET6
;
1454 address
->m_error
= GSOCK_INVOP
;
1459 if (address
->m_addr
)
1460 free(address
->m_addr
);
1462 address
->m_len
= len
;
1463 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1465 if (address
->m_addr
== NULL
)
1467 address
->m_error
= GSOCK_MEMERR
;
1468 return GSOCK_MEMERR
;
1471 memcpy(address
->m_addr
, addr
, len
);
1473 return GSOCK_NOERROR
;
1476 GSocketError
_GAddress_translate_to(GAddress
*address
,
1477 struct sockaddr
**addr
, int *len
)
1479 if (!address
->m_addr
)
1481 address
->m_error
= GSOCK_INVADDR
;
1482 return GSOCK_INVADDR
;
1485 *len
= address
->m_len
;
1486 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1489 address
->m_error
= GSOCK_MEMERR
;
1490 return GSOCK_MEMERR
;
1493 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1494 return GSOCK_NOERROR
;
1498 * -------------------------------------------------------------------------
1499 * Internet address family
1500 * -------------------------------------------------------------------------
1503 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1505 address
->m_len
= sizeof(struct sockaddr_in
);
1506 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1507 if (address
->m_addr
== NULL
)
1509 address
->m_error
= GSOCK_MEMERR
;
1510 return GSOCK_MEMERR
;
1513 memset( address
->m_addr
, 0 , address
->m_len
) ;
1514 address
->m_family
= GSOCK_INET
;
1515 address
->m_realfamily
= PF_INET
;
1516 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1517 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1519 return GSOCK_NOERROR
;
1522 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1525 struct in_addr
*addr
;
1527 assert( address
!= NULL
);
1528 CHECK_ADDRESS( address
, INET
);
1530 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1532 // If it is a numeric host name, convert it now
1533 #if defined(HAVE_INET_ATON)
1534 if (inet_aton(hostname
, addr
) == 0)
1536 #elif defined(HAVE_INET_ADDR)
1537 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1540 // Use gethostbyname by default
1542 int val
= 1; // VA doesn't like constants in conditional expressions
1547 struct in_addr
*array_addr
;
1549 // It is a real name, we solve it
1550 if ((he
= gethostbyname(hostname
)) == NULL
)
1552 // Reset to invalid address
1553 addr
->s_addr
= INADDR_NONE
;
1554 address
->m_error
= GSOCK_NOHOST
;
1555 return GSOCK_NOHOST
;
1557 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1558 addr
->s_addr
= array_addr
[0].s_addr
;
1561 return GSOCK_NOERROR
;
1564 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1566 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1569 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1570 unsigned long hostaddr
)
1572 struct in_addr
*addr
;
1574 assert( address
!= NULL
);
1575 CHECK_ADDRESS( address
, INET
);
1577 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1578 addr
->s_addr
= htonl(hostaddr
) ;
1580 return GSOCK_NOERROR
;
1583 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1584 const char *protocol
)
1587 struct sockaddr_in
*addr
;
1589 assert( address
!= NULL
);
1590 CHECK_ADDRESS( address
, INET
);
1594 address
->m_error
= GSOCK_INVPORT
;
1595 return GSOCK_INVPORT
;
1598 se
= getservbyname(port
, protocol
);
1601 // the cast to int suppresses compiler warnings
1602 // about subscript having the type char
1603 if (isdigit((int)port
[0]))
1607 port_int
= atoi(port
);
1608 addr
= (struct sockaddr_in
*)address
->m_addr
;
1609 addr
->sin_port
= htons(port_int
);
1610 return GSOCK_NOERROR
;
1613 address
->m_error
= GSOCK_INVPORT
;
1614 return GSOCK_INVPORT
;
1617 addr
= (struct sockaddr_in
*)address
->m_addr
;
1618 addr
->sin_port
= se
->s_port
;
1620 return GSOCK_NOERROR
;
1623 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1625 struct sockaddr_in
*addr
;
1627 assert( address
!= NULL
);
1628 CHECK_ADDRESS( address
, INET
);
1630 addr
= (struct sockaddr_in
*)address
->m_addr
;
1631 addr
->sin_port
= htons(port
);
1633 return GSOCK_NOERROR
;
1636 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1640 struct sockaddr_in
*addr
;
1642 assert( address
!= NULL
);
1643 CHECK_ADDRESS( address
, INET
);
1645 addr
= (struct sockaddr_in
*)address
->m_addr
;
1646 addr_buf
= (char *)&(addr
->sin_addr
);
1648 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1651 address
->m_error
= GSOCK_NOHOST
;
1652 return GSOCK_NOHOST
;
1655 strncpy(hostname
, he
->h_name
, sbuf
);
1657 return GSOCK_NOERROR
;
1660 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1662 struct sockaddr_in
*addr
;
1664 assert( address
!= NULL
);
1665 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1667 addr
= (struct sockaddr_in
*)address
->m_addr
;
1669 return ntohl(addr
->sin_addr
.s_addr
) ;
1672 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1674 struct sockaddr_in
*addr
;
1676 assert( address
!= NULL
);
1677 CHECK_ADDRESS_RETVAL( address
, INET
, 0 );
1679 addr
= (struct sockaddr_in
*)address
->m_addr
;
1681 return ntohs(addr
->sin_port
);
1685 * -------------------------------------------------------------------------
1686 * Unix address family
1687 * -------------------------------------------------------------------------
1690 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1692 address
->m_len
= sizeof(struct sockaddr_un
);
1693 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1694 if (address
->m_addr
== NULL
)
1696 address
->m_error
= GSOCK_MEMERR
;
1697 return GSOCK_MEMERR
;
1700 address
->m_family
= GSOCK_UNIX
;
1701 address
->m_realfamily
= PF_UNIX
;
1702 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1703 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1705 return GSOCK_NOERROR
;
1708 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1710 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1712 struct sockaddr_un
*addr
;
1714 assert( address
!= NULL
);
1715 CHECK_ADDRESS( address
, UNIX
);
1717 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1718 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1719 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1721 return GSOCK_NOERROR
;
1724 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1726 struct sockaddr_un
*addr
;
1728 assert( address
!= NULL
);
1729 CHECK_ADDRESS( address
, UNIX
);
1731 addr
= (struct sockaddr_un
*)address
->m_addr
;
1733 strncpy(path
, addr
->sun_path
, sbuf
);
1735 return GSOCK_NOERROR
;
1738 /* Address handling */
1740 /* GSocket_SetLocal:
1744 * Set or get the local or peer address for this socket. The 'set'
1745 * functions return GSOCK_NOERROR on success, an error code otherwise.
1746 * The 'get' functions return a pointer to a GAddress object on success,
1747 * or NULL otherwise, in which case they set the error code of the
1748 * corresponding GSocket.
1751 * GSOCK_INVSOCK - the socket is not valid.
1752 * GSOCK_INVADDR - the address is not valid.
1755 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
1757 assert( socket
!= NULL
);
1759 // the socket must be initialized, or it must be a server
1760 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
1762 socket
->m_error
= GSOCK_INVSOCK
;
1763 return GSOCK_INVSOCK
;
1767 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1769 socket
->m_error
= GSOCK_INVADDR
;
1770 return GSOCK_INVADDR
;
1773 if (socket
->m_local
)
1774 GAddress_destroy(socket
->m_local
);
1776 socket
->m_local
= GAddress_copy(address
);
1778 return GSOCK_NOERROR
;
1781 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
1783 assert(socket
!= NULL
);
1786 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1788 socket
->m_error
= GSOCK_INVADDR
;
1789 return GSOCK_INVADDR
;
1793 GAddress_destroy(socket
->m_peer
);
1795 socket
->m_peer
= GAddress_copy(address
);
1797 return GSOCK_NOERROR
;
1800 GAddress
*GSocket_GetLocal(GSocket
*socket
)
1803 struct sockaddr addr
;
1804 socklen_t size
= sizeof(addr
);
1807 assert( socket
!= NULL
);
1809 // try to get it from the m_local var first
1810 if (socket
->m_local
)
1811 return GAddress_copy(socket
->m_local
);
1813 // else, if the socket is initialized, try getsockname
1814 if (socket
->m_fd
== INVALID_SOCKET
)
1816 socket
->m_error
= GSOCK_INVSOCK
;
1820 if (getsockname(socket
->m_fd
, &addr
, (socklen_t
*) &size
) < 0)
1822 socket
->m_error
= GSOCK_IOERR
;
1826 // got a valid address from getsockname, create a GAddress object
1827 address
= GAddress_new();
1828 if (address
== NULL
)
1830 socket
->m_error
= GSOCK_MEMERR
;
1834 err
= _GAddress_translate_from(address
, &addr
, size
);
1835 if (err
!= GSOCK_NOERROR
)
1837 GAddress_destroy(address
);
1838 socket
->m_error
= err
;
1845 GAddress
*GSocket_GetPeer(GSocket
*socket
)
1847 assert(socket
!= NULL
);
1849 // try to get it from the m_peer var
1851 return GAddress_copy(socket
->m_peer
);
1857 GSocket
*GSocket_new(void)
1860 socket
= (GSocket
*)malloc(sizeof(GSocket
));
1865 socket
->m_fd
= INVALID_SOCKET
;
1867 for (int i
=0;i
<GSOCK_MAX_EVENT
;i
++)
1869 socket
->m_cbacks
[i
] = NULL
;
1872 socket
->m_detected
= 0;
1874 socket
->m_local
= NULL
;
1875 socket
->m_peer
= NULL
;
1876 socket
->m_error
= GSOCK_NOERROR
;
1878 socket
->m_non_blocking
= false ;
1879 socket
->m_stream
= true;
1880 // socket->m_oriented = true;
1881 socket
->m_server
= false;
1882 socket
->m_establishing
= false;
1883 socket
->m_timeout
= 10 * 60 * 1000;
1884 // 10 minutes * 60 sec * 1000 millisec
1886 socket
->m_cfSocket
= NULL
;
1887 socket
->m_runLoopSource
= NULL
;
1888 socket
->m_readStream
= NULL
;
1889 socket
->m_writeStream
= NULL
;
1894 void GSocket_close(GSocket
*socket
)
1896 if ( socket
->m_cfSocket
!= NULL
)
1898 if ( socket
->m_readStream
)
1900 CFReadStreamClose(socket
->m_readStream
);
1901 CFRelease( socket
->m_readStream
) ;
1902 socket
->m_readStream
= NULL
;
1905 if ( socket
->m_writeStream
)
1907 CFWriteStreamClose(socket
->m_writeStream
);
1908 CFRelease( socket
->m_writeStream
) ;
1909 socket
->m_writeStream
= NULL
;
1912 CFSocketInvalidate( socket
->m_cfSocket
) ;
1913 CFRelease( socket
->m_cfSocket
) ;
1914 socket
->m_cfSocket
= NULL
;
1915 socket
->m_fd
= INVALID_SOCKET
;
1919 void GSocket_Shutdown(GSocket
*socket
)
1921 GSocket_close( socket
);
1923 // Disable GUI callbacks
1924 for (int evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
1925 socket
->m_cbacks
[evt
] = NULL
;
1927 socket
->m_detected
= GSOCK_LOST_FLAG
;
1930 void GSocket_destroy(GSocket
*socket
)
1932 assert( socket
!= NULL
);
1934 // Check that the socket is really shut down
1935 if (socket
->m_fd
!= INVALID_SOCKET
)
1936 GSocket_Shutdown(socket
);
1938 // Destroy private addresses
1939 if (socket
->m_local
)
1940 GAddress_destroy(socket
->m_local
);
1943 GAddress_destroy(socket
->m_peer
);
1945 // Destroy the socket itself
1949 GSocketError
GSocket_Connect(GSocket
*socket
, GSocketStream stream
)
1951 assert( socket
!= NULL
);
1953 if (socket
->m_fd
!= INVALID_SOCKET
)
1955 socket
->m_error
= GSOCK_INVSOCK
;
1956 return GSOCK_INVSOCK
;
1959 if (!socket
->m_peer
)
1961 socket
->m_error
= GSOCK_INVADDR
;
1962 return GSOCK_INVADDR
;
1965 // Streamed or dgram socket?
1966 socket
->m_stream
= (stream
== GSOCK_STREAMED
);
1967 socket
->m_oriented
= true;
1968 socket
->m_server
= false;
1969 socket
->m_establishing
= false;
1971 GSocketError returnErr
= GSOCK_NOERROR
;
1974 CFAllocatorRef alloc
= kCFAllocatorDefault
;
1975 CFSocketContext ctx
;
1976 memset( &ctx
, 0 , sizeof( ctx
) ) ;
1978 socket
->m_cfSocket
= CFSocketCreate( alloc
, socket
->m_peer
->m_realfamily
,
1979 stream
== GSOCK_STREAMED
? SOCK_STREAM
: SOCK_DGRAM
, 0 ,
1980 kCFSocketReadCallBack
| kCFSocketWriteCallBack
| kCFSocketConnectCallBack
, wxMacCFSocketCallback
, &ctx
) ;
1981 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
1983 socket
->m_fd
= CFSocketGetNative( socket
->m_cfSocket
) ;
1985 CFStreamCreatePairWithSocket ( alloc
, socket
->m_fd
, &socket
->m_readStream
, &socket
->m_writeStream
);
1986 if ((socket
->m_readStream
== NULL
) || (socket
->m_writeStream
== NULL
))
1988 GSocket_close(socket
);
1989 socket
->m_error
= GSOCK_IOERR
;
1993 if ( !CFReadStreamOpen( socket
->m_readStream
) || !CFWriteStreamOpen( socket
->m_writeStream
) )
1995 GSocket_close(socket
);
1996 socket
->m_error
= GSOCK_IOERR
;
2000 CFRunLoopSourceRef rls
= CFSocketCreateRunLoopSource(alloc
, socket
->m_cfSocket
, 0);
2001 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls
, kCFRunLoopCommonModes
);
2004 CFDataRef address
= CFDataCreateWithBytesNoCopy(alloc
, (const UInt8
*) socket
->m_peer
->m_addr
, socket
->m_peer
->m_len
, kCFAllocatorNull
);
2006 return GSOCK_MEMERR
;
2008 err
= CFSocketConnectToAddress( socket
->m_cfSocket
, address
, socket
->m_non_blocking
? -1 : socket
->m_timeout
/ 1000 ) ;
2011 if (err
!= kCFSocketSuccess
)
2013 if ( err
== kCFSocketTimeout
)
2015 GSocket_close(socket
);
2016 socket
->m_error
= GSOCK_TIMEDOUT
;
2017 return GSOCK_TIMEDOUT
;
2020 // we don't know whether a connect in progress will be issued like this
2021 if ( err
!= kCFSocketTimeout
&& socket
->m_non_blocking
)
2023 socket
->m_establishing
= true;
2024 socket
->m_error
= GSOCK_WOULDBLOCK
;
2025 return GSOCK_WOULDBLOCK
;
2028 GSocket_close(socket
);
2029 socket
->m_error
= GSOCK_IOERR
;
2033 return GSOCK_NOERROR
;
2038 /* GSocket_SetNonBlocking:
2039 * Sets the socket to non-blocking mode.
2040 * All IO calls will return immediately.
2042 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
2044 assert( socket
!= NULL
);
2046 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2048 socket
->m_non_blocking
= non_block
;
2052 * GSocket_SetTimeout:
2053 * Sets the timeout for blocking calls. Time is expressed in
2056 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
2058 assert( socket
!= NULL
);
2060 socket
->m_timeout
= millisec
;
2063 /* GSocket_GetError:
2064 * Returns the last error which occurred for this socket. Note that successful
2065 * operations do not clear this back to GSOCK_NOERROR, so use it only
2068 GSocketError
GSocket_GetError(GSocket
*socket
)
2070 assert( socket
!= NULL
);
2072 return socket
->m_error
;
2078 * There is data to be read in the input buffer. If, after a read
2079 * operation, there is still data available, the callback function will
2082 * The socket is available for writing. That is, the next write call
2083 * won't block. This event is generated only once, when the connection is
2084 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2085 * when the output buffer empties again. This means that the app should
2086 * assume that it can write since the first OUTPUT event, and no more
2087 * OUTPUT events will be generated unless an error occurs.
2089 * Connection successfully established, for client sockets, or incoming
2090 * client connection, for server sockets. Wait for this event (also watch
2091 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2093 * The connection is lost (or a connection request failed); this could
2094 * be due to a failure, or due to the peer closing it gracefully.
2097 /* GSocket_SetCallback:
2098 * Enables the callbacks specified by 'flags'. Note that 'flags'
2099 * may be a combination of flags OR'ed toghether, so the same
2100 * callback function can be made to accept different events.
2101 * The callback function must have the following prototype:
2103 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2105 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
2106 GSocketCallback callback
, char *cdata
)
2110 assert( socket
!= NULL
);
2112 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2114 if ((flags
& (1 << count
)) != 0)
2116 socket
->m_cbacks
[count
] = callback
;
2117 socket
->m_data
[count
] = cdata
;
2122 /* GSocket_UnsetCallback:
2123 * Disables all callbacks specified by 'flags', which may be a
2124 * combination of flags OR'ed toghether.
2126 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
2130 assert(socket
!= NULL
);
2132 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2134 if ((flags
& (1 << count
)) != 0)
2136 socket
->m_cbacks
[count
] = NULL
;
2137 socket
->m_data
[count
] = NULL
;
2143 #define CALL_CALLBACK(socket, event) { \
2144 _GSocket_Disable(socket, event); \
2145 if (socket->m_cbacks[event]) \
2146 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2149 void _GSocket_Install_Callback(GSocket
*socket
, GSocketEvent event
)
2154 case GSOCK_CONNECTION
:
2155 if (socket
->m_server
)
2156 c
= kCFSocketReadCallBack
;
2158 c
= kCFSocketConnectCallBack
;
2163 c
= kCFSocketReadCallBack
;
2167 c
= kCFSocketWriteCallBack
;
2174 CFSocketEnableCallBacks(socket
->m_cfSocket
, c
);
2177 void _GSocket_Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
2182 case GSOCK_CONNECTION
:
2183 if (socket
->m_server
)
2184 c
= kCFSocketReadCallBack
;
2186 c
= kCFSocketConnectCallBack
;
2191 c
= kCFSocketReadCallBack
;
2195 c
= kCFSocketWriteCallBack
;
2203 CFSocketDisableCallBacks(socket
->m_cfSocket
, c
);
2206 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
2208 socket
->m_detected
&= ~(1 << event
);
2209 _GSocket_Install_Callback(socket
, event
);
2212 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
2214 socket
->m_detected
|= (1 << event
);
2215 _GSocket_Uninstall_Callback(socket
, event
);
2218 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
2219 CFDataRef address
, const void* data
, void* info
)
2221 GSocket
* socket
= (GSocket
*)info
;
2223 switch (callbackType
)
2225 case kCFSocketConnectCallBack
:
2228 SInt32 error
= *((SInt32
*)data
) ;
2229 CALL_CALLBACK( socket
, GSOCK_LOST
) ;
2230 GSocket_Shutdown(socket
);
2234 CALL_CALLBACK( socket
, GSOCK_CONNECTION
) ;
2238 case kCFSocketReadCallBack
:
2239 CALL_CALLBACK( socket
, GSOCK_INPUT
) ;
2242 case kCFSocketWriteCallBack
:
2243 CALL_CALLBACK( socket
, GSOCK_OUTPUT
) ;
2247 break; // We shouldn't get here.
2251 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
2255 assert(socket
!= NULL
);
2256 // if ( !CFReadStreamHasBytesAvailable() )
2257 ret
= CFReadStreamRead( socket
->m_readStream
, (UInt8
*) buffer
, size
) ;
2262 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
2266 assert(socket
!= NULL
);
2267 ret
= CFWriteStreamWrite( socket
->m_writeStream
, (UInt8
*) buffer
, size
) ;
2272 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
2274 assert( socket
!= NULL
);
2276 return flags
& socket
->m_detected
;
2279 // ==========================================================================
2281 // ==========================================================================
2283 class wxSocketModule
: public wxModule
2286 virtual bool OnInit()
2288 // wxSocketBase will call GSocket_Init() itself when/if needed
2292 virtual void OnExit()
2294 if ( wxSocketBase::IsInitialized() )
2295 wxSocketBase::Shutdown();
2299 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2302 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)