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"
53 // we use MSG_NOSIGNAL to avoid getting SIGPIPE when sending data to a remote
54 // host which closed the connection if it is available, otherwise we rely on
55 // SO_NOSIGPIPE existency
57 // this should cover all the current Unix systems (Windows never sends any
58 // signals anyhow) but if we find one that has neither we should explicitly
59 // ignore SIGPIPE for it
61 #define wxSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
62 #else // MSG_NOSIGNAL not available (BSD including OS X)
63 #if defined(__UNIX__) && !defined(SO_NOSIGPIPE)
64 #error "Writing to socket could generate unhandled SIGPIPE."
65 #error "Please post information about your system to wx-dev."
68 #define wxSOCKET_MSG_NOSIGNAL 0
71 // DLL options compatibility check:
73 WX_CHECK_BUILD_OPTIONS("wxNet")
75 // --------------------------------------------------------------------------
76 // macros and constants
77 // --------------------------------------------------------------------------
80 #define MAX_DISCARD_SIZE (10 * 1024)
82 #define wxTRACE_Socket _T("wxSocket")
84 // --------------------------------------------------------------------------
86 // --------------------------------------------------------------------------
88 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
89 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
90 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
91 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
92 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
94 // ----------------------------------------------------------------------------
96 // ----------------------------------------------------------------------------
101 void SetTimeValFromMS(timeval
& tv
, unsigned long ms
)
103 tv
.tv_sec
= (ms
/ 1000);
104 tv
.tv_usec
= (ms
% 1000) * 1000;
107 } // anonymous namespace
109 // --------------------------------------------------------------------------
111 // --------------------------------------------------------------------------
113 class wxSocketState
: public wxObject
116 wxSocketFlags m_flags
;
117 wxSocketEventFlags m_eventmask
;
122 wxSocketState() : wxObject() {}
124 DECLARE_NO_COPY_CLASS(wxSocketState
)
127 // ============================================================================
129 // ============================================================================
131 wxSocketManager
*wxSocketManager::ms_manager
= NULL
;
134 void wxSocketManager::Set(wxSocketManager
*manager
)
136 wxASSERT_MSG( !ms_manager
, "too late to set manager now" );
138 ms_manager
= manager
;
142 void wxSocketManager::Init()
144 wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" );
147 Details: Initialize() creates a hidden window as a sink for socket
148 events, such as 'read completed'. wxMSW has only one message loop
149 for the main thread. If Initialize is called in a secondary thread,
150 the socket window will be created for the secondary thread, but
151 since there is no message loop on this thread, it will never
152 receive events and all socket operations will time out.
153 BTW, the main thread must not be stopped using sleep or block
154 on a semaphore (a bad idea in any case) or socket operations
157 On the Mac side, Initialize() stores a pointer to the CFRunLoop for
158 the main thread. Because secondary threads do not have run loops,
159 adding event notifications to the "Current" loop would have no
160 effect at all, events would never fire.
162 wxASSERT_MSG( wxIsMainThread(),
163 "sockets must be initialized from the main thread" );
165 wxAppConsole
* const app
= wxAppConsole::GetInstance();
166 wxCHECK_RET( app
, "sockets can't be initialized without wxApp" );
168 ms_manager
= app
->GetTraits()->GetSocketManager();
171 // ==========================================================================
173 // ==========================================================================
175 wxSocketImpl::wxSocketImpl(wxSocketBase
& wxsocket
)
176 : m_wxsocket(&wxsocket
)
178 m_fd
= INVALID_SOCKET
;
181 m_error
= wxSOCKET_NOERROR
;
185 SetTimeout(wxsocket
.GetTimeout() * 1000);
187 m_establishing
= false;
191 m_initialRecvBufferSize
= -1;
192 m_initialSendBufferSize
= -1;
195 wxSocketImpl::~wxSocketImpl()
197 if (m_fd
!= INVALID_SOCKET
)
201 GAddress_destroy(m_local
);
204 GAddress_destroy(m_peer
);
207 bool wxSocketImpl::PreCreateCheck(GAddress
*addr
)
209 if ( m_fd
!= INVALID_SOCKET
)
211 m_error
= wxSOCKET_INVSOCK
;
215 if ( !addr
|| !addr
->m_addr
)
217 m_error
= wxSOCKET_INVADDR
;
224 void wxSocketImpl::PostCreation()
226 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
228 EnableSocketOption(SO_NOSIGPIPE
);
232 EnableSocketOption(SO_REUSEADDR
);
236 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
238 EnableSocketOption(SO_BROADCAST
);
241 if ( m_initialRecvBufferSize
>= 0 )
242 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
243 if ( m_initialSendBufferSize
>= 0 )
244 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
246 // we always put our sockets in unblocked mode and handle blocking
247 // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
248 UnblockAndRegisterWithEventLoop();
251 wxSocketError
wxSocketImpl::UpdateLocalAddress()
253 WX_SOCKLEN_T lenAddr
= sizeof(*m_local
->m_addr
);
254 if ( getsockname(m_fd
, m_local
->m_addr
, &lenAddr
) != 0 )
257 m_error
= wxSOCKET_IOERR
;
261 m_local
->m_len
= lenAddr
;
263 return wxSOCKET_NOERROR
;
266 wxSocketError
wxSocketImpl::CreateServer()
268 if ( !PreCreateCheck(m_local
) )
274 // do create the socket
275 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
277 if ( m_fd
== INVALID_SOCKET
)
279 m_error
= wxSOCKET_IOERR
;
280 return wxSOCKET_IOERR
;
285 // and then bind to and listen on it
287 // FIXME: should we test for m_dobind here?
288 if ( bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0 )
289 m_error
= wxSOCKET_IOERR
;
293 if ( listen(m_fd
, 5) != 0 )
294 m_error
= wxSOCKET_IOERR
;
303 // finally retrieve the address we effectively bound to
304 return UpdateLocalAddress();
307 wxSocketError
wxSocketImpl::CreateClient(bool wait
)
309 if ( !PreCreateCheck(m_peer
) )
312 m_fd
= socket(m_peer
->m_realfamily
, SOCK_STREAM
, 0);
314 if ( m_fd
== INVALID_SOCKET
)
316 m_error
= wxSOCKET_IOERR
;
317 return wxSOCKET_IOERR
;
322 // If a local address has been set, then bind to it before calling connect
323 if ( m_local
&& m_local
->m_addr
)
325 if ( bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0 )
328 m_error
= wxSOCKET_IOERR
;
334 int rc
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
335 if ( rc
== SOCKET_ERROR
)
337 wxSocketError err
= GetLastError();
338 if ( err
== wxSOCKET_WOULDBLOCK
)
340 m_establishing
= true;
342 // block waiting for connection if we should (otherwise just return
343 // wxSOCKET_WOULDBLOCK to the caller)
346 err
= SelectWithTimeout(wxSOCKET_CONNECTION_FLAG
)
349 m_establishing
= false;
357 m_error
= wxSOCKET_NOERROR
;
364 wxSocketError
wxSocketImpl::CreateUDP()
366 if ( !PreCreateCheck(m_local
) )
372 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
374 if ( m_fd
== INVALID_SOCKET
)
376 m_error
= wxSOCKET_IOERR
;
377 return wxSOCKET_IOERR
;
384 if ( bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0 )
387 m_error
= wxSOCKET_IOERR
;
391 return UpdateLocalAddress();
394 return wxSOCKET_NOERROR
;
397 wxSocketImpl
*wxSocketImpl::Accept(wxSocketBase
& wxsocket
)
400 WX_SOCKLEN_T fromlen
= sizeof(from
);
401 const SOCKET fd
= accept(m_fd
, &from
, &fromlen
);
403 if ( fd
== INVALID_SOCKET
)
406 wxSocketImpl
* const sock
= Create(wxsocket
);
409 sock
->m_peer
= GAddress_new();
410 _GAddress_translate_from(sock
->m_peer
, &from
, fromlen
);
412 sock
->UnblockAndRegisterWithEventLoop();
418 void wxSocketImpl::Close()
420 if ( m_fd
!= INVALID_SOCKET
)
423 m_fd
= INVALID_SOCKET
;
428 * Disallow further read/write operations on this socket, close
429 * the fd and disable all callbacks.
431 void wxSocketImpl::Shutdown()
433 if ( m_fd
!= INVALID_SOCKET
)
435 shutdown(m_fd
, 1 /* SD_SEND */);
441 * Sets the timeout for blocking calls. Time is expressed in
444 void wxSocketImpl::SetTimeout(unsigned long millis
)
446 SetTimeValFromMS(m_timeout
, millis
);
449 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
451 m_wxsocket
->OnRequest(event
);
454 /* Address handling */
457 * Set or get the local or peer address for this socket. The 'set'
458 * functions return wxSOCKET_NOERROR on success, an error code otherwise.
459 * The 'get' functions return a pointer to a GAddress object on success,
460 * or NULL otherwise, in which case they set the error code of the
461 * corresponding socket.
464 * wxSOCKET_INVSOCK - the socket is not valid.
465 * wxSOCKET_INVADDR - the address is not valid.
467 wxSocketError
wxSocketImpl::SetLocal(GAddress
*address
)
469 /* the socket must be initialized, or it must be a server */
470 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
472 m_error
= wxSOCKET_INVSOCK
;
473 return wxSOCKET_INVSOCK
;
477 if (address
== NULL
|| address
->m_family
== wxSOCKET_NOFAMILY
)
479 m_error
= wxSOCKET_INVADDR
;
480 return wxSOCKET_INVADDR
;
484 GAddress_destroy(m_local
);
486 m_local
= GAddress_copy(address
);
488 return wxSOCKET_NOERROR
;
491 wxSocketError
wxSocketImpl::SetPeer(GAddress
*address
)
494 if (address
== NULL
|| address
->m_family
== wxSOCKET_NOFAMILY
)
496 m_error
= wxSOCKET_INVADDR
;
497 return wxSOCKET_INVADDR
;
501 GAddress_destroy(m_peer
);
503 m_peer
= GAddress_copy(address
);
505 return wxSOCKET_NOERROR
;
508 GAddress
*wxSocketImpl::GetLocal()
512 WX_SOCKLEN_T size
= sizeof(addr
);
515 /* try to get it from the m_local var first */
517 return GAddress_copy(m_local
);
519 /* else, if the socket is initialized, try getsockname */
520 if (m_fd
== INVALID_SOCKET
)
522 m_error
= wxSOCKET_INVSOCK
;
526 if (getsockname(m_fd
, (sockaddr
*)&addr
, &size
) == SOCKET_ERROR
)
528 m_error
= wxSOCKET_IOERR
;
532 /* got a valid address from getsockname, create a GAddress object */
533 if ((address
= GAddress_new()) == NULL
)
535 m_error
= wxSOCKET_MEMERR
;
539 if ((err
= _GAddress_translate_from(address
, (sockaddr
*)&addr
, size
)) != wxSOCKET_NOERROR
)
541 GAddress_destroy(address
);
549 GAddress
*wxSocketImpl::GetPeer()
551 /* try to get it from the m_peer var */
553 return GAddress_copy(m_peer
);
558 // ----------------------------------------------------------------------------
560 // ----------------------------------------------------------------------------
562 // this macro wraps the given expression (normally a syscall) in a loop which
563 // ignores any interruptions, i.e. reevaluates it again if it failed and errno
566 #define DO_WHILE_EINTR( rc, syscall ) \
570 while ( rc == -1 && errno == EINTR )
572 #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
575 int wxSocketImpl::RecvStream(void *buffer
, int size
)
578 DO_WHILE_EINTR( ret
, recv(m_fd
, static_cast<char *>(buffer
), size
, 0) );
582 // receiving 0 bytes for a TCP socket indicates that the connection was
583 // closed by peer so shut down our end as well (for UDP sockets empty
584 // datagrams are also possible)
585 m_establishing
= false;
586 NotifyOnStateChange(wxSOCKET_LOST
);
590 // do not return an error in this case however
596 int wxSocketImpl::SendStream(const void *buffer
, int size
)
599 DO_WHILE_EINTR( ret
, send(m_fd
, static_cast<const char *>(buffer
), size
,
600 wxSOCKET_MSG_NOSIGNAL
) );
605 int wxSocketImpl::RecvDgram(void *buffer
, int size
)
608 WX_SOCKLEN_T fromlen
= sizeof(from
);
611 DO_WHILE_EINTR( ret
, recvfrom(m_fd
, static_cast<char *>(buffer
), size
,
612 0, &from
, &fromlen
) );
614 if ( ret
== SOCKET_ERROR
)
617 /* Translate a system address into a wxSocketImpl address */
619 m_peer
= GAddress_new();
621 m_error
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
622 if ( m_error
!= wxSOCKET_NOERROR
)
624 GAddress_destroy(m_peer
);
632 int wxSocketImpl::SendDgram(const void *buffer
, int size
)
636 m_error
= wxSOCKET_INVADDR
;
640 struct sockaddr
*addr
;
642 m_error
= _GAddress_translate_to(m_peer
, &addr
, &len
);
643 if ( m_error
!= wxSOCKET_NOERROR
)
647 DO_WHILE_EINTR( ret
, sendto(m_fd
, static_cast<const char *>(buffer
), size
,
655 int wxSocketImpl::Read(void *buffer
, int size
)
657 // server sockets can't be used for IO, only to accept new connections
658 if ( m_fd
== INVALID_SOCKET
|| m_server
)
660 m_error
= wxSOCKET_INVSOCK
;
664 int ret
= m_stream
? RecvStream(buffer
, size
)
665 : RecvDgram(buffer
, size
);
667 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
672 int wxSocketImpl::Write(const void *buffer
, int size
)
674 if ( m_fd
== INVALID_SOCKET
|| m_server
)
676 m_error
= wxSOCKET_INVSOCK
;
680 int ret
= m_stream
? SendStream(buffer
, size
)
681 : SendDgram(buffer
, size
);
683 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
688 // ==========================================================================
690 // ==========================================================================
692 // --------------------------------------------------------------------------
693 // Initialization and shutdown
694 // --------------------------------------------------------------------------
696 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
697 // to m_countInit with a crit section
698 size_t wxSocketBase::m_countInit
= 0;
700 bool wxSocketBase::IsInitialized()
702 return m_countInit
> 0;
705 bool wxSocketBase::Initialize()
707 if ( !m_countInit
++ )
709 wxSocketManager
* const manager
= wxSocketManager::Get();
710 if ( !manager
|| !manager
->OnInit() )
721 void wxSocketBase::Shutdown()
723 // we should be initialized
724 wxASSERT_MSG( m_countInit
> 0, _T("extra call to Shutdown()") );
725 if ( --m_countInit
== 0 )
727 wxSocketManager
* const manager
= wxSocketManager::Get();
728 wxCHECK_RET( manager
, "should have a socket manager" );
734 // --------------------------------------------------------------------------
736 // --------------------------------------------------------------------------
738 void wxSocketBase::Init()
741 m_type
= wxSOCKET_UNINIT
;
752 m_beingDeleted
= false;
767 if ( !IsInitialized() )
769 // this Initialize() will be undone by wxSocketModule::OnExit(), all
770 // the other calls to it should be matched by a call to Shutdown()
775 wxSocketBase::wxSocketBase()
780 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
789 wxSocketBase::~wxSocketBase()
791 // Just in case the app called Destroy() *and* then deleted the socket
792 // immediately: don't leave dangling pointers.
793 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
795 traits
->RemoveFromPendingDelete(this);
797 // Shutdown and close the socket
801 // Destroy the implementation object
804 // Free the pushback buffer
809 bool wxSocketBase::Destroy()
811 // Delayed destruction: the socket will be deleted during the next idle
812 // loop iteration. This ensures that all pending events have been
814 m_beingDeleted
= true;
816 // Shutdown and close the socket
819 // Suppress events from now on
822 // schedule this object for deletion
823 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
826 // let the traits object decide what to do with us
827 traits
->ScheduleForDestroy(this);
829 else // no app or no traits
831 // in wxBase we might have no app object at all, don't leak memory
838 // ----------------------------------------------------------------------------
840 // ----------------------------------------------------------------------------
842 void wxSocketBase::SetError(wxSocketError error
)
844 m_impl
->m_error
= error
;
847 wxSocketError
wxSocketBase::LastError() const
849 return m_impl
->GetError();
852 // --------------------------------------------------------------------------
854 // --------------------------------------------------------------------------
856 // The following IO operations update m_lcount:
857 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
858 bool wxSocketBase::Close()
860 // Interrupt pending waits
867 m_establishing
= false;
871 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
876 m_lcount
= DoRead(buffer
, nbytes
);
878 // Allow read events from now on
884 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
886 // We use pointer arithmetic here which doesn't work with void pointers.
887 char *buffer
= static_cast<char *>(buffer_
);
889 // Try the push back buffer first, even before checking whether the socket
890 // is valid to allow reading previously pushed back data from an already
892 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
896 // If it's indeed closed or if read everything, there is nothing more to do.
897 if ( !m_impl
|| !nbytes
)
900 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
903 // wxSOCKET_NOWAIT overrides all the other flags and means that we are
904 // polling the socket and don't block at all.
905 if ( m_flags
& wxSOCKET_NOWAIT
)
907 int ret
= m_impl
->Read(buffer
, nbytes
);
910 if ( m_impl
->GetLastError() != wxSOCKET_WOULDBLOCK
)
911 SetError(wxSOCKET_IOERR
);
913 else // not an error, even if we didn't read anything
918 else // blocking socket
922 // Wait until socket becomes ready for reading
923 if ( !WaitForRead() )
926 const int ret
= m_impl
->Read(buffer
, nbytes
);
929 // for connection-oriented (e.g. TCP) sockets we can only read
930 // 0 bytes if the other end has been closed, and for
931 // connectionless ones (UDP) this flag doesn't make sense
932 // anyhow so we can set it to true too without doing any harm
939 SetError(wxSOCKET_IOERR
);
945 // If wxSOCKET_WAITALL is not set, we can leave now as we did read
946 // something and we don't need to wait for all nbytes bytes to be
948 if ( !(m_flags
& wxSOCKET_WAITALL
) )
951 // Otherwise continue reading until we do read everything.
959 // it's an error to not read everything in wxSOCKET_WAITALL mode or to
960 // not read anything otherwise
961 if ( ((m_flags
& wxSOCKET_WAITALL
) && nbytes
) || !total
)
962 SetError(wxSOCKET_IOERR
);
968 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
972 unsigned char sig
[4];
973 unsigned char len
[4];
979 int old_flags
= m_flags
;
980 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
983 if ( DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
985 wxUint32 sig
= (wxUint32
)msg
.sig
[0];
986 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
987 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
988 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
990 if ( sig
== 0xfeeddead )
992 wxUint32 len
= (wxUint32
)msg
.len
[0];
993 len
|= (wxUint32
)(msg
.len
[1] << 8);
994 len
|= (wxUint32
)(msg
.len
[2] << 16);
995 len
|= (wxUint32
)(msg
.len
[3] << 24);
1000 len2
= len
- nbytes
;
1006 // Don't attempt to read if the msg was zero bytes long.
1007 m_lcount
= len
? DoRead(buffer
, len
) : 0;
1011 char discard_buffer
[MAX_DISCARD_SIZE
];
1014 // NOTE: discarded bytes don't add to m_lcount.
1017 discard_len
= len2
> MAX_DISCARD_SIZE
1020 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
1021 len2
-= (wxUint32
)discard_len
;
1023 while ((discard_len
> 0) && len2
);
1026 if ( !len2
&& DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1028 sig
= (wxUint32
)msg
.sig
[0];
1029 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1030 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1031 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1033 if ( sig
== 0xdeadfeed )
1040 SetError(wxSOCKET_IOERR
);
1043 SetFlags(old_flags
);
1048 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
1053 m_lcount
= DoRead(buffer
, nbytes
);
1054 Pushback(buffer
, m_lcount
);
1056 // Allow read events again
1062 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
1064 // Mask write events
1067 m_lcount
= DoWrite(buffer
, nbytes
);
1069 // Allow write events again
1075 // This function is a mirror image of DoRead() except that it doesn't use the
1076 // push back buffer, please see comments there
1077 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
1079 const char *buffer
= static_cast<const char *>(buffer_
);
1081 // Return if there is nothing to read or the socket is (already?) closed.
1082 if ( !m_impl
|| !nbytes
)
1085 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1088 if ( m_flags
& wxSOCKET_NOWAIT
)
1090 const int ret
= m_impl
->Write(buffer
, nbytes
);
1093 if ( m_impl
->GetLastError() != wxSOCKET_WOULDBLOCK
)
1094 SetError(wxSOCKET_IOERR
);
1101 else // blocking socket
1105 if ( !WaitForWrite() )
1108 const int ret
= m_impl
->Write(buffer
, nbytes
);
1117 SetError(wxSOCKET_IOERR
);
1122 if ( !(m_flags
& wxSOCKET_WAITALL
) )
1132 if ( ((m_flags
& wxSOCKET_WAITALL
) && nbytes
) || !total
)
1133 SetError(wxSOCKET_IOERR
);
1139 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
1143 unsigned char sig
[4];
1144 unsigned char len
[4];
1147 // Mask write events
1150 const int old_flags
= m_flags
;
1151 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
1153 msg
.sig
[0] = (unsigned char) 0xad;
1154 msg
.sig
[1] = (unsigned char) 0xde;
1155 msg
.sig
[2] = (unsigned char) 0xed;
1156 msg
.sig
[3] = (unsigned char) 0xfe;
1158 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
1159 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
1160 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
1161 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1164 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
) )
1166 m_lcount
= DoWrite(buffer
, nbytes
);
1167 if ( m_lcount
== nbytes
)
1169 msg
.sig
[0] = (unsigned char) 0xed;
1170 msg
.sig
[1] = (unsigned char) 0xfe;
1171 msg
.sig
[2] = (unsigned char) 0xad;
1172 msg
.sig
[3] = (unsigned char) 0xde;
1176 msg
.len
[3] = (char) 0;
1178 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
))
1184 SetError(wxSOCKET_IOERR
);
1187 SetFlags(old_flags
);
1192 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1195 Pushback(buffer
, nbytes
);
1197 SetError(wxSOCKET_NOERROR
);
1203 wxSocketBase
& wxSocketBase::Discard()
1205 char *buffer
= new char[MAX_DISCARD_SIZE
];
1212 const int old_flags
= m_flags
;
1213 SetFlags(wxSOCKET_NOWAIT
);
1217 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1220 while (ret
== MAX_DISCARD_SIZE
);
1224 SetError(wxSOCKET_NOERROR
);
1226 // Allow read events again
1229 SetFlags(old_flags
);
1234 // --------------------------------------------------------------------------
1236 // --------------------------------------------------------------------------
1239 This function will check for the events specified in the flags parameter,
1240 and it will return a mask indicating which operations can be performed.
1242 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
,
1243 const timeval
*timeout
)
1245 if ( m_fd
== INVALID_SOCKET
)
1246 return (wxSOCKET_LOST_FLAG
& flags
);
1252 tv
.tv_sec
= tv
.tv_usec
= 0;
1254 // prepare the FD sets, passing NULL for the one(s) we don't use
1256 readfds
, *preadfds
= NULL
,
1257 writefds
, *pwritefds
= NULL
,
1258 exceptfds
; // always want to know about errors
1260 if ( flags
& wxSOCKET_INPUT_FLAG
)
1262 preadfds
= &readfds
;
1263 wxFD_ZERO(preadfds
);
1264 wxFD_SET(m_fd
, preadfds
);
1267 // when using non-blocking connect() the socket becomes connected
1268 // (successfully or not) when it becomes writable
1269 if ( flags
& (wxSOCKET_OUTPUT_FLAG
| wxSOCKET_CONNECTION_FLAG
) )
1271 pwritefds
= &writefds
;
1272 wxFD_ZERO(pwritefds
);
1273 wxFD_SET(m_fd
, pwritefds
);
1276 wxFD_ZERO(&exceptfds
);
1277 wxFD_SET(m_fd
, &exceptfds
);
1279 const int rc
= select(m_fd
+ 1, preadfds
, pwritefds
, &exceptfds
, &tv
);
1281 // check for errors first
1282 if ( rc
== -1 || wxFD_ISSET(m_fd
, &exceptfds
) )
1284 m_establishing
= false;
1286 return wxSOCKET_LOST_FLAG
& flags
;
1292 wxASSERT_MSG( rc
== 1, "unexpected select() return value" );
1294 wxSocketEventFlags detected
= 0;
1295 if ( preadfds
&& wxFD_ISSET(m_fd
, preadfds
) )
1296 detected
|= wxSOCKET_INPUT_FLAG
;
1298 if ( pwritefds
&& wxFD_ISSET(m_fd
, pwritefds
) )
1300 // check for the case of non-blocking connect()
1301 if ( m_establishing
&& !m_server
)
1304 SOCKOPTLEN_T len
= sizeof(error
);
1305 m_establishing
= false;
1306 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1309 detected
= wxSOCKET_LOST_FLAG
;
1311 detected
|= wxSOCKET_CONNECTION_FLAG
;
1313 else // not called to get non-blocking connect() status
1315 detected
|= wxSOCKET_OUTPUT_FLAG
;
1319 return detected
& flags
;
1323 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1325 wxCHECK_MSG( m_impl
, false, "can't wait on invalid socket" );
1327 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1328 m_interrupt
= false;
1331 // Use either the provided timeout or the default timeout value associated
1332 // with this socket.
1334 // TODO: allow waiting forever, see #9443
1335 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1336 : seconds
* 1000 + milliseconds
;
1337 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1339 // Get the active event loop which we'll use for the message dispatching
1340 // when running in the main thread unless this was explicitly disabled by
1341 // setting wxSOCKET_BLOCK flag
1342 wxEventLoopBase
*eventLoop
;
1343 if ( !(m_flags
& wxSOCKET_BLOCK
) && wxIsMainThread() )
1345 eventLoop
= wxEventLoop::GetActive();
1347 else // in worker thread
1349 // We never dispatch messages from threads other than the main one.
1353 // Wait until we receive the event we're waiting for or the timeout expires
1354 // (but note that we always execute the loop at least once, even if timeout
1355 // is 0 as this is used for polling)
1356 bool gotEvent
= false;
1357 for ( bool firstTime
= true; !m_interrupt
; firstTime
= false )
1359 long timeLeft
= wxMilliClockToLong(timeEnd
- wxGetLocalTimeMillis());
1368 // This function is only called if wxSOCKET_BLOCK flag was not used and
1369 // so we should dispatch the events if there is an event loop capable
1371 wxSocketEventFlags events
;
1374 // reset them before starting to wait
1377 eventLoop
->DispatchTimeout(timeLeft
);
1379 events
= m_eventsgot
;
1381 else // no event loop or waiting in another thread
1383 // as explained below, we should always check for wxSOCKET_LOST_FLAG
1385 SetTimeValFromMS(tv
, timeLeft
);
1386 events
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
, &tv
);
1389 // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
1390 // it, as continuing to wait for anything else after getting it is
1392 if ( events
& wxSOCKET_LOST_FLAG
)
1394 m_connected
= false;
1395 m_establishing
= false;
1396 if ( flags
& wxSOCKET_LOST_FLAG
)
1401 // otherwise mask out the bits we're not interested in
1404 // Incoming connection (server) or connection established (client)?
1405 if ( events
& wxSOCKET_CONNECTION_FLAG
)
1408 m_establishing
= false;
1413 // Data available or output buffer ready?
1414 if ( (events
& wxSOCKET_INPUT_FLAG
) || (events
& wxSOCKET_OUTPUT_FLAG
) )
1424 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1426 return DoWait(seconds
, milliseconds
,
1427 wxSOCKET_INPUT_FLAG
|
1428 wxSOCKET_OUTPUT_FLAG
|
1429 wxSOCKET_CONNECTION_FLAG
|
1434 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1436 // Check pushback buffer before entering DoWait
1440 // Note that wxSOCKET_INPUT_LOST has to be explicitly passed to DoWait
1441 // because of the semantics of WaitForRead: a return value of true means
1442 // that a Read call will return immediately, not that there is
1443 // actually data to read.
1444 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1448 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1450 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1453 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1455 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
);
1458 // --------------------------------------------------------------------------
1460 // --------------------------------------------------------------------------
1463 // Get local or peer address
1466 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
1473 peer
= m_impl
->GetPeer();
1475 // copying a null address would just trigger an assert anyway
1480 addr_man
.SetAddress(peer
);
1481 GAddress_destroy(peer
);
1486 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
1493 local
= m_impl
->GetLocal();
1494 addr_man
.SetAddress(local
);
1495 GAddress_destroy(local
);
1501 // Save and restore socket state
1504 void wxSocketBase::SaveState()
1506 wxSocketState
*state
;
1508 state
= new wxSocketState();
1510 state
->m_flags
= m_flags
;
1511 state
->m_notify
= m_notify
;
1512 state
->m_eventmask
= m_eventmask
;
1513 state
->m_clientData
= m_clientData
;
1515 m_states
.Append(state
);
1518 void wxSocketBase::RestoreState()
1520 wxList::compatibility_iterator node
;
1521 wxSocketState
*state
;
1523 node
= m_states
.GetLast();
1527 state
= (wxSocketState
*)node
->GetData();
1529 m_flags
= state
->m_flags
;
1530 m_notify
= state
->m_notify
;
1531 m_eventmask
= state
->m_eventmask
;
1532 m_clientData
= state
->m_clientData
;
1534 m_states
.Erase(node
);
1539 // Timeout and flags
1542 void wxSocketBase::SetTimeout(long seconds
)
1544 m_timeout
= seconds
;
1547 m_impl
->SetTimeout(m_timeout
* 1000);
1550 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1552 // Do some sanity checking on the flags used: not all values can be used
1554 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1555 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1556 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1557 "wxSOCKET_NOWAIT doesn't make sense" );
1563 // --------------------------------------------------------------------------
1565 // --------------------------------------------------------------------------
1567 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1569 wxSocketEventFlags flag
= 0;
1570 switch ( notification
)
1572 case wxSOCKET_INPUT
:
1573 flag
= wxSOCKET_INPUT_FLAG
;
1576 case wxSOCKET_OUTPUT
:
1577 flag
= wxSOCKET_OUTPUT_FLAG
;
1580 case wxSOCKET_CONNECTION
:
1581 flag
= wxSOCKET_CONNECTION_FLAG
;
1585 flag
= wxSOCKET_LOST_FLAG
;
1589 wxFAIL_MSG( "unknown wxSocket notification" );
1592 // if we lost the connection the socket is now closed
1593 if ( notification
== wxSOCKET_LOST
)
1596 // remember the events which were generated for this socket, we're going to
1597 // use this in DoWait()
1598 m_eventsgot
|= flag
;
1600 // send the wx event if enabled and we're interested in it
1601 if ( m_notify
&& (m_eventmask
& flag
) && m_handler
)
1603 // If we are in the middle of a R/W operation, do not propagate events
1604 // to users. Also, filter 'late' events which are no longer valid.
1605 if ( notification
== wxSOCKET_INPUT
)
1607 if ( m_reading
|| !m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1610 else if ( notification
== wxSOCKET_OUTPUT
)
1612 if ( m_writing
|| !m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1616 wxSocketEvent
event(m_id
);
1617 event
.m_event
= notification
;
1618 event
.m_clientData
= m_clientData
;
1619 event
.SetEventObject(this);
1621 m_handler
->AddPendingEvent(event
);
1625 void wxSocketBase::Notify(bool notify
)
1630 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1632 m_eventmask
= flags
;
1635 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1637 m_handler
= &handler
;
1641 // --------------------------------------------------------------------------
1643 // --------------------------------------------------------------------------
1645 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1649 if (m_unread
== NULL
)
1650 m_unread
= malloc(size
);
1655 tmp
= malloc(m_unrd_size
+ size
);
1656 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1662 m_unrd_size
+= size
;
1664 memcpy(m_unread
, buffer
, size
);
1667 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1669 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1674 if (size
> (m_unrd_size
-m_unrd_cur
))
1675 size
= m_unrd_size
-m_unrd_cur
;
1677 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1682 if (m_unrd_size
== m_unrd_cur
)
1695 // ==========================================================================
1697 // ==========================================================================
1699 // --------------------------------------------------------------------------
1701 // --------------------------------------------------------------------------
1703 wxSocketServer::wxSocketServer(const wxSockAddress
& addr_man
,
1704 wxSocketFlags flags
)
1705 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1707 wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") );
1709 m_impl
= wxSocketImpl::Create(*this);
1713 wxLogTrace( wxTRACE_Socket
, _T("*** Failed to create m_impl") );
1717 // Setup the socket as server
1718 m_impl
->SetLocal(addr_man
.GetAddress());
1720 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1721 m_impl
->SetReusable();
1723 if (GetFlags() & wxSOCKET_BROADCAST
) {
1724 m_impl
->SetBroadcast();
1726 if (GetFlags() & wxSOCKET_NOBIND
) {
1727 m_impl
->DontDoBind();
1730 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1735 wxLogTrace( wxTRACE_Socket
, _T("*** CreateServer() failed") );
1739 wxLogTrace( wxTRACE_Socket
, _T("wxSocketServer on fd %d"), m_impl
->m_fd
);
1742 // --------------------------------------------------------------------------
1744 // --------------------------------------------------------------------------
1746 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1748 if ( !m_impl
|| (m_impl
->m_fd
== INVALID_SOCKET
) || !m_impl
->IsServer() )
1750 wxFAIL_MSG( "can only be called for a valid server socket" );
1752 SetError(wxSOCKET_INVSOCK
);
1759 // wait until we get a connection
1760 if ( !m_impl
->SelectWithTimeout(wxSOCKET_INPUT_FLAG
) )
1762 SetError(wxSOCKET_TIMEDOUT
);
1768 sock
.m_impl
= m_impl
->Accept(sock
);
1772 SetError(m_impl
->GetLastError());
1777 sock
.m_type
= wxSOCKET_BASE
;
1778 sock
.m_connected
= true;
1783 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1785 wxSocketBase
* sock
= new wxSocketBase();
1787 sock
->SetFlags(m_flags
);
1789 if (!AcceptWith(*sock
, wait
))
1798 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1800 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
);
1803 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1805 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1807 SOCKOPTLEN_T lenreal
= *optlen
;
1808 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1809 static_cast<char *>(optval
), &lenreal
) != 0 )
1818 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1820 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1822 return setsockopt(m_impl
->m_fd
, level
, optname
,
1823 static_cast<const char *>(optval
), optlen
) == 0;
1826 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1828 GAddress
* la
= local
.GetAddress();
1830 // If the address is valid, save it for use when we call Connect
1831 if (la
&& la
->m_addr
)
1833 m_localAddress
= local
;
1841 // ==========================================================================
1843 // ==========================================================================
1845 // --------------------------------------------------------------------------
1847 // --------------------------------------------------------------------------
1849 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1850 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1852 m_initialRecvBufferSize
=
1853 m_initialSendBufferSize
= -1;
1856 wxSocketClient::~wxSocketClient()
1860 // --------------------------------------------------------------------------
1862 // --------------------------------------------------------------------------
1864 bool wxSocketClient::DoConnect(const wxSockAddress
& remote
,
1865 const wxSockAddress
* local
,
1870 // Shutdown and destroy the old socket
1875 m_connected
= false;
1876 m_establishing
= false;
1878 // Create and set up the new one
1879 m_impl
= wxSocketImpl::Create(*this);
1883 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1884 if (GetFlags() & wxSOCKET_REUSEADDR
)
1885 m_impl
->SetReusable();
1886 if (GetFlags() & wxSOCKET_BROADCAST
)
1887 m_impl
->SetBroadcast();
1888 if (GetFlags() & wxSOCKET_NOBIND
)
1889 m_impl
->DontDoBind();
1891 // Bind to the local IP address and port, when provided or if one had been
1893 if ( !local
&& m_localAddress
.GetAddress() )
1894 local
= &m_localAddress
;
1897 m_impl
->SetLocal(local
->GetAddress());
1899 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1901 m_impl
->SetPeer(remote
.GetAddress());
1903 // Finally do create the socket and connect to the peer
1904 const wxSocketError err
= m_impl
->CreateClient(wait
);
1906 if ( err
!= wxSOCKET_NOERROR
)
1908 if ( err
== wxSOCKET_WOULDBLOCK
)
1910 wxASSERT_MSG( !wait
, "shouldn't get this for blocking connect" );
1912 m_establishing
= true;
1922 bool wxSocketClient::Connect(const wxSockAddress
& remote
, bool wait
)
1924 return DoConnect(remote
, NULL
, wait
);
1927 bool wxSocketClient::Connect(const wxSockAddress
& remote
,
1928 const wxSockAddress
& local
,
1931 return DoConnect(remote
, &local
, wait
);
1934 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1938 // this happens if the initial attempt to connect succeeded without
1943 wxCHECK_MSG( m_establishing
&& m_impl
, false,
1944 "No connection establishment attempt in progress" );
1946 // we must specify wxSOCKET_LOST_FLAG here explicitly because we must return
1947 // true if the connection establishment process is finished, whether it is
1948 // over because we successfully connected or because we were not able to
1950 return DoWait(seconds
, milliseconds
,
1951 wxSOCKET_CONNECTION_FLAG
| wxSOCKET_LOST_FLAG
);
1954 // ==========================================================================
1956 // ==========================================================================
1958 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
1959 wxSocketFlags flags
)
1960 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1962 // Create the socket
1963 m_impl
= wxSocketImpl::Create(*this);
1968 // Setup the socket as non connection oriented
1969 m_impl
->SetLocal(addr
.GetAddress());
1970 if (flags
& wxSOCKET_REUSEADDR
)
1972 m_impl
->SetReusable();
1974 if (GetFlags() & wxSOCKET_BROADCAST
)
1976 m_impl
->SetBroadcast();
1978 if (GetFlags() & wxSOCKET_NOBIND
)
1980 m_impl
->DontDoBind();
1983 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
1990 // Initialize all stuff
1991 m_connected
= false;
1992 m_establishing
= false;
1995 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
2004 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
2008 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
2010 m_impl
->SetPeer(addr
.GetAddress());
2015 // ==========================================================================
2017 // ==========================================================================
2019 class wxSocketModule
: public wxModule
2022 virtual bool OnInit()
2024 // wxSocketBase will call Initialize() itself only if sockets are
2025 // really used, don't do it from here
2029 virtual void OnExit()
2031 if ( wxSocketBase::IsInitialized() )
2032 wxSocketBase::Shutdown();
2036 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2039 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
2041 #endif // wxUSE_SOCKETS