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