X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/5b90e570c9cd075069292da898cf23b8e9408f75..95fa881e92cb5284be976d5c7267a03e5fb4c7ab:/src/common/socket.cpp diff --git a/src/common/socket.cpp b/src/common/socket.cpp index e99a4a017f..222ca488ba 100644 --- a/src/common/socket.cpp +++ b/src/common/socket.cpp @@ -69,6 +69,21 @@ IMPLEMENT_CLASS(wxSocketClient, wxSocketBase) IMPLEMENT_CLASS(wxDatagramSocket, wxSocketBase) IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent) +// ---------------------------------------------------------------------------- +// private functions +// ---------------------------------------------------------------------------- + +namespace +{ + +void SetTimeValFromMS(timeval& tv, unsigned long ms) +{ + tv.tv_sec = (ms / 1000); + tv.tv_usec = (ms % 1000) * 1000; +} + +} // anonymous namespace + // -------------------------------------------------------------------------- // private classes // -------------------------------------------------------------------------- @@ -87,31 +102,6 @@ public: DECLARE_NO_COPY_CLASS(wxSocketState) }; -// Conditionally make the socket non-blocking for the lifetime of this object. -class wxSocketUnblocker -{ -public: - wxSocketUnblocker(wxSocketImpl *socket, bool unblock = true) - : m_impl(socket), - m_unblock(unblock) - { - if ( m_unblock ) - m_impl->SetNonBlocking(true); - } - - ~wxSocketUnblocker() - { - if ( m_unblock ) - m_impl->SetNonBlocking(false); - } - -private: - wxSocketImpl * const m_impl; - bool m_unblock; - - DECLARE_NO_COPY_CLASS(wxSocketUnblocker) -}; - // ============================================================================ // wxSocketManager // ============================================================================ @@ -170,7 +160,6 @@ wxSocketImpl::wxSocketImpl(wxSocketBase& wxsocket) m_error = wxSOCKET_NOERROR; m_server = false; m_stream = true; - m_non_blocking = false; SetTimeout(wxsocket.GetTimeout() * 1000); @@ -233,14 +222,14 @@ void wxSocketImpl::PostCreation() if ( m_initialSendBufferSize >= 0 ) SetSocketOption(SO_SNDBUF, m_initialSendBufferSize); - // FIXME: shouldn't we check for m_non_blocking here? as it is now, all our - // sockets are non-blocking + // we always put our sockets in unblocked mode and handle blocking + // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified UnblockAndRegisterWithEventLoop(); } wxSocketError wxSocketImpl::UpdateLocalAddress() { - WX_SOCKLEN_T lenAddr; + WX_SOCKLEN_T lenAddr = sizeof(*m_local->m_addr); if ( getsockname(m_fd, m_local->m_addr, &lenAddr) != 0 ) { Close(); @@ -294,7 +283,7 @@ wxSocketError wxSocketImpl::CreateServer() return UpdateLocalAddress(); } -wxSocketError wxSocketImpl::CreateClient() +wxSocketError wxSocketImpl::CreateClient(bool wait) { if ( !PreCreateCheck(m_peer) ) return m_error; @@ -303,8 +292,8 @@ wxSocketError wxSocketImpl::CreateClient() if ( m_fd == INVALID_SOCKET ) { - m_error = wxSOCKET_IOERR; - return wxSOCKET_IOERR; + m_error = wxSOCKET_IOERR; + return wxSOCKET_IOERR; } PostCreation(); @@ -320,9 +309,34 @@ wxSocketError wxSocketImpl::CreateClient() } } - // Connect to the peer and handle the EWOULDBLOCK return value in - // platform-specific code - return DoHandleConnect(connect(m_fd, m_peer->m_addr, m_peer->m_len)); + // Do connect now + int rc = connect(m_fd, m_peer->m_addr, m_peer->m_len); + if ( rc == SOCKET_ERROR ) + { + wxSocketError err = GetLastError(); + if ( err == wxSOCKET_WOULDBLOCK ) + { + m_establishing = true; + + // block waiting for connection if we should (otherwise just return + // wxSOCKET_WOULDBLOCK to the caller) + if ( wait ) + { + err = SelectWithTimeout(wxSOCKET_CONNECTION_FLAG) + ? wxSOCKET_NOERROR + : wxSOCKET_TIMEDOUT; + m_establishing = false; + } + } + + m_error = err; + } + else // connected + { + m_error = wxSOCKET_NOERROR; + } + + return m_error; } @@ -359,6 +373,26 @@ wxSocketError wxSocketImpl::CreateUDP() return wxSOCKET_NOERROR; } +wxSocketImpl *wxSocketImpl::Accept(wxSocketBase& wxsocket) +{ + wxSockAddr from; + WX_SOCKLEN_T fromlen = sizeof(from); + const int fd = accept(m_fd, &from, &fromlen); + + if ( fd == INVALID_SOCKET ) + return NULL; + + wxSocketImpl * const sock = Create(wxsocket); + sock->m_fd = fd; + + sock->m_peer = GAddress_new(); + _GAddress_translate_from(sock->m_peer, &from, fromlen); + + sock->UnblockAndRegisterWithEventLoop(); + + return sock; +} + void wxSocketImpl::Close() { @@ -390,8 +424,7 @@ void wxSocketImpl::Shutdown() */ void wxSocketImpl::SetTimeout(unsigned long millis) { - m_timeout.tv_sec = (millis / 1000); - m_timeout.tv_usec = (millis % 1000) * 1000; + SetTimeValFromMS(m_timeout, millis); } void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event) @@ -503,38 +536,6 @@ GAddress *wxSocketImpl::GetPeer() return NULL; } -bool wxSocketImpl::DoBlockWithTimeout(wxSocketEventFlags flags) -{ - if ( !m_non_blocking ) - { - fd_set fds; - wxFD_ZERO(&fds); - wxFD_SET(m_fd, &fds); - - fd_set - *readfds = flags & wxSOCKET_INPUT_FLAG ? &fds : NULL, - *writefds = flags & wxSOCKET_OUTPUT_FLAG ? &fds : NULL; - - // make a copy as it can be modified by select() - struct timeval tv = m_timeout; - int ret = select(m_fd + 1, readfds, writefds, NULL, &tv); - - switch ( ret ) - { - case 0: - m_error = wxSOCKET_TIMEDOUT; - return false; - - case -1: - m_error = wxSOCKET_IOERR; - return false; - } - } - //else: we're non-blocking, never block - - return true; -} - // ========================================================================== // wxSocketBase // ========================================================================== @@ -612,7 +613,8 @@ void wxSocketBase::Init() m_handler = NULL; m_clientData = NULL; m_notify = false; - m_eventmask = 0; + m_eventmask = + m_eventsgot = 0; if ( !IsInitialized() ) { @@ -666,7 +668,7 @@ bool wxSocketBase::Destroy() // Shutdown and close the socket Close(); - // Supress events from now on + // Suppress events from now on Notify(false); // schedule this object for deletion @@ -700,9 +702,6 @@ wxSocketError wxSocketBase::LastError() const // The following IO operations update m_error and m_lcount: // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard} -// -// TODO: Should Connect, Accept and AcceptWith update m_error? - bool wxSocketBase::Close() { // Interrupt pending waits @@ -758,7 +757,6 @@ wxUint32 wxSocketBase::DoRead(void* buffer_, wxUint32 nbytes) // polling the socket and don't block at all. if ( m_flags & wxSOCKET_NOWAIT ) { - wxSocketUnblocker unblock(m_impl); int ret = m_impl->Read(buffer, nbytes); if ( ret < 0 ) return 0; @@ -769,10 +767,8 @@ wxUint32 wxSocketBase::DoRead(void* buffer_, wxUint32 nbytes) { for ( ;; ) { - // Wait until socket becomes ready for reading dispatching the GUI - // events in the meanwhile unless wxSOCKET_BLOCK was explicitly - // specified to disable this. - if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForRead() ) + // Wait until socket becomes ready for reading + if ( !WaitForRead() ) break; const int ret = m_impl->Read(buffer, nbytes); @@ -966,7 +962,6 @@ wxUint32 wxSocketBase::DoWrite(const void *buffer_, wxUint32 nbytes) wxUint32 total = 0; if ( m_flags & wxSOCKET_NOWAIT ) { - wxSocketUnblocker unblock(m_impl); const int ret = m_impl->Write(buffer, nbytes); if ( ret > 0 ) total += ret; @@ -975,7 +970,7 @@ wxUint32 wxSocketBase::DoWrite(const void *buffer_, wxUint32 nbytes) { for ( ;; ) { - if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForWrite() ) + if ( !WaitForWrite() ) break; const int ret = m_impl->Write(buffer, nbytes); @@ -1105,29 +1100,26 @@ wxSocketBase& wxSocketBase::Discard() // -------------------------------------------------------------------------- /* - * Polls the socket to determine its status. This function will - * check for the events specified in the 'flags' parameter, and - * it will return a mask indicating which operations can be - * performed. This function won't block, regardless of the - * mode (blocking | nonblocking) of the socket. + This function will check for the events specified in the flags parameter, + and it will return a mask indicating which operations can be performed. */ -wxSocketEventFlags wxSocketImpl::Select(wxSocketEventFlags flags) +wxSocketEventFlags wxSocketImpl::Select(wxSocketEventFlags flags, + const timeval *timeout) { - assert(this); - wxSocketEventFlags result = 0; - fd_set readfds; - fd_set writefds; - fd_set exceptfds; - struct timeval tv; if (m_fd == INVALID_SOCKET) return (wxSOCKET_LOST_FLAG & flags); - /* Do not use a static struct, Linux can garble it */ - tv.tv_sec = 0; - tv.tv_usec = 0; + struct timeval tv; + if ( timeout ) + tv = *timeout; + else + tv.tv_sec = tv.tv_usec = 0; + fd_set readfds; + fd_set writefds; + fd_set exceptfds; wxFD_ZERO(&readfds); wxFD_ZERO(&writefds); wxFD_ZERO(&exceptfds); @@ -1210,12 +1202,6 @@ wxSocketEventFlags wxSocketImpl::Select(wxSocketEventFlags flags) return (result | m_detected) & flags; } -// All Wait functions poll the socket using Select() to -// check for the specified combination of conditions, until one -// of these conditions become true, an error occurs, or the -// timeout elapses. The polling loop runs the event loop so that -// this won't block the GUI. - bool wxSocketBase::DoWait(long seconds, long milliseconds, wxSocketEventFlags flags) { @@ -1234,9 +1220,10 @@ wxSocketBase::DoWait(long seconds, long milliseconds, wxSocketEventFlags flags) const wxMilliClock_t timeEnd = wxGetLocalTimeMillis() + timeout; // Get the active event loop which we'll use for the message dispatching - // when running in the main thread + // when running in the main thread unless this was explicitly disabled by + // setting wxSOCKET_BLOCK flag wxEventLoopBase *eventLoop; - if ( wxIsMainThread() ) + if ( !(m_flags & wxSOCKET_BLOCK) && wxIsMainThread() ) { eventLoop = wxEventLoop::GetActive(); } @@ -1246,35 +1233,46 @@ wxSocketBase::DoWait(long seconds, long milliseconds, wxSocketEventFlags flags) eventLoop = NULL; } - // Wait in an active polling loop: notice that the loop is executed at - // least once, even if timeout is 0 (i.e. polling). + // Wait until we receive the event we're waiting for or the timeout expires + // (but note that we always execute the loop at least once, even if timeout + // is 0 as this is used for polling) bool gotEvent = false; - for ( ;; ) + for ( bool firstTime = true; !m_interrupt ; firstTime = false ) { - // We always stop waiting when the connection is lost as it doesn't - // make sense to continue further, even if wxSOCKET_LOST_FLAG is not - // specified in flags to wait for. - const wxSocketEventFlags - result = m_impl->Select(flags | wxSOCKET_LOST_FLAG); - - // Incoming connection (server) or connection established (client)? - if ( result & wxSOCKET_CONNECTION_FLAG ) + long timeLeft = wxMilliClockToLong(timeEnd - wxGetLocalTimeMillis()); + if ( timeLeft < 0 ) { - m_connected = true; - m_establishing = false; - gotEvent = true; - break; + if ( !firstTime ) + break; // timed out + + timeLeft = 0; } - // Data available or output buffer ready? - if ( (result & wxSOCKET_INPUT_FLAG) || (result & wxSOCKET_OUTPUT_FLAG) ) + // This function is only called if wxSOCKET_BLOCK flag was not used and + // so we should dispatch the events if there is an event loop capable + // of doing it. + wxSocketEventFlags events; + if ( eventLoop ) { - gotEvent = true; - break; + // reset them before starting to wait + m_eventsgot = 0; + + eventLoop->DispatchTimeout(timeLeft); + + events = m_eventsgot; + } + else // no event loop or waiting in another thread + { + // as explained below, we should always check for wxSOCKET_LOST_FLAG + timeval tv; + SetTimeValFromMS(tv, timeLeft); + events = m_impl->Select(flags | wxSOCKET_LOST_FLAG, &tv); } - // Connection lost - if ( result & wxSOCKET_LOST_FLAG ) + // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include + // it, as continuing to wait for anything else after getting it is + // pointless + if ( events & wxSOCKET_LOST_FLAG ) { m_connected = false; m_establishing = false; @@ -1283,30 +1281,24 @@ wxSocketBase::DoWait(long seconds, long milliseconds, wxSocketEventFlags flags) break; } - if ( m_interrupt ) - break; - - // Wait more? - const wxMilliClock_t timeNow = wxGetLocalTimeMillis(); - if ( timeNow >= timeEnd ) - break; + // otherwise mask out the bits we're not interested in + events &= flags; - if ( eventLoop ) + // Incoming connection (server) or connection established (client)? + if ( events & wxSOCKET_CONNECTION_FLAG ) { - // This function is only called if wxSOCKET_BLOCK flag was not used - // and so we should dispatch the events if there is an event loop - // capable of doing it. - if ( eventLoop->Pending() ) - eventLoop->Dispatch(); + m_connected = true; + m_establishing = false; + gotEvent = true; + break; } -#if wxUSE_THREADS - else // no event loop or waiting in another thread + + // Data available or output buffer ready? + if ( (events & wxSOCKET_INPUT_FLAG) || (events & wxSOCKET_OUTPUT_FLAG) ) { - // We're busy waiting but at least give up the rest of our current - // time slice. - wxThread::Yield(); + gotEvent = true; + break; } -#endif // wxUSE_THREADS } return gotEvent; @@ -1457,71 +1449,65 @@ void wxSocketBase::SetFlags(wxSocketFlags flags) void wxSocketBase::OnRequest(wxSocketNotify notification) { - switch(notification) + wxSocketEventFlags flag = 0; + switch ( notification ) { - case wxSOCKET_CONNECTION: - m_establishing = false; - m_connected = true; - break; - - // If we are in the middle of a R/W operation, do not - // propagate events to users. Also, filter 'late' events - // which are no longer valid. - case wxSOCKET_INPUT: - if (m_reading || !m_impl->Select(wxSOCKET_INPUT_FLAG)) - return; + flag = wxSOCKET_INPUT_FLAG; break; case wxSOCKET_OUTPUT: - if (m_writing || !m_impl->Select(wxSOCKET_OUTPUT_FLAG)) - return; + flag = wxSOCKET_OUTPUT_FLAG; + break; + + case wxSOCKET_CONNECTION: + flag = wxSOCKET_CONNECTION_FLAG; break; case wxSOCKET_LOST: - m_connected = false; - m_establishing = false; + flag = wxSOCKET_LOST_FLAG; break; - case wxSOCKET_MAX_EVENT: - wxFAIL_MSG( "unexpected notification" ); - return; + default: + wxFAIL_MSG( "unknown wxSocket notification" ); } - // Schedule the event + // if we lost the connection the socket is now closed + if ( notification == wxSOCKET_LOST ) + m_closed = true; - wxSocketEventFlags flag = 0; - wxUnusedVar(flag); - switch (notification) - { - case wxSOCKET_INPUT: flag = wxSOCKET_INPUT_FLAG; break; - case wxSOCKET_OUTPUT: flag = wxSOCKET_OUTPUT_FLAG; break; - case wxSOCKET_CONNECTION: flag = wxSOCKET_CONNECTION_FLAG; break; - case wxSOCKET_LOST: flag = wxSOCKET_LOST_FLAG; break; - default: - wxLogWarning(_("wxSocket: unknown event!.")); - return; - } + // remember the events which were generated for this socket, we're going to + // use this in DoWait() + m_eventsgot |= flag; - if (((m_eventmask & flag) == flag) && m_notify) + // send the wx event if enabled and we're interested in it + if ( m_notify && (m_eventmask & flag) && m_handler ) { - if (m_handler) + // If we are in the middle of a R/W operation, do not propagate events + // to users. Also, filter 'late' events which are no longer valid. + if ( notification == wxSOCKET_INPUT ) { - wxSocketEvent event(m_id); - event.m_event = notification; - event.m_clientData = m_clientData; - event.SetEventObject(this); - - m_handler->AddPendingEvent(event); + if ( m_reading || !m_impl->Select(wxSOCKET_INPUT_FLAG) ) + return; + } + else if ( notification == wxSOCKET_OUTPUT ) + { + if ( m_writing || !m_impl->Select(wxSOCKET_OUTPUT_FLAG) ) + return; } + + wxSocketEvent event(m_id); + event.m_event = notification; + event.m_clientData = m_clientData; + event.SetEventObject(this); + + m_handler->AddPendingEvent(event); } } void wxSocketBase::Notify(bool notify) { m_notify = notify; - if (m_impl) - m_impl->Notify(notify); } void wxSocketBase::SetNotify(wxSocketEventFlags flags) @@ -1612,7 +1598,6 @@ wxSocketServer::wxSocketServer(const wxSockAddress& addr_man, } // Setup the socket as server - m_impl->Notify(m_notify); m_impl->SetLocal(addr_man.GetAddress()); if (GetFlags() & wxSOCKET_REUSEADDR) { @@ -1643,17 +1628,34 @@ wxSocketServer::wxSocketServer(const wxSockAddress& addr_man, bool wxSocketServer::AcceptWith(wxSocketBase& sock, bool wait) { - if (!m_impl) + if ( !m_impl || (m_impl->m_fd == INVALID_SOCKET) || !m_impl->IsServer() ) + { + wxFAIL_MSG( "can only be called for a valid server socket" ); + + m_error = wxSOCKET_INVSOCK; + return false; + } + + if ( wait ) + { + // wait until we get a connection + if ( !m_impl->SelectWithTimeout(wxSOCKET_INPUT_FLAG) ) + { + m_error = wxSOCKET_TIMEDOUT; + + return false; + } + } - // If wait == false, then the call should be nonblocking. - // When we are finished, we put the socket to blocking mode - // again. - wxSocketUnblocker unblock(m_impl, !wait); - sock.m_impl = m_impl->WaitConnection(sock); + sock.m_impl = m_impl->Accept(sock); if ( !sock.m_impl ) + { + m_error = m_impl->GetLastError(); + return false; + } sock.m_type = wxSOCKET_BASE; sock.m_connected = true; @@ -1685,7 +1687,7 @@ bool wxSocketBase::GetOption(int level, int optname, void *optval, int *optlen) { wxASSERT_MSG( m_impl, _T("Socket not initialised") ); - SOCKOPTLEN_T lenreal; + SOCKOPTLEN_T lenreal = *optlen; if ( getsockopt(m_impl->m_fd, level, optname, static_cast(optval), &lenreal) != 0 ) return false; @@ -1742,69 +1744,56 @@ wxSocketClient::~wxSocketClient() // Connect // -------------------------------------------------------------------------- -bool wxSocketClient::DoConnect(const wxSockAddress& addr_man, +bool wxSocketClient::DoConnect(const wxSockAddress& remote, const wxSockAddress* local, bool wait) { - if (m_impl) + if ( m_impl ) { - // Shutdown and destroy the socket + // Shutdown and destroy the old socket Close(); delete m_impl; } - m_impl = wxSocketImpl::Create(*this); m_connected = false; m_establishing = false; - if (!m_impl) + // Create and set up the new one + m_impl = wxSocketImpl::Create(*this); + if ( !m_impl ) return false; - // If wait == false, then the call should be nonblocking. When we are - // finished, we put the socket to blocking mode again. - wxSocketUnblocker unblock(m_impl, !wait); - // Reuse makes sense for clients too, if we are trying to rebind to the same port if (GetFlags() & wxSOCKET_REUSEADDR) - { m_impl->SetReusable(); - } if (GetFlags() & wxSOCKET_BROADCAST) - { m_impl->SetBroadcast(); - } if (GetFlags() & wxSOCKET_NOBIND) - { m_impl->DontDoBind(); - } - // If no local address was passed and one has been set, use the one that was Set - if (!local && m_localAddress.GetAddress()) - { + // Bind to the local IP address and port, when provided or if one had been + // set before + if ( !local && m_localAddress.GetAddress() ) local = &m_localAddress; - } - - // Bind to the local IP address and port, when provided - if (local) - { - GAddress* la = local->GetAddress(); - if (la && la->m_addr) - m_impl->SetLocal(la); - } + if ( local ) + m_impl->SetLocal(local->GetAddress()); m_impl->SetInitialSocketBuffers(m_initialRecvBufferSize, m_initialSendBufferSize); - m_impl->SetPeer(addr_man.GetAddress()); - const wxSocketError err = m_impl->CreateClient(); + m_impl->SetPeer(remote.GetAddress()); - //this will register for callbacks - must be called after m_impl->m_fd was initialized - m_impl->Notify(m_notify); + // Finally do create the socket and connect to the peer + const wxSocketError err = m_impl->CreateClient(wait); - if (err != wxSOCKET_NOERROR) + if ( err != wxSOCKET_NOERROR ) { - if (err == wxSOCKET_WOULDBLOCK) + if ( err == wxSOCKET_WOULDBLOCK ) + { + wxASSERT_MSG( !wait, "shouldn't get this for blocking connect" ); + m_establishing = true; + } return false; } @@ -1813,16 +1802,16 @@ bool wxSocketClient::DoConnect(const wxSockAddress& addr_man, return true; } -bool wxSocketClient::Connect(const wxSockAddress& addr_man, bool wait) +bool wxSocketClient::Connect(const wxSockAddress& remote, bool wait) { - return DoConnect(addr_man, NULL, wait); + return DoConnect(remote, NULL, wait); } -bool wxSocketClient::Connect(const wxSockAddress& addr_man, +bool wxSocketClient::Connect(const wxSockAddress& remote, const wxSockAddress& local, bool wait) { - return DoConnect(addr_man, &local, wait); + return DoConnect(remote, &local, wait); } bool wxSocketClient::WaitOnConnect(long seconds, long milliseconds) @@ -1859,7 +1848,6 @@ wxDatagramSocket::wxDatagramSocket( const wxSockAddress& addr, if (!m_impl) return; - m_impl->Notify(m_notify); // Setup the socket as non connection oriented m_impl->SetLocal(addr.GetAddress()); if (flags & wxSOCKET_REUSEADDR)