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