1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
6 // Copyright: (C) 1999-1997, Guilhem Lavaux
7 // (C) 2000-1999, Guillermo Rodriguez Garcia
9 // License: see wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ==========================================================================
14 // ==========================================================================
16 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
17 #pragma implementation "socket.h"
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
30 #include "wx/apptrait.h"
32 #include "wx/object.h"
33 #include "wx/string.h"
36 #include "wx/module.h"
41 #include "wx/sckaddr.h"
42 #include "wx/socket.h"
43 #include "wx/mac/carbon/private.h"
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
50 #define HAVE_INET_ATON
52 // DLL options compatibility check:
54 WX_CHECK_BUILD_OPTIONS("wxNet")
56 // --------------------------------------------------------------------------
57 // macros and constants
58 // --------------------------------------------------------------------------
61 #define MAX_DISCARD_SIZE (10 * 1024)
63 #ifndef INVALID_SOCKET
64 #define INVALID_SOCKET -1
67 // what to do within waits: we have 2 cases: from the main thread itself we
68 // have to call wxYield() to let the events (including the GUI events and the
69 // low-level (not wxWindows) events from GSocket) be processed. From another
70 // thread it is enough to just call wxThread::Yield() which will give away the
71 // rest of our time slice: the explanation is that the events will be processed
72 // by the main thread anyhow, without calling wxYield(), but we don't want to
73 // eat the CPU time uselessly while sitting in the loop waiting for the data
75 #define PROCESS_EVENTS() \
77 if ( wxThread::IsMain() ) \
82 #else // !wxUSE_THREADS
83 #define PROCESS_EVENTS() wxYield()
84 #endif // wxUSE_THREADS/!wxUSE_THREADS
86 #define wxTRACE_Socket _T("wxSocket")
88 // --------------------------------------------------------------------------
90 // --------------------------------------------------------------------------
92 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
93 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
94 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
95 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
96 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
98 // --------------------------------------------------------------------------
100 // --------------------------------------------------------------------------
102 class wxSocketState
: public wxObject
105 wxSocketFlags m_flags
;
106 wxSocketEventFlags m_eventmask
;
111 wxSocketState() : wxObject() {}
113 DECLARE_NO_COPY_CLASS(wxSocketState
)
118 CFSocketNativeHandle m_fd
;
121 GSocketError m_error
;
128 unsigned long m_timeout
;
132 GSocketEventFlags m_detected
;
133 GSocketCallback m_cbacks
[GSOCK_MAX_EVENT
];
134 char *m_data
[GSOCK_MAX_EVENT
];
136 CFSocketRef m_cfSocket
;
137 CFRunLoopSourceRef m_runLoopSource
;
138 CFReadStreamRef m_readStream
;
139 CFWriteStreamRef m_writeStream
;
144 struct sockaddr
*m_addr
;
147 GAddressType m_family
;
150 GSocketError m_error
;
154 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
155 CFDataRef address
, const void* data
, void* info
) ;
156 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
) ;
157 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
) ;
159 // ==========================================================================
161 // ==========================================================================
163 // --------------------------------------------------------------------------
164 // Initialization and shutdown
165 // --------------------------------------------------------------------------
167 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
168 // to m_countInit with a crit section
169 size_t wxSocketBase::m_countInit
= 0;
171 bool wxSocketBase::IsInitialized()
173 return m_countInit
> 0;
176 bool wxSocketBase::Initialize()
178 if ( !m_countInit
++ )
181 wxAppTraits
*traits
= wxAppConsole::GetInstance() ?
182 wxAppConsole::GetInstance()->GetTraits() : NULL
;
183 GSocketGUIFunctionsTable
*functions
=
184 traits
? traits
->GetSocketGUIFunctionsTable() : NULL
;
185 GSocket_SetGUIFunctions(functions
);
187 if ( !GSocket_Init() )
199 void wxSocketBase::Shutdown()
201 // we should be initialized
202 wxASSERT_MSG( m_countInit
, _T("extra call to Shutdown()") );
203 if ( !--m_countInit
)
211 // --------------------------------------------------------------------------
213 // --------------------------------------------------------------------------
215 void wxSocketBase::Init()
218 m_type
= wxSOCKET_UNINIT
;
229 m_beingDeleted
= FALSE
;
243 if ( !IsInitialized() )
245 // this Initialize() will be undone by wxSocketModule::OnExit(), all the
246 // other calls to it should be matched by a call to Shutdown()
251 wxSocketBase::wxSocketBase()
256 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
264 wxSocketBase::~wxSocketBase()
266 // Just in case the app called Destroy() *and* then deleted
267 // the socket immediately: don't leave dangling pointers.
268 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
270 traits
->RemoveFromPendingDelete(this);
272 // Shutdown and close the socket
276 // Destroy the GSocket object
279 GSocket_destroy(m_socket
);
282 // Free the pushback buffer
287 bool wxSocketBase::Destroy()
289 // Delayed destruction: the socket will be deleted during the next
290 // idle loop iteration. This ensures that all pending events have
292 m_beingDeleted
= TRUE
;
294 // Shutdown and close the socket
297 // Supress events from now on
300 // schedule this object for deletion
301 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
304 // let the traits object decide what to do with us
305 traits
->ScheduleForDestroy(this);
307 else // no app or no traits
309 // in wxBase we might have no app object at all, don't leak memory
316 // --------------------------------------------------------------------------
318 // --------------------------------------------------------------------------
320 // The following IO operations update m_error and m_lcount:
321 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
323 // TODO: Should Connect, Accept and AcceptWith update m_error?
325 bool wxSocketBase::Close()
327 // Interrupt pending waits
332 GSocket_Shutdown(m_socket
);
336 m_establishing
= FALSE
;
340 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
345 m_lcount
= _Read(buffer
, nbytes
);
347 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
348 if (m_flags
& wxSOCKET_WAITALL
)
349 m_error
= (m_lcount
!= nbytes
);
351 m_error
= (m_lcount
== 0);
353 // Allow read events from now on
359 wxUint32
wxSocketBase::_Read(void* buffer
, wxUint32 nbytes
)
363 // Try the pushback buffer first
364 total
= GetPushback(buffer
, nbytes
, FALSE
);
366 buffer
= (char *)buffer
+ total
;
368 // Return now in one of the following cases:
369 // - the socket is invalid,
370 // - we got all the data,
371 // - we got *some* data and we are not using wxSOCKET_WAITALL.
374 ((total
!= 0) && !(m_flags
& wxSOCKET_WAITALL
)) )
377 // Possible combinations (they are checked in this order)
379 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
385 if (m_flags
& wxSOCKET_NOWAIT
)
387 GSocket_SetNonBlocking(m_socket
, 1);
388 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
389 GSocket_SetNonBlocking(m_socket
, 0);
400 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForRead() )
403 ret
= GSocket_Read(m_socket
, (char *)buffer
, nbytes
);
409 buffer
= (char *)buffer
+ ret
;
412 // If we got here and wxSOCKET_WAITALL is not set, we can leave
413 // now. Otherwise, wait until we recv all the data or until there
416 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
423 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
425 wxUint32 len
, len2
, sig
, total
;
430 unsigned char sig
[4];
431 unsigned char len
[4];
440 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
442 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
445 sig
= (wxUint32
)msg
.sig
[0];
446 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
447 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
448 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
450 if (sig
!= 0xfeeddead)
452 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
456 len
= (wxUint32
)msg
.len
[0];
457 len
|= (wxUint32
)(msg
.len
[1] << 8);
458 len
|= (wxUint32
)(msg
.len
[2] << 16);
459 len
|= (wxUint32
)(msg
.len
[3] << 24);
469 // Don't attemp to read if the msg was zero bytes long.
472 total
= _Read(buffer
, len
);
479 char *discard_buffer
= new char[MAX_DISCARD_SIZE
];
482 // NOTE: discarded bytes don't add to m_lcount.
485 discard_len
= ((len2
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE
: len2
);
486 discard_len
= _Read(discard_buffer
, (wxUint32
)discard_len
);
487 len2
-= (wxUint32
)discard_len
;
489 while ((discard_len
> 0) && len2
);
491 delete [] discard_buffer
;
496 if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
))
499 sig
= (wxUint32
)msg
.sig
[0];
500 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
501 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
502 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
504 if (sig
!= 0xdeadfeed)
506 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
522 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
527 m_lcount
= _Read(buffer
, nbytes
);
528 Pushback(buffer
, m_lcount
);
530 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
531 if (m_flags
& wxSOCKET_WAITALL
)
532 m_error
= (m_lcount
!= nbytes
);
534 m_error
= (m_lcount
== 0);
536 // Allow read events again
542 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
547 m_lcount
= _Write(buffer
, nbytes
);
549 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
550 if (m_flags
& wxSOCKET_WAITALL
)
551 m_error
= (m_lcount
!= nbytes
);
553 m_error
= (m_lcount
== 0);
555 // Allow write events again
561 wxUint32
wxSocketBase::_Write(const void *buffer
, wxUint32 nbytes
)
565 // If the socket is invalid or parameters are ill, return immediately
566 if (!m_socket
|| !buffer
|| !nbytes
)
569 // Possible combinations (they are checked in this order)
571 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
576 if (m_flags
& wxSOCKET_NOWAIT
)
578 GSocket_SetNonBlocking(m_socket
, 1);
579 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
580 GSocket_SetNonBlocking(m_socket
, 0);
591 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForWrite() )
594 ret
= GSocket_Write(m_socket
, (const char *)buffer
, nbytes
);
600 buffer
= (const char *)buffer
+ ret
;
603 // If we got here and wxSOCKET_WAITALL is not set, we can leave
604 // now. Otherwise, wait until we send all the data or until there
607 more
= (ret
> 0 && nbytes
> 0 && (m_flags
& wxSOCKET_WAITALL
));
614 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
620 unsigned char sig
[4];
621 unsigned char len
[4];
629 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
631 msg
.sig
[0] = (unsigned char) 0xad;
632 msg
.sig
[1] = (unsigned char) 0xde;
633 msg
.sig
[2] = (unsigned char) 0xed;
634 msg
.sig
[3] = (unsigned char) 0xfe;
636 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
637 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
638 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
639 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
641 if (_Write(&msg
, sizeof(msg
)) < sizeof(msg
))
644 total
= _Write(buffer
, nbytes
);
649 msg
.sig
[0] = (unsigned char) 0xed;
650 msg
.sig
[1] = (unsigned char) 0xfe;
651 msg
.sig
[2] = (unsigned char) 0xad;
652 msg
.sig
[3] = (unsigned char) 0xde;
653 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
655 if ((_Write(&msg
, sizeof(msg
))) < sizeof(msg
))
669 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
672 Pushback(buffer
, nbytes
);
680 wxSocketBase
& wxSocketBase::Discard()
682 char *buffer
= new char[MAX_DISCARD_SIZE
];
689 SetFlags(wxSOCKET_NOWAIT
);
693 ret
= _Read(buffer
, MAX_DISCARD_SIZE
);
696 while (ret
== MAX_DISCARD_SIZE
);
702 // Allow read events again
708 // --------------------------------------------------------------------------
710 // --------------------------------------------------------------------------
712 // All Wait functions poll the socket using GSocket_Select() to
713 // check for the specified combination of conditions, until one
714 // of these conditions become true, an error occurs, or the
715 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
716 // this won't block the GUI.
718 bool wxSocketBase::_Wait(long seconds
,
720 wxSocketEventFlags flags
)
723 GSocketEventFlags result
;
726 // Set this to TRUE to interrupt ongoing waits
729 // Check for valid socket
733 // Check for valid timeout value.
735 timeout
= seconds
* 1000 + milliseconds
;
737 timeout
= m_timeout
* 1000;
739 #if !defined(wxUSE_GUI) || !wxUSE_GUI
740 GSocket_SetTimeout(m_socket
, timeout
);
743 // Wait in an active polling loop.
745 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
746 // hurt. It has to be here because the (GSocket) event might arrive
747 // a bit delayed, and it has to be in OnRequest as well because we
748 // don't know whether the Wait functions are being used.
750 // Do this at least once (important if timeout == 0, when
751 // we are just polling). Also, if just polling, do not yield.
758 result
= GSocket_Select(m_socket
, flags
| GSOCK_LOST_FLAG
);
760 // Incoming connection (server) or connection established (client)
761 if (result
& GSOCK_CONNECTION_FLAG
)
764 m_establishing
= FALSE
;
768 // Data available or output buffer ready
769 if ((result
& GSOCK_INPUT_FLAG
) || (result
& GSOCK_OUTPUT_FLAG
))
775 if (result
& GSOCK_LOST_FLAG
)
778 m_establishing
= FALSE
;
779 return (flags
& GSOCK_LOST_FLAG
) != 0;
783 if ((!timeout
) || (chrono
.Time() > timeout
) || (m_interrupt
))
792 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
794 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
796 GSOCK_CONNECTION_FLAG
|
800 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
802 // Check pushback buffer before entering _Wait
806 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
807 // _Wait becuase of the semantics of WaitForRead: a return
808 // value of TRUE means that a GSocket_Read call will return
809 // immediately, not that there is actually data to read.
811 return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG
|
815 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
817 return _Wait(seconds
, milliseconds
, GSOCK_OUTPUT_FLAG
);
820 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
822 return _Wait(seconds
, milliseconds
, GSOCK_LOST_FLAG
);
825 // --------------------------------------------------------------------------
827 // --------------------------------------------------------------------------
830 // Get local or peer address
833 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
840 peer
= GSocket_GetPeer(m_socket
);
842 // copying a null address would just trigger an assert anyway
847 addr_man
.SetAddress(peer
);
848 GAddress_destroy(peer
);
853 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
861 local
= GSocket_GetLocal(m_socket
);
862 addr_man
.SetAddress(local
);
863 GAddress_destroy(local
);
869 // Save and restore socket state
872 void wxSocketBase::SaveState()
874 wxSocketState
*state
;
876 state
= new wxSocketState();
878 state
->m_flags
= m_flags
;
879 state
->m_notify
= m_notify
;
880 state
->m_eventmask
= m_eventmask
;
881 state
->m_clientData
= m_clientData
;
883 m_states
.Append(state
);
886 void wxSocketBase::RestoreState()
888 wxList::compatibility_iterator node
;
889 wxSocketState
*state
;
891 node
= m_states
.GetLast();
895 state
= (wxSocketState
*)node
->GetData();
897 m_flags
= state
->m_flags
;
898 m_notify
= state
->m_notify
;
899 m_eventmask
= state
->m_eventmask
;
900 m_clientData
= state
->m_clientData
;
902 m_states
.Erase(node
);
910 void wxSocketBase::SetTimeout(long seconds
)
916 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
920 void wxSocketBase::SetFlags(wxSocketFlags flags
)
926 // --------------------------------------------------------------------------
928 // --------------------------------------------------------------------------
930 // A note on how events are processed, which is probably the most
931 // difficult thing to get working right while keeping the same API
932 // and functionality for all platforms.
934 // When GSocket detects an event, it calls wx_socket_callback, which in
935 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
936 // object. OnRequest does some housekeeping, and if the event is to be
937 // propagated to the user, it creates a new wxSocketEvent object and
938 // posts it. The event is not processed immediately, but delayed with
939 // AddPendingEvent instead. This is necessary in order to decouple the
940 // event processing from wx_socket_callback; otherwise, subsequent IO
941 // calls made from the user event handler would fail, as gtk callbacks
942 // are not reentrant.
944 // Note that, unlike events, user callbacks (now deprecated) are _not_
945 // decoupled from wx_socket_callback and thus they suffer from a variety
946 // of problems. Avoid them where possible and use events instead.
949 void LINKAGEMODE
wx_socket_callback(GSocket
* WXUNUSED(socket
),
950 GSocketEvent notification
,
953 wxSocketBase
*sckobj
= (wxSocketBase
*)cdata
;
955 sckobj
->OnRequest((wxSocketNotify
) notification
);
958 void wxSocketBase::OnRequest(wxSocketNotify notification
)
960 // NOTE: We duplicate some of the code in _Wait, but this doesn't
961 // hurt. It has to be here because the (GSocket) event might arrive
962 // a bit delayed, and it has to be in _Wait as well because we don't
963 // know whether the Wait functions are being used.
967 case wxSOCKET_CONNECTION
:
968 m_establishing
= FALSE
;
972 // If we are in the middle of a R/W operation, do not
973 // propagate events to users. Also, filter 'late' events
974 // which are no longer valid.
977 if (m_reading
|| !GSocket_Select(m_socket
, GSOCK_INPUT_FLAG
))
981 case wxSOCKET_OUTPUT
:
982 if (m_writing
|| !GSocket_Select(m_socket
, GSOCK_OUTPUT_FLAG
))
988 m_establishing
= FALSE
;
995 // Schedule the event
997 wxSocketEventFlags flag
= 0;
999 switch (notification
)
1001 case GSOCK_INPUT
: flag
= GSOCK_INPUT_FLAG
; break;
1002 case GSOCK_OUTPUT
: flag
= GSOCK_OUTPUT_FLAG
; break;
1003 case GSOCK_CONNECTION
: flag
= GSOCK_CONNECTION_FLAG
; break;
1004 case GSOCK_LOST
: flag
= GSOCK_LOST_FLAG
; break;
1006 wxLogWarning(_("wxSocket: unknown event!."));
1010 if (((m_eventmask
& flag
) == flag
) && m_notify
)
1014 wxSocketEvent
event(m_id
);
1015 event
.m_event
= notification
;
1016 event
.m_clientData
= m_clientData
;
1017 event
.SetEventObject(this);
1019 m_handler
->AddPendingEvent(event
);
1024 void wxSocketBase::Notify(bool notify
)
1029 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1031 m_eventmask
= flags
;
1034 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1036 m_handler
= &handler
;
1040 // --------------------------------------------------------------------------
1042 // --------------------------------------------------------------------------
1044 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1048 if (m_unread
== NULL
)
1049 m_unread
= malloc(size
);
1054 tmp
= malloc(m_unrd_size
+ size
);
1055 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1061 m_unrd_size
+= size
;
1063 memcpy(m_unread
, buffer
, size
);
1066 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1071 if (size
> (m_unrd_size
-m_unrd_cur
))
1072 size
= m_unrd_size
-m_unrd_cur
;
1074 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1079 if (m_unrd_size
== m_unrd_cur
)
1092 // ==========================================================================
1094 // ==========================================================================
1096 // --------------------------------------------------------------------------
1098 // --------------------------------------------------------------------------
1100 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1101 wxSocketFlags flags
)
1102 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1104 wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") );
1106 m_socket
= GSocket_new();
1110 wxLogTrace( wxTRACE_Socket
, _T("*** GSocket_new failed") );
1114 // Setup the socket as server
1117 GSocket_SetLocal(m_socket
, addr_man
.GetAddress());
1118 if (GSocket_SetServer(m_socket
) != GSOCK_NOERROR
)
1120 GSocket_destroy(m_socket
);
1123 wxLogTrace( wxTRACE_Socket
, _T("*** GSocket_SetServer failed") );
1127 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1128 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1129 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1130 wx_socket_callback
, (char *)this);
1134 // --------------------------------------------------------------------------
1136 // --------------------------------------------------------------------------
1138 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1140 GSocket
*child_socket
;
1145 // If wait == FALSE, then the call should be nonblocking.
1146 // When we are finished, we put the socket to blocking mode
1151 GSocket_SetNonBlocking(m_socket
, 1);
1153 child_socket
= GSocket_WaitConnection(m_socket
);
1156 GSocket_SetNonBlocking(m_socket
, 0);
1161 sock
.m_type
= wxSOCKET_BASE
;
1162 sock
.m_socket
= child_socket
;
1163 sock
.m_connected
= TRUE
;
1165 GSocket_SetTimeout(sock
.m_socket
, sock
.m_timeout
* 1000);
1166 GSocket_SetCallback(sock
.m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1167 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1168 wx_socket_callback
, (char *)&sock
);
1173 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1175 wxSocketBase
* sock
= new wxSocketBase();
1177 sock
->SetFlags(m_flags
);
1179 if (!AcceptWith(*sock
, wait
))
1188 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1190 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
);
1193 // ==========================================================================
1195 // ==========================================================================
1197 // --------------------------------------------------------------------------
1199 // --------------------------------------------------------------------------
1201 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1202 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1206 wxSocketClient::~wxSocketClient()
1210 // --------------------------------------------------------------------------
1212 // --------------------------------------------------------------------------
1214 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1220 // Shutdown and destroy the socket
1222 GSocket_destroy(m_socket
);
1225 m_socket
= GSocket_new();
1226 m_connected
= FALSE
;
1227 m_establishing
= FALSE
;
1232 GSocket_SetTimeout(m_socket
, m_timeout
* 1000);
1233 GSocket_SetCallback(m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1234 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1235 wx_socket_callback
, (char *)this);
1237 // If wait == FALSE, then the call should be nonblocking.
1238 // When we are finished, we put the socket to blocking mode
1242 GSocket_SetNonBlocking(m_socket
, 1);
1244 GSocket_SetPeer(m_socket
, addr_man
.GetAddress());
1245 err
= GSocket_Connect(m_socket
, GSOCK_STREAMED
);
1248 GSocket_SetNonBlocking(m_socket
, 0);
1250 if (err
!= GSOCK_NOERROR
)
1252 if (err
== GSOCK_WOULDBLOCK
)
1253 m_establishing
= TRUE
;
1262 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1264 if (m_connected
) // Already connected
1267 if (!m_establishing
|| !m_socket
) // No connection in progress
1270 return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
|
1274 // ==========================================================================
1276 // ==========================================================================
1278 /* NOTE: experimental stuff - might change */
1280 wxDatagramSocket::wxDatagramSocket( wxSockAddress
& addr
,
1281 wxSocketFlags flags
)
1282 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1285 // Create the socket
1286 m_socket
= GSocket_new();
1291 // Setup the socket as non connection oriented
1292 GSocket_SetLocal(m_socket
, addr
.GetAddress());
1293 if( GSocket_SetNonOriented(m_socket
) != GSOCK_NOERROR
)
1295 GSocket_destroy(m_socket
);
1300 // Initialize all stuff
1301 m_connected
= FALSE
;
1302 m_establishing
= FALSE
;
1303 GSocket_SetTimeout( m_socket
, m_timeout
);
1304 GSocket_SetCallback( m_socket
, GSOCK_INPUT_FLAG
| GSOCK_OUTPUT_FLAG
|
1305 GSOCK_LOST_FLAG
| GSOCK_CONNECTION_FLAG
,
1306 wx_socket_callback
, (char*)this );
1310 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1319 wxDatagramSocket
& wxDatagramSocket::SendTo( wxSockAddress
& addr
,
1323 GSocket_SetPeer(m_socket
, addr
.GetAddress());
1329 * -------------------------------------------------------------------------
1331 * -------------------------------------------------------------------------
1334 /* CHECK_ADDRESS verifies that the current address family is either
1335 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1336 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1337 * an appropiate error code.
1339 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1341 #define CHECK_ADDRESS(address, family) \
1343 if (address->m_family == GSOCK_NOFAMILY) \
1344 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1345 return address->m_error; \
1346 if (address->m_family != GSOCK_##family) \
1348 address->m_error = GSOCK_INVADDR; \
1349 return GSOCK_INVADDR; \
1353 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1355 if (address->m_family == GSOCK_NOFAMILY) \
1356 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1358 if (address->m_family != GSOCK_##family) \
1360 address->m_error = GSOCK_INVADDR; \
1366 GAddress
*GAddress_new(void)
1370 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1373 address
->m_family
= GSOCK_NOFAMILY
;
1374 address
->m_addr
= NULL
;
1380 GAddress
*GAddress_copy(GAddress
*address
)
1384 assert(address
!= NULL
);
1386 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1389 memcpy(addr2
, address
, sizeof(GAddress
));
1391 if (address
->m_addr
&& address
->m_len
> 0)
1393 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1394 if (addr2
->m_addr
== NULL
)
1399 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1405 void GAddress_destroy(GAddress
*address
)
1407 assert(address
!= NULL
);
1409 if (address
->m_addr
)
1410 free(address
->m_addr
);
1415 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1417 assert(address
!= NULL
);
1419 address
->m_family
= type
;
1422 GAddressType
GAddress_GetFamily(GAddress
*address
)
1424 assert(address
!= NULL
);
1426 return address
->m_family
;
1429 GSocketError
_GAddress_translate_from(GAddress
*address
,
1430 struct sockaddr
*addr
, int len
)
1432 address
->m_realfamily
= addr
->sa_family
;
1433 switch (addr
->sa_family
)
1436 address
->m_family
= GSOCK_INET
;
1439 address
->m_family
= GSOCK_UNIX
;
1443 address
->m_family
= GSOCK_INET6
;
1448 address
->m_error
= GSOCK_INVOP
;
1453 if (address
->m_addr
)
1454 free(address
->m_addr
);
1456 address
->m_len
= len
;
1457 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1459 if (address
->m_addr
== NULL
)
1461 address
->m_error
= GSOCK_MEMERR
;
1462 return GSOCK_MEMERR
;
1464 memcpy(address
->m_addr
, addr
, len
);
1466 return GSOCK_NOERROR
;
1469 GSocketError
_GAddress_translate_to(GAddress
*address
,
1470 struct sockaddr
**addr
, int *len
)
1472 if (!address
->m_addr
)
1474 address
->m_error
= GSOCK_INVADDR
;
1475 return GSOCK_INVADDR
;
1478 *len
= address
->m_len
;
1479 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1482 address
->m_error
= GSOCK_MEMERR
;
1483 return GSOCK_MEMERR
;
1486 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1487 return GSOCK_NOERROR
;
1491 * -------------------------------------------------------------------------
1492 * Internet address family
1493 * -------------------------------------------------------------------------
1496 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1498 address
->m_len
= sizeof(struct sockaddr_in
);
1499 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1500 if (address
->m_addr
== NULL
)
1502 address
->m_error
= GSOCK_MEMERR
;
1503 return GSOCK_MEMERR
;
1506 memset( address
->m_addr
, 0 , address
->m_len
) ;
1507 address
->m_family
= GSOCK_INET
;
1508 address
->m_realfamily
= PF_INET
;
1509 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1510 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1512 return GSOCK_NOERROR
;
1515 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1518 struct in_addr
*addr
;
1520 assert(address
!= NULL
);
1522 CHECK_ADDRESS(address
, INET
);
1524 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1526 /* If it is a numeric host name, convert it now */
1527 #if defined(HAVE_INET_ATON)
1528 if (inet_aton(hostname
, addr
) == 0)
1530 #elif defined(HAVE_INET_ADDR)
1531 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1534 /* Use gethostbyname by default */
1536 int val
= 1; /* VA doesn't like constants in conditional expressions */
1541 struct in_addr
*array_addr
;
1543 /* It is a real name, we solve it */
1544 if ((he
= gethostbyname(hostname
)) == NULL
)
1546 /* Reset to invalid address */
1547 addr
->s_addr
= INADDR_NONE
;
1548 address
->m_error
= GSOCK_NOHOST
;
1549 return GSOCK_NOHOST
;
1551 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1552 addr
->s_addr
= array_addr
[0].s_addr
;
1554 return GSOCK_NOERROR
;
1557 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1559 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1562 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1563 unsigned long hostaddr
)
1565 struct in_addr
*addr
;
1567 assert(address
!= NULL
);
1569 CHECK_ADDRESS(address
, INET
);
1571 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1572 addr
->s_addr
= htonl(hostaddr
) ;
1574 return GSOCK_NOERROR
;
1577 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1578 const char *protocol
)
1581 struct sockaddr_in
*addr
;
1583 assert(address
!= NULL
);
1584 CHECK_ADDRESS(address
, INET
);
1588 address
->m_error
= GSOCK_INVPORT
;
1589 return GSOCK_INVPORT
;
1592 se
= getservbyname(port
, protocol
);
1595 /* the cast to int suppresses compiler warnings about subscript having the
1597 if (isdigit((int)port
[0]))
1601 port_int
= atoi(port
);
1602 addr
= (struct sockaddr_in
*)address
->m_addr
;
1603 addr
->sin_port
= htons(port_int
);
1604 return GSOCK_NOERROR
;
1607 address
->m_error
= GSOCK_INVPORT
;
1608 return GSOCK_INVPORT
;
1611 addr
= (struct sockaddr_in
*)address
->m_addr
;
1612 addr
->sin_port
= se
->s_port
;
1614 return GSOCK_NOERROR
;
1617 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1619 struct sockaddr_in
*addr
;
1621 assert(address
!= NULL
);
1622 CHECK_ADDRESS(address
, INET
);
1624 addr
= (struct sockaddr_in
*)address
->m_addr
;
1625 addr
->sin_port
= htons(port
);
1627 return GSOCK_NOERROR
;
1630 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1634 struct sockaddr_in
*addr
;
1636 assert(address
!= NULL
);
1637 CHECK_ADDRESS(address
, INET
);
1639 addr
= (struct sockaddr_in
*)address
->m_addr
;
1640 addr_buf
= (char *)&(addr
->sin_addr
);
1642 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1645 address
->m_error
= GSOCK_NOHOST
;
1646 return GSOCK_NOHOST
;
1649 strncpy(hostname
, he
->h_name
, sbuf
);
1651 return GSOCK_NOERROR
;
1654 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1656 struct sockaddr_in
*addr
;
1658 assert(address
!= NULL
);
1659 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1661 addr
= (struct sockaddr_in
*)address
->m_addr
;
1663 return ntohl(addr
->sin_addr
.s_addr
) ;
1666 unsigned short GAddress_INET_GetPort(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
;
1674 return ntohs(addr
->sin_port
);
1678 * -------------------------------------------------------------------------
1679 * Unix address family
1680 * -------------------------------------------------------------------------
1683 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1685 address
->m_len
= sizeof(struct sockaddr_un
);
1686 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1687 if (address
->m_addr
== NULL
)
1689 address
->m_error
= GSOCK_MEMERR
;
1690 return GSOCK_MEMERR
;
1693 address
->m_family
= GSOCK_UNIX
;
1694 address
->m_realfamily
= PF_UNIX
;
1695 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1696 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1698 return GSOCK_NOERROR
;
1701 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1703 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1705 struct sockaddr_un
*addr
;
1707 assert(address
!= NULL
);
1709 CHECK_ADDRESS(address
, UNIX
);
1711 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1712 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1713 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1715 return GSOCK_NOERROR
;
1718 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1720 struct sockaddr_un
*addr
;
1722 assert(address
!= NULL
);
1723 CHECK_ADDRESS(address
, UNIX
);
1725 addr
= (struct sockaddr_un
*)address
->m_addr
;
1727 strncpy(path
, addr
->sun_path
, sbuf
);
1729 return GSOCK_NOERROR
;
1732 /* Address handling */
1734 /* GSocket_SetLocal:
1738 * Set or get the local or peer address for this socket. The 'set'
1739 * functions return GSOCK_NOERROR on success, an error code otherwise.
1740 * The 'get' functions return a pointer to a GAddress object on success,
1741 * or NULL otherwise, in which case they set the error code of the
1742 * corresponding GSocket.
1745 * GSOCK_INVSOCK - the socket is not valid.
1746 * GSOCK_INVADDR - the address is not valid.
1749 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
1751 assert(socket
!= NULL
);
1753 /* the socket must be initialized, or it must be a server */
1754 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
1756 socket
->m_error
= GSOCK_INVSOCK
;
1757 return GSOCK_INVSOCK
;
1761 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1763 socket
->m_error
= GSOCK_INVADDR
;
1764 return GSOCK_INVADDR
;
1767 if (socket
->m_local
)
1768 GAddress_destroy(socket
->m_local
);
1770 socket
->m_local
= GAddress_copy(address
);
1772 return GSOCK_NOERROR
;
1775 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
1777 assert(socket
!= NULL
);
1780 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
1782 socket
->m_error
= GSOCK_INVADDR
;
1783 return GSOCK_INVADDR
;
1787 GAddress_destroy(socket
->m_peer
);
1789 socket
->m_peer
= GAddress_copy(address
);
1791 return GSOCK_NOERROR
;
1794 GAddress
*GSocket_GetLocal(GSocket
*socket
)
1797 struct sockaddr addr
;
1798 socklen_t size
= sizeof(addr
);
1801 assert(socket
!= NULL
);
1803 /* try to get it from the m_local var first */
1804 if (socket
->m_local
)
1805 return GAddress_copy(socket
->m_local
);
1807 /* else, if the socket is initialized, try getsockname */
1808 if (socket
->m_fd
== INVALID_SOCKET
)
1810 socket
->m_error
= GSOCK_INVSOCK
;
1814 if (getsockname(socket
->m_fd
, &addr
, (socklen_t
*) &size
) < 0)
1816 socket
->m_error
= GSOCK_IOERR
;
1820 /* got a valid address from getsockname, create a GAddress object */
1821 address
= GAddress_new();
1822 if (address
== NULL
)
1824 socket
->m_error
= GSOCK_MEMERR
;
1828 err
= _GAddress_translate_from(address
, &addr
, size
);
1829 if (err
!= GSOCK_NOERROR
)
1831 GAddress_destroy(address
);
1832 socket
->m_error
= err
;
1839 GAddress
*GSocket_GetPeer(GSocket
*socket
)
1841 assert(socket
!= NULL
);
1843 /* try to get it from the m_peer var */
1845 return GAddress_copy(socket
->m_peer
);
1855 GSocket
*GSocket_new(void)
1858 socket
= (GSocket
*)malloc(sizeof(GSocket
));
1863 socket
->m_fd
= INVALID_SOCKET
;
1865 for (int i
=0;i
<GSOCK_MAX_EVENT
;i
++)
1867 socket
->m_cbacks
[i
] = NULL
;
1869 socket
->m_detected
= 0;
1871 socket
->m_local
= NULL
;
1872 socket
->m_peer
= NULL
;
1873 socket
->m_error
= GSOCK_NOERROR
;
1875 socket
->m_non_blocking
= FALSE
;
1876 socket
->m_stream
= TRUE
;
1877 // socket->m_oriented = TRUE;
1878 socket
->m_server
= FALSE
;
1879 socket
->m_establishing
= FALSE
;
1880 socket
->m_timeout
= 10*60*1000;
1881 /* 10 minutes * 60 sec * 1000 millisec */
1883 socket
->m_cfSocket
= NULL
;
1884 socket
->m_runLoopSource
= NULL
;
1885 socket
->m_readStream
= NULL
;
1886 socket
->m_writeStream
= NULL
;
1891 void GSocket_close(GSocket
*socket
)
1893 if ( socket
->m_cfSocket
!= NULL
)
1895 if ( socket
->m_readStream
)
1897 CFReadStreamClose(socket
->m_readStream
);
1898 CFRelease( socket
->m_readStream
) ;
1899 socket
->m_readStream
= NULL
;
1901 if ( socket
->m_writeStream
)
1903 CFWriteStreamClose(socket
->m_writeStream
);
1904 CFRelease( socket
->m_writeStream
) ;
1905 socket
->m_writeStream
= NULL
;
1908 CFSocketInvalidate( socket
->m_cfSocket
) ;
1909 CFRelease( socket
->m_cfSocket
) ;
1910 socket
->m_cfSocket
= NULL
;
1911 socket
->m_fd
= INVALID_SOCKET
;
1915 void GSocket_Shutdown(GSocket
*socket
)
1917 GSocket_close( socket
) ;
1919 /* Disable GUI callbacks */
1920 for (int evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
1921 socket
->m_cbacks
[evt
] = NULL
;
1923 socket
->m_detected
= GSOCK_LOST_FLAG
;
1926 void GSocket_destroy(GSocket
*socket
)
1928 assert(socket
!= NULL
);
1930 /* Check that the socket is really shutdowned */
1931 if (socket
->m_fd
!= INVALID_SOCKET
)
1932 GSocket_Shutdown(socket
);
1934 /* Destroy private addresses */
1935 if (socket
->m_local
)
1936 GAddress_destroy(socket
->m_local
);
1939 GAddress_destroy(socket
->m_peer
);
1941 /* Destroy the socket itself */
1945 GSocketError
GSocket_Connect(GSocket
*socket
, GSocketStream stream
)
1947 assert(socket
!= NULL
);
1949 if (socket
->m_fd
!= INVALID_SOCKET
)
1951 socket
->m_error
= GSOCK_INVSOCK
;
1952 return GSOCK_INVSOCK
;
1955 if (!socket
->m_peer
)
1957 socket
->m_error
= GSOCK_INVADDR
;
1958 return GSOCK_INVADDR
;
1961 /* Streamed or dgram socket? */
1962 socket
->m_stream
= (stream
== GSOCK_STREAMED
);
1963 socket
->m_oriented
= TRUE
;
1964 socket
->m_server
= FALSE
;
1965 socket
->m_establishing
= FALSE
;
1967 GSocketError returnErr
= GSOCK_NOERROR
;
1970 CFAllocatorRef alloc
= kCFAllocatorDefault
;
1971 CFSocketContext ctx
;
1972 memset( &ctx
, 0 , sizeof( ctx
) ) ;
1974 socket
->m_cfSocket
= CFSocketCreate( alloc
, socket
->m_peer
->m_realfamily
,
1975 stream
== GSOCK_STREAMED
? SOCK_STREAM
: SOCK_DGRAM
, 0 ,
1976 kCFSocketReadCallBack
| kCFSocketWriteCallBack
| kCFSocketConnectCallBack
, wxMacCFSocketCallback
, &ctx
) ;
1977 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
1979 socket
->m_fd
= CFSocketGetNative( socket
->m_cfSocket
) ;
1981 CFStreamCreatePairWithSocket ( alloc
, socket
->m_fd
, &socket
->m_readStream
, &socket
->m_writeStream
);
1982 if ((socket
->m_readStream
== NULL
) || (socket
->m_writeStream
== NULL
))
1984 GSocket_close(socket
);
1985 socket
->m_error
= GSOCK_IOERR
;
1989 if ( !CFReadStreamOpen( socket
->m_readStream
) || !CFWriteStreamOpen( socket
->m_writeStream
) )
1991 GSocket_close(socket
);
1992 socket
->m_error
= GSOCK_IOERR
;
1996 CFRunLoopSourceRef rls
= CFSocketCreateRunLoopSource(alloc
, socket
->m_cfSocket
, 0);
1997 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls
, kCFRunLoopCommonModes
);
2000 CFDataRef address
= CFDataCreateWithBytesNoCopy(alloc
, (const UInt8
*) socket
->m_peer
->m_addr
, socket
->m_peer
->m_len
, kCFAllocatorNull
);
2002 return GSOCK_MEMERR
;
2004 err
= CFSocketConnectToAddress( socket
->m_cfSocket
, address
, socket
->m_non_blocking
? -1 : socket
->m_timeout
/ 1000 ) ;
2007 if (err
!= kCFSocketSuccess
)
2009 if ( err
== kCFSocketTimeout
)
2011 GSocket_close(socket
);
2012 socket
->m_error
= GSOCK_TIMEDOUT
;
2013 return GSOCK_TIMEDOUT
;
2015 // we don't know whether a connect in progress will be issued like this
2016 if ( err
!= kCFSocketTimeout
&& socket
->m_non_blocking
)
2018 socket
->m_establishing
= TRUE
;
2019 socket
->m_error
= GSOCK_WOULDBLOCK
;
2020 return GSOCK_WOULDBLOCK
;
2023 GSocket_close(socket
);
2024 socket
->m_error
= GSOCK_IOERR
;
2028 return GSOCK_NOERROR
;
2033 /* GSocket_SetNonBlocking:
2034 * Sets the socket to non-blocking mode. All IO calls will return
2037 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
2039 assert(socket
!= NULL
);
2041 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2043 socket
->m_non_blocking
= non_block
;
2046 /* GSocket_SetTimeout:
2047 * Sets the timeout for blocking calls. Time is expressed in
2050 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
2052 assert(socket
!= NULL
);
2054 socket
->m_timeout
= millisec
;
2057 /* GSocket_GetError:
2058 * Returns the last error occured for this socket. Note that successful
2059 * operations do not clear this back to GSOCK_NOERROR, so use it only
2062 GSocketError
GSocket_GetError(GSocket
*socket
)
2064 assert(socket
!= NULL
);
2066 return socket
->m_error
;
2072 * There is data to be read in the input buffer. If, after a read
2073 * operation, there is still data available, the callback function will
2076 * The socket is available for writing. That is, the next write call
2077 * won't block. This event is generated only once, when the connection is
2078 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2079 * when the output buffer empties again. This means that the app should
2080 * assume that it can write since the first OUTPUT event, and no more
2081 * OUTPUT events will be generated unless an error occurs.
2083 * Connection succesfully established, for client sockets, or incoming
2084 * client connection, for server sockets. Wait for this event (also watch
2085 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2087 * The connection is lost (or a connection request failed); this could
2088 * be due to a failure, or due to the peer closing it gracefully.
2091 /* GSocket_SetCallback:
2092 * Enables the callbacks specified by 'flags'. Note that 'flags'
2093 * may be a combination of flags OR'ed toghether, so the same
2094 * callback function can be made to accept different events.
2095 * The callback function must have the following prototype:
2097 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2099 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
2100 GSocketCallback callback
, char *cdata
)
2104 assert(socket
!= NULL
);
2106 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2108 if ((flags
& (1 << count
)) != 0)
2110 socket
->m_cbacks
[count
] = callback
;
2111 socket
->m_data
[count
] = cdata
;
2116 /* GSocket_UnsetCallback:
2117 * Disables all callbacks specified by 'flags', which may be a
2118 * combination of flags OR'ed toghether.
2120 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
2124 assert(socket
!= NULL
);
2126 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
2128 if ((flags
& (1 << count
)) != 0)
2130 socket
->m_cbacks
[count
] = NULL
;
2131 socket
->m_data
[count
] = NULL
;
2137 #define CALL_CALLBACK(socket, event) { \
2138 _GSocket_Disable(socket, event); \
2139 if (socket->m_cbacks[event]) \
2140 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2143 void _GSocket_Install_Callback(GSocket
*socket
, GSocketEvent event
)
2148 case GSOCK_CONNECTION
:
2149 if(socket
->m_server
)
2150 c
= kCFSocketReadCallBack
;
2152 c
= kCFSocketConnectCallBack
;
2156 c
= kCFSocketReadCallBack
;
2159 c
= kCFSocketWriteCallBack
;
2164 CFSocketEnableCallBacks(socket
->m_cfSocket
, c
);
2167 void _GSocket_Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
2172 case GSOCK_CONNECTION
:
2173 if(socket
->m_server
)
2174 c
= kCFSocketReadCallBack
;
2176 c
= kCFSocketConnectCallBack
;
2180 c
= kCFSocketReadCallBack
;
2183 c
= kCFSocketWriteCallBack
;
2188 CFSocketDisableCallBacks(socket
->m_cfSocket
, c
);
2191 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
2193 socket
->m_detected
&= ~(1 << event
);
2194 _GSocket_Install_Callback(socket
, event
);
2197 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
2199 socket
->m_detected
|= (1 << event
);
2200 _GSocket_Uninstall_Callback(socket
, event
);
2203 void wxMacCFSocketCallback(CFSocketRef s
, CFSocketCallBackType callbackType
,
2204 CFDataRef address
, const void* data
, void* info
)
2206 GSocket
* socket
= (GSocket
*)info
;
2208 switch (callbackType
)
2210 case kCFSocketConnectCallBack
:
2213 SInt32 error
= *((SInt32
*)data
) ;
2214 CALL_CALLBACK( socket
, GSOCK_LOST
) ;
2215 GSocket_Shutdown(socket
);
2219 CALL_CALLBACK( socket
, GSOCK_CONNECTION
) ;
2222 case kCFSocketReadCallBack
:
2223 CALL_CALLBACK( socket
, GSOCK_INPUT
) ;
2225 case kCFSocketWriteCallBack
:
2226 CALL_CALLBACK( socket
, GSOCK_OUTPUT
) ;
2229 break; /* We shouldn't get here. */
2233 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
2237 assert(socket
!= NULL
);
2238 // if ( !CFReadStreamHasBytesAvailable() )
2239 ret
= CFReadStreamRead( socket
->m_readStream
, (UInt8
*) buffer
, size
) ;
2244 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
2248 assert(socket
!= NULL
);
2249 ret
= CFWriteStreamWrite( socket
->m_writeStream
, (UInt8
*) buffer
, size
) ;
2253 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
2255 assert(socket
!= NULL
);
2256 return flags
& socket
->m_detected
;
2259 // ==========================================================================
2261 // ==========================================================================
2263 class wxSocketModule
: public wxModule
2266 virtual bool OnInit()
2268 // wxSocketBase will call GSocket_Init() itself when/if needed
2272 virtual void OnExit()
2274 if ( wxSocketBase::IsInitialized() )
2275 wxSocketBase::Shutdown();
2279 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2282 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)