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
;
179 m_error
= wxSOCKET_NOERROR
;
183 SetTimeout(wxsocket
.GetTimeout() * 1000);
185 m_establishing
= false;
189 m_initialRecvBufferSize
= -1;
190 m_initialSendBufferSize
= -1;
193 wxSocketImpl::~wxSocketImpl()
195 if ( m_fd
!= INVALID_SOCKET
)
199 bool wxSocketImpl::PreCreateCheck(const wxSockAddressImpl
& addr
)
201 if ( m_fd
!= INVALID_SOCKET
)
203 m_error
= wxSOCKET_INVSOCK
;
209 m_error
= wxSOCKET_INVADDR
;
216 void wxSocketImpl::PostCreation()
218 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
220 EnableSocketOption(SO_NOSIGPIPE
);
224 EnableSocketOption(SO_REUSEADDR
);
228 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
230 EnableSocketOption(SO_BROADCAST
);
233 if ( m_initialRecvBufferSize
>= 0 )
234 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
235 if ( m_initialSendBufferSize
>= 0 )
236 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
238 // we always put our sockets in unblocked mode and handle blocking
239 // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
240 UnblockAndRegisterWithEventLoop();
243 wxSocketError
wxSocketImpl::UpdateLocalAddress()
245 WX_SOCKLEN_T lenAddr
= m_local
.GetLen();
246 if ( getsockname(m_fd
, m_local
.GetWritableAddr(), &lenAddr
) != 0 )
249 m_error
= wxSOCKET_IOERR
;
253 return wxSOCKET_NOERROR
;
256 wxSocketError
wxSocketImpl::CreateServer()
258 if ( !PreCreateCheck(m_local
) )
264 // do create the socket
265 m_fd
= socket(m_local
.GetFamily(), 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
.GetAddr(), m_local
.GetLen()) != 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(bool wait
)
299 if ( !PreCreateCheck(m_peer
) )
302 m_fd
= socket(m_peer
.GetFamily(), 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
.IsOk() )
315 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
318 m_error
= wxSOCKET_IOERR
;
324 int rc
= connect(m_fd
, m_peer
.GetAddr(), m_peer
.GetLen());
325 if ( rc
== SOCKET_ERROR
)
327 wxSocketError err
= GetLastError();
328 if ( err
== wxSOCKET_WOULDBLOCK
)
330 m_establishing
= true;
332 // block waiting for connection if we should (otherwise just return
333 // wxSOCKET_WOULDBLOCK to the caller)
336 err
= SelectWithTimeout(wxSOCKET_CONNECTION_FLAG
)
339 m_establishing
= false;
347 m_error
= wxSOCKET_NOERROR
;
354 wxSocketError
wxSocketImpl::CreateUDP()
356 if ( !PreCreateCheck(m_local
) )
362 m_fd
= socket(m_local
.GetFamily(), SOCK_DGRAM
, 0);
364 if ( m_fd
== INVALID_SOCKET
)
366 m_error
= wxSOCKET_IOERR
;
367 return wxSOCKET_IOERR
;
374 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
377 m_error
= wxSOCKET_IOERR
;
381 return UpdateLocalAddress();
384 return wxSOCKET_NOERROR
;
387 wxSocketImpl
*wxSocketImpl::Accept(wxSocketBase
& wxsocket
)
389 wxSockAddressStorage from
;
390 WX_SOCKLEN_T fromlen
= sizeof(from
);
391 const SOCKET fd
= accept(m_fd
, &from
.addr
, &fromlen
);
393 if ( fd
== INVALID_SOCKET
)
396 wxSocketImpl
* const sock
= Create(wxsocket
);
398 sock
->m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
400 sock
->UnblockAndRegisterWithEventLoop();
406 void wxSocketImpl::Close()
408 if ( m_fd
!= INVALID_SOCKET
)
411 m_fd
= INVALID_SOCKET
;
416 * Disallow further read/write operations on this socket, close
417 * the fd and disable all callbacks.
419 void wxSocketImpl::Shutdown()
421 if ( m_fd
!= INVALID_SOCKET
)
423 shutdown(m_fd
, 1 /* SD_SEND */);
429 * Sets the timeout for blocking calls. Time is expressed in
432 void wxSocketImpl::SetTimeout(unsigned long millis
)
434 SetTimeValFromMS(m_timeout
, millis
);
437 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
439 m_wxsocket
->OnRequest(event
);
442 /* Address handling */
443 wxSocketError
wxSocketImpl::SetLocal(const wxSockAddressImpl
& local
)
445 /* the socket must be initialized, or it must be a server */
446 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
448 m_error
= wxSOCKET_INVSOCK
;
449 return wxSOCKET_INVSOCK
;
454 m_error
= wxSOCKET_INVADDR
;
455 return wxSOCKET_INVADDR
;
460 return wxSOCKET_NOERROR
;
463 wxSocketError
wxSocketImpl::SetPeer(const wxSockAddressImpl
& peer
)
467 m_error
= wxSOCKET_INVADDR
;
468 return wxSOCKET_INVADDR
;
473 return wxSOCKET_NOERROR
;
476 const wxSockAddressImpl
& wxSocketImpl::GetLocal()
478 if ( !m_local
.IsOk() )
479 UpdateLocalAddress();
484 // ----------------------------------------------------------------------------
486 // ----------------------------------------------------------------------------
488 // this macro wraps the given expression (normally a syscall) in a loop which
489 // ignores any interruptions, i.e. reevaluates it again if it failed and errno
492 #define DO_WHILE_EINTR( rc, syscall ) \
496 while ( rc == -1 && errno == EINTR )
498 #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
501 int wxSocketImpl::RecvStream(void *buffer
, int size
)
504 DO_WHILE_EINTR( ret
, recv(m_fd
, static_cast<char *>(buffer
), size
, 0) );
508 // receiving 0 bytes for a TCP socket indicates that the connection was
509 // closed by peer so shut down our end as well (for UDP sockets empty
510 // datagrams are also possible)
511 m_establishing
= false;
512 NotifyOnStateChange(wxSOCKET_LOST
);
516 // do not return an error in this case however
522 int wxSocketImpl::SendStream(const void *buffer
, int size
)
525 DO_WHILE_EINTR( ret
, send(m_fd
, static_cast<const char *>(buffer
), size
,
526 wxSOCKET_MSG_NOSIGNAL
) );
531 int wxSocketImpl::RecvDgram(void *buffer
, int size
)
533 wxSockAddressStorage from
;
534 WX_SOCKLEN_T fromlen
= sizeof(from
);
537 DO_WHILE_EINTR( ret
, recvfrom(m_fd
, static_cast<char *>(buffer
), size
,
538 0, &from
.addr
, &fromlen
) );
540 if ( ret
== SOCKET_ERROR
)
543 m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
544 if ( !m_peer
.IsOk() )
550 int wxSocketImpl::SendDgram(const void *buffer
, int size
)
552 if ( !m_peer
.IsOk() )
554 m_error
= wxSOCKET_INVADDR
;
559 DO_WHILE_EINTR( ret
, sendto(m_fd
, static_cast<const char *>(buffer
), size
,
560 0, m_peer
.GetAddr(), m_peer
.GetLen()) );
565 int wxSocketImpl::Read(void *buffer
, int size
)
567 // server sockets can't be used for IO, only to accept new connections
568 if ( m_fd
== INVALID_SOCKET
|| m_server
)
570 m_error
= wxSOCKET_INVSOCK
;
574 int ret
= m_stream
? RecvStream(buffer
, size
)
575 : RecvDgram(buffer
, size
);
577 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
582 int wxSocketImpl::Write(const void *buffer
, int size
)
584 if ( m_fd
== INVALID_SOCKET
|| m_server
)
586 m_error
= wxSOCKET_INVSOCK
;
590 int ret
= m_stream
? SendStream(buffer
, size
)
591 : SendDgram(buffer
, size
);
593 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
598 // ==========================================================================
600 // ==========================================================================
602 // --------------------------------------------------------------------------
603 // Initialization and shutdown
604 // --------------------------------------------------------------------------
606 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
607 // to m_countInit with a crit section
608 size_t wxSocketBase::m_countInit
= 0;
610 bool wxSocketBase::IsInitialized()
612 return m_countInit
> 0;
615 bool wxSocketBase::Initialize()
617 if ( !m_countInit
++ )
619 wxSocketManager
* const manager
= wxSocketManager::Get();
620 if ( !manager
|| !manager
->OnInit() )
631 void wxSocketBase::Shutdown()
633 // we should be initialized
634 wxASSERT_MSG( m_countInit
> 0, _T("extra call to Shutdown()") );
635 if ( --m_countInit
== 0 )
637 wxSocketManager
* const manager
= wxSocketManager::Get();
638 wxCHECK_RET( manager
, "should have a socket manager" );
644 // --------------------------------------------------------------------------
646 // --------------------------------------------------------------------------
648 void wxSocketBase::Init()
651 m_type
= wxSOCKET_UNINIT
;
662 m_beingDeleted
= false;
677 if ( !IsInitialized() )
679 // this Initialize() will be undone by wxSocketModule::OnExit(), all
680 // the other calls to it should be matched by a call to Shutdown()
685 wxSocketBase::wxSocketBase()
690 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
699 wxSocketBase::~wxSocketBase()
701 // Just in case the app called Destroy() *and* then deleted the socket
702 // immediately: don't leave dangling pointers.
703 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
705 traits
->RemoveFromPendingDelete(this);
707 // Shutdown and close the socket
711 // Destroy the implementation object
714 // Free the pushback buffer
719 bool wxSocketBase::Destroy()
721 // Delayed destruction: the socket will be deleted during the next idle
722 // loop iteration. This ensures that all pending events have been
724 m_beingDeleted
= true;
726 // Shutdown and close the socket
729 // Suppress events from now on
732 // schedule this object for deletion
733 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
736 // let the traits object decide what to do with us
737 traits
->ScheduleForDestroy(this);
739 else // no app or no traits
741 // in wxBase we might have no app object at all, don't leak memory
748 // ----------------------------------------------------------------------------
750 // ----------------------------------------------------------------------------
752 void wxSocketBase::SetError(wxSocketError error
)
754 m_impl
->m_error
= error
;
757 wxSocketError
wxSocketBase::LastError() const
759 return m_impl
->GetError();
762 // --------------------------------------------------------------------------
764 // --------------------------------------------------------------------------
766 // The following IO operations update m_lcount:
767 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
768 bool wxSocketBase::Close()
770 // Interrupt pending waits
776 m_establishing
= false;
780 void wxSocketBase::ShutdownOutput()
786 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
791 m_lcount
= DoRead(buffer
, nbytes
);
793 // Allow read events from now on
799 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
801 // We use pointer arithmetic here which doesn't work with void pointers.
802 char *buffer
= static_cast<char *>(buffer_
);
804 // Try the push back buffer first, even before checking whether the socket
805 // is valid to allow reading previously pushed back data from an already
807 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
811 // If it's indeed closed or if read everything, there is nothing more to do.
812 if ( !m_impl
|| !nbytes
)
815 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
818 // wxSOCKET_NOWAIT overrides all the other flags and means that we are
819 // polling the socket and don't block at all.
820 if ( m_flags
& wxSOCKET_NOWAIT
)
822 int ret
= m_impl
->Read(buffer
, nbytes
);
825 if ( m_impl
->GetLastError() != wxSOCKET_WOULDBLOCK
)
826 SetError(wxSOCKET_IOERR
);
828 else // not an error, even if we didn't read anything
833 else // blocking socket
837 // Wait until socket becomes ready for reading
838 if ( !WaitForRead() )
841 const int ret
= m_impl
->Read(buffer
, nbytes
);
844 // for connection-oriented (e.g. TCP) sockets we can only read
845 // 0 bytes if the other end has been closed, and for
846 // connectionless ones (UDP) this flag doesn't make sense
847 // anyhow so we can set it to true too without doing any harm
854 SetError(wxSOCKET_IOERR
);
860 // If wxSOCKET_WAITALL is not set, we can leave now as we did read
861 // something and we don't need to wait for all nbytes bytes to be
863 if ( !(m_flags
& wxSOCKET_WAITALL
) )
866 // Otherwise continue reading until we do read everything.
874 // it's an error to not read everything in wxSOCKET_WAITALL mode or to
875 // not read anything otherwise
876 if ( ((m_flags
& wxSOCKET_WAITALL
) && nbytes
) || !total
)
877 SetError(wxSOCKET_IOERR
);
883 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
887 unsigned char sig
[4];
888 unsigned char len
[4];
894 int old_flags
= m_flags
;
895 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
898 if ( DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
900 wxUint32 sig
= (wxUint32
)msg
.sig
[0];
901 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
902 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
903 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
905 if ( sig
== 0xfeeddead )
907 wxUint32 len
= (wxUint32
)msg
.len
[0];
908 len
|= (wxUint32
)(msg
.len
[1] << 8);
909 len
|= (wxUint32
)(msg
.len
[2] << 16);
910 len
|= (wxUint32
)(msg
.len
[3] << 24);
921 // Don't attempt to read if the msg was zero bytes long.
922 m_lcount
= len
? DoRead(buffer
, len
) : 0;
926 char discard_buffer
[MAX_DISCARD_SIZE
];
929 // NOTE: discarded bytes don't add to m_lcount.
932 discard_len
= len2
> MAX_DISCARD_SIZE
935 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
936 len2
-= (wxUint32
)discard_len
;
938 while ((discard_len
> 0) && len2
);
941 if ( !len2
&& DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
943 sig
= (wxUint32
)msg
.sig
[0];
944 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
945 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
946 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
948 if ( sig
== 0xdeadfeed )
955 SetError(wxSOCKET_IOERR
);
963 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
968 m_lcount
= DoRead(buffer
, nbytes
);
969 Pushback(buffer
, m_lcount
);
971 // Allow read events again
977 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
982 m_lcount
= DoWrite(buffer
, nbytes
);
984 // Allow write events again
990 // This function is a mirror image of DoRead() except that it doesn't use the
991 // push back buffer, please see comments there
992 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
994 const char *buffer
= static_cast<const char *>(buffer_
);
996 // Return if there is nothing to read or the socket is (already?) closed.
997 if ( !m_impl
|| !nbytes
)
1000 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1003 if ( m_flags
& wxSOCKET_NOWAIT
)
1005 const int ret
= m_impl
->Write(buffer
, nbytes
);
1008 if ( m_impl
->GetLastError() != wxSOCKET_WOULDBLOCK
)
1009 SetError(wxSOCKET_IOERR
);
1016 else // blocking socket
1020 if ( !WaitForWrite() )
1023 const int ret
= m_impl
->Write(buffer
, nbytes
);
1032 SetError(wxSOCKET_IOERR
);
1037 if ( !(m_flags
& wxSOCKET_WAITALL
) )
1047 if ( ((m_flags
& wxSOCKET_WAITALL
) && nbytes
) || !total
)
1048 SetError(wxSOCKET_IOERR
);
1054 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
1058 unsigned char sig
[4];
1059 unsigned char len
[4];
1062 // Mask write events
1065 const int old_flags
= m_flags
;
1066 SetFlags((m_flags
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
);
1068 msg
.sig
[0] = (unsigned char) 0xad;
1069 msg
.sig
[1] = (unsigned char) 0xde;
1070 msg
.sig
[2] = (unsigned char) 0xed;
1071 msg
.sig
[3] = (unsigned char) 0xfe;
1073 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
1074 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
1075 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
1076 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1079 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
) )
1081 m_lcount
= DoWrite(buffer
, nbytes
);
1082 if ( m_lcount
== nbytes
)
1084 msg
.sig
[0] = (unsigned char) 0xed;
1085 msg
.sig
[1] = (unsigned char) 0xfe;
1086 msg
.sig
[2] = (unsigned char) 0xad;
1087 msg
.sig
[3] = (unsigned char) 0xde;
1091 msg
.len
[3] = (char) 0;
1093 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
))
1099 SetError(wxSOCKET_IOERR
);
1102 SetFlags(old_flags
);
1107 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1110 Pushback(buffer
, nbytes
);
1112 SetError(wxSOCKET_NOERROR
);
1118 wxSocketBase
& wxSocketBase::Discard()
1120 char *buffer
= new char[MAX_DISCARD_SIZE
];
1127 const int old_flags
= m_flags
;
1128 SetFlags(wxSOCKET_NOWAIT
);
1132 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1135 while (ret
== MAX_DISCARD_SIZE
);
1139 SetError(wxSOCKET_NOERROR
);
1141 // Allow read events again
1144 SetFlags(old_flags
);
1149 // --------------------------------------------------------------------------
1151 // --------------------------------------------------------------------------
1154 This function will check for the events specified in the flags parameter,
1155 and it will return a mask indicating which operations can be performed.
1157 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
,
1158 const timeval
*timeout
)
1160 if ( m_fd
== INVALID_SOCKET
)
1161 return (wxSOCKET_LOST_FLAG
& flags
);
1167 tv
.tv_sec
= tv
.tv_usec
= 0;
1169 // prepare the FD sets, passing NULL for the one(s) we don't use
1171 readfds
, *preadfds
= NULL
,
1172 writefds
, *pwritefds
= NULL
,
1173 exceptfds
; // always want to know about errors
1175 if ( flags
& wxSOCKET_INPUT_FLAG
)
1177 preadfds
= &readfds
;
1178 wxFD_ZERO(preadfds
);
1179 wxFD_SET(m_fd
, preadfds
);
1182 // when using non-blocking connect() the socket becomes connected
1183 // (successfully or not) when it becomes writable
1184 if ( flags
& (wxSOCKET_OUTPUT_FLAG
| wxSOCKET_CONNECTION_FLAG
) )
1186 pwritefds
= &writefds
;
1187 wxFD_ZERO(pwritefds
);
1188 wxFD_SET(m_fd
, pwritefds
);
1191 wxFD_ZERO(&exceptfds
);
1192 wxFD_SET(m_fd
, &exceptfds
);
1194 const int rc
= select(m_fd
+ 1, preadfds
, pwritefds
, &exceptfds
, &tv
);
1196 // check for errors first
1197 if ( rc
== -1 || wxFD_ISSET(m_fd
, &exceptfds
) )
1199 m_establishing
= false;
1201 return wxSOCKET_LOST_FLAG
& flags
;
1207 wxASSERT_MSG( rc
== 1, "unexpected select() return value" );
1209 wxSocketEventFlags detected
= 0;
1210 if ( preadfds
&& wxFD_ISSET(m_fd
, preadfds
) )
1211 detected
|= wxSOCKET_INPUT_FLAG
;
1213 if ( pwritefds
&& wxFD_ISSET(m_fd
, pwritefds
) )
1215 // check for the case of non-blocking connect()
1216 if ( m_establishing
&& !m_server
)
1219 SOCKOPTLEN_T len
= sizeof(error
);
1220 m_establishing
= false;
1221 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1224 detected
= wxSOCKET_LOST_FLAG
;
1226 detected
|= wxSOCKET_CONNECTION_FLAG
;
1228 else // not called to get non-blocking connect() status
1230 detected
|= wxSOCKET_OUTPUT_FLAG
;
1234 return detected
& flags
;
1238 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1240 wxCHECK_MSG( m_impl
, false, "can't wait on invalid socket" );
1242 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1243 m_interrupt
= false;
1246 // Use either the provided timeout or the default timeout value associated
1247 // with this socket.
1249 // TODO: allow waiting forever, see #9443
1250 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1251 : seconds
* 1000 + milliseconds
;
1252 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1254 // Get the active event loop which we'll use for the message dispatching
1255 // when running in the main thread unless this was explicitly disabled by
1256 // setting wxSOCKET_BLOCK flag
1257 wxEventLoopBase
*eventLoop
;
1258 if ( !(m_flags
& wxSOCKET_BLOCK
) && wxIsMainThread() )
1260 eventLoop
= wxEventLoop::GetActive();
1262 else // in worker thread
1264 // We never dispatch messages from threads other than the main one.
1268 // Wait until we receive the event we're waiting for or the timeout expires
1269 // (but note that we always execute the loop at least once, even if timeout
1270 // is 0 as this is used for polling)
1271 bool gotEvent
= false;
1272 for ( bool firstTime
= true; !m_interrupt
; firstTime
= false )
1274 long timeLeft
= wxMilliClockToLong(timeEnd
- wxGetLocalTimeMillis());
1283 // This function is only called if wxSOCKET_BLOCK flag was not used and
1284 // so we should dispatch the events if there is an event loop capable
1286 wxSocketEventFlags events
;
1289 // reset them before starting to wait
1292 eventLoop
->DispatchTimeout(timeLeft
);
1294 events
= m_eventsgot
;
1296 else // no event loop or waiting in another thread
1298 // as explained below, we should always check for wxSOCKET_LOST_FLAG
1300 SetTimeValFromMS(tv
, timeLeft
);
1301 events
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
, &tv
);
1304 // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
1305 // it, as continuing to wait for anything else after getting it is
1307 if ( events
& wxSOCKET_LOST_FLAG
)
1309 m_connected
= false;
1310 m_establishing
= false;
1311 if ( flags
& wxSOCKET_LOST_FLAG
)
1316 // otherwise mask out the bits we're not interested in
1319 // Incoming connection (server) or connection established (client)?
1320 if ( events
& wxSOCKET_CONNECTION_FLAG
)
1323 m_establishing
= false;
1328 // Data available or output buffer ready?
1329 if ( (events
& wxSOCKET_INPUT_FLAG
) || (events
& wxSOCKET_OUTPUT_FLAG
) )
1339 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1341 return DoWait(seconds
, milliseconds
,
1342 wxSOCKET_INPUT_FLAG
|
1343 wxSOCKET_OUTPUT_FLAG
|
1344 wxSOCKET_CONNECTION_FLAG
|
1349 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1351 // Check pushback buffer before entering DoWait
1355 // Note that wxSOCKET_INPUT_LOST has to be explicitly passed to DoWait
1356 // because of the semantics of WaitForRead: a return value of true means
1357 // that a Read call will return immediately, not that there is
1358 // actually data to read.
1359 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1363 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1365 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
| wxSOCKET_LOST_FLAG
);
1368 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1370 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
);
1373 // --------------------------------------------------------------------------
1375 // --------------------------------------------------------------------------
1378 // Get local or peer address
1381 bool wxSocketBase::GetPeer(wxSockAddress
& addr
) const
1383 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1385 const wxSockAddressImpl
& peer
= m_impl
->GetPeer();
1389 addr
.SetAddress(peer
);
1394 bool wxSocketBase::GetLocal(wxSockAddress
& addr
) const
1396 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1398 const wxSockAddressImpl
& local
= m_impl
->GetLocal();
1399 if ( !local
.IsOk() )
1402 addr
.SetAddress(local
);
1408 // Save and restore socket state
1411 void wxSocketBase::SaveState()
1413 wxSocketState
*state
;
1415 state
= new wxSocketState();
1417 state
->m_flags
= m_flags
;
1418 state
->m_notify
= m_notify
;
1419 state
->m_eventmask
= m_eventmask
;
1420 state
->m_clientData
= m_clientData
;
1422 m_states
.Append(state
);
1425 void wxSocketBase::RestoreState()
1427 wxList::compatibility_iterator node
;
1428 wxSocketState
*state
;
1430 node
= m_states
.GetLast();
1434 state
= (wxSocketState
*)node
->GetData();
1436 m_flags
= state
->m_flags
;
1437 m_notify
= state
->m_notify
;
1438 m_eventmask
= state
->m_eventmask
;
1439 m_clientData
= state
->m_clientData
;
1441 m_states
.Erase(node
);
1446 // Timeout and flags
1449 void wxSocketBase::SetTimeout(long seconds
)
1451 m_timeout
= seconds
;
1454 m_impl
->SetTimeout(m_timeout
* 1000);
1457 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1459 // Do some sanity checking on the flags used: not all values can be used
1461 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1462 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1463 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1464 "wxSOCKET_NOWAIT doesn't make sense" );
1470 // --------------------------------------------------------------------------
1472 // --------------------------------------------------------------------------
1474 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1476 wxSocketEventFlags flag
= 0;
1477 switch ( notification
)
1479 case wxSOCKET_INPUT
:
1480 flag
= wxSOCKET_INPUT_FLAG
;
1483 case wxSOCKET_OUTPUT
:
1484 flag
= wxSOCKET_OUTPUT_FLAG
;
1487 case wxSOCKET_CONNECTION
:
1488 flag
= wxSOCKET_CONNECTION_FLAG
;
1492 flag
= wxSOCKET_LOST_FLAG
;
1496 wxFAIL_MSG( "unknown wxSocket notification" );
1499 // if we lost the connection the socket is now closed
1500 if ( notification
== wxSOCKET_LOST
)
1503 // remember the events which were generated for this socket, we're going to
1504 // use this in DoWait()
1505 m_eventsgot
|= flag
;
1507 // send the wx event if enabled and we're interested in it
1508 if ( m_notify
&& (m_eventmask
& flag
) && m_handler
)
1510 // If we are in the middle of a R/W operation, do not propagate events
1511 // to users. Also, filter 'late' events which are no longer valid.
1512 if ( notification
== wxSOCKET_INPUT
)
1514 if ( m_reading
|| !m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1517 else if ( notification
== wxSOCKET_OUTPUT
)
1519 if ( m_writing
|| !m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1523 wxSocketEvent
event(m_id
);
1524 event
.m_event
= notification
;
1525 event
.m_clientData
= m_clientData
;
1526 event
.SetEventObject(this);
1528 m_handler
->AddPendingEvent(event
);
1532 void wxSocketBase::Notify(bool notify
)
1537 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1539 m_eventmask
= flags
;
1542 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1544 m_handler
= &handler
;
1548 // --------------------------------------------------------------------------
1550 // --------------------------------------------------------------------------
1552 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1556 if (m_unread
== NULL
)
1557 m_unread
= malloc(size
);
1562 tmp
= malloc(m_unrd_size
+ size
);
1563 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1569 m_unrd_size
+= size
;
1571 memcpy(m_unread
, buffer
, size
);
1574 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1576 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1581 if (size
> (m_unrd_size
-m_unrd_cur
))
1582 size
= m_unrd_size
-m_unrd_cur
;
1584 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1589 if (m_unrd_size
== m_unrd_cur
)
1602 // ==========================================================================
1604 // ==========================================================================
1606 // --------------------------------------------------------------------------
1608 // --------------------------------------------------------------------------
1610 wxSocketServer::wxSocketServer(const wxSockAddress
& addr
,
1611 wxSocketFlags flags
)
1612 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1614 wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") );
1616 m_impl
= wxSocketImpl::Create(*this);
1620 wxLogTrace( wxTRACE_Socket
, _T("*** Failed to create m_impl") );
1624 // Setup the socket as server
1625 m_impl
->SetLocal(addr
.GetAddress());
1627 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1628 m_impl
->SetReusable();
1630 if (GetFlags() & wxSOCKET_BROADCAST
) {
1631 m_impl
->SetBroadcast();
1633 if (GetFlags() & wxSOCKET_NOBIND
) {
1634 m_impl
->DontDoBind();
1637 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1642 wxLogTrace( wxTRACE_Socket
, _T("*** CreateServer() failed") );
1646 wxLogTrace( wxTRACE_Socket
, _T("wxSocketServer on fd %d"), m_impl
->m_fd
);
1649 // --------------------------------------------------------------------------
1651 // --------------------------------------------------------------------------
1653 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1655 if ( !m_impl
|| (m_impl
->m_fd
== INVALID_SOCKET
) || !m_impl
->IsServer() )
1657 wxFAIL_MSG( "can only be called for a valid server socket" );
1659 SetError(wxSOCKET_INVSOCK
);
1666 // wait until we get a connection
1667 if ( !m_impl
->SelectWithTimeout(wxSOCKET_INPUT_FLAG
) )
1669 SetError(wxSOCKET_TIMEDOUT
);
1675 sock
.m_impl
= m_impl
->Accept(sock
);
1679 SetError(m_impl
->GetLastError());
1684 sock
.m_type
= wxSOCKET_BASE
;
1685 sock
.m_connected
= true;
1690 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1692 wxSocketBase
* sock
= new wxSocketBase();
1694 sock
->SetFlags(m_flags
);
1696 if (!AcceptWith(*sock
, wait
))
1705 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1707 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
);
1710 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1712 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1714 SOCKOPTLEN_T lenreal
= *optlen
;
1715 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1716 static_cast<char *>(optval
), &lenreal
) != 0 )
1725 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1727 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1729 return setsockopt(m_impl
->m_fd
, level
, optname
,
1730 static_cast<const char *>(optval
), optlen
) == 0;
1733 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1735 m_localAddress
= local
;
1740 // ==========================================================================
1742 // ==========================================================================
1744 // --------------------------------------------------------------------------
1746 // --------------------------------------------------------------------------
1748 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1749 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1751 m_initialRecvBufferSize
=
1752 m_initialSendBufferSize
= -1;
1755 wxSocketClient::~wxSocketClient()
1759 // --------------------------------------------------------------------------
1761 // --------------------------------------------------------------------------
1763 bool wxSocketClient::DoConnect(const wxSockAddress
& remote
,
1764 const wxSockAddress
* local
,
1769 // Shutdown and destroy the old socket
1774 m_connected
= false;
1775 m_establishing
= false;
1777 // Create and set up the new one
1778 m_impl
= wxSocketImpl::Create(*this);
1782 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1783 if (GetFlags() & wxSOCKET_REUSEADDR
)
1784 m_impl
->SetReusable();
1785 if (GetFlags() & wxSOCKET_BROADCAST
)
1786 m_impl
->SetBroadcast();
1787 if (GetFlags() & wxSOCKET_NOBIND
)
1788 m_impl
->DontDoBind();
1790 // Bind to the local IP address and port, when provided or if one had been
1792 if ( !local
&& m_localAddress
.GetAddress().IsOk() )
1793 local
= &m_localAddress
;
1796 m_impl
->SetLocal(local
->GetAddress());
1798 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1800 m_impl
->SetPeer(remote
.GetAddress());
1802 // Finally do create the socket and connect to the peer
1803 const wxSocketError err
= m_impl
->CreateClient(wait
);
1805 if ( err
!= wxSOCKET_NOERROR
)
1807 if ( err
== wxSOCKET_WOULDBLOCK
)
1809 wxASSERT_MSG( !wait
, "shouldn't get this for blocking connect" );
1811 m_establishing
= true;
1821 bool wxSocketClient::Connect(const wxSockAddress
& remote
, bool wait
)
1823 return DoConnect(remote
, NULL
, wait
);
1826 bool wxSocketClient::Connect(const wxSockAddress
& remote
,
1827 const wxSockAddress
& local
,
1830 return DoConnect(remote
, &local
, wait
);
1833 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1837 // this happens if the initial attempt to connect succeeded without
1842 wxCHECK_MSG( m_establishing
&& m_impl
, false,
1843 "No connection establishment attempt in progress" );
1845 // we must specify wxSOCKET_LOST_FLAG here explicitly because we must return
1846 // true if the connection establishment process is finished, whether it is
1847 // over because we successfully connected or because we were not able to
1849 return DoWait(seconds
, milliseconds
,
1850 wxSOCKET_CONNECTION_FLAG
| wxSOCKET_LOST_FLAG
);
1853 // ==========================================================================
1855 // ==========================================================================
1857 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
1858 wxSocketFlags flags
)
1859 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1861 // Create the socket
1862 m_impl
= wxSocketImpl::Create(*this);
1867 // Setup the socket as non connection oriented
1868 m_impl
->SetLocal(addr
.GetAddress());
1869 if (flags
& wxSOCKET_REUSEADDR
)
1871 m_impl
->SetReusable();
1873 if (GetFlags() & wxSOCKET_BROADCAST
)
1875 m_impl
->SetBroadcast();
1877 if (GetFlags() & wxSOCKET_NOBIND
)
1879 m_impl
->DontDoBind();
1882 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
1889 // Initialize all stuff
1890 m_connected
= false;
1891 m_establishing
= false;
1894 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
1903 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
1907 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1909 m_impl
->SetPeer(addr
.GetAddress());
1914 // ==========================================================================
1916 // ==========================================================================
1918 class wxSocketModule
: public wxModule
1921 virtual bool OnInit()
1923 // wxSocketBase will call Initialize() itself only if sockets are
1924 // really used, don't do it from here
1928 virtual void OnExit()
1930 if ( wxSocketBase::IsInitialized() )
1931 wxSocketBase::Shutdown();
1935 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
1938 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
1940 #endif // wxUSE_SOCKETS