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 // wxSocketWaitModeChanger: temporarily change the socket flags affecting its
129 class wxSocketWaitModeChanger
132 // temporarily set the flags to include the flag value which may be either
133 // wxSOCKET_NOWAIT or wxSOCKET_WAITALL
134 wxSocketWaitModeChanger(wxSocketBase
*socket
, int flag
)
136 m_oldflags(socket
->GetFlags())
139 wxASSERT_MSG( flag
== wxSOCKET_WAITALL
|| flag
== wxSOCKET_NOWAIT
,
142 // preserve wxSOCKET_BLOCK value when switching to wxSOCKET_WAITALL
143 // mode but not when switching to wxSOCKET_NOWAIT as the latter is
144 // incompatible with wxSOCKET_BLOCK
145 if ( flag
!= wxSOCKET_NOWAIT
)
146 flag
|= m_oldflags
& wxSOCKET_BLOCK
;
148 socket
->SetFlags(flag
);
151 ~wxSocketWaitModeChanger()
153 m_socket
->SetFlags(m_oldflags
);
157 wxSocketBase
* const m_socket
;
158 const int m_oldflags
;
160 DECLARE_NO_COPY_CLASS(wxSocketWaitModeChanger
)
163 // wxSocketRead/WriteGuard are instantiated before starting reading
164 // from/writing to the socket
165 class wxSocketReadGuard
168 wxSocketReadGuard(wxSocketBase
*socket
)
171 wxASSERT_MSG( !m_socket
->m_reading
, "read reentrancy?" );
173 m_socket
->m_reading
= true;
178 m_socket
->m_reading
= false;
182 wxSocketBase
* const m_socket
;
184 DECLARE_NO_COPY_CLASS(wxSocketReadGuard
)
187 class wxSocketWriteGuard
190 wxSocketWriteGuard(wxSocketBase
*socket
)
193 wxASSERT_MSG( !m_socket
->m_writing
, "write reentrancy?" );
195 m_socket
->m_writing
= true;
198 ~wxSocketWriteGuard()
200 m_socket
->m_writing
= false;
204 wxSocketBase
* const m_socket
;
206 DECLARE_NO_COPY_CLASS(wxSocketWriteGuard
)
209 // ============================================================================
211 // ============================================================================
213 wxSocketManager
*wxSocketManager::ms_manager
= NULL
;
216 void wxSocketManager::Set(wxSocketManager
*manager
)
218 wxASSERT_MSG( !ms_manager
, "too late to set manager now" );
220 ms_manager
= manager
;
224 void wxSocketManager::Init()
226 wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" );
229 Details: Initialize() creates a hidden window as a sink for socket
230 events, such as 'read completed'. wxMSW has only one message loop
231 for the main thread. If Initialize is called in a secondary thread,
232 the socket window will be created for the secondary thread, but
233 since there is no message loop on this thread, it will never
234 receive events and all socket operations will time out.
235 BTW, the main thread must not be stopped using sleep or block
236 on a semaphore (a bad idea in any case) or socket operations
239 On the Mac side, Initialize() stores a pointer to the CFRunLoop for
240 the main thread. Because secondary threads do not have run loops,
241 adding event notifications to the "Current" loop would have no
242 effect at all, events would never fire.
244 wxASSERT_MSG( wxIsMainThread(),
245 "sockets must be initialized from the main thread" );
247 wxAppConsole
* const app
= wxAppConsole::GetInstance();
248 wxCHECK_RET( app
, "sockets can't be initialized without wxApp" );
250 ms_manager
= app
->GetTraits()->GetSocketManager();
253 // ==========================================================================
255 // ==========================================================================
257 wxSocketImpl::wxSocketImpl(wxSocketBase
& wxsocket
)
258 : m_wxsocket(&wxsocket
)
260 m_fd
= INVALID_SOCKET
;
261 m_error
= wxSOCKET_NOERROR
;
265 SetTimeout(wxsocket
.GetTimeout() * 1000);
267 m_establishing
= false;
271 m_initialRecvBufferSize
= -1;
272 m_initialSendBufferSize
= -1;
275 wxSocketImpl::~wxSocketImpl()
277 if ( m_fd
!= INVALID_SOCKET
)
281 bool wxSocketImpl::PreCreateCheck(const wxSockAddressImpl
& addr
)
283 if ( m_fd
!= INVALID_SOCKET
)
285 m_error
= wxSOCKET_INVSOCK
;
291 m_error
= wxSOCKET_INVADDR
;
298 void wxSocketImpl::PostCreation()
300 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
302 EnableSocketOption(SO_NOSIGPIPE
);
306 EnableSocketOption(SO_REUSEADDR
);
310 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
312 EnableSocketOption(SO_BROADCAST
);
315 if ( m_initialRecvBufferSize
>= 0 )
316 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
317 if ( m_initialSendBufferSize
>= 0 )
318 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
320 // we always put our sockets in unblocked mode and handle blocking
321 // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
322 UnblockAndRegisterWithEventLoop();
325 wxSocketError
wxSocketImpl::UpdateLocalAddress()
327 WX_SOCKLEN_T lenAddr
= m_local
.GetLen();
328 if ( getsockname(m_fd
, m_local
.GetWritableAddr(), &lenAddr
) != 0 )
331 m_error
= wxSOCKET_IOERR
;
335 return wxSOCKET_NOERROR
;
338 wxSocketError
wxSocketImpl::CreateServer()
340 if ( !PreCreateCheck(m_local
) )
346 // do create the socket
347 m_fd
= socket(m_local
.GetFamily(), SOCK_STREAM
, 0);
349 if ( m_fd
== INVALID_SOCKET
)
351 m_error
= wxSOCKET_IOERR
;
352 return wxSOCKET_IOERR
;
357 // and then bind to and listen on it
359 // FIXME: should we test for m_dobind here?
360 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
361 m_error
= wxSOCKET_IOERR
;
365 if ( listen(m_fd
, 5) != 0 )
366 m_error
= wxSOCKET_IOERR
;
375 // finally retrieve the address we effectively bound to
376 return UpdateLocalAddress();
379 wxSocketError
wxSocketImpl::CreateClient(bool wait
)
381 if ( !PreCreateCheck(m_peer
) )
384 m_fd
= socket(m_peer
.GetFamily(), SOCK_STREAM
, 0);
386 if ( m_fd
== INVALID_SOCKET
)
388 m_error
= wxSOCKET_IOERR
;
389 return wxSOCKET_IOERR
;
394 // If a local address has been set, then bind to it before calling connect
395 if ( m_local
.IsOk() )
397 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
400 m_error
= wxSOCKET_IOERR
;
406 int rc
= connect(m_fd
, m_peer
.GetAddr(), m_peer
.GetLen());
407 if ( rc
== SOCKET_ERROR
)
409 wxSocketError err
= GetLastError();
410 if ( err
== wxSOCKET_WOULDBLOCK
)
412 m_establishing
= true;
414 // block waiting for connection if we should (otherwise just return
415 // wxSOCKET_WOULDBLOCK to the caller)
418 err
= SelectWithTimeout(wxSOCKET_CONNECTION_FLAG
)
421 m_establishing
= false;
429 m_error
= wxSOCKET_NOERROR
;
436 wxSocketError
wxSocketImpl::CreateUDP()
438 if ( !PreCreateCheck(m_local
) )
444 m_fd
= socket(m_local
.GetFamily(), SOCK_DGRAM
, 0);
446 if ( m_fd
== INVALID_SOCKET
)
448 m_error
= wxSOCKET_IOERR
;
449 return wxSOCKET_IOERR
;
456 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
459 m_error
= wxSOCKET_IOERR
;
463 return UpdateLocalAddress();
466 return wxSOCKET_NOERROR
;
469 wxSocketImpl
*wxSocketImpl::Accept(wxSocketBase
& wxsocket
)
471 wxSockAddressStorage from
;
472 WX_SOCKLEN_T fromlen
= sizeof(from
);
473 const SOCKET fd
= accept(m_fd
, &from
.addr
, &fromlen
);
475 if ( fd
== INVALID_SOCKET
)
478 wxSocketImpl
* const sock
= Create(wxsocket
);
480 sock
->m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
482 sock
->UnblockAndRegisterWithEventLoop();
488 void wxSocketImpl::Close()
490 if ( m_fd
!= INVALID_SOCKET
)
493 m_fd
= INVALID_SOCKET
;
498 * Disallow further read/write operations on this socket, close
499 * the fd and disable all callbacks.
501 void wxSocketImpl::Shutdown()
503 if ( m_fd
!= INVALID_SOCKET
)
505 shutdown(m_fd
, 1 /* SD_SEND */);
511 * Sets the timeout for blocking calls. Time is expressed in
514 void wxSocketImpl::SetTimeout(unsigned long millis
)
516 SetTimeValFromMS(m_timeout
, millis
);
519 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
521 m_wxsocket
->OnRequest(event
);
524 /* Address handling */
525 wxSocketError
wxSocketImpl::SetLocal(const wxSockAddressImpl
& local
)
527 /* the socket must be initialized, or it must be a server */
528 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
530 m_error
= wxSOCKET_INVSOCK
;
531 return wxSOCKET_INVSOCK
;
536 m_error
= wxSOCKET_INVADDR
;
537 return wxSOCKET_INVADDR
;
542 return wxSOCKET_NOERROR
;
545 wxSocketError
wxSocketImpl::SetPeer(const wxSockAddressImpl
& peer
)
549 m_error
= wxSOCKET_INVADDR
;
550 return wxSOCKET_INVADDR
;
555 return wxSOCKET_NOERROR
;
558 const wxSockAddressImpl
& wxSocketImpl::GetLocal()
560 if ( !m_local
.IsOk() )
561 UpdateLocalAddress();
566 // ----------------------------------------------------------------------------
568 // ----------------------------------------------------------------------------
570 // this macro wraps the given expression (normally a syscall) in a loop which
571 // ignores any interruptions, i.e. reevaluates it again if it failed and errno
574 #define DO_WHILE_EINTR( rc, syscall ) \
578 while ( rc == -1 && errno == EINTR )
580 #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
583 int wxSocketImpl::RecvStream(void *buffer
, int size
)
586 DO_WHILE_EINTR( ret
, recv(m_fd
, static_cast<char *>(buffer
), size
, 0) );
590 // receiving 0 bytes for a TCP socket indicates that the connection was
591 // closed by peer so shut down our end as well (for UDP sockets empty
592 // datagrams are also possible)
593 m_establishing
= false;
594 NotifyOnStateChange(wxSOCKET_LOST
);
598 // do not return an error in this case however
604 int wxSocketImpl::SendStream(const void *buffer
, int size
)
607 DO_WHILE_EINTR( ret
, send(m_fd
, static_cast<const char *>(buffer
), size
,
608 wxSOCKET_MSG_NOSIGNAL
) );
613 int wxSocketImpl::RecvDgram(void *buffer
, int size
)
615 wxSockAddressStorage from
;
616 WX_SOCKLEN_T fromlen
= sizeof(from
);
619 DO_WHILE_EINTR( ret
, recvfrom(m_fd
, static_cast<char *>(buffer
), size
,
620 0, &from
.addr
, &fromlen
) );
622 if ( ret
== SOCKET_ERROR
)
625 m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
626 if ( !m_peer
.IsOk() )
632 int wxSocketImpl::SendDgram(const void *buffer
, int size
)
634 if ( !m_peer
.IsOk() )
636 m_error
= wxSOCKET_INVADDR
;
641 DO_WHILE_EINTR( ret
, sendto(m_fd
, static_cast<const char *>(buffer
), size
,
642 0, m_peer
.GetAddr(), m_peer
.GetLen()) );
647 int wxSocketImpl::Read(void *buffer
, int size
)
649 // server sockets can't be used for IO, only to accept new connections
650 if ( m_fd
== INVALID_SOCKET
|| m_server
)
652 m_error
= wxSOCKET_INVSOCK
;
656 int ret
= m_stream
? RecvStream(buffer
, size
)
657 : RecvDgram(buffer
, size
);
659 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
664 int wxSocketImpl::Write(const void *buffer
, int size
)
666 if ( m_fd
== INVALID_SOCKET
|| m_server
)
668 m_error
= wxSOCKET_INVSOCK
;
672 int ret
= m_stream
? SendStream(buffer
, size
)
673 : SendDgram(buffer
, size
);
675 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
680 // ==========================================================================
682 // ==========================================================================
684 // --------------------------------------------------------------------------
685 // Initialization and shutdown
686 // --------------------------------------------------------------------------
688 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
689 // to m_countInit with a crit section
690 size_t wxSocketBase::m_countInit
= 0;
692 bool wxSocketBase::IsInitialized()
694 return m_countInit
> 0;
697 bool wxSocketBase::Initialize()
699 if ( !m_countInit
++ )
701 wxSocketManager
* const manager
= wxSocketManager::Get();
702 if ( !manager
|| !manager
->OnInit() )
713 void wxSocketBase::Shutdown()
715 // we should be initialized
716 wxASSERT_MSG( m_countInit
> 0, _T("extra call to Shutdown()") );
717 if ( --m_countInit
== 0 )
719 wxSocketManager
* const manager
= wxSocketManager::Get();
720 wxCHECK_RET( manager
, "should have a socket manager" );
726 // --------------------------------------------------------------------------
728 // --------------------------------------------------------------------------
730 void wxSocketBase::Init()
733 m_type
= wxSOCKET_UNINIT
;
744 m_beingDeleted
= false;
759 if ( !IsInitialized() )
761 // this Initialize() will be undone by wxSocketModule::OnExit(), all
762 // the other calls to it should be matched by a call to Shutdown()
767 wxSocketBase::wxSocketBase()
772 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
781 wxSocketBase::~wxSocketBase()
783 // Just in case the app called Destroy() *and* then deleted the socket
784 // immediately: don't leave dangling pointers.
785 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
787 traits
->RemoveFromPendingDelete(this);
789 // Shutdown and close the socket
793 // Destroy the implementation object
796 // Free the pushback buffer
801 bool wxSocketBase::Destroy()
803 // Delayed destruction: the socket will be deleted during the next idle
804 // loop iteration. This ensures that all pending events have been
806 m_beingDeleted
= true;
808 // Shutdown and close the socket
811 // Suppress events from now on
814 // schedule this object for deletion
815 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
818 // let the traits object decide what to do with us
819 traits
->ScheduleForDestroy(this);
821 else // no app or no traits
823 // in wxBase we might have no app object at all, don't leak memory
830 // ----------------------------------------------------------------------------
832 // ----------------------------------------------------------------------------
834 void wxSocketBase::SetError(wxSocketError error
)
836 m_impl
->m_error
= error
;
839 wxSocketError
wxSocketBase::LastError() const
841 return m_impl
->GetError();
844 // --------------------------------------------------------------------------
846 // --------------------------------------------------------------------------
848 // The following IO operations update m_lcount:
849 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
850 bool wxSocketBase::Close()
852 // Interrupt pending waits
858 m_establishing
= false;
862 void wxSocketBase::ShutdownOutput()
868 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
870 wxSocketReadGuard
read(this);
872 m_lcount
= DoRead(buffer
, nbytes
);
877 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
879 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
881 // We use pointer arithmetic here which doesn't work with void pointers.
882 char *buffer
= static_cast<char *>(buffer_
);
883 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
885 // Try the push back buffer first, even before checking whether the socket
886 // is valid to allow reading previously pushed back data from an already
888 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
894 // our socket is non-blocking so Read() will return immediately if
895 // there is nothing to read yet and it's more efficient to try it first
896 // before entering DoWait() which is going to start dispatching GUI
897 // events and, even more importantly, we must do this under Windows
898 // where we're not going to get notifications about socket being ready
899 // for reading before we read all the existing data from it
900 const int ret
= m_connected
? m_impl
->Read(buffer
, nbytes
) : 0;
903 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
905 // if we don't want to wait, just return immediately
906 if ( m_flags
& wxSOCKET_NOWAIT
)
909 // otherwise wait until the socket becomes ready for reading or
910 // an error occurs on it
911 if ( !DoWaitWithTimeout(wxSOCKET_INPUT_FLAG
|
912 wxSOCKET_LOST_FLAG
) )
914 // and exit if the timeout elapsed before it did
915 SetError(wxSOCKET_TIMEDOUT
);
924 SetError(wxSOCKET_IOERR
);
930 // for connection-oriented (e.g. TCP) sockets we can only read
931 // 0 bytes if the other end has been closed, and for connectionless
932 // ones (UDP) this flag doesn't make sense anyhow so we can set it
933 // to true too without doing any harm
936 // we're not going to read anything else and so if we haven't read
937 // anything (or not everything in wxSOCKET_WAITALL case) already,
939 if ( (m_flags
& wxSOCKET_WAITALL
) || !total
)
940 SetError(wxSOCKET_IOERR
);
946 // if we are happy to read something and not the entire nbytes bytes,
948 if ( !(m_flags
& wxSOCKET_WAITALL
) )
958 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
962 unsigned char sig
[4];
963 unsigned char len
[4];
966 wxSocketReadGuard
read(this);
968 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL
);
971 if ( DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
973 wxUint32 sig
= (wxUint32
)msg
.sig
[0];
974 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
975 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
976 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
978 if ( sig
== 0xfeeddead )
980 wxUint32 len
= (wxUint32
)msg
.len
[0];
981 len
|= (wxUint32
)(msg
.len
[1] << 8);
982 len
|= (wxUint32
)(msg
.len
[2] << 16);
983 len
|= (wxUint32
)(msg
.len
[3] << 24);
994 // Don't attempt to read if the msg was zero bytes long.
995 m_lcount
= len
? DoRead(buffer
, len
) : 0;
999 char discard_buffer
[MAX_DISCARD_SIZE
];
1002 // NOTE: discarded bytes don't add to m_lcount.
1005 discard_len
= len2
> MAX_DISCARD_SIZE
1008 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
1009 len2
-= (wxUint32
)discard_len
;
1011 while ((discard_len
> 0) && len2
);
1014 if ( !len2
&& DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1016 sig
= (wxUint32
)msg
.sig
[0];
1017 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1018 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1019 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1021 if ( sig
== 0xdeadfeed )
1028 SetError(wxSOCKET_IOERR
);
1033 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
1035 wxSocketReadGuard
read(this);
1037 m_lcount
= DoRead(buffer
, nbytes
);
1039 Pushback(buffer
, m_lcount
);
1044 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
1046 wxSocketWriteGuard
write(this);
1048 m_lcount
= DoWrite(buffer
, nbytes
);
1053 // This function is a mirror image of DoRead() except that it doesn't use the
1054 // push back buffer and doesn't treat 0 return value specially (normally this
1055 // shouldn't happen at all here), so please see comments there for explanations
1056 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
1058 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
1060 const char *buffer
= static_cast<const char *>(buffer_
);
1061 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1068 if ( (m_flags
& wxSOCKET_WAITALL
) || !total
)
1069 SetError(wxSOCKET_IOERR
);
1073 const int ret
= m_impl
->Write(buffer
, nbytes
);
1076 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
1078 if ( m_flags
& wxSOCKET_NOWAIT
)
1081 if ( !DoWaitWithTimeout(wxSOCKET_OUTPUT_FLAG
|
1082 wxSOCKET_LOST_FLAG
) )
1084 SetError(wxSOCKET_TIMEDOUT
);
1090 else // "real" error
1092 SetError(wxSOCKET_IOERR
);
1099 if ( !(m_flags
& wxSOCKET_WAITALL
) )
1109 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
1113 unsigned char sig
[4];
1114 unsigned char len
[4];
1117 wxSocketWriteGuard
write(this);
1119 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL
);
1121 msg
.sig
[0] = (unsigned char) 0xad;
1122 msg
.sig
[1] = (unsigned char) 0xde;
1123 msg
.sig
[2] = (unsigned char) 0xed;
1124 msg
.sig
[3] = (unsigned char) 0xfe;
1126 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
1127 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
1128 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
1129 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1132 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
) )
1134 m_lcount
= DoWrite(buffer
, nbytes
);
1135 if ( m_lcount
== nbytes
)
1137 msg
.sig
[0] = (unsigned char) 0xed;
1138 msg
.sig
[1] = (unsigned char) 0xfe;
1139 msg
.sig
[2] = (unsigned char) 0xad;
1140 msg
.sig
[3] = (unsigned char) 0xde;
1144 msg
.len
[3] = (char) 0;
1146 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
))
1152 SetError(wxSOCKET_IOERR
);
1157 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1160 Pushback(buffer
, nbytes
);
1162 SetError(wxSOCKET_NOERROR
);
1168 wxSocketBase
& wxSocketBase::Discard()
1170 char *buffer
= new char[MAX_DISCARD_SIZE
];
1174 wxSocketReadGuard
read(this);
1176 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1180 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1183 while (ret
== MAX_DISCARD_SIZE
);
1187 SetError(wxSOCKET_NOERROR
);
1192 // --------------------------------------------------------------------------
1194 // --------------------------------------------------------------------------
1197 This function will check for the events specified in the flags parameter,
1198 and it will return a mask indicating which operations can be performed.
1200 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
,
1201 const timeval
*timeout
)
1203 if ( m_fd
== INVALID_SOCKET
)
1204 return (wxSOCKET_LOST_FLAG
& flags
);
1210 tv
.tv_sec
= tv
.tv_usec
= 0;
1212 // prepare the FD sets, passing NULL for the one(s) we don't use
1214 readfds
, *preadfds
= NULL
,
1215 writefds
, *pwritefds
= NULL
,
1216 exceptfds
; // always want to know about errors
1218 if ( flags
& wxSOCKET_INPUT_FLAG
)
1220 preadfds
= &readfds
;
1221 wxFD_ZERO(preadfds
);
1222 wxFD_SET(m_fd
, preadfds
);
1225 // when using non-blocking connect() the socket becomes connected
1226 // (successfully or not) when it becomes writable
1227 if ( flags
& (wxSOCKET_OUTPUT_FLAG
| wxSOCKET_CONNECTION_FLAG
) )
1229 pwritefds
= &writefds
;
1230 wxFD_ZERO(pwritefds
);
1231 wxFD_SET(m_fd
, pwritefds
);
1234 wxFD_ZERO(&exceptfds
);
1235 wxFD_SET(m_fd
, &exceptfds
);
1237 const int rc
= select(m_fd
+ 1, preadfds
, pwritefds
, &exceptfds
, &tv
);
1239 // check for errors first
1240 if ( rc
== -1 || wxFD_ISSET(m_fd
, &exceptfds
) )
1242 m_establishing
= false;
1244 return wxSOCKET_LOST_FLAG
& flags
;
1250 wxASSERT_MSG( rc
== 1, "unexpected select() return value" );
1252 wxSocketEventFlags detected
= 0;
1253 if ( preadfds
&& wxFD_ISSET(m_fd
, preadfds
) )
1254 detected
|= wxSOCKET_INPUT_FLAG
;
1256 if ( pwritefds
&& wxFD_ISSET(m_fd
, pwritefds
) )
1258 // check for the case of non-blocking connect()
1259 if ( m_establishing
&& !m_server
)
1262 SOCKOPTLEN_T len
= sizeof(error
);
1263 m_establishing
= false;
1264 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1267 detected
= wxSOCKET_LOST_FLAG
;
1269 detected
|= wxSOCKET_CONNECTION_FLAG
;
1271 else // not called to get non-blocking connect() status
1273 detected
|= wxSOCKET_OUTPUT_FLAG
;
1277 return detected
& flags
;
1281 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1283 // Use either the provided timeout or the default timeout value associated
1284 // with this socket.
1286 // TODO: allow waiting forever, see #9443
1287 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1288 : seconds
* 1000 + milliseconds
;
1290 return DoWait(timeout
, flags
);
1294 wxSocketBase::DoWait(long timeout
, wxSocketEventFlags flags
)
1296 wxCHECK_MSG( m_impl
, false, "can't wait on invalid socket" );
1298 // we're never going to become ready if we're not connected (any more)
1299 if ( !m_connected
&& !m_establishing
)
1300 return (flags
& wxSOCKET_LOST_FLAG
) != 0;
1302 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1303 m_interrupt
= false;
1306 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1308 // Get the active event loop which we'll use for the message dispatching
1309 // when running in the main thread unless this was explicitly disabled by
1310 // setting wxSOCKET_BLOCK flag
1311 wxEventLoopBase
*eventLoop
;
1312 if ( !(m_flags
& wxSOCKET_BLOCK
) && wxIsMainThread() )
1314 eventLoop
= wxEventLoop::GetActive();
1316 else // in worker thread
1318 // We never dispatch messages from threads other than the main one.
1322 // Wait until we receive the event we're waiting for or the timeout expires
1323 // (but note that we always execute the loop at least once, even if timeout
1324 // is 0 as this is used for polling)
1325 bool gotEvent
= false;
1326 for ( bool firstTime
= true; !m_interrupt
; firstTime
= false )
1328 long timeLeft
= wxMilliClockToLong(timeEnd
- wxGetLocalTimeMillis());
1337 wxSocketEventFlags events
;
1340 // reset them before starting to wait
1343 eventLoop
->DispatchTimeout(timeLeft
);
1345 events
= m_eventsgot
;
1347 else // no event loop or waiting in another thread
1349 // as explained below, we should always check for wxSOCKET_LOST_FLAG
1351 SetTimeValFromMS(tv
, timeLeft
);
1352 events
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
, &tv
);
1355 // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
1356 // it, as continuing to wait for anything else after getting it is
1358 if ( events
& wxSOCKET_LOST_FLAG
)
1360 m_connected
= false;
1361 m_establishing
= false;
1362 if ( flags
& wxSOCKET_LOST_FLAG
)
1367 // otherwise mask out the bits we're not interested in
1370 // Incoming connection (server) or connection established (client)?
1371 if ( events
& wxSOCKET_CONNECTION_FLAG
)
1374 m_establishing
= false;
1379 // Data available or output buffer ready?
1380 if ( (events
& wxSOCKET_INPUT_FLAG
) || (events
& wxSOCKET_OUTPUT_FLAG
) )
1390 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1392 return DoWait(seconds
, milliseconds
,
1393 wxSOCKET_INPUT_FLAG
|
1394 wxSOCKET_OUTPUT_FLAG
|
1395 wxSOCKET_CONNECTION_FLAG
|
1400 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1402 // Check pushback buffer before entering DoWait
1406 // Check if the socket is not already ready for input, if it is, there is
1407 // no need to start waiting for it (worse, we'll actually never get a
1408 // notification about the socket becoming ready if it is already under
1410 if ( m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1413 // Note that wxSOCKET_LOST_FLAG has to be explicitly passed to DoWait
1414 // because of the semantics of WaitForRead: a return value of true means
1415 // that a Read call will return immediately, not that there is
1416 // actually data to read.
1417 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1421 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1423 if ( m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1426 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1429 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1431 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
);
1434 // --------------------------------------------------------------------------
1436 // --------------------------------------------------------------------------
1439 // Get local or peer address
1442 bool wxSocketBase::GetPeer(wxSockAddress
& addr
) const
1444 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1446 const wxSockAddressImpl
& peer
= m_impl
->GetPeer();
1450 addr
.SetAddress(peer
);
1455 bool wxSocketBase::GetLocal(wxSockAddress
& addr
) const
1457 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1459 const wxSockAddressImpl
& local
= m_impl
->GetLocal();
1460 if ( !local
.IsOk() )
1463 addr
.SetAddress(local
);
1469 // Save and restore socket state
1472 void wxSocketBase::SaveState()
1474 wxSocketState
*state
;
1476 state
= new wxSocketState();
1478 state
->m_flags
= m_flags
;
1479 state
->m_notify
= m_notify
;
1480 state
->m_eventmask
= m_eventmask
;
1481 state
->m_clientData
= m_clientData
;
1483 m_states
.Append(state
);
1486 void wxSocketBase::RestoreState()
1488 wxList::compatibility_iterator node
;
1489 wxSocketState
*state
;
1491 node
= m_states
.GetLast();
1495 state
= (wxSocketState
*)node
->GetData();
1497 m_flags
= state
->m_flags
;
1498 m_notify
= state
->m_notify
;
1499 m_eventmask
= state
->m_eventmask
;
1500 m_clientData
= state
->m_clientData
;
1502 m_states
.Erase(node
);
1507 // Timeout and flags
1510 void wxSocketBase::SetTimeout(long seconds
)
1512 m_timeout
= seconds
;
1515 m_impl
->SetTimeout(m_timeout
* 1000);
1518 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1520 // Do some sanity checking on the flags used: not all values can be used
1522 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1523 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1524 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1525 "wxSOCKET_NOWAIT doesn't make sense" );
1531 // --------------------------------------------------------------------------
1533 // --------------------------------------------------------------------------
1535 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1537 wxSocketEventFlags flag
= 0;
1538 switch ( notification
)
1540 case wxSOCKET_INPUT
:
1541 flag
= wxSOCKET_INPUT_FLAG
;
1544 case wxSOCKET_OUTPUT
:
1545 flag
= wxSOCKET_OUTPUT_FLAG
;
1548 case wxSOCKET_CONNECTION
:
1549 flag
= wxSOCKET_CONNECTION_FLAG
;
1553 flag
= wxSOCKET_LOST_FLAG
;
1557 wxFAIL_MSG( "unknown wxSocket notification" );
1560 // if we lost the connection the socket is now closed
1561 if ( notification
== wxSOCKET_LOST
)
1564 // remember the events which were generated for this socket, we're going to
1565 // use this in DoWait()
1566 m_eventsgot
|= flag
;
1568 // send the wx event if enabled and we're interested in it
1569 if ( m_notify
&& (m_eventmask
& flag
) && m_handler
)
1571 // If we are in the middle of a R/W operation, do not propagate events
1572 // to users. Also, filter 'late' events which are no longer valid.
1573 if ( notification
== wxSOCKET_INPUT
)
1575 if ( m_reading
|| !m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1578 else if ( notification
== wxSOCKET_OUTPUT
)
1580 if ( m_writing
|| !m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1584 wxSocketEvent
event(m_id
);
1585 event
.m_event
= notification
;
1586 event
.m_clientData
= m_clientData
;
1587 event
.SetEventObject(this);
1589 m_handler
->AddPendingEvent(event
);
1593 void wxSocketBase::Notify(bool notify
)
1598 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1600 m_eventmask
= flags
;
1603 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1605 m_handler
= &handler
;
1609 // --------------------------------------------------------------------------
1611 // --------------------------------------------------------------------------
1613 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1617 if (m_unread
== NULL
)
1618 m_unread
= malloc(size
);
1623 tmp
= malloc(m_unrd_size
+ size
);
1624 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1630 m_unrd_size
+= size
;
1632 memcpy(m_unread
, buffer
, size
);
1635 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1637 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1642 if (size
> (m_unrd_size
-m_unrd_cur
))
1643 size
= m_unrd_size
-m_unrd_cur
;
1645 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1650 if (m_unrd_size
== m_unrd_cur
)
1663 // ==========================================================================
1665 // ==========================================================================
1667 // --------------------------------------------------------------------------
1669 // --------------------------------------------------------------------------
1671 wxSocketServer::wxSocketServer(const wxSockAddress
& addr
,
1672 wxSocketFlags flags
)
1673 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1675 wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") );
1677 m_impl
= wxSocketImpl::Create(*this);
1681 wxLogTrace( wxTRACE_Socket
, _T("*** Failed to create m_impl") );
1685 // Setup the socket as server
1686 m_impl
->SetLocal(addr
.GetAddress());
1688 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1689 m_impl
->SetReusable();
1691 if (GetFlags() & wxSOCKET_BROADCAST
) {
1692 m_impl
->SetBroadcast();
1694 if (GetFlags() & wxSOCKET_NOBIND
) {
1695 m_impl
->DontDoBind();
1698 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1703 wxLogTrace( wxTRACE_Socket
, _T("*** CreateServer() failed") );
1707 wxLogTrace( wxTRACE_Socket
, _T("wxSocketServer on fd %d"), m_impl
->m_fd
);
1710 // --------------------------------------------------------------------------
1712 // --------------------------------------------------------------------------
1714 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1716 if ( !m_impl
|| (m_impl
->m_fd
== INVALID_SOCKET
) || !m_impl
->IsServer() )
1718 wxFAIL_MSG( "can only be called for a valid server socket" );
1720 SetError(wxSOCKET_INVSOCK
);
1727 // wait until we get a connection
1728 if ( !m_impl
->SelectWithTimeout(wxSOCKET_INPUT_FLAG
) )
1730 SetError(wxSOCKET_TIMEDOUT
);
1736 sock
.m_impl
= m_impl
->Accept(sock
);
1740 SetError(m_impl
->GetLastError());
1745 sock
.m_type
= wxSOCKET_BASE
;
1746 sock
.m_connected
= true;
1751 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1753 wxSocketBase
* sock
= new wxSocketBase();
1755 sock
->SetFlags(m_flags
);
1757 if (!AcceptWith(*sock
, wait
))
1766 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1768 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
);
1771 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1773 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1775 SOCKOPTLEN_T lenreal
= *optlen
;
1776 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1777 static_cast<char *>(optval
), &lenreal
) != 0 )
1786 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1788 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1790 return setsockopt(m_impl
->m_fd
, level
, optname
,
1791 static_cast<const char *>(optval
), optlen
) == 0;
1794 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1796 m_localAddress
= local
;
1801 // ==========================================================================
1803 // ==========================================================================
1805 // --------------------------------------------------------------------------
1807 // --------------------------------------------------------------------------
1809 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1810 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1812 m_initialRecvBufferSize
=
1813 m_initialSendBufferSize
= -1;
1816 wxSocketClient::~wxSocketClient()
1820 // --------------------------------------------------------------------------
1822 // --------------------------------------------------------------------------
1824 bool wxSocketClient::DoConnect(const wxSockAddress
& remote
,
1825 const wxSockAddress
* local
,
1830 // Shutdown and destroy the old socket
1835 m_connected
= false;
1836 m_establishing
= false;
1838 // Create and set up the new one
1839 m_impl
= wxSocketImpl::Create(*this);
1843 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1844 if (GetFlags() & wxSOCKET_REUSEADDR
)
1845 m_impl
->SetReusable();
1846 if (GetFlags() & wxSOCKET_BROADCAST
)
1847 m_impl
->SetBroadcast();
1848 if (GetFlags() & wxSOCKET_NOBIND
)
1849 m_impl
->DontDoBind();
1851 // Bind to the local IP address and port, when provided or if one had been
1853 if ( !local
&& m_localAddress
.GetAddress().IsOk() )
1854 local
= &m_localAddress
;
1857 m_impl
->SetLocal(local
->GetAddress());
1859 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1861 m_impl
->SetPeer(remote
.GetAddress());
1863 // Finally do create the socket and connect to the peer
1864 const wxSocketError err
= m_impl
->CreateClient(wait
);
1866 if ( err
!= wxSOCKET_NOERROR
)
1868 if ( err
== wxSOCKET_WOULDBLOCK
)
1870 wxASSERT_MSG( !wait
, "shouldn't get this for blocking connect" );
1872 m_establishing
= true;
1882 bool wxSocketClient::Connect(const wxSockAddress
& remote
, bool wait
)
1884 return DoConnect(remote
, NULL
, wait
);
1887 bool wxSocketClient::Connect(const wxSockAddress
& remote
,
1888 const wxSockAddress
& local
,
1891 return DoConnect(remote
, &local
, wait
);
1894 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1898 // this happens if the initial attempt to connect succeeded without
1903 wxCHECK_MSG( m_establishing
&& m_impl
, false,
1904 "No connection establishment attempt in progress" );
1906 // we must specify wxSOCKET_LOST_FLAG here explicitly because we must return
1907 // true if the connection establishment process is finished, whether it is
1908 // over because we successfully connected or because we were not able to
1910 return DoWait(seconds
, milliseconds
,
1911 wxSOCKET_CONNECTION_FLAG
| wxSOCKET_LOST_FLAG
);
1914 // ==========================================================================
1916 // ==========================================================================
1918 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
1919 wxSocketFlags flags
)
1920 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1922 // Create the socket
1923 m_impl
= wxSocketImpl::Create(*this);
1928 // Setup the socket as non connection oriented
1929 m_impl
->SetLocal(addr
.GetAddress());
1930 if (flags
& wxSOCKET_REUSEADDR
)
1932 m_impl
->SetReusable();
1934 if (GetFlags() & wxSOCKET_BROADCAST
)
1936 m_impl
->SetBroadcast();
1938 if (GetFlags() & wxSOCKET_NOBIND
)
1940 m_impl
->DontDoBind();
1943 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
1950 // Initialize all stuff
1951 m_connected
= false;
1952 m_establishing
= false;
1955 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1964 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
1968 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1970 m_impl
->SetPeer(addr
.GetAddress());
1975 // ==========================================================================
1977 // ==========================================================================
1979 class wxSocketModule
: public wxModule
1982 virtual bool OnInit()
1984 // wxSocketBase will call Initialize() itself only if sockets are
1985 // really used, don't do it from here
1989 virtual void OnExit()
1991 if ( wxSocketBase::IsInitialized() )
1992 wxSocketBase::Shutdown();
1996 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
1999 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
2001 #endif // wxUSE_SOCKETS