PageRenderTime 56ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/src/common/socket.cpp

https://github.com/jay/wxWidgets
C++ | 2170 lines | 1409 code | 435 blank | 326 comment | 257 complexity | 98704a70ce9062ddb44c2f4b17fa9a0b MD5 | raw file
Possible License(s): LGPL-3.0, AGPL-3.0, GPL-2.0, LGPL-2.0
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: src/common/socket.cpp
  3. // Purpose: Socket handler classes
  4. // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
  5. // Created: April 1997
  6. // Copyright: (C) 1999-1997, Guilhem Lavaux
  7. // (C) 1999-2000, Guillermo Rodriguez Garcia
  8. // (C) 2008 Vadim Zeitlin
  9. // Licence: wxWindows licence
  10. /////////////////////////////////////////////////////////////////////////////
  11. // ==========================================================================
  12. // Declarations
  13. // ==========================================================================
  14. // For compilers that support precompilation, includes "wx.h".
  15. #include "wx/wxprec.h"
  16. #ifdef __BORLANDC__
  17. #pragma hdrstop
  18. #endif
  19. #if wxUSE_SOCKETS
  20. #include "wx/socket.h"
  21. #ifndef WX_PRECOMP
  22. #include "wx/object.h"
  23. #include "wx/string.h"
  24. #include "wx/intl.h"
  25. #include "wx/log.h"
  26. #include "wx/event.h"
  27. #include "wx/app.h"
  28. #include "wx/utils.h"
  29. #include "wx/timer.h"
  30. #include "wx/module.h"
  31. #include "wx/filefn.h"
  32. #endif
  33. #include "wx/apptrait.h"
  34. #include "wx/sckaddr.h"
  35. #include "wx/scopeguard.h"
  36. #include "wx/stopwatch.h"
  37. #include "wx/thread.h"
  38. #include "wx/evtloop.h"
  39. #include "wx/link.h"
  40. #include "wx/private/fd.h"
  41. #include "wx/private/socket.h"
  42. #ifdef __UNIX__
  43. #include <errno.h>
  44. #endif
  45. // we use MSG_NOSIGNAL to avoid getting SIGPIPE when sending data to a remote
  46. // host which closed the connection if it is available, otherwise we rely on
  47. // SO_NOSIGPIPE existency
  48. //
  49. // this should cover all the current Unix systems (Windows never sends any
  50. // signals anyhow) but if we find one that has neither we should explicitly
  51. // ignore SIGPIPE for it
  52. // OpenVMS has neither MSG_NOSIGNAL nor SO_NOSIGPIPE. However the socket sample
  53. // seems to work. Not sure if problems will show up on OpenVMS using sockets.
  54. #ifdef MSG_NOSIGNAL
  55. #define wxSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
  56. #else // MSG_NOSIGNAL not available (BSD including OS X)
  57. // next best possibility is to use SO_NOSIGPIPE socket option, this covers
  58. // BSD systems (including OS X) -- but if we don't have it neither (AIX and
  59. // old HP-UX do not), we have to fall back to the old way of simply
  60. // disabling SIGPIPE temporarily, so define a class to do it in a safe way
  61. #if defined(__UNIX__) && !defined(SO_NOSIGPIPE)
  62. extern "C" { typedef void (*wxSigHandler_t)(int); }
  63. namespace
  64. {
  65. class IgnoreSignal
  66. {
  67. public:
  68. // ctor disables the given signal
  69. IgnoreSignal(int sig)
  70. : m_handler(signal(sig, SIG_IGN)),
  71. m_sig(sig)
  72. {
  73. }
  74. // dtor restores the old handler
  75. ~IgnoreSignal()
  76. {
  77. signal(m_sig, m_handler);
  78. }
  79. private:
  80. const wxSigHandler_t m_handler;
  81. const int m_sig;
  82. wxDECLARE_NO_COPY_CLASS(IgnoreSignal);
  83. };
  84. } // anonymous namespace
  85. #define wxNEEDS_IGNORE_SIGPIPE
  86. #endif // Unix without SO_NOSIGPIPE
  87. #define wxSOCKET_MSG_NOSIGNAL 0
  88. #endif
  89. // DLL options compatibility check:
  90. #include "wx/build.h"
  91. WX_CHECK_BUILD_OPTIONS("wxNet")
  92. // --------------------------------------------------------------------------
  93. // macros and constants
  94. // --------------------------------------------------------------------------
  95. // event
  96. wxDEFINE_EVENT(wxEVT_SOCKET, wxSocketEvent);
  97. // discard buffer
  98. #define MAX_DISCARD_SIZE (10 * 1024)
  99. #define wxTRACE_Socket wxT("wxSocket")
  100. // --------------------------------------------------------------------------
  101. // wxWin macros
  102. // --------------------------------------------------------------------------
  103. IMPLEMENT_CLASS(wxSocketBase, wxObject)
  104. IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
  105. IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
  106. IMPLEMENT_CLASS(wxDatagramSocket, wxSocketBase)
  107. IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
  108. // ----------------------------------------------------------------------------
  109. // private functions
  110. // ----------------------------------------------------------------------------
  111. namespace
  112. {
  113. void SetTimeValFromMS(timeval& tv, unsigned long ms)
  114. {
  115. tv.tv_sec = (ms / 1000);
  116. tv.tv_usec = (ms % 1000) * 1000;
  117. }
  118. } // anonymous namespace
  119. // --------------------------------------------------------------------------
  120. // private classes
  121. // --------------------------------------------------------------------------
  122. class wxSocketState : public wxObject
  123. {
  124. public:
  125. wxSocketFlags m_flags;
  126. wxSocketEventFlags m_eventmask;
  127. bool m_notify;
  128. void *m_clientData;
  129. public:
  130. wxSocketState() : wxObject() {}
  131. wxDECLARE_NO_COPY_CLASS(wxSocketState);
  132. };
  133. // wxSocketWaitModeChanger: temporarily change the socket flags affecting its
  134. // wait mode
  135. class wxSocketWaitModeChanger
  136. {
  137. public:
  138. // temporarily set the flags to include the flag value which may be either
  139. // wxSOCKET_NOWAIT or wxSOCKET_WAITALL
  140. wxSocketWaitModeChanger(wxSocketBase *socket, int flag)
  141. : m_socket(socket),
  142. m_oldflags(socket->GetFlags())
  143. {
  144. // We can be passed only wxSOCKET_WAITALL{_READ,_WRITE} or
  145. // wxSOCKET_NOWAIT{_READ,_WRITE} normally.
  146. wxASSERT_MSG( !(flag & wxSOCKET_WAITALL) || !(flag & wxSOCKET_NOWAIT),
  147. "not a wait flag" );
  148. // preserve wxSOCKET_BLOCK value when switching to wxSOCKET_WAITALL
  149. // mode but not when switching to wxSOCKET_NOWAIT as the latter is
  150. // incompatible with wxSOCKET_BLOCK
  151. if ( flag != wxSOCKET_NOWAIT )
  152. flag |= m_oldflags & wxSOCKET_BLOCK;
  153. socket->SetFlags(flag);
  154. }
  155. ~wxSocketWaitModeChanger()
  156. {
  157. m_socket->SetFlags(m_oldflags);
  158. }
  159. private:
  160. wxSocketBase * const m_socket;
  161. const int m_oldflags;
  162. wxDECLARE_NO_COPY_CLASS(wxSocketWaitModeChanger);
  163. };
  164. // wxSocketRead/WriteGuard are instantiated before starting reading
  165. // from/writing to the socket
  166. class wxSocketReadGuard
  167. {
  168. public:
  169. wxSocketReadGuard(wxSocketBase *socket)
  170. : m_socket(socket)
  171. {
  172. wxASSERT_MSG( !m_socket->m_reading, "read reentrancy?" );
  173. m_socket->m_reading = true;
  174. }
  175. ~wxSocketReadGuard()
  176. {
  177. m_socket->m_reading = false;
  178. // connection could have been lost while reading, in this case calling
  179. // ReenableEvents() would assert and is not necessary anyhow
  180. wxSocketImpl * const impl = m_socket->m_impl;
  181. if ( impl && impl->m_fd != INVALID_SOCKET )
  182. impl->ReenableEvents(wxSOCKET_INPUT_FLAG);
  183. }
  184. private:
  185. wxSocketBase * const m_socket;
  186. wxDECLARE_NO_COPY_CLASS(wxSocketReadGuard);
  187. };
  188. class wxSocketWriteGuard
  189. {
  190. public:
  191. wxSocketWriteGuard(wxSocketBase *socket)
  192. : m_socket(socket)
  193. {
  194. wxASSERT_MSG( !m_socket->m_writing, "write reentrancy?" );
  195. m_socket->m_writing = true;
  196. }
  197. ~wxSocketWriteGuard()
  198. {
  199. m_socket->m_writing = false;
  200. wxSocketImpl * const impl = m_socket->m_impl;
  201. if ( impl && impl->m_fd != INVALID_SOCKET )
  202. impl->ReenableEvents(wxSOCKET_OUTPUT_FLAG);
  203. }
  204. private:
  205. wxSocketBase * const m_socket;
  206. wxDECLARE_NO_COPY_CLASS(wxSocketWriteGuard);
  207. };
  208. // ============================================================================
  209. // wxSocketManager
  210. // ============================================================================
  211. wxSocketManager *wxSocketManager::ms_manager = NULL;
  212. /* static */
  213. void wxSocketManager::Set(wxSocketManager *manager)
  214. {
  215. wxASSERT_MSG( !ms_manager, "too late to set manager now" );
  216. ms_manager = manager;
  217. }
  218. /* static */
  219. void wxSocketManager::Init()
  220. {
  221. wxASSERT_MSG( !ms_manager, "shouldn't be initialized twice" );
  222. /*
  223. Details: Initialize() creates a hidden window as a sink for socket
  224. events, such as 'read completed'. wxMSW has only one message loop
  225. for the main thread. If Initialize is called in a secondary thread,
  226. the socket window will be created for the secondary thread, but
  227. since there is no message loop on this thread, it will never
  228. receive events and all socket operations will time out.
  229. BTW, the main thread must not be stopped using sleep or block
  230. on a semaphore (a bad idea in any case) or socket operations
  231. will time out.
  232. On the Mac side, Initialize() stores a pointer to the CFRunLoop for
  233. the main thread. Because secondary threads do not have run loops,
  234. adding event notifications to the "Current" loop would have no
  235. effect at all, events would never fire.
  236. */
  237. wxASSERT_MSG( wxIsMainThread(),
  238. "sockets must be initialized from the main thread" );
  239. wxAppConsole * const app = wxAppConsole::GetInstance();
  240. wxCHECK_RET( app, "sockets can't be initialized without wxApp" );
  241. ms_manager = app->GetTraits()->GetSocketManager();
  242. }
  243. // ==========================================================================
  244. // wxSocketImpl
  245. // ==========================================================================
  246. wxSocketImpl::wxSocketImpl(wxSocketBase& wxsocket)
  247. : m_wxsocket(&wxsocket)
  248. {
  249. m_fd = INVALID_SOCKET;
  250. m_error = wxSOCKET_NOERROR;
  251. m_server = false;
  252. m_stream = true;
  253. SetTimeout(wxsocket.GetTimeout() * 1000);
  254. m_establishing = false;
  255. m_reusable = false;
  256. m_broadcast = false;
  257. m_dobind = true;
  258. m_initialRecvBufferSize = -1;
  259. m_initialSendBufferSize = -1;
  260. }
  261. wxSocketImpl::~wxSocketImpl()
  262. {
  263. if ( m_fd != INVALID_SOCKET )
  264. Shutdown();
  265. }
  266. bool wxSocketImpl::PreCreateCheck(const wxSockAddressImpl& addr)
  267. {
  268. if ( m_fd != INVALID_SOCKET )
  269. {
  270. m_error = wxSOCKET_INVSOCK;
  271. return false;
  272. }
  273. if ( !addr.IsOk() )
  274. {
  275. m_error = wxSOCKET_INVADDR;
  276. return false;
  277. }
  278. return true;
  279. }
  280. void wxSocketImpl::PostCreation()
  281. {
  282. // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
  283. #ifdef SO_NOSIGPIPE
  284. EnableSocketOption(SO_NOSIGPIPE);
  285. #endif
  286. if ( m_reusable )
  287. EnableSocketOption(SO_REUSEADDR);
  288. if ( m_broadcast )
  289. {
  290. wxASSERT_MSG( !m_stream, "broadcasting is for datagram sockets only" );
  291. EnableSocketOption(SO_BROADCAST);
  292. }
  293. if ( m_initialRecvBufferSize >= 0 )
  294. SetSocketOption(SO_RCVBUF, m_initialRecvBufferSize);
  295. if ( m_initialSendBufferSize >= 0 )
  296. SetSocketOption(SO_SNDBUF, m_initialSendBufferSize);
  297. // we always put our sockets in unblocked mode and handle blocking
  298. // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
  299. UnblockAndRegisterWithEventLoop();
  300. }
  301. wxSocketError wxSocketImpl::UpdateLocalAddress()
  302. {
  303. if ( !m_local.IsOk() )
  304. {
  305. // ensure that we have a valid object using the correct family: correct
  306. // being the same one as our peer uses as we have no other way to
  307. // determine it
  308. m_local.Create(m_peer.GetFamily());
  309. }
  310. WX_SOCKLEN_T lenAddr = m_local.GetLen();
  311. if ( getsockname(m_fd, m_local.GetWritableAddr(), &lenAddr) != 0 )
  312. {
  313. Close();
  314. m_error = wxSOCKET_IOERR;
  315. return m_error;
  316. }
  317. return wxSOCKET_NOERROR;
  318. }
  319. wxSocketError wxSocketImpl::CreateServer()
  320. {
  321. if ( !PreCreateCheck(m_local) )
  322. return m_error;
  323. m_server = true;
  324. m_stream = true;
  325. // do create the socket
  326. m_fd = socket(m_local.GetFamily(), SOCK_STREAM, 0);
  327. if ( m_fd == INVALID_SOCKET )
  328. {
  329. m_error = wxSOCKET_IOERR;
  330. return wxSOCKET_IOERR;
  331. }
  332. PostCreation();
  333. // and then bind to and listen on it
  334. //
  335. // FIXME: should we test for m_dobind here?
  336. if ( bind(m_fd, m_local.GetAddr(), m_local.GetLen()) != 0 )
  337. m_error = wxSOCKET_IOERR;
  338. if ( IsOk() )
  339. {
  340. if ( listen(m_fd, 5) != 0 )
  341. m_error = wxSOCKET_IOERR;
  342. }
  343. if ( !IsOk() )
  344. {
  345. Close();
  346. return m_error;
  347. }
  348. // finally retrieve the address we effectively bound to
  349. return UpdateLocalAddress();
  350. }
  351. wxSocketError wxSocketImpl::CreateClient(bool wait)
  352. {
  353. if ( !PreCreateCheck(m_peer) )
  354. return m_error;
  355. m_fd = socket(m_peer.GetFamily(), SOCK_STREAM, 0);
  356. if ( m_fd == INVALID_SOCKET )
  357. {
  358. m_error = wxSOCKET_IOERR;
  359. return wxSOCKET_IOERR;
  360. }
  361. PostCreation();
  362. // If a local address has been set, then bind to it before calling connect
  363. if ( m_local.IsOk() )
  364. {
  365. if ( bind(m_fd, m_local.GetAddr(), m_local.GetLen()) != 0 )
  366. {
  367. Close();
  368. m_error = wxSOCKET_IOERR;
  369. return m_error;
  370. }
  371. }
  372. // Do connect now
  373. int rc = connect(m_fd, m_peer.GetAddr(), m_peer.GetLen());
  374. if ( rc == SOCKET_ERROR )
  375. {
  376. wxSocketError err = GetLastError();
  377. if ( err == wxSOCKET_WOULDBLOCK )
  378. {
  379. m_establishing = true;
  380. // block waiting for connection if we should (otherwise just return
  381. // wxSOCKET_WOULDBLOCK to the caller)
  382. if ( wait )
  383. {
  384. err = SelectWithTimeout(wxSOCKET_CONNECTION_FLAG)
  385. ? wxSOCKET_NOERROR
  386. : wxSOCKET_TIMEDOUT;
  387. m_establishing = false;
  388. }
  389. }
  390. m_error = err;
  391. }
  392. else // connected
  393. {
  394. m_error = wxSOCKET_NOERROR;
  395. }
  396. return m_error;
  397. }
  398. wxSocketError wxSocketImpl::CreateUDP()
  399. {
  400. if ( !PreCreateCheck(m_local) )
  401. return m_error;
  402. m_stream = false;
  403. m_server = false;
  404. m_fd = socket(m_local.GetFamily(), SOCK_DGRAM, 0);
  405. if ( m_fd == INVALID_SOCKET )
  406. {
  407. m_error = wxSOCKET_IOERR;
  408. return wxSOCKET_IOERR;
  409. }
  410. PostCreation();
  411. if ( m_dobind )
  412. {
  413. if ( bind(m_fd, m_local.GetAddr(), m_local.GetLen()) != 0 )
  414. {
  415. Close();
  416. m_error = wxSOCKET_IOERR;
  417. return m_error;
  418. }
  419. return UpdateLocalAddress();
  420. }
  421. return wxSOCKET_NOERROR;
  422. }
  423. wxSocketImpl *wxSocketImpl::Accept(wxSocketBase& wxsocket)
  424. {
  425. wxSockAddressStorage from;
  426. WX_SOCKLEN_T fromlen = sizeof(from);
  427. const wxSOCKET_T fd = accept(m_fd, &from.addr, &fromlen);
  428. wxScopeGuard closeSocket = wxMakeGuard(wxClose, fd);
  429. // accepting is similar to reading in the sense that it resets "ready for
  430. // read" flag on the socket
  431. ReenableEvents(wxSOCKET_INPUT_FLAG);
  432. if ( fd == INVALID_SOCKET )
  433. return NULL;
  434. wxSocketManager * const manager = wxSocketManager::Get();
  435. if ( !manager )
  436. return NULL;
  437. wxSocketImpl * const sock = manager->CreateSocket(wxsocket);
  438. if ( !sock )
  439. return NULL;
  440. // Ownership of the socket now passes to wxSocketImpl object.
  441. closeSocket.Dismiss();
  442. sock->m_fd = fd;
  443. sock->m_peer = wxSockAddressImpl(from.addr, fromlen);
  444. sock->UnblockAndRegisterWithEventLoop();
  445. return sock;
  446. }
  447. void wxSocketImpl::Close()
  448. {
  449. if ( m_fd != INVALID_SOCKET )
  450. {
  451. DoClose();
  452. m_fd = INVALID_SOCKET;
  453. }
  454. }
  455. void wxSocketImpl::Shutdown()
  456. {
  457. if ( m_fd != INVALID_SOCKET )
  458. {
  459. shutdown(m_fd, 1 /* SD_SEND */);
  460. Close();
  461. }
  462. }
  463. /*
  464. * Sets the timeout for blocking calls. Time is expressed in
  465. * milliseconds.
  466. */
  467. void wxSocketImpl::SetTimeout(unsigned long millis)
  468. {
  469. SetTimeValFromMS(m_timeout, millis);
  470. }
  471. void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event)
  472. {
  473. m_wxsocket->OnRequest(event);
  474. }
  475. /* Address handling */
  476. wxSocketError wxSocketImpl::SetLocal(const wxSockAddressImpl& local)
  477. {
  478. /* the socket must be initialized, or it must be a server */
  479. if (m_fd != INVALID_SOCKET && !m_server)
  480. {
  481. m_error = wxSOCKET_INVSOCK;
  482. return wxSOCKET_INVSOCK;
  483. }
  484. if ( !local.IsOk() )
  485. {
  486. m_error = wxSOCKET_INVADDR;
  487. return wxSOCKET_INVADDR;
  488. }
  489. m_local = local;
  490. return wxSOCKET_NOERROR;
  491. }
  492. wxSocketError wxSocketImpl::SetPeer(const wxSockAddressImpl& peer)
  493. {
  494. if ( !peer.IsOk() )
  495. {
  496. m_error = wxSOCKET_INVADDR;
  497. return wxSOCKET_INVADDR;
  498. }
  499. m_peer = peer;
  500. return wxSOCKET_NOERROR;
  501. }
  502. const wxSockAddressImpl& wxSocketImpl::GetLocal()
  503. {
  504. if ( !m_local.IsOk() )
  505. UpdateLocalAddress();
  506. return m_local;
  507. }
  508. // ----------------------------------------------------------------------------
  509. // wxSocketImpl IO
  510. // ----------------------------------------------------------------------------
  511. // this macro wraps the given expression (normally a syscall) in a loop which
  512. // ignores any interruptions, i.e. reevaluates it again if it failed and errno
  513. // is EINTR
  514. #ifdef __UNIX__
  515. #define DO_WHILE_EINTR( rc, syscall ) \
  516. do { \
  517. rc = (syscall); \
  518. } \
  519. while ( rc == -1 && errno == EINTR )
  520. #else
  521. #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
  522. #endif
  523. int wxSocketImpl::RecvStream(void *buffer, int size)
  524. {
  525. int ret;
  526. DO_WHILE_EINTR( ret, recv(m_fd, static_cast<char *>(buffer), size, 0) );
  527. if ( !ret )
  528. {
  529. // receiving 0 bytes for a TCP socket indicates that the connection was
  530. // closed by peer so shut down our end as well (for UDP sockets empty
  531. // datagrams are also possible)
  532. m_establishing = false;
  533. NotifyOnStateChange(wxSOCKET_LOST);
  534. Shutdown();
  535. // do not return an error in this case however
  536. }
  537. return ret;
  538. }
  539. int wxSocketImpl::SendStream(const void *buffer, int size)
  540. {
  541. #ifdef wxNEEDS_IGNORE_SIGPIPE
  542. IgnoreSignal ignore(SIGPIPE);
  543. #endif
  544. int ret;
  545. DO_WHILE_EINTR( ret, send(m_fd, static_cast<const char *>(buffer), size,
  546. wxSOCKET_MSG_NOSIGNAL) );
  547. return ret;
  548. }
  549. int wxSocketImpl::RecvDgram(void *buffer, int size)
  550. {
  551. wxSockAddressStorage from;
  552. WX_SOCKLEN_T fromlen = sizeof(from);
  553. int ret;
  554. DO_WHILE_EINTR( ret, recvfrom(m_fd, static_cast<char *>(buffer), size,
  555. 0, &from.addr, &fromlen) );
  556. if ( ret == SOCKET_ERROR )
  557. return SOCKET_ERROR;
  558. m_peer = wxSockAddressImpl(from.addr, fromlen);
  559. if ( !m_peer.IsOk() )
  560. return -1;
  561. return ret;
  562. }
  563. int wxSocketImpl::SendDgram(const void *buffer, int size)
  564. {
  565. if ( !m_peer.IsOk() )
  566. {
  567. m_error = wxSOCKET_INVADDR;
  568. return -1;
  569. }
  570. int ret;
  571. DO_WHILE_EINTR( ret, sendto(m_fd, static_cast<const char *>(buffer), size,
  572. 0, m_peer.GetAddr(), m_peer.GetLen()) );
  573. return ret;
  574. }
  575. int wxSocketImpl::Read(void *buffer, int size)
  576. {
  577. // server sockets can't be used for IO, only to accept new connections
  578. if ( m_fd == INVALID_SOCKET || m_server )
  579. {
  580. m_error = wxSOCKET_INVSOCK;
  581. return -1;
  582. }
  583. int ret = m_stream ? RecvStream(buffer, size)
  584. : RecvDgram(buffer, size);
  585. m_error = ret == SOCKET_ERROR ? GetLastError() : wxSOCKET_NOERROR;
  586. return ret;
  587. }
  588. int wxSocketImpl::Write(const void *buffer, int size)
  589. {
  590. if ( m_fd == INVALID_SOCKET || m_server )
  591. {
  592. m_error = wxSOCKET_INVSOCK;
  593. return -1;
  594. }
  595. int ret = m_stream ? SendStream(buffer, size)
  596. : SendDgram(buffer, size);
  597. m_error = ret == SOCKET_ERROR ? GetLastError() : wxSOCKET_NOERROR;
  598. return ret;
  599. }
  600. // ==========================================================================
  601. // wxSocketBase
  602. // ==========================================================================
  603. // --------------------------------------------------------------------------
  604. // Initialization and shutdown
  605. // --------------------------------------------------------------------------
  606. namespace
  607. {
  608. // counts the number of calls to Initialize() minus the number of calls to
  609. // Shutdown(): we don't really need it any more but it was documented that
  610. // Shutdown() must be called the same number of times as Initialize() and using
  611. // a counter helps us to check it
  612. int gs_socketInitCount = 0;
  613. } // anonymous namespace
  614. bool wxSocketBase::IsInitialized()
  615. {
  616. wxASSERT_MSG( wxIsMainThread(), "unsafe to call from other threads" );
  617. return gs_socketInitCount != 0;
  618. }
  619. bool wxSocketBase::Initialize()
  620. {
  621. wxCHECK_MSG( wxIsMainThread(), false,
  622. "must be called from the main thread" );
  623. if ( !gs_socketInitCount )
  624. {
  625. wxSocketManager * const manager = wxSocketManager::Get();
  626. if ( !manager || !manager->OnInit() )
  627. return false;
  628. }
  629. gs_socketInitCount++;
  630. return true;
  631. }
  632. void wxSocketBase::Shutdown()
  633. {
  634. wxCHECK_RET( wxIsMainThread(), "must be called from the main thread" );
  635. wxCHECK_RET( gs_socketInitCount > 0, "too many calls to Shutdown()" );
  636. if ( !--gs_socketInitCount )
  637. {
  638. wxSocketManager * const manager = wxSocketManager::Get();
  639. wxCHECK_RET( manager, "should have a socket manager" );
  640. manager->OnExit();
  641. }
  642. }
  643. // --------------------------------------------------------------------------
  644. // Ctor and dtor
  645. // --------------------------------------------------------------------------
  646. void wxSocketBase::Init()
  647. {
  648. m_impl = NULL;
  649. m_type = wxSOCKET_UNINIT;
  650. // state
  651. m_flags = 0;
  652. m_connected =
  653. m_establishing =
  654. m_reading =
  655. m_writing =
  656. m_closed = false;
  657. m_lcount = 0;
  658. m_lcount_read = 0;
  659. m_lcount_write = 0;
  660. m_timeout = 600;
  661. m_beingDeleted = false;
  662. // pushback buffer
  663. m_unread = NULL;
  664. m_unrd_size = 0;
  665. m_unrd_cur = 0;
  666. // events
  667. m_id = wxID_ANY;
  668. m_handler = NULL;
  669. m_clientData = NULL;
  670. m_notify = false;
  671. m_eventmask =
  672. m_eventsgot = 0;
  673. // when we create the first socket in the main thread we initialize the
  674. // OS-dependent socket stuff: notice that this means that the user code
  675. // needs to call wxSocket::Initialize() itself if the first socket it
  676. // creates is not created in the main thread
  677. if ( wxIsMainThread() )
  678. {
  679. if ( !Initialize() )
  680. {
  681. wxLogError(_("Cannot initialize sockets"));
  682. }
  683. }
  684. }
  685. wxSocketBase::wxSocketBase()
  686. {
  687. Init();
  688. }
  689. wxSocketBase::wxSocketBase(wxSocketFlags flags, wxSocketType type)
  690. {
  691. Init();
  692. SetFlags(flags);
  693. m_type = type;
  694. }
  695. wxSocketBase::~wxSocketBase()
  696. {
  697. // Shutdown and close the socket
  698. if (!m_beingDeleted)
  699. Close();
  700. // Destroy the implementation object
  701. delete m_impl;
  702. // Free the pushback buffer
  703. free(m_unread);
  704. }
  705. bool wxSocketBase::Destroy()
  706. {
  707. // Delayed destruction: the socket will be deleted during the next idle
  708. // loop iteration. This ensures that all pending events have been
  709. // processed.
  710. m_beingDeleted = true;
  711. // Shutdown and close the socket
  712. Close();
  713. // Suppress events from now on
  714. Notify(false);
  715. // Schedule this object for deletion instead of destroying it right now if
  716. // it can have other events pending for it and we have a way to do it.
  717. //
  718. // Notice that sockets used in other threads won't have any events for them
  719. // and we shouldn't use delayed destruction mechanism for them as it's not
  720. // MT-safe.
  721. if ( wxIsMainThread() && wxTheApp )
  722. {
  723. wxTheApp->ScheduleForDestruction(this);
  724. }
  725. else // no app
  726. {
  727. // in wxBase we might have no app object at all, don't leak memory
  728. delete this;
  729. }
  730. return true;
  731. }
  732. // ----------------------------------------------------------------------------
  733. // simple accessors
  734. // ----------------------------------------------------------------------------
  735. void wxSocketBase::SetError(wxSocketError error)
  736. {
  737. m_impl->m_error = error;
  738. }
  739. wxSocketError wxSocketBase::LastError() const
  740. {
  741. return m_impl->GetError();
  742. }
  743. // --------------------------------------------------------------------------
  744. // Basic IO calls
  745. // --------------------------------------------------------------------------
  746. // The following IO operations update m_lcount:
  747. // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
  748. bool wxSocketBase::Close()
  749. {
  750. // Interrupt pending waits
  751. InterruptWait();
  752. ShutdownOutput();
  753. m_connected = false;
  754. m_establishing = false;
  755. return true;
  756. }
  757. void wxSocketBase::ShutdownOutput()
  758. {
  759. if ( m_impl )
  760. m_impl->Shutdown();
  761. }
  762. wxSocketBase& wxSocketBase::Read(void* buffer, wxUint32 nbytes)
  763. {
  764. wxSocketReadGuard read(this);
  765. m_lcount_read = DoRead(buffer, nbytes);
  766. m_lcount = m_lcount_read;
  767. return *this;
  768. }
  769. wxUint32 wxSocketBase::DoRead(void* buffer_, wxUint32 nbytes)
  770. {
  771. wxCHECK_MSG( m_impl, 0, "socket must be valid" );
  772. // We use pointer arithmetic here which doesn't work with void pointers.
  773. char *buffer = static_cast<char *>(buffer_);
  774. wxCHECK_MSG( buffer, 0, "NULL buffer" );
  775. // Try the push back buffer first, even before checking whether the socket
  776. // is valid to allow reading previously pushed back data from an already
  777. // closed socket.
  778. wxUint32 total = GetPushback(buffer, nbytes, false);
  779. nbytes -= total;
  780. buffer += total;
  781. while ( nbytes )
  782. {
  783. // our socket is non-blocking so Read() will return immediately if
  784. // there is nothing to read yet and it's more efficient to try it first
  785. // before entering DoWait() which is going to start dispatching GUI
  786. // events and, even more importantly, we must do this under Windows
  787. // where we're not going to get notifications about socket being ready
  788. // for reading before we read all the existing data from it
  789. const int ret = !m_impl->m_stream || m_connected
  790. ? m_impl->Read(buffer, nbytes)
  791. : 0;
  792. if ( ret == -1 )
  793. {
  794. if ( m_impl->GetLastError() == wxSOCKET_WOULDBLOCK )
  795. {
  796. // if we don't want to wait, just return immediately
  797. if ( m_flags & wxSOCKET_NOWAIT_READ )
  798. {
  799. // this shouldn't be counted as an error in this case
  800. SetError(wxSOCKET_NOERROR);
  801. break;
  802. }
  803. // otherwise wait until the socket becomes ready for reading or
  804. // an error occurs on it
  805. if ( !DoWaitWithTimeout(wxSOCKET_INPUT_FLAG) )
  806. {
  807. // and exit if the timeout elapsed before it did
  808. SetError(wxSOCKET_TIMEDOUT);
  809. break;
  810. }
  811. // retry reading
  812. continue;
  813. }
  814. else // "real" error
  815. {
  816. SetError(wxSOCKET_IOERR);
  817. break;
  818. }
  819. }
  820. else if ( ret == 0 )
  821. {
  822. // for connection-oriented (e.g. TCP) sockets we can only read
  823. // 0 bytes if the other end has been closed, and for connectionless
  824. // ones (UDP) this flag doesn't make sense anyhow so we can set it
  825. // to true too without doing any harm
  826. m_closed = true;
  827. // we're not going to read anything else and so if we haven't read
  828. // anything (or not everything in wxSOCKET_WAITALL case) already,
  829. // signal an error
  830. if ( (m_flags & wxSOCKET_WAITALL_READ) || !total )
  831. SetError(wxSOCKET_IOERR);
  832. break;
  833. }
  834. total += ret;
  835. // if we are happy to read something and not the entire nbytes bytes,
  836. // then we're done
  837. if ( !(m_flags & wxSOCKET_WAITALL_READ) )
  838. break;
  839. nbytes -= ret;
  840. buffer += ret;
  841. }
  842. return total;
  843. }
  844. wxSocketBase& wxSocketBase::ReadMsg(void* buffer, wxUint32 nbytes)
  845. {
  846. struct
  847. {
  848. unsigned char sig[4];
  849. unsigned char len[4];
  850. } msg;
  851. wxSocketReadGuard read(this);
  852. wxSocketWaitModeChanger changeFlags(this, wxSOCKET_WAITALL_READ);
  853. bool ok = false;
  854. if ( DoRead(&msg, sizeof(msg)) == sizeof(msg) )
  855. {
  856. wxUint32 sig = (wxUint32)msg.sig[0];
  857. sig |= (wxUint32)(msg.sig[1] << 8);
  858. sig |= (wxUint32)(msg.sig[2] << 16);
  859. sig |= (wxUint32)(msg.sig[3] << 24);
  860. if ( sig == 0xfeeddead )
  861. {
  862. wxUint32 len = (wxUint32)msg.len[0];
  863. len |= (wxUint32)(msg.len[1] << 8);
  864. len |= (wxUint32)(msg.len[2] << 16);
  865. len |= (wxUint32)(msg.len[3] << 24);
  866. wxUint32 len2;
  867. if (len > nbytes)
  868. {
  869. len2 = len - nbytes;
  870. len = nbytes;
  871. }
  872. else
  873. len2 = 0;
  874. // Don't attempt to read if the msg was zero bytes long.
  875. m_lcount_read = len ? DoRead(buffer, len) : 0;
  876. m_lcount = m_lcount_read;
  877. if ( len2 )
  878. {
  879. char discard_buffer[MAX_DISCARD_SIZE];
  880. long discard_len;
  881. // NOTE: discarded bytes don't add to m_lcount.
  882. do
  883. {
  884. discard_len = len2 > MAX_DISCARD_SIZE
  885. ? MAX_DISCARD_SIZE
  886. : len2;
  887. discard_len = DoRead(discard_buffer, (wxUint32)discard_len);
  888. len2 -= (wxUint32)discard_len;
  889. }
  890. while ((discard_len > 0) && len2);
  891. }
  892. if ( !len2 && DoRead(&msg, sizeof(msg)) == sizeof(msg) )
  893. {
  894. sig = (wxUint32)msg.sig[0];
  895. sig |= (wxUint32)(msg.sig[1] << 8);
  896. sig |= (wxUint32)(msg.sig[2] << 16);
  897. sig |= (wxUint32)(msg.sig[3] << 24);
  898. if ( sig == 0xdeadfeed )
  899. ok = true;
  900. }
  901. }
  902. }
  903. if ( !ok )
  904. SetError(wxSOCKET_IOERR);
  905. return *this;
  906. }
  907. wxSocketBase& wxSocketBase::Peek(void* buffer, wxUint32 nbytes)
  908. {
  909. wxSocketReadGuard read(this);
  910. // Peek() should never block
  911. wxSocketWaitModeChanger changeFlags(this, wxSOCKET_NOWAIT);
  912. m_lcount = DoRead(buffer, nbytes);
  913. Pushback(buffer, m_lcount);
  914. return *this;
  915. }
  916. wxSocketBase& wxSocketBase::Write(const void *buffer, wxUint32 nbytes)
  917. {
  918. wxSocketWriteGuard write(this);
  919. m_lcount_write = DoWrite(buffer, nbytes);
  920. m_lcount = m_lcount_write;
  921. return *this;
  922. }
  923. // This function is a mirror image of DoRead() except that it doesn't use the
  924. // push back buffer and doesn't treat 0 return value specially (normally this
  925. // shouldn't happen at all here), so please see comments there for explanations
  926. wxUint32 wxSocketBase::DoWrite(const void *buffer_, wxUint32 nbytes)
  927. {
  928. wxCHECK_MSG( m_impl, 0, "socket must be valid" );
  929. const char *buffer = static_cast<const char *>(buffer_);
  930. wxCHECK_MSG( buffer, 0, "NULL buffer" );
  931. wxUint32 total = 0;
  932. while ( nbytes )
  933. {
  934. if ( m_impl->m_stream && !m_connected )
  935. {
  936. if ( (m_flags & wxSOCKET_WAITALL_WRITE) || !total )
  937. SetError(wxSOCKET_IOERR);
  938. break;
  939. }
  940. const int ret = m_impl->Write(buffer, nbytes);
  941. if ( ret == -1 )
  942. {
  943. if ( m_impl->GetLastError() == wxSOCKET_WOULDBLOCK )
  944. {
  945. if ( m_flags & wxSOCKET_NOWAIT_WRITE )
  946. break;
  947. if ( !DoWaitWithTimeout(wxSOCKET_OUTPUT_FLAG) )
  948. {
  949. SetError(wxSOCKET_TIMEDOUT);
  950. break;
  951. }
  952. continue;
  953. }
  954. else // "real" error
  955. {
  956. SetError(wxSOCKET_IOERR);
  957. break;
  958. }
  959. }
  960. total += ret;
  961. if ( !(m_flags & wxSOCKET_WAITALL_WRITE) )
  962. break;
  963. nbytes -= ret;
  964. buffer += ret;
  965. }
  966. return total;
  967. }
  968. wxSocketBase& wxSocketBase::WriteMsg(const void *buffer, wxUint32 nbytes)
  969. {
  970. struct
  971. {
  972. unsigned char sig[4];
  973. unsigned char len[4];
  974. } msg;
  975. wxSocketWriteGuard write(this);
  976. wxSocketWaitModeChanger changeFlags(this, wxSOCKET_WAITALL_WRITE);
  977. msg.sig[0] = (unsigned char) 0xad;
  978. msg.sig[1] = (unsigned char) 0xde;
  979. msg.sig[2] = (unsigned char) 0xed;
  980. msg.sig[3] = (unsigned char) 0xfe;
  981. msg.len[0] = (unsigned char) (nbytes & 0xff);
  982. msg.len[1] = (unsigned char) ((nbytes >> 8) & 0xff);
  983. msg.len[2] = (unsigned char) ((nbytes >> 16) & 0xff);
  984. msg.len[3] = (unsigned char) ((nbytes >> 24) & 0xff);
  985. bool ok = false;
  986. if ( DoWrite(&msg, sizeof(msg)) == sizeof(msg) )
  987. {
  988. m_lcount_write = DoWrite(buffer, nbytes);
  989. m_lcount = m_lcount_write;
  990. if ( m_lcount_write == nbytes )
  991. {
  992. msg.sig[0] = (unsigned char) 0xed;
  993. msg.sig[1] = (unsigned char) 0xfe;
  994. msg.sig[2] = (unsigned char) 0xad;
  995. msg.sig[3] = (unsigned char) 0xde;
  996. msg.len[0] =
  997. msg.len[1] =
  998. msg.len[2] =
  999. msg.len[3] = (char) 0;
  1000. if ( DoWrite(&msg, sizeof(msg)) == sizeof(msg))
  1001. ok = true;
  1002. }
  1003. }
  1004. if ( !ok )
  1005. SetError(wxSOCKET_IOERR);
  1006. return *this;
  1007. }
  1008. wxSocketBase& wxSocketBase::Unread(const void *buffer, wxUint32 nbytes)
  1009. {
  1010. if (nbytes != 0)
  1011. Pushback(buffer, nbytes);
  1012. SetError(wxSOCKET_NOERROR);
  1013. m_lcount = nbytes;
  1014. return *this;
  1015. }
  1016. wxSocketBase& wxSocketBase::Discard()
  1017. {
  1018. char *buffer = new char[MAX_DISCARD_SIZE];
  1019. wxUint32 ret;
  1020. wxUint32 total = 0;
  1021. wxSocketReadGuard read(this);
  1022. wxSocketWaitModeChanger changeFlags(this, wxSOCKET_NOWAIT);
  1023. do
  1024. {
  1025. ret = DoRead(buffer, MAX_DISCARD_SIZE);
  1026. total += ret;
  1027. }
  1028. while (ret == MAX_DISCARD_SIZE);
  1029. delete[] buffer;
  1030. m_lcount = total;
  1031. SetError(wxSOCKET_NOERROR);
  1032. return *this;
  1033. }
  1034. // --------------------------------------------------------------------------
  1035. // Wait functions
  1036. // --------------------------------------------------------------------------
  1037. /*
  1038. This function will check for the events specified in the flags parameter,
  1039. and it will return a mask indicating which operations can be performed.
  1040. */
  1041. wxSocketEventFlags wxSocketImpl::Select(wxSocketEventFlags flags,
  1042. const timeval *timeout)
  1043. {
  1044. if ( m_fd == INVALID_SOCKET )
  1045. return (wxSOCKET_LOST_FLAG & flags);
  1046. struct timeval tv;
  1047. if ( timeout )
  1048. tv = *timeout;
  1049. else
  1050. tv.tv_sec = tv.tv_usec = 0;
  1051. // prepare the FD sets, passing NULL for the one(s) we don't use
  1052. fd_set
  1053. readfds, *preadfds = NULL,
  1054. writefds, *pwritefds = NULL,
  1055. exceptfds; // always want to know about errors
  1056. if ( flags & wxSOCKET_INPUT_FLAG )
  1057. preadfds = &readfds;
  1058. if ( flags & wxSOCKET_OUTPUT_FLAG )
  1059. pwritefds = &writefds;
  1060. // When using non-blocking connect() the client socket becomes connected
  1061. // (successfully or not) when it becomes writable but when using
  1062. // non-blocking accept() the server socket becomes connected when it
  1063. // becomes readable.
  1064. if ( flags & wxSOCKET_CONNECTION_FLAG )
  1065. {
  1066. if ( m_server )
  1067. preadfds = &readfds;
  1068. else
  1069. pwritefds = &writefds;
  1070. }
  1071. if ( preadfds )
  1072. {
  1073. wxFD_ZERO(preadfds);
  1074. wxFD_SET(m_fd, preadfds);
  1075. }
  1076. if ( pwritefds )
  1077. {
  1078. wxFD_ZERO(pwritefds);
  1079. wxFD_SET(m_fd, pwritefds);
  1080. }
  1081. wxFD_ZERO(&exceptfds);
  1082. wxFD_SET(m_fd, &exceptfds);
  1083. const int rc = select(m_fd + 1, preadfds, pwritefds, &exceptfds, &tv);
  1084. // check for errors first
  1085. if ( rc == -1 || wxFD_ISSET(m_fd, &exceptfds) )
  1086. {
  1087. m_establishing = false;
  1088. return wxSOCKET_LOST_FLAG & flags;
  1089. }
  1090. if ( rc == 0 )
  1091. return 0;
  1092. wxASSERT_MSG( rc == 1, "unexpected select() return value" );
  1093. wxSocketEventFlags detected = 0;
  1094. if ( preadfds && wxFD_ISSET(m_fd, preadfds) )
  1095. {
  1096. // check for the case of a server socket waiting for connection
  1097. if ( m_server && (flags & wxSOCKET_CONNECTION_FLAG) )
  1098. {
  1099. int error;
  1100. SOCKOPTLEN_T len = sizeof(error);
  1101. m_establishing = false;
  1102. getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
  1103. if ( error )
  1104. detected = wxSOCKET_LOST_FLAG;
  1105. else
  1106. detected |= wxSOCKET_CONNECTION_FLAG;
  1107. }
  1108. else // not called to get non-blocking accept() status
  1109. {
  1110. detected |= wxSOCKET_INPUT_FLAG;
  1111. }
  1112. }
  1113. if ( pwritefds && wxFD_ISSET(m_fd, pwritefds) )
  1114. {
  1115. // check for the case of non-blocking connect()
  1116. if ( m_establishing && !m_server )
  1117. {
  1118. int error;
  1119. SOCKOPTLEN_T len = sizeof(error);
  1120. m_establishing = false;
  1121. getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
  1122. if ( error )
  1123. detected = wxSOCKET_LOST_FLAG;
  1124. else
  1125. detected |= wxSOCKET_CONNECTION_FLAG;
  1126. }
  1127. else // not called to get non-blocking connect() status
  1128. {
  1129. detected |= wxSOCKET_OUTPUT_FLAG;
  1130. }
  1131. }
  1132. return detected & flags;
  1133. }
  1134. int
  1135. wxSocketBase::DoWait(long seconds, long milliseconds, wxSocketEventFlags flags)
  1136. {
  1137. // Use either the provided timeout or the default timeout value associated
  1138. // with this socket.
  1139. //
  1140. // TODO: allow waiting forever, see #9443
  1141. const long timeout = seconds == -1 ? m_timeout * 1000
  1142. : seconds * 1000 + milliseconds;
  1143. return DoWait(timeout, flags);
  1144. }
  1145. int
  1146. wxSocketBase::DoWait(long timeout, wxSocketEventFlags flags)
  1147. {
  1148. wxCHECK_MSG( m_impl, -1, "can't wait on invalid socket" );
  1149. // we're never going to become ready in a TCP client if we're not connected
  1150. // any more (OTOH a server can call this to precisely wait for a connection
  1151. // so do wait for it in this case and UDP client is never "connected")
  1152. if ( !m_impl->IsServer() &&
  1153. m_impl->m_stream && !m_connected && !m_establishing )
  1154. return -1;
  1155. // This can be set to true from Interrupt() to exit this function a.s.a.p.
  1156. m_interrupt = false;
  1157. const wxMilliClock_t timeEnd = wxGetLocalTimeMillis() + timeout;
  1158. // Get the active event loop which we'll use for the message dispatching
  1159. // when running in the main thread unless this was explicitly disabled by
  1160. // setting wxSOCKET_BLOCK flag
  1161. wxEventLoopBase *eventLoop;
  1162. if ( !(m_flags & wxSOCKET_BLOCK) && wxIsMainThread() )
  1163. {
  1164. eventLoop = wxEventLoop::GetActive();
  1165. }
  1166. else // in worker thread
  1167. {
  1168. // We never dispatch messages from threads other than the main one.
  1169. eventLoop = NULL;
  1170. }
  1171. // Make sure the events we're interested in are enabled before waiting for
  1172. // them: this is really necessary here as otherwise this could happen:
  1173. // 1. DoRead(wxSOCKET_WAITALL) is called
  1174. // 2. There is nothing to read so DoWait(wxSOCKET_INPUT_FLAG) is called
  1175. // 3. Some, but not all data appears, wxSocketImplUnix::OnReadWaiting()
  1176. // is called and wxSOCKET_INPUT_FLAG events are disabled in it
  1177. // 4. Because of wxSOCKET_WAITALL we call DoWait() again but the events
  1178. // are still disabled and we block forever
  1179. //
  1180. // More elegant solution would be nice but for now simply re-enabling the
  1181. // events here will do
  1182. m_impl->ReenableEvents(flags & (wxSOCKET_INPUT_FLAG | wxSOCKET_OUTPUT_FLAG));
  1183. // Wait until we receive the event we're waiting for or the timeout expires
  1184. // (but note that we always execute the loop at least once, even if timeout
  1185. // is 0 as this is used for polling)
  1186. int rc = 0;
  1187. for ( bool firstTime = true; !m_interrupt; firstTime = false )
  1188. {
  1189. long timeLeft = wxMilliClockToLong(timeEnd - wxGetLocalTimeMillis());
  1190. if ( timeLeft < 0 )
  1191. {
  1192. if ( !firstTime )
  1193. break; // timed out
  1194. timeLeft = 0;
  1195. }
  1196. wxSocketEventFlags events;
  1197. if ( eventLoop )
  1198. {
  1199. // reset them before starting to wait
  1200. m_eventsgot = 0;
  1201. eventLoop->DispatchTimeout(timeLeft);
  1202. events = m_eventsgot;
  1203. }
  1204. else // no event loop or waiting in another thread
  1205. {
  1206. // as explained below, we should always check for wxSOCKET_LOST_FLAG
  1207. timeval tv;
  1208. SetTimeValFromMS(tv, timeLeft);
  1209. events = m_impl->Select(flags | wxSOCKET_LOST_FLAG, &tv);
  1210. }
  1211. // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
  1212. // it, as continuing to wait for anything else after getting it is
  1213. // pointless
  1214. if ( events & wxSOCKET_LOST_FLAG )
  1215. {
  1216. m_connected = false;
  1217. m_establishing = false;
  1218. rc = -1;
  1219. break;
  1220. }
  1221. // otherwise mask out the bits we're not interested in
  1222. events &= flags;
  1223. // Incoming connection (server) or connection established (client)?
  1224. if ( events & wxSOCKET_CONNECTION_FLAG )
  1225. {
  1226. m_connected = true;
  1227. m_establishing = false;
  1228. rc = true;
  1229. break;
  1230. }
  1231. // Data available or output buffer ready?
  1232. if ( (events & wxSOCKET_INPUT_FLAG) || (events & wxSOCKET_OUTPUT_FLAG) )
  1233. {
  1234. rc = true;
  1235. break;
  1236. }
  1237. }
  1238. return rc;
  1239. }
  1240. bool wxSocketBase::Wait(long seconds, long milliseconds)
  1241. {
  1242. return DoWait(seconds, milliseconds,
  1243. wxSOCKET_INPUT_FLAG |
  1244. wxSOCKET_OUTPUT_FLAG |
  1245. wxSOCKET_CONNECTION_FLAG) != 0;
  1246. }
  1247. bool wxSocketBase::WaitForRead(long seconds, long milliseconds)
  1248. {
  1249. // Check pushback buffer before entering DoWait
  1250. if ( m_unread )
  1251. return true;
  1252. // Check if the socket is not already ready for input, if it is, there is
  1253. // no need to start waiting for it (worse, we'll actually never get a
  1254. // notification about the socket becoming ready if it is already under
  1255. // Windows)
  1256. if ( m_impl->Select(wxSOCKET_INPUT_FLAG) )
  1257. return true;
  1258. return DoWait(seconds, milliseconds, wxSOCKET_INPUT_FLAG) != 0;
  1259. }
  1260. bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
  1261. {
  1262. if ( m_impl->Select(wxSOCKET_OUTPUT_FLAG) )
  1263. return true;
  1264. return DoWait(seconds, milliseconds, wxSOCKET_OUTPUT_FLAG) != 0;
  1265. }
  1266. bool wxSocketBase::WaitForLost(long seconds, long milliseconds)
  1267. {
  1268. return DoWait(seconds, milliseconds, wxSOCKET_LOST_FLAG) == -1;
  1269. }
  1270. // --------------------------------------------------------------------------
  1271. // Miscellaneous
  1272. // --------------------------------------------------------------------------
  1273. //
  1274. // Get local or peer address
  1275. //
  1276. bool wxSocketBase::GetPeer(wxSockAddress& addr) const
  1277. {
  1278. wxCHECK_MSG( m_impl, false, "invalid socket" );
  1279. const wxSockAddressImpl& peer = m_impl->GetPeer();
  1280. if ( !peer.IsOk() )
  1281. return false;
  1282. addr.SetAddress(peer);
  1283. return true;
  1284. }
  1285. bool wxSocketBase::GetLocal(wxSockAddress& addr) const
  1286. {
  1287. wxCHECK_MSG( m_impl, false, "invalid socket" );
  1288. const wxSockAddressImpl& local = m_impl->GetLocal();
  1289. if ( !local.IsOk() )
  1290. return false;
  1291. addr.SetAddress(local);
  1292. return true;
  1293. }
  1294. //
  1295. // Save and restore socket state
  1296. //
  1297. void wxSocketBase::SaveState()
  1298. {
  1299. wxSocketState *state;
  1300. state = new wxSocketState();
  1301. state->m_flags = m_flags;
  1302. state->m_notify = m_notify;
  1303. state->m_eventmask = m_eventmask;
  1304. state->m_clientData = m_clientData;
  1305. m_states.Append(state);
  1306. }
  1307. void wxSocketBase::RestoreState()
  1308. {
  1309. wxList::compatibility_iterator node;
  1310. wxSocketState *state;
  1311. node = m_states.GetLast();
  1312. if (!node)
  1313. return;
  1314. state = (wxSocketState *)node->GetData();
  1315. m_flags = state->m_flags;
  1316. m_notify = state->m_notify;
  1317. m_eventmask = state->m_eventmask;
  1318. m_clientData = state->m_clientData;
  1319. m_states.Erase(node);
  1320. delete state;
  1321. }
  1322. //
  1323. // Timeout and flags
  1324. //
  1325. void wxSocketBase::SetTimeout(long seconds)
  1326. {
  1327. m_timeout = seconds;
  1328. if (m_impl)
  1329. m_impl->SetTimeout(m_timeout * 1000);
  1330. }
  1331. void wxSocketBase::SetFlags(wxSocketFlags flags)
  1332. {
  1333. // Do some sanity checking on the flags used: not all values can be used
  1334. // together.
  1335. wxASSERT_MSG( !(flags & wxSOCKET_NOWAIT) ||
  1336. !(flags & (wxSOCKET_WAITALL | wxSOCKET_BLOCK)),
  1337. "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
  1338. "wxSOCKET_NOWAIT doesn't make sense" );
  1339. m_flags = flags;
  1340. }
  1341. // --------------------------------------------------------------------------
  1342. // Event handling
  1343. // --------------------------------------------------------------------------
  1344. void wxSocketBase::OnRequest(wxSocketNotify notification)
  1345. {
  1346. wxSocketEventFlags flag = 0;
  1347. switch ( notification )
  1348. {
  1349. case wxSOCKET_INPUT:
  1350. flag = wxSOCKET_INPUT_FLAG;
  1351. break;
  1352. case wxSOCKET_OUTPUT:
  1353. flag = wxSOCKET_OUTPUT_FLAG;
  1354. break;
  1355. case wxSOCKET_CONNECTION:
  1356. flag = wxSOCKET_CONNECTION_FLAG;
  1357. // we're now successfully connected
  1358. m_connected = true;
  1359. m_establishing = false;
  1360. // error was previously set to wxSOCKET_WOULDBLOCK, but this is not
  1361. // the case any longer
  1362. SetError(wxSOCKET_NOERROR);
  1363. break;
  1364. case wxSOCKET_LOST:
  1365. flag = wxSOCKET_LOST_FLAG;
  1366. // if we lost the connection the socket is now closed and not
  1367. // connected any more
  1368. m_connected = false;
  1369. m_closed = true;
  1370. break;
  1371. default:
  1372. wxFAIL_MSG( "unknown wxSocket notification" );
  1373. }
  1374. // remember the events which were generated for this socket, we're going to
  1375. // use this in DoWait()
  1376. m_eventsgot |= flag;
  1377. // send the wx event if enabled and we're interested in it
  1378. if ( m_notify && (m_eventmask & flag) && m_handler )
  1379. {
  1380. // don't generate the events when we're inside DoWait() called from our
  1381. // own code as we are going to consume the data that has just become
  1382. // available ourselves and the user code won't see it at all
  1383. if ( (notification == wxSOCKET_INPUT && m_reading) ||
  1384. (notification == wxSOCKET_OUTPUT && m_writing) )
  1385. {
  1386. return;
  1387. }
  1388. wxSocketEvent event(m_id);
  1389. event.m_event = notification;
  1390. event.m_clientData = m_clientData;
  1391. event.SetEventObject(this);
  1392. m_handler->AddPendingEvent(event);
  1393. }
  1394. }
  1395. void wxSocketBase::Notify(bool notify)
  1396. {
  1397. m_notify = notify;
  1398. }
  1399. void wxSocketBase::SetNotify(wxSocketEventFlags flags)
  1400. {
  1401. m_eventmask = flags;
  1402. }
  1403. void wxSocketBase::SetEventHandler(wxEvtHandler& handler, int id)
  1404. {
  1405. m_handler = &handler;
  1406. m_id = id;
  1407. }
  1408. // --------------------------------------------------------------------------
  1409. // Pushback buffer
  1410. // --------------------------------------------------------------------------
  1411. void wxSocketBase::Pushback(const void *buffer, wxUint32 size)
  1412. {
  1413. if (!size) return;
  1414. if (m_unread == NULL)
  1415. m_unread = malloc(size);
  1416. else
  1417. {
  1418. void *tmp;
  1419. tmp = malloc(m_unrd_size + size);
  1420. memcpy((char *)tmp + size, m_unread, m_unrd_size);
  1421. free(m_unread);
  1422. m_unread = tmp;
  1423. }
  1424. m_unrd_size += size;
  1425. memcpy(m_unread, buffer, size);
  1426. }
  1427. wxUint32 wxSocketBase::GetPushback(void *buffer, wxUint32 size, bool peek)
  1428. {
  1429. wxCHECK_MSG( buffer, 0, "NULL buffer" );
  1430. if (!m_unrd_size)
  1431. return 0;
  1432. if (size > (m_unrd_size-m_unrd_cur))
  1433. size = m_unrd_size-m_unrd_cur;
  1434. memcpy(buffer, (char *)m_unread + m_unrd_cur, size);
  1435. if (!peek)
  1436. {
  1437. m_unrd_cur += size;
  1438. if (m_unrd_size == m_unrd_cur)
  1439. {
  1440. free(m_unread);
  1441. m_unread = NULL;
  1442. m_unrd_size = 0;
  1443. m_unrd_cur = 0;
  1444. }
  1445. }
  1446. return size;
  1447. }
  1448. // ==========================================================================
  1449. // wxSocketServer
  1450. // ==========================================================================
  1451. // --------------------------------------------------------------------------
  1452. // Ctor
  1453. // --------------------------------------------------------------------------
  1454. wxSocketServer::wxSocketServer(const wxSockAddress& addr,
  1455. wxSocketFlags flags)
  1456. : wxSocketBase(flags, wxSOCKET_SERVER)
  1457. {
  1458. wxLogTrace( wxTRACE_Socket, wxT("Opening wxSocketServer") );
  1459. wxSocketManager * const manager = wxSocketManager::Get();
  1460. m_impl = manager ? manager->CreateSocket(*this) : NULL;
  1461. if (!m_impl)
  1462. {
  1463. wxLogTrace( wxTRACE_Socket, wxT("*** Failed to create m_impl") );
  1464. return;
  1465. }
  1466. // Setup the socket as server
  1467. m_impl->SetLocal(addr.GetAddress());
  1468. if (GetFlags() & wxSOCKET_REUSEADDR) {
  1469. m_impl->SetReusable();
  1470. }
  1471. if (GetFlags() & wxSOCKET_BROADCAST) {
  1472. m_impl->SetBroadcast();
  1473. }
  1474. if (GetFlags() & wxSOCKET_NOBIND) {
  1475. m_impl->DontDoBind();
  1476. }
  1477. if (m_impl->CreateServer() != wxSOCKET_NOERROR)
  1478. {
  1479. wxDELETE(m_impl);
  1480. wxLogTrace( wxTRACE_Socket, wxT("*** CreateServer() failed") );
  1481. return;
  1482. }
  1483. // Notice that we need a cast as wxSOCKET_T is 64 bit under Win64 and that
  1484. // the cast is safe because a wxSOCKET_T is a handle and so limited to 32
  1485. // (or, actually, even 24) bit values anyhow.
  1486. wxLogTrace( wxTRACE_Socket, wxT("wxSocketServer on fd %u"),
  1487. static_cast<unsigned>(m_impl->m_fd) );
  1488. }
  1489. // --------------------------------------------------------------------------
  1490. // Accept
  1491. // --------------------------------------------------------------------------
  1492. bool wxSocketServer::AcceptWith(wxSocketBase& sock, bool wait)
  1493. {
  1494. if ( !m_impl || (m_impl->m_fd == INVALID_SOCKET) || !m_impl->IsServer() )
  1495. {
  1496. wxFAIL_MSG( "can only be called for a valid server socket" );
  1497. SetError(wxSOCKET_INVSOCK);
  1498. return false;
  1499. }
  1500. if ( wait )
  1501. {
  1502. // wait until we get a connection
  1503. if ( !m_impl->SelectWithTimeout(wxSOCKET_INPUT_FLAG) )
  1504. {
  1505. SetError(wxSOCKET_TIMEDOUT);
  1506. return false;
  1507. }
  1508. }
  1509. sock.m_impl = m_impl->Accept(sock);
  1510. if ( !sock.m_impl )
  1511. {
  1512. SetError(m_impl->GetLastError());
  1513. return false;
  1514. }
  1515. sock.m_type = wxSOCKET_BASE;
  1516. sock.m_connected = true;
  1517. return true;
  1518. }
  1519. wxSocketBase *wxSocketServer::Accept(bool wait)
  1520. {
  1521. wxSocketBase* sock = new wxSocketBase();
  1522. sock->SetFlags(m_flags);
  1523. if (!AcceptWith(*sock, wait))
  1524. {
  1525. sock->Destroy();
  1526. sock = NULL;
  1527. }
  1528. return sock;
  1529. }
  1530. bool wxSocketServer::WaitForAccept(long seconds, long milliseconds)
  1531. {
  1532. return DoWait(seconds, milliseconds, wxSOCKET_CONNECTION_FLAG) == 1;
  1533. }
  1534. wxSOCKET_T wxSocketBase::GetSocket() const
  1535. {
  1536. wxASSERT_MSG( m_impl, wxS("Socket not initialised") );
  1537. return m_impl->m_fd;
  1538. }
  1539. bool wxSocketBase::GetOption(int level, int optname, void *optval, int *optlen)
  1540. {
  1541. wxASSERT_MSG( m_impl, wxT("Socket not initialised") );
  1542. SOCKOPTLEN_T lenreal = *optlen;
  1543. if ( getsockopt(m_impl->m_fd, level, optname,
  1544. static_cast<char *>(optval), &lenreal) != 0 )
  1545. return false;
  1546. *optlen = lenreal;
  1547. return true;
  1548. }
  1549. bool
  1550. wxSocketBase::SetOption(int level, int optname, const void *optval, int optlen)
  1551. {
  1552. wxASSERT_MSG( m_impl, wxT("Socket not initialised") );
  1553. return setsockopt(m_impl->m_fd, level, optname,
  1554. static_cast<const char *>(optval), optlen) == 0;
  1555. }
  1556. bool wxSocketBase::SetLocal(const wxIPV4address& local)
  1557. {
  1558. m_localAddress = local;
  1559. return true;
  1560. }
  1561. // ==========================================================================
  1562. // wxSocketClient
  1563. // ==========================================================================
  1564. // --------------------------------------------------------------------------
  1565. // Ctor and dtor
  1566. // --------------------------------------------------------------------------
  1567. wxSocketClient::wxSocketClient(wxSocketFlags flags)
  1568. : wxSocketBase(flags, wxSOCKET_CLIENT)
  1569. {
  1570. m_initialRecvBufferSize =
  1571. m_initialSendBufferSize = -1;
  1572. }
  1573. // --------------------------------------------------------------------------
  1574. // Connect
  1575. // --------------------------------------------------------------------------
  1576. bool wxSocketClient::DoConnect(const wxSockAddress& remote,
  1577. const wxSockAddress* local,
  1578. bool wait)
  1579. {
  1580. if ( m_impl )
  1581. {
  1582. // Shutdown and destroy the old socket
  1583. Close();
  1584. delete m_impl;
  1585. }
  1586. m_connected = false;
  1587. m_establishing = false;
  1588. // Create and set up the new one
  1589. wxSocketManager * const manager = wxSocketManager::Get();
  1590. m_impl = manager ? manager->CreateSocket(*this) : NULL;
  1591. if ( !m_impl )
  1592. return false;
  1593. // Reuse makes sense for clients too, if we are trying to rebind to the same port
  1594. if (GetFlags() & wxSOCKET_REUSEADDR)
  1595. m_impl->SetReusable();
  1596. if (GetFlags() & wxSOCKET_BROADCAST)
  1597. m_impl->SetBroadcast();
  1598. if (GetFlags() & wxSOCKET_NOBIND)
  1599. m_impl->DontDoBind();
  1600. // Bind to the local IP address and port, when provided or if one had been
  1601. // set before
  1602. if ( !local && m_localAddress.GetAddress().IsOk() )
  1603. local = &m_localAddress;
  1604. if ( local )
  1605. m_impl->SetLocal(local->GetAddress());
  1606. m_impl->SetInitialSocketBuffers(m_initialRecvBufferSize, m_initialSendBufferSize);
  1607. m_impl->SetPeer(remote.GetAddress());
  1608. // Finally do create the socket and connect to the peer
  1609. const wxSocketError err = m_impl->CreateClient(wait);
  1610. if ( err != wxSOCKET_NOERROR )
  1611. {
  1612. if ( err == wxSOCKET_WOULDBLOCK )
  1613. {
  1614. wxASSERT_MSG( !wait, "shouldn't get this for blocking connect" );
  1615. m_establishing = true;
  1616. }
  1617. return false;
  1618. }
  1619. m_connected = true;
  1620. return true;
  1621. }
  1622. bool wxSocketClient::Connect(const wxSockAddress& remote, bool wait)
  1623. {
  1624. return DoConnect(remote, NULL, wait);
  1625. }
  1626. bool wxSocketClient::Connect(const wxSockAddress& remote,
  1627. const wxSockAddress& local,
  1628. bool wait)
  1629. {
  1630. return DoConnect(remote, &local, wait);
  1631. }
  1632. bool wxSocketClient::WaitOnConnect(long seconds, long milliseconds)
  1633. {
  1634. if ( m_connected )
  1635. {
  1636. // this happens if the initial attempt to connect succeeded without
  1637. // blocking
  1638. return true;
  1639. }
  1640. wxCHECK_MSG( m_establishing && m_impl, false,
  1641. "No connection establishment attempt in progress" );
  1642. // notice that we return true even if DoWait() returned -1, i.e. if an
  1643. // error occurred and connection was lost: this is intentional as we should
  1644. // return false only if timeout expired without anything happening
  1645. return DoWait(seconds, milliseconds, wxSOCKET_CONNECTION_FLAG) != 0;
  1646. }
  1647. // ==========================================================================
  1648. // wxDatagramSocket
  1649. // ==========================================================================
  1650. wxDatagramSocket::wxDatagramSocket( const wxSockAddress& addr,
  1651. wxSocketFlags flags )
  1652. : wxSocketBase( flags, wxSOCKET_DATAGRAM )
  1653. {
  1654. // Create the socket
  1655. wxSocketManager * const manager = wxSocketManager::Get();
  1656. m_impl = manager ? manager->CreateSocket(*this) : NULL;
  1657. if (!m_impl)
  1658. return;
  1659. // Setup the socket as non connection oriented
  1660. m_impl->SetLocal(addr.GetAddress());
  1661. if (flags & wxSOCKET_REUSEADDR)
  1662. {
  1663. m_impl->SetReusable();
  1664. }
  1665. if (GetFlags() & wxSOCKET_BROADCAST)
  1666. {
  1667. m_impl->SetBroadcast();
  1668. }
  1669. if (GetFlags() & wxSOCKET_NOBIND)
  1670. {
  1671. m_impl->DontDoBind();
  1672. }
  1673. if ( m_impl->CreateUDP() != wxSOCKET_NOERROR )
  1674. {
  1675. wxDELETE(m_impl);
  1676. return;
  1677. }
  1678. // Initialize all stuff
  1679. m_connected = false;
  1680. m_establishing = false;
  1681. }
  1682. wxDatagramSocket& wxDatagramSocket::RecvFrom( wxSockAddress& addr,
  1683. void* buf,
  1684. wxUint32 nBytes )
  1685. {
  1686. Read(buf, nBytes);
  1687. GetPeer(addr);
  1688. return (*this);
  1689. }
  1690. wxDatagramSocket& wxDatagramSocket::SendTo( const wxSockAddress& addr,
  1691. const void* buf,
  1692. wxUint32 nBytes )
  1693. {
  1694. wxASSERT_MSG( m_impl, wxT("Socket not initialised") );
  1695. m_impl->SetPeer(addr.GetAddress());
  1696. Write(buf, nBytes);
  1697. return (*this);
  1698. }
  1699. // ==========================================================================
  1700. // wxSocketModule
  1701. // ==========================================================================
  1702. class wxSocketModule : public wxModule
  1703. {
  1704. public:
  1705. virtual bool OnInit() wxOVERRIDE
  1706. {
  1707. // wxSocketBase will call Initialize() itself only if sockets are
  1708. // really used, don't do it from here
  1709. return true;
  1710. }
  1711. virtual void OnExit() wxOVERRIDE
  1712. {
  1713. if ( wxSocketBase::IsInitialized() )
  1714. wxSocketBase::Shutdown();
  1715. }
  1716. private:
  1717. DECLARE_DYNAMIC_CLASS(wxSocketModule)
  1718. };
  1719. IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
  1720. #if defined(wxUSE_SELECT_DISPATCHER) && wxUSE_SELECT_DISPATCHER
  1721. // NOTE: we need to force linking against socketiohandler.cpp otherwise in
  1722. // static builds of wxWidgets the ManagerSetter::ManagerSetter ctor
  1723. // contained there wouldn't be ever called
  1724. wxFORCE_LINK_MODULE( socketiohandler )
  1725. #endif
  1726. // same for ManagerSetter in the MSW file
  1727. #ifdef __WINDOWS__
  1728. wxFORCE_LINK_MODULE( mswsocket )
  1729. #endif
  1730. // and for OSXManagerSetter in the OS X one
  1731. #ifdef __WXOSX__
  1732. wxFORCE_LINK_MODULE( osxsocket )
  1733. #endif
  1734. #endif // wxUSE_SOCKETS