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