1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/socket.cpp
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
6 // Copyright: (C) 1999-1997, Guilhem Lavaux
7 // (C) 1999-2000, Guillermo Rodriguez Garcia
8 // (C) 2008 Vadim Zeitlin
10 // License: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 // ==========================================================================
15 // ==========================================================================
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
26 #include "wx/socket.h"
29 #include "wx/object.h"
30 #include "wx/string.h"
37 #include "wx/module.h"
40 #include "wx/apptrait.h"
41 #include "wx/sckaddr.h"
42 #include "wx/stopwatch.h"
43 #include "wx/thread.h"
44 #include "wx/evtloop.h"
46 #include "wx/private/fd.h"
47 #include "wx/private/socket.h"
49 // DLL options compatibility check:
51 WX_CHECK_BUILD_OPTIONS("wxNet")
53 // --------------------------------------------------------------------------
54 // macros and constants
55 // --------------------------------------------------------------------------
58 #define MAX_DISCARD_SIZE (10 * 1024)
60 #define wxTRACE_Socket _T("wxSocket")
62 // --------------------------------------------------------------------------
64 // --------------------------------------------------------------------------
66 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
67 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
68 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
69 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
70 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
72 // --------------------------------------------------------------------------
74 // --------------------------------------------------------------------------
76 class wxSocketState
: public wxObject
79 wxSocketFlags m_flags
;
80 wxSocketEventFlags m_eventmask
;
85 wxSocketState() : wxObject() {}
87 DECLARE_NO_COPY_CLASS(wxSocketState
)
90 // Conditionally make the socket non-blocking for the lifetime of this object.
91 class wxSocketUnblocker
94 wxSocketUnblocker(wxSocketImpl
*socket
, bool unblock
= true)
99 m_impl
->SetNonBlocking(true);
105 m_impl
->SetNonBlocking(false);
109 wxSocketImpl
* const m_impl
;
112 DECLARE_NO_COPY_CLASS(wxSocketUnblocker
)
115 // ============================================================================
117 // ============================================================================
119 wxSocketManager
*wxSocketManager::ms_manager
= NULL
;
122 void wxSocketManager::Set(wxSocketManager
*manager
)
124 wxASSERT_MSG( !ms_manager
, "too late to set manager now" );
126 ms_manager
= manager
;
130 void wxSocketManager::Init()
132 wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" );
135 Details: Initialize() creates a hidden window as a sink for socket
136 events, such as 'read completed'. wxMSW has only one message loop
137 for the main thread. If Initialize is called in a secondary thread,
138 the socket window will be created for the secondary thread, but
139 since there is no message loop on this thread, it will never
140 receive events and all socket operations will time out.
141 BTW, the main thread must not be stopped using sleep or block
142 on a semaphore (a bad idea in any case) or socket operations
145 On the Mac side, Initialize() stores a pointer to the CFRunLoop for
146 the main thread. Because secondary threads do not have run loops,
147 adding event notifications to the "Current" loop would have no
148 effect at all, events would never fire.
150 wxASSERT_MSG( wxIsMainThread(),
151 "sockets must be initialized from the main thread" );
153 wxAppConsole
* const app
= wxAppConsole::GetInstance();
154 wxCHECK_RET( app
, "sockets can't be initialized without wxApp" );
156 ms_manager
= app
->GetTraits()->GetSocketManager();
159 // ==========================================================================
161 // ==========================================================================
163 wxSocketImpl::wxSocketImpl(wxSocketBase
& wxsocket
)
164 : m_wxsocket(&wxsocket
)
166 m_fd
= INVALID_SOCKET
;
170 m_error
= wxSOCKET_NOERROR
;
173 m_non_blocking
= false;
175 SetTimeout(wxsocket
.GetTimeout() * 1000);
177 m_establishing
= false;
181 m_initialRecvBufferSize
= -1;
182 m_initialSendBufferSize
= -1;
185 wxSocketImpl::~wxSocketImpl()
187 if (m_fd
!= INVALID_SOCKET
)
191 GAddress_destroy(m_local
);
194 GAddress_destroy(m_peer
);
197 bool wxSocketImpl::PreCreateCheck(GAddress
*addr
)
199 if ( m_fd
!= INVALID_SOCKET
)
201 m_error
= wxSOCKET_INVSOCK
;
205 if ( !addr
|| !addr
->m_addr
)
207 m_error
= wxSOCKET_INVADDR
;
214 void wxSocketImpl::PostCreation()
216 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
218 EnableSocketOption(SO_NOSIGPIPE
);
222 EnableSocketOption(SO_REUSEADDR
);
226 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
228 EnableSocketOption(SO_BROADCAST
);
231 if ( m_initialRecvBufferSize
>= 0 )
232 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
233 if ( m_initialSendBufferSize
>= 0 )
234 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
236 // FIXME: shouldn't we check for m_non_blocking here? as it is now, all our
237 // sockets are non-blocking
238 UnblockAndRegisterWithEventLoop();
241 wxSocketError
wxSocketImpl::UpdateLocalAddress()
243 WX_SOCKLEN_T lenAddr
;
244 if ( getsockname(m_fd
, m_local
->m_addr
, &lenAddr
) != 0 )
247 m_error
= wxSOCKET_IOERR
;
251 m_local
->m_len
= lenAddr
;
253 return wxSOCKET_NOERROR
;
256 wxSocketError
wxSocketImpl::CreateServer()
258 if ( !PreCreateCheck(m_local
) )
264 // do create the socket
265 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
267 if ( m_fd
== INVALID_SOCKET
)
269 m_error
= wxSOCKET_IOERR
;
270 return wxSOCKET_IOERR
;
275 // and then bind to and listen on it
277 // FIXME: should we test for m_dobind here?
278 if ( bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0 )
279 m_error
= wxSOCKET_IOERR
;
283 if ( listen(m_fd
, 5) != 0 )
284 m_error
= wxSOCKET_IOERR
;
293 // finally retrieve the address we effectively bound to
294 return UpdateLocalAddress();
297 wxSocketError
wxSocketImpl::CreateClient()
299 if ( !PreCreateCheck(m_peer
) )
302 m_fd
= socket(m_peer
->m_realfamily
, SOCK_STREAM
, 0);
304 if ( m_fd
== INVALID_SOCKET
)
306 m_error
= wxSOCKET_IOERR
;
307 return wxSOCKET_IOERR
;
312 // If a local address has been set, then bind to it before calling connect
313 if ( m_local
&& m_local
->m_addr
)
315 if ( bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0 )
318 m_error
= wxSOCKET_IOERR
;
323 // Connect to the peer and handle the EWOULDBLOCK return value in
324 // platform-specific code
325 return DoHandleConnect(connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
));
329 wxSocketError
wxSocketImpl::CreateUDP()
331 if ( !PreCreateCheck(m_local
) )
337 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
339 if ( m_fd
== INVALID_SOCKET
)
341 m_error
= wxSOCKET_IOERR
;
342 return wxSOCKET_IOERR
;
349 if ( bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0 )
352 m_error
= wxSOCKET_IOERR
;
356 return UpdateLocalAddress();
359 return wxSOCKET_NOERROR
;
363 void wxSocketImpl::Close()
365 if ( m_fd
!= INVALID_SOCKET
)
368 m_fd
= INVALID_SOCKET
;
373 * Disallow further read/write operations on this socket, close
374 * the fd and disable all callbacks.
376 void wxSocketImpl::Shutdown()
378 if ( m_fd
!= INVALID_SOCKET
)
380 shutdown(m_fd
, 1 /* SD_SEND */);
384 m_detected
= wxSOCKET_LOST_FLAG
;
388 * Sets the timeout for blocking calls. Time is expressed in
391 void wxSocketImpl::SetTimeout(unsigned long millis
)
393 m_timeout
.tv_sec
= (millis
/ 1000);
394 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
397 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
399 m_wxsocket
->OnRequest(event
);
402 /* Address handling */
405 * Set or get the local or peer address for this socket. The 'set'
406 * functions return wxSOCKET_NOERROR on success, an error code otherwise.
407 * The 'get' functions return a pointer to a GAddress object on success,
408 * or NULL otherwise, in which case they set the error code of the
409 * corresponding socket.
412 * wxSOCKET_INVSOCK - the socket is not valid.
413 * wxSOCKET_INVADDR - the address is not valid.
415 wxSocketError
wxSocketImpl::SetLocal(GAddress
*address
)
417 /* the socket must be initialized, or it must be a server */
418 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
420 m_error
= wxSOCKET_INVSOCK
;
421 return wxSOCKET_INVSOCK
;
425 if (address
== NULL
|| address
->m_family
== wxSOCKET_NOFAMILY
)
427 m_error
= wxSOCKET_INVADDR
;
428 return wxSOCKET_INVADDR
;
432 GAddress_destroy(m_local
);
434 m_local
= GAddress_copy(address
);
436 return wxSOCKET_NOERROR
;
439 wxSocketError
wxSocketImpl::SetPeer(GAddress
*address
)
442 if (address
== NULL
|| address
->m_family
== wxSOCKET_NOFAMILY
)
444 m_error
= wxSOCKET_INVADDR
;
445 return wxSOCKET_INVADDR
;
449 GAddress_destroy(m_peer
);
451 m_peer
= GAddress_copy(address
);
453 return wxSOCKET_NOERROR
;
456 GAddress
*wxSocketImpl::GetLocal()
460 WX_SOCKLEN_T size
= sizeof(addr
);
463 /* try to get it from the m_local var first */
465 return GAddress_copy(m_local
);
467 /* else, if the socket is initialized, try getsockname */
468 if (m_fd
== INVALID_SOCKET
)
470 m_error
= wxSOCKET_INVSOCK
;
474 if (getsockname(m_fd
, (sockaddr
*)&addr
, &size
) == SOCKET_ERROR
)
476 m_error
= wxSOCKET_IOERR
;
480 /* got a valid address from getsockname, create a GAddress object */
481 if ((address
= GAddress_new()) == NULL
)
483 m_error
= wxSOCKET_MEMERR
;
487 if ((err
= _GAddress_translate_from(address
, (sockaddr
*)&addr
, size
)) != wxSOCKET_NOERROR
)
489 GAddress_destroy(address
);
497 GAddress
*wxSocketImpl::GetPeer()
499 /* try to get it from the m_peer var */
501 return GAddress_copy(m_peer
);
506 // ==========================================================================
508 // ==========================================================================
510 // --------------------------------------------------------------------------
511 // Initialization and shutdown
512 // --------------------------------------------------------------------------
514 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
515 // to m_countInit with a crit section
516 size_t wxSocketBase::m_countInit
= 0;
518 bool wxSocketBase::IsInitialized()
520 return m_countInit
> 0;
523 bool wxSocketBase::Initialize()
525 if ( !m_countInit
++ )
527 wxSocketManager
* const manager
= wxSocketManager::Get();
528 if ( !manager
|| !manager
->OnInit() )
539 void wxSocketBase::Shutdown()
541 // we should be initialized
542 wxASSERT_MSG( m_countInit
> 0, _T("extra call to Shutdown()") );
543 if ( --m_countInit
== 0 )
545 wxSocketManager
* const manager
= wxSocketManager::Get();
546 wxCHECK_RET( manager
, "should have a socket manager" );
552 // --------------------------------------------------------------------------
554 // --------------------------------------------------------------------------
556 void wxSocketBase::Init()
559 m_type
= wxSOCKET_UNINIT
;
571 m_beingDeleted
= false;
585 if ( !IsInitialized() )
587 // this Initialize() will be undone by wxSocketModule::OnExit(), all
588 // the other calls to it should be matched by a call to Shutdown()
593 wxSocketBase::wxSocketBase()
598 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
607 wxSocketBase::~wxSocketBase()
609 // Just in case the app called Destroy() *and* then deleted the socket
610 // immediately: don't leave dangling pointers.
611 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
613 traits
->RemoveFromPendingDelete(this);
615 // Shutdown and close the socket
619 // Destroy the implementation object
622 // Free the pushback buffer
627 bool wxSocketBase::Destroy()
629 // Delayed destruction: the socket will be deleted during the next idle
630 // loop iteration. This ensures that all pending events have been
632 m_beingDeleted
= true;
634 // Shutdown and close the socket
637 // Supress events from now on
640 // schedule this object for deletion
641 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
644 // let the traits object decide what to do with us
645 traits
->ScheduleForDestroy(this);
647 else // no app or no traits
649 // in wxBase we might have no app object at all, don't leak memory
656 // ----------------------------------------------------------------------------
658 // ----------------------------------------------------------------------------
660 wxSocketError
wxSocketBase::LastError() const
662 return m_impl
->GetError();
665 // --------------------------------------------------------------------------
667 // --------------------------------------------------------------------------
669 // The following IO operations update m_error and m_lcount:
670 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
672 // TODO: Should Connect, Accept and AcceptWith update m_error?
674 bool wxSocketBase::Close()
676 // Interrupt pending waits
683 m_establishing
= false;
687 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
692 m_lcount
= DoRead(buffer
, nbytes
);
694 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
695 if (m_flags
& wxSOCKET_WAITALL
)
696 m_error
= (m_lcount
!= nbytes
);
698 m_error
= (m_lcount
== 0);
700 // Allow read events from now on
706 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
708 // We use pointer arithmetic here which doesn't work with void pointers.
709 char *buffer
= static_cast<char *>(buffer_
);
711 // Try the push back buffer first, even before checking whether the socket
712 // is valid to allow reading previously pushed back data from an already
714 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
718 // If it's indeed closed or if read everything, there is nothing more to do.
719 if ( !m_impl
|| !nbytes
)
722 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
725 // wxSOCKET_NOWAIT overrides all the other flags and means that we are
726 // polling the socket and don't block at all.
727 if ( m_flags
& wxSOCKET_NOWAIT
)
729 wxSocketUnblocker
unblock(m_impl
);
730 int ret
= m_impl
->Read(buffer
, nbytes
);
736 else // blocking socket
740 // Wait until socket becomes ready for reading dispatching the GUI
741 // events in the meanwhile unless wxSOCKET_BLOCK was explicitly
742 // specified to disable this.
743 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForRead() )
746 const int ret
= m_impl
->Read(buffer
, nbytes
);
749 // for connection-oriented (e.g. TCP) sockets we can only read
750 // 0 bytes if the other end has been closed, and for
751 // connectionless ones (UDP) this flag doesn't make sense
752 // anyhow so we can set it to true too without doing any harm
759 // this will be always interpreted as error by Read()
765 // If wxSOCKET_WAITALL is not set, we can leave now as we did read
766 // something and we don't need to wait for all nbytes bytes to be
768 if ( !(m_flags
& wxSOCKET_WAITALL
) )
771 // Otherwise continue reading until we do read everything.
783 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
785 wxUint32 len
, len2
, sig
, total
;
790 unsigned char sig
[4];
791 unsigned char len
[4];
800 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
802 if (DoRead(&msg
, sizeof(msg
)) != sizeof(msg
))
805 sig
= (wxUint32
)msg
.sig
[0];
806 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
807 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
808 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
810 if (sig
!= 0xfeeddead)
812 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
816 len
= (wxUint32
)msg
.len
[0];
817 len
|= (wxUint32
)(msg
.len
[1] << 8);
818 len
|= (wxUint32
)(msg
.len
[2] << 16);
819 len
|= (wxUint32
)(msg
.len
[3] << 24);
829 // Don't attempt to read if the msg was zero bytes long.
832 total
= DoRead(buffer
, len
);
840 char *discard_buffer
= new char[MAX_DISCARD_SIZE
];
843 // NOTE: discarded bytes don't add to m_lcount.
846 discard_len
= ((len2
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE
: len2
);
847 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
848 len2
-= (wxUint32
)discard_len
;
850 while ((discard_len
> 0) && len2
);
852 delete [] discard_buffer
;
857 if (DoRead(&msg
, sizeof(msg
)) != sizeof(msg
))
860 sig
= (wxUint32
)msg
.sig
[0];
861 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
862 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
863 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
865 if (sig
!= 0xdeadfeed)
867 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
883 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
888 m_lcount
= DoRead(buffer
, nbytes
);
889 Pushback(buffer
, m_lcount
);
891 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
892 if (m_flags
& wxSOCKET_WAITALL
)
893 m_error
= (m_lcount
!= nbytes
);
895 m_error
= (m_lcount
== 0);
897 // Allow read events again
903 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
908 m_lcount
= DoWrite(buffer
, nbytes
);
910 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
911 if (m_flags
& wxSOCKET_WAITALL
)
912 m_error
= (m_lcount
!= nbytes
);
914 m_error
= (m_lcount
== 0);
916 // Allow write events again
922 // This function is a mirror image of DoRead() except that it doesn't use the
923 // push back buffer, please see comments there
924 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
926 const char *buffer
= static_cast<const char *>(buffer_
);
928 // Return if there is nothing to read or the socket is (already?) closed.
929 if ( !m_impl
|| !nbytes
)
932 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
935 if ( m_flags
& wxSOCKET_NOWAIT
)
937 wxSocketUnblocker
unblock(m_impl
);
938 const int ret
= m_impl
->Write(buffer
, nbytes
);
942 else // blocking socket
946 if ( !(m_flags
& wxSOCKET_BLOCK
) && !WaitForWrite() )
949 const int ret
= m_impl
->Write(buffer
, nbytes
);
960 if ( !(m_flags
& wxSOCKET_WAITALL
) )
974 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
980 unsigned char sig
[4];
981 unsigned char len
[4];
989 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
991 msg
.sig
[0] = (unsigned char) 0xad;
992 msg
.sig
[1] = (unsigned char) 0xde;
993 msg
.sig
[2] = (unsigned char) 0xed;
994 msg
.sig
[3] = (unsigned char) 0xfe;
996 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
997 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
998 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
999 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1001 if (DoWrite(&msg
, sizeof(msg
)) < sizeof(msg
))
1004 total
= DoWrite(buffer
, nbytes
);
1009 msg
.sig
[0] = (unsigned char) 0xed;
1010 msg
.sig
[1] = (unsigned char) 0xfe;
1011 msg
.sig
[2] = (unsigned char) 0xad;
1012 msg
.sig
[3] = (unsigned char) 0xde;
1016 msg
.len
[3] = (char) 0;
1018 if ((DoWrite(&msg
, sizeof(msg
))) < sizeof(msg
))
1021 // everything was OK
1032 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1035 Pushback(buffer
, nbytes
);
1043 wxSocketBase
& wxSocketBase::Discard()
1045 char *buffer
= new char[MAX_DISCARD_SIZE
];
1052 SetFlags(wxSOCKET_NOWAIT
);
1056 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1059 while (ret
== MAX_DISCARD_SIZE
);
1065 // Allow read events again
1071 // --------------------------------------------------------------------------
1073 // --------------------------------------------------------------------------
1076 * Polls the socket to determine its status. This function will
1077 * check for the events specified in the 'flags' parameter, and
1078 * it will return a mask indicating which operations can be
1079 * performed. This function won't block, regardless of the
1080 * mode (blocking | nonblocking) of the socket.
1082 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
)
1086 wxSocketEventFlags result
= 0;
1093 return (wxSOCKET_LOST_FLAG
& flags
);
1095 /* Do not use a static struct, Linux can garble it */
1099 wxFD_ZERO(&readfds
);
1100 wxFD_ZERO(&writefds
);
1101 wxFD_ZERO(&exceptfds
);
1102 wxFD_SET(m_fd
, &readfds
);
1103 if (flags
& wxSOCKET_OUTPUT_FLAG
|| flags
& wxSOCKET_CONNECTION_FLAG
)
1104 wxFD_SET(m_fd
, &writefds
);
1105 wxFD_SET(m_fd
, &exceptfds
);
1107 /* Check 'sticky' CONNECTION flag first */
1108 result
|= wxSOCKET_CONNECTION_FLAG
& m_detected
;
1110 /* If we have already detected a LOST event, then don't try
1111 * to do any further processing.
1113 if ((m_detected
& wxSOCKET_LOST_FLAG
) != 0)
1115 m_establishing
= false;
1116 return (wxSOCKET_LOST_FLAG
& flags
);
1119 /* Try select now */
1120 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) < 0)
1122 /* What to do here? */
1123 return (result
& flags
);
1126 /* Check for exceptions and errors */
1127 if (wxFD_ISSET(m_fd
, &exceptfds
))
1129 m_establishing
= false;
1130 m_detected
= wxSOCKET_LOST_FLAG
;
1132 /* LOST event: Abort any further processing */
1133 return (wxSOCKET_LOST_FLAG
& flags
);
1136 /* Check for readability */
1137 if (wxFD_ISSET(m_fd
, &readfds
))
1139 result
|= wxSOCKET_INPUT_FLAG
;
1141 if (m_server
&& m_stream
)
1143 /* This is a TCP server socket that detected a connection.
1144 While the INPUT_FLAG is also set, it doesn't matter on
1145 this kind of sockets, as we can only Accept() from them. */
1146 m_detected
|= wxSOCKET_CONNECTION_FLAG
;
1150 /* Check for writability */
1151 if (wxFD_ISSET(m_fd
, &writefds
))
1153 if (m_establishing
&& !m_server
)
1156 SOCKOPTLEN_T len
= sizeof(error
);
1157 m_establishing
= false;
1158 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1162 m_detected
= wxSOCKET_LOST_FLAG
;
1164 /* LOST event: Abort any further processing */
1165 return (wxSOCKET_LOST_FLAG
& flags
);
1169 m_detected
|= wxSOCKET_CONNECTION_FLAG
;
1174 result
|= wxSOCKET_OUTPUT_FLAG
;
1178 return (result
| m_detected
) & flags
;
1181 // All Wait functions poll the socket using Select() to
1182 // check for the specified combination of conditions, until one
1183 // of these conditions become true, an error occurs, or the
1184 // timeout elapses. The polling loop runs the event loop so that
1185 // this won't block the GUI.
1188 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1190 wxCHECK_MSG( m_impl
, false, "can't wait on invalid socket" );
1192 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1193 m_interrupt
= false;
1196 // Use either the provided timeout or the default timeout value associated
1197 // with this socket.
1199 // TODO: allow waiting forever, see #9443
1200 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1201 : seconds
* 1000 + milliseconds
;
1202 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1204 // Get the active event loop which we'll use for the message dispatching
1205 // when running in the main thread
1206 wxEventLoopBase
*eventLoop
;
1207 if ( wxIsMainThread() )
1209 eventLoop
= wxEventLoop::GetActive();
1211 else // in worker thread
1213 // We never dispatch messages from threads other than the main one.
1217 // Wait in an active polling loop: notice that the loop is executed at
1218 // least once, even if timeout is 0 (i.e. polling).
1219 bool gotEvent
= false;
1222 // We always stop waiting when the connection is lost as it doesn't
1223 // make sense to continue further, even if wxSOCKET_LOST_FLAG is not
1224 // specified in flags to wait for.
1225 const wxSocketEventFlags
1226 result
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
);
1228 // Incoming connection (server) or connection established (client)?
1229 if ( result
& wxSOCKET_CONNECTION_FLAG
)
1232 m_establishing
= false;
1237 // Data available or output buffer ready?
1238 if ( (result
& wxSOCKET_INPUT_FLAG
) || (result
& wxSOCKET_OUTPUT_FLAG
) )
1245 if ( result
& wxSOCKET_LOST_FLAG
)
1247 m_connected
= false;
1248 m_establishing
= false;
1249 if ( flags
& wxSOCKET_LOST_FLAG
)
1258 const wxMilliClock_t timeNow
= wxGetLocalTimeMillis();
1259 if ( timeNow
>= timeEnd
)
1264 // This function is only called if wxSOCKET_BLOCK flag was not used
1265 // and so we should dispatch the events if there is an event loop
1266 // capable of doing it.
1267 if ( eventLoop
->Pending() )
1268 eventLoop
->Dispatch();
1271 else // no event loop or waiting in another thread
1273 // We're busy waiting but at least give up the rest of our current
1277 #endif // wxUSE_THREADS
1283 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1285 return DoWait(seconds
, milliseconds
,
1286 wxSOCKET_INPUT_FLAG
|
1287 wxSOCKET_OUTPUT_FLAG
|
1288 wxSOCKET_CONNECTION_FLAG
|
1293 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1295 // Check pushback buffer before entering DoWait
1299 // Note that wxSOCKET_INPUT_LOST has to be explicitly passed to DoWait
1300 // because of the semantics of WaitForRead: a return value of true means
1301 // that a Read call will return immediately, not that there is
1302 // actually data to read.
1303 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1307 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1309 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1312 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1314 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
);
1317 // --------------------------------------------------------------------------
1319 // --------------------------------------------------------------------------
1322 // Get local or peer address
1325 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
1332 peer
= m_impl
->GetPeer();
1334 // copying a null address would just trigger an assert anyway
1339 addr_man
.SetAddress(peer
);
1340 GAddress_destroy(peer
);
1345 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
1352 local
= m_impl
->GetLocal();
1353 addr_man
.SetAddress(local
);
1354 GAddress_destroy(local
);
1360 // Save and restore socket state
1363 void wxSocketBase::SaveState()
1365 wxSocketState
*state
;
1367 state
= new wxSocketState();
1369 state
->m_flags
= m_flags
;
1370 state
->m_notify
= m_notify
;
1371 state
->m_eventmask
= m_eventmask
;
1372 state
->m_clientData
= m_clientData
;
1374 m_states
.Append(state
);
1377 void wxSocketBase::RestoreState()
1379 wxList::compatibility_iterator node
;
1380 wxSocketState
*state
;
1382 node
= m_states
.GetLast();
1386 state
= (wxSocketState
*)node
->GetData();
1388 m_flags
= state
->m_flags
;
1389 m_notify
= state
->m_notify
;
1390 m_eventmask
= state
->m_eventmask
;
1391 m_clientData
= state
->m_clientData
;
1393 m_states
.Erase(node
);
1398 // Timeout and flags
1401 void wxSocketBase::SetTimeout(long seconds
)
1403 m_timeout
= seconds
;
1406 m_impl
->SetTimeout(m_timeout
* 1000);
1409 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1411 // Do some sanity checking on the flags used: not all values can be used
1413 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1414 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1415 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1416 "wxSOCKET_NOWAIT doesn't make sense" );
1422 // --------------------------------------------------------------------------
1424 // --------------------------------------------------------------------------
1426 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1428 switch(notification
)
1430 case wxSOCKET_CONNECTION
:
1431 m_establishing
= false;
1435 // If we are in the middle of a R/W operation, do not
1436 // propagate events to users. Also, filter 'late' events
1437 // which are no longer valid.
1439 case wxSOCKET_INPUT
:
1440 if (m_reading
|| !m_impl
->Select(wxSOCKET_INPUT_FLAG
))
1444 case wxSOCKET_OUTPUT
:
1445 if (m_writing
|| !m_impl
->Select(wxSOCKET_OUTPUT_FLAG
))
1450 m_connected
= false;
1451 m_establishing
= false;
1454 case wxSOCKET_MAX_EVENT
:
1455 wxFAIL_MSG( "unexpected notification" );
1459 // Schedule the event
1461 wxSocketEventFlags flag
= 0;
1463 switch (notification
)
1465 case wxSOCKET_INPUT
: flag
= wxSOCKET_INPUT_FLAG
; break;
1466 case wxSOCKET_OUTPUT
: flag
= wxSOCKET_OUTPUT_FLAG
; break;
1467 case wxSOCKET_CONNECTION
: flag
= wxSOCKET_CONNECTION_FLAG
; break;
1468 case wxSOCKET_LOST
: flag
= wxSOCKET_LOST_FLAG
; break;
1470 wxLogWarning(_("wxSocket: unknown event!."));
1474 if (((m_eventmask
& flag
) == flag
) && m_notify
)
1478 wxSocketEvent
event(m_id
);
1479 event
.m_event
= notification
;
1480 event
.m_clientData
= m_clientData
;
1481 event
.SetEventObject(this);
1483 m_handler
->AddPendingEvent(event
);
1488 void wxSocketBase::Notify(bool notify
)
1492 m_impl
->Notify(notify
);
1495 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1497 m_eventmask
= flags
;
1500 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1502 m_handler
= &handler
;
1506 // --------------------------------------------------------------------------
1508 // --------------------------------------------------------------------------
1510 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1514 if (m_unread
== NULL
)
1515 m_unread
= malloc(size
);
1520 tmp
= malloc(m_unrd_size
+ size
);
1521 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1527 m_unrd_size
+= size
;
1529 memcpy(m_unread
, buffer
, size
);
1532 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1534 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1539 if (size
> (m_unrd_size
-m_unrd_cur
))
1540 size
= m_unrd_size
-m_unrd_cur
;
1542 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1547 if (m_unrd_size
== m_unrd_cur
)
1560 // ==========================================================================
1562 // ==========================================================================
1564 // --------------------------------------------------------------------------
1566 // --------------------------------------------------------------------------
1568 wxSocketServer::wxSocketServer(const wxSockAddress
& addr_man
,
1569 wxSocketFlags flags
)
1570 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1572 wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") );
1574 m_impl
= wxSocketImpl::Create(*this);
1578 wxLogTrace( wxTRACE_Socket
, _T("*** Failed to create m_impl") );
1582 // Setup the socket as server
1583 m_impl
->Notify(m_notify
);
1584 m_impl
->SetLocal(addr_man
.GetAddress());
1586 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1587 m_impl
->SetReusable();
1589 if (GetFlags() & wxSOCKET_BROADCAST
) {
1590 m_impl
->SetBroadcast();
1592 if (GetFlags() & wxSOCKET_NOBIND
) {
1593 m_impl
->DontDoBind();
1596 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1601 wxLogTrace( wxTRACE_Socket
, _T("*** CreateServer() failed") );
1605 wxLogTrace( wxTRACE_Socket
, _T("wxSocketServer on fd %d"), m_impl
->m_fd
);
1608 // --------------------------------------------------------------------------
1610 // --------------------------------------------------------------------------
1612 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1617 // If wait == false, then the call should be nonblocking.
1618 // When we are finished, we put the socket to blocking mode
1620 wxSocketUnblocker
unblock(m_impl
, !wait
);
1621 sock
.m_impl
= m_impl
->WaitConnection(sock
);
1626 sock
.m_type
= wxSOCKET_BASE
;
1627 sock
.m_connected
= true;
1632 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1634 wxSocketBase
* sock
= new wxSocketBase();
1636 sock
->SetFlags(m_flags
);
1638 if (!AcceptWith(*sock
, wait
))
1647 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1649 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
);
1652 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1654 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1656 SOCKOPTLEN_T lenreal
;
1657 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1658 static_cast<char *>(optval
), &lenreal
) != 0 )
1667 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1669 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1671 return setsockopt(m_impl
->m_fd
, level
, optname
,
1672 static_cast<const char *>(optval
), optlen
) == 0;
1675 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1677 GAddress
* la
= local
.GetAddress();
1679 // If the address is valid, save it for use when we call Connect
1680 if (la
&& la
->m_addr
)
1682 m_localAddress
= local
;
1690 // ==========================================================================
1692 // ==========================================================================
1694 // --------------------------------------------------------------------------
1696 // --------------------------------------------------------------------------
1698 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1699 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1701 m_initialRecvBufferSize
=
1702 m_initialSendBufferSize
= -1;
1705 wxSocketClient::~wxSocketClient()
1709 // --------------------------------------------------------------------------
1711 // --------------------------------------------------------------------------
1713 bool wxSocketClient::DoConnect(const wxSockAddress
& addr_man
,
1714 const wxSockAddress
* local
,
1719 // Shutdown and destroy the socket
1724 m_impl
= wxSocketImpl::Create(*this);
1725 m_connected
= false;
1726 m_establishing
= false;
1731 // If wait == false, then the call should be nonblocking. When we are
1732 // finished, we put the socket to blocking mode again.
1733 wxSocketUnblocker
unblock(m_impl
, !wait
);
1735 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1736 if (GetFlags() & wxSOCKET_REUSEADDR
)
1738 m_impl
->SetReusable();
1740 if (GetFlags() & wxSOCKET_BROADCAST
)
1742 m_impl
->SetBroadcast();
1744 if (GetFlags() & wxSOCKET_NOBIND
)
1746 m_impl
->DontDoBind();
1749 // If no local address was passed and one has been set, use the one that was Set
1750 if (!local
&& m_localAddress
.GetAddress())
1752 local
= &m_localAddress
;
1755 // Bind to the local IP address and port, when provided
1758 GAddress
* la
= local
->GetAddress();
1760 if (la
&& la
->m_addr
)
1761 m_impl
->SetLocal(la
);
1764 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1766 m_impl
->SetPeer(addr_man
.GetAddress());
1767 const wxSocketError err
= m_impl
->CreateClient();
1769 //this will register for callbacks - must be called after m_impl->m_fd was initialized
1770 m_impl
->Notify(m_notify
);
1772 if (err
!= wxSOCKET_NOERROR
)
1774 if (err
== wxSOCKET_WOULDBLOCK
)
1775 m_establishing
= true;
1784 bool wxSocketClient::Connect(const wxSockAddress
& addr_man
, bool wait
)
1786 return DoConnect(addr_man
, NULL
, wait
);
1789 bool wxSocketClient::Connect(const wxSockAddress
& addr_man
,
1790 const wxSockAddress
& local
,
1793 return DoConnect(addr_man
, &local
, wait
);
1796 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1800 // this happens if the initial attempt to connect succeeded without
1805 wxCHECK_MSG( m_establishing
&& m_impl
, false,
1806 "No connection establishment attempt in progress" );
1808 // we must specify wxSOCKET_LOST_FLAG here explicitly because we must return
1809 // true if the connection establishment process is finished, whether it is
1810 // over because we successfully connected or because we were not able to
1812 return DoWait(seconds
, milliseconds
,
1813 wxSOCKET_CONNECTION_FLAG
| wxSOCKET_LOST_FLAG
);
1816 // ==========================================================================
1818 // ==========================================================================
1820 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
1821 wxSocketFlags flags
)
1822 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1824 // Create the socket
1825 m_impl
= wxSocketImpl::Create(*this);
1830 m_impl
->Notify(m_notify
);
1831 // Setup the socket as non connection oriented
1832 m_impl
->SetLocal(addr
.GetAddress());
1833 if (flags
& wxSOCKET_REUSEADDR
)
1835 m_impl
->SetReusable();
1837 if (GetFlags() & wxSOCKET_BROADCAST
)
1839 m_impl
->SetBroadcast();
1841 if (GetFlags() & wxSOCKET_NOBIND
)
1843 m_impl
->DontDoBind();
1846 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
1853 // Initialize all stuff
1854 m_connected
= false;
1855 m_establishing
= false;
1858 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1867 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
1871 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1873 m_impl
->SetPeer(addr
.GetAddress());
1878 // ==========================================================================
1880 // ==========================================================================
1882 class wxSocketModule
: public wxModule
1885 virtual bool OnInit()
1887 // wxSocketBase will call Initialize() itself only if sockets are
1888 // really used, don't do it from here
1892 virtual void OnExit()
1894 if ( wxSocketBase::IsInitialized() )
1895 wxSocketBase::Shutdown();
1899 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
1902 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
1904 #endif // wxUSE_SOCKETS