]> git.saurik.com Git - wxWidgets.git/blob - src/common/socket.cpp
fixed bug with Broadcast() not waking up all threads (Pieter van der Meulen)
[wxWidgets.git] / src / common / socket.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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) 2000-1999, Guillermo Rodriguez Garcia
8 // RCS_ID: $Id$
9 // License: see wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ==========================================================================
13 // Declarations
14 // ==========================================================================
15
16 #ifdef __GNUG__
17 #pragma implementation "socket.h"
18 #endif
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_SOCKETS
28
29 #include "wx/app.h"
30 #include "wx/defs.h"
31 #include "wx/object.h"
32 #include "wx/string.h"
33 #include "wx/timer.h"
34 #include "wx/utils.h"
35 #include "wx/module.h"
36 #include "wx/log.h"
37 #include "wx/intl.h"
38 #include "wx/event.h"
39
40 #if wxUSE_GUI
41 #include "wx/gdicmn.h" // for wxPendingDelete
42 #endif // wxUSE_GUI
43
44 #include "wx/sckaddr.h"
45 #include "wx/socket.h"
46
47 // --------------------------------------------------------------------------
48 // macros and constants
49 // --------------------------------------------------------------------------
50
51 // discard buffer
52 #define MAX_DISCARD_SIZE (10 * 1024)
53
54 // what to do within waits
55 #if wxUSE_GUI
56 #define PROCESS_EVENTS() wxYield()
57 #else
58 #define PROCESS_EVENTS()
59 #endif
60
61 // --------------------------------------------------------------------------
62 // wxWin macros
63 // --------------------------------------------------------------------------
64
65 IMPLEMENT_CLASS(wxSocketBase, wxObject)
66 IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
67 IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
68 IMPLEMENT_CLASS(wxDatagramSocket, wxSocketBase)
69 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
70
71 // --------------------------------------------------------------------------
72 // private classes
73 // --------------------------------------------------------------------------
74
75 class wxSocketState : public wxObject
76 {
77 public:
78 wxSocketFlags m_flags;
79 wxSocketEventFlags m_eventmask;
80 bool m_notify;
81 void *m_clientData;
82 #if WXWIN_COMPATIBILITY
83 wxSocketBase::wxSockCbk m_cbk;
84 char *m_cdata;
85 #endif // WXWIN_COMPATIBILITY
86
87 public:
88 wxSocketState() : wxObject() {}
89 };
90
91 // ==========================================================================
92 // wxSocketBase
93 // ==========================================================================
94
95 // --------------------------------------------------------------------------
96 // Ctor and dtor
97 // --------------------------------------------------------------------------
98
99 void wxSocketBase::Init()
100 {
101 m_socket = NULL;
102 m_type = wxSOCKET_UNINIT;
103
104 // state
105 m_flags = 0;
106 m_connected =
107 m_establishing =
108 m_reading =
109 m_writing =
110 m_error = FALSE;
111 m_lcount = 0;
112 m_timeout = 600;
113 m_beingDeleted = FALSE;
114
115 // pushback buffer
116 m_unread = NULL;
117 m_unrd_size = 0;
118 m_unrd_cur = 0;
119
120 // events
121 m_id = -1;
122 m_handler = NULL;
123 m_clientData = NULL;
124 m_notify = FALSE;
125 m_eventmask = 0;
126 #if WXWIN_COMPATIBILITY
127 m_cbk = NULL;
128 m_cdata = NULL;
129 #endif // WXWIN_COMPATIBILITY
130 }
131
132 wxSocketBase::wxSocketBase()
133 {
134 Init();
135 }
136
137 wxSocketBase::wxSocketBase(wxSocketFlags flags, wxSocketType type)
138 {
139 Init();
140
141 m_flags = flags;
142 m_type = type;
143 }
144
145 wxSocketBase::~wxSocketBase()
146 {
147 // Just in case the app called Destroy() *and* then deleted
148 // the socket immediately: don't leave dangling pointers.
149 #if wxUSE_GUI
150 wxPendingDelete.DeleteObject(this);
151 #endif
152
153 // Shutdown and close the socket
154 if (!m_beingDeleted)
155 Close();
156
157 // Destroy the GSocket object
158 if (m_socket)
159 GSocket_destroy(m_socket);
160
161 // Free the pushback buffer
162 if (m_unread)
163 free(m_unread);
164 }
165
166 bool wxSocketBase::Destroy()
167 {
168 // Delayed destruction: the socket will be deleted during the next
169 // idle loop iteration. This ensures that all pending events have
170 // been processed.
171 m_beingDeleted = TRUE;
172
173 // Shutdown and close the socket
174 Close();
175
176 // Supress events from now on
177 Notify(FALSE);
178
179 #if wxUSE_GUI
180 if ( !wxPendingDelete.Member(this) )
181 wxPendingDelete.Append(this);
182 #else
183 delete this;
184 #endif
185
186 return TRUE;
187 }
188
189 // --------------------------------------------------------------------------
190 // Basic IO calls
191 // --------------------------------------------------------------------------
192
193 // The following IO operations update m_error and m_lcount:
194 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
195 //
196 // TODO: Should Connect, Accept and AcceptWith update m_error?
197
198 bool wxSocketBase::Close()
199 {
200 // Interrupt pending waits
201 InterruptWait();
202
203 if (m_socket)
204 {
205 // Disable callbacks
206 GSocket_UnsetCallback(m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
207 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG);
208
209 // Shutdown the connection
210 GSocket_Shutdown(m_socket);
211 }
212
213 m_connected = FALSE;
214 m_establishing = FALSE;
215 return TRUE;
216 }
217
218 wxSocketBase& wxSocketBase::Read(void* buffer, wxUint32 nbytes)
219 {
220 // Mask read events
221 m_reading = TRUE;
222
223 m_lcount = _Read(buffer, nbytes);
224
225 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
226 if (m_flags & wxSOCKET_WAITALL)
227 m_error = (m_lcount != nbytes);
228 else
229 m_error = (m_lcount == 0);
230
231 // Allow read events from now on
232 m_reading = FALSE;
233
234 return *this;
235 }
236
237 wxUint32 wxSocketBase::_Read(void* buffer, wxUint32 nbytes)
238 {
239 int total;
240 int ret = 1;
241
242 // Try the pushback buffer first
243 total = GetPushback(buffer, nbytes, FALSE);
244 nbytes -= total;
245 buffer = (char *)buffer + total;
246
247 // Return now in one of the following cases:
248 // - the socket is invalid,
249 // - we got all the data,
250 // - we got *some* data and we are not using wxSOCKET_WAITALL.
251 if ( !m_socket ||
252 !nbytes ||
253 ((total != 0) && !(m_flags & wxSOCKET_WAITALL)) )
254 return total;
255
256 // Possible combinations (they are checked in this order)
257 // wxSOCKET_NOWAIT
258 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
259 // wxSOCKET_BLOCK
260 // wxSOCKET_NONE
261 //
262 if (m_flags & wxSOCKET_NOWAIT)
263 {
264 GSocket_SetNonBlocking(m_socket, 1);
265 ret = GSocket_Read(m_socket, (char *)buffer, nbytes);
266 GSocket_SetNonBlocking(m_socket, 0);
267
268 if (ret > 0)
269 total += ret;
270 }
271 else
272 {
273 bool more = TRUE;
274
275 while (more)
276 {
277 if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForRead() )
278 break;
279
280 ret = GSocket_Read(m_socket, (char *)buffer, nbytes);
281
282 if (ret > 0)
283 {
284 total += ret;
285 nbytes -= ret;
286 buffer = (char *)buffer + ret;
287 }
288
289 // If we got here and wxSOCKET_WAITALL is not set, we can leave
290 // now. Otherwise, wait until we recv all the data or until there
291 // is an error.
292 //
293 more = (ret > 0 && nbytes > 0 && (m_flags & wxSOCKET_WAITALL));
294 }
295 }
296
297 return total;
298 }
299
300 wxSocketBase& wxSocketBase::ReadMsg(void* buffer, wxUint32 nbytes)
301 {
302 wxUint32 len, len2, sig, total;
303 bool error;
304 int old_flags;
305 struct
306 {
307 unsigned char sig[4];
308 unsigned char len[4];
309 } msg;
310
311 // Mask read events
312 m_reading = TRUE;
313
314 total = 0;
315 error = TRUE;
316 old_flags = m_flags;
317 SetFlags((m_flags & wxSOCKET_BLOCK) | wxSOCKET_WAITALL);
318
319 if (_Read(&msg, sizeof(msg)) != sizeof(msg))
320 goto exit;
321
322 sig = (wxUint32)msg.sig[0];
323 sig |= (wxUint32)(msg.sig[1] << 8);
324 sig |= (wxUint32)(msg.sig[2] << 16);
325 sig |= (wxUint32)(msg.sig[3] << 24);
326
327 if (sig != 0xfeeddead)
328 {
329 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
330 goto exit;
331 }
332
333 len = (wxUint32)msg.len[0];
334 len |= (wxUint32)(msg.len[1] << 8);
335 len |= (wxUint32)(msg.len[2] << 16);
336 len |= (wxUint32)(msg.len[3] << 24);
337
338 if (len > nbytes)
339 {
340 len2 = len - nbytes;
341 len = nbytes;
342 }
343 else
344 len2 = 0;
345
346 // Don't attemp to read if the msg was zero bytes long.
347 if (len)
348 {
349 total = _Read(buffer, len);
350
351 if (total != len)
352 goto exit;
353 }
354 if (len2)
355 {
356 char *discard_buffer = new char[MAX_DISCARD_SIZE];
357 long discard_len;
358
359 // NOTE: discarded bytes don't add to m_lcount.
360 do
361 {
362 discard_len = ((len2 > MAX_DISCARD_SIZE)? MAX_DISCARD_SIZE : len2);
363 discard_len = _Read(discard_buffer, (wxUint32)discard_len);
364 len2 -= (wxUint32)discard_len;
365 }
366 while ((discard_len > 0) && len2);
367
368 delete [] discard_buffer;
369
370 if (len2 != 0)
371 goto exit;
372 }
373 if (_Read(&msg, sizeof(msg)) != sizeof(msg))
374 goto exit;
375
376 sig = (wxUint32)msg.sig[0];
377 sig |= (wxUint32)(msg.sig[1] << 8);
378 sig |= (wxUint32)(msg.sig[2] << 16);
379 sig |= (wxUint32)(msg.sig[3] << 24);
380
381 if (sig != 0xdeadfeed)
382 {
383 wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
384 goto exit;
385 }
386
387 // everything was OK
388 error = FALSE;
389
390 exit:
391 m_error = error;
392 m_lcount = total;
393 m_reading = FALSE;
394 SetFlags(old_flags);
395
396 return *this;
397 }
398
399 wxSocketBase& wxSocketBase::Peek(void* buffer, wxUint32 nbytes)
400 {
401 // Mask read events
402 m_reading = TRUE;
403
404 m_lcount = _Read(buffer, nbytes);
405 Pushback(buffer, m_lcount);
406
407 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
408 if (m_flags & wxSOCKET_WAITALL)
409 m_error = (m_lcount != nbytes);
410 else
411 m_error = (m_lcount == 0);
412
413 // Allow read events again
414 m_reading = FALSE;
415
416 return *this;
417 }
418
419 wxSocketBase& wxSocketBase::Write(const void *buffer, wxUint32 nbytes)
420 {
421 // Mask write events
422 m_writing = TRUE;
423
424 m_lcount = _Write(buffer, nbytes);
425
426 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
427 if (m_flags & wxSOCKET_WAITALL)
428 m_error = (m_lcount != nbytes);
429 else
430 m_error = (m_lcount == 0);
431
432 // Allow write events again
433 m_writing = FALSE;
434
435 return *this;
436 }
437
438 wxUint32 wxSocketBase::_Write(const void *buffer, wxUint32 nbytes)
439 {
440 wxUint32 total = 0;
441 int ret = 1;
442
443 // If the socket is invalid or parameters are ill, return immediately
444 if (!m_socket || !buffer || !nbytes)
445 return 0;
446
447 // Possible combinations (they are checked in this order)
448 // wxSOCKET_NOWAIT
449 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
450 // wxSOCKET_BLOCK
451 // wxSOCKET_NONE
452 //
453 if (m_flags & wxSOCKET_NOWAIT)
454 {
455 GSocket_SetNonBlocking(m_socket, 1);
456 ret = GSocket_Write(m_socket, (const char *)buffer, nbytes);
457 GSocket_SetNonBlocking(m_socket, 0);
458
459 if (ret > 0)
460 total = ret;
461 }
462 else
463 {
464 bool more = TRUE;
465
466 while (more)
467 {
468 if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForWrite() )
469 break;
470
471 ret = GSocket_Write(m_socket, (const char *)buffer, nbytes);
472
473 if (ret > 0)
474 {
475 total += ret;
476 nbytes -= ret;
477 buffer = (const char *)buffer + ret;
478 }
479
480 // If we got here and wxSOCKET_WAITALL is not set, we can leave
481 // now. Otherwise, wait until we send all the data or until there
482 // is an error.
483 //
484 more = (ret > 0 && nbytes > 0 && (m_flags & wxSOCKET_WAITALL));
485 }
486 }
487
488 return total;
489 }
490
491 wxSocketBase& wxSocketBase::WriteMsg(const void *buffer, wxUint32 nbytes)
492 {
493 wxUint32 total;
494 bool error;
495 int old_flags;
496 struct
497 {
498 unsigned char sig[4];
499 unsigned char len[4];
500 } msg;
501
502 // Mask write events
503 m_writing = TRUE;
504
505 error = TRUE;
506 total = 0;
507 old_flags = m_flags;
508 SetFlags((m_flags & wxSOCKET_BLOCK) | wxSOCKET_WAITALL);
509
510 msg.sig[0] = (unsigned char) 0xad;
511 msg.sig[1] = (unsigned char) 0xde;
512 msg.sig[2] = (unsigned char) 0xed;
513 msg.sig[3] = (unsigned char) 0xfe;
514
515 msg.len[0] = (unsigned char) (nbytes & 0xff);
516 msg.len[1] = (unsigned char) ((nbytes >> 8) & 0xff);
517 msg.len[2] = (unsigned char) ((nbytes >> 16) & 0xff);
518 msg.len[3] = (unsigned char) ((nbytes >> 24) & 0xff);
519
520 if (_Write(&msg, sizeof(msg)) < sizeof(msg))
521 goto exit;
522
523 total = _Write(buffer, nbytes);
524
525 if (total < nbytes)
526 goto exit;
527
528 msg.sig[0] = (unsigned char) 0xed;
529 msg.sig[1] = (unsigned char) 0xfe;
530 msg.sig[2] = (unsigned char) 0xad;
531 msg.sig[3] = (unsigned char) 0xde;
532 msg.len[0] = msg.len[1] = msg.len[2] = msg.len[3] = (char) 0;
533
534 if ((_Write(&msg, sizeof(msg))) < sizeof(msg))
535 goto exit;
536
537 // everything was OK
538 error = FALSE;
539
540 exit:
541 m_error = error;
542 m_lcount = total;
543 m_writing = FALSE;
544
545 return *this;
546 }
547
548 wxSocketBase& wxSocketBase::Unread(const void *buffer, wxUint32 nbytes)
549 {
550 if (nbytes != 0)
551 Pushback(buffer, nbytes);
552
553 m_error = FALSE;
554 m_lcount = nbytes;
555
556 return *this;
557 }
558
559 wxSocketBase& wxSocketBase::Discard()
560 {
561 int old_flags;
562 char *buffer = new char[MAX_DISCARD_SIZE];
563 wxUint32 ret;
564 wxUint32 total = 0;
565
566 // Mask read events
567 m_reading = TRUE;
568
569 old_flags = m_flags;
570 SetFlags(wxSOCKET_NOWAIT);
571
572 do
573 {
574 ret = _Read(buffer, MAX_DISCARD_SIZE);
575 total += ret;
576 }
577 while (ret == MAX_DISCARD_SIZE);
578
579 delete[] buffer;
580 m_lcount = total;
581 m_error = FALSE;
582
583 // Allow read events again
584 m_reading = FALSE;
585
586 return *this;
587 }
588
589 // --------------------------------------------------------------------------
590 // Wait functions
591 // --------------------------------------------------------------------------
592
593 // All Wait functions poll the socket using GSocket_Select() to
594 // check for the specified combination of conditions, until one
595 // of these conditions become true, an error occurs, or the
596 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
597 // this won't block the GUI.
598
599 bool wxSocketBase::_Wait(long seconds,
600 long milliseconds,
601 wxSocketEventFlags flags)
602 {
603 GSocketEventFlags result;
604 long timeout;
605
606 // Set this to TRUE to interrupt ongoing waits
607 m_interrupt = FALSE;
608
609 // Check for valid socket
610 if (!m_socket)
611 return FALSE;
612
613 // Check for valid timeout value.
614 if (seconds != -1)
615 timeout = seconds * 1000 + milliseconds;
616 else
617 timeout = m_timeout * 1000;
618
619 // Wait in an active polling loop.
620 //
621 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
622 // hurt. It has to be here because the (GSocket) event might arrive
623 // a bit delayed, and it has to be in OnRequest as well because we
624 // don't know whether the Wait functions are being used.
625 //
626 // Do this at least once (important if timeout == 0, when
627 // we are just polling). Also, if just polling, do not yield.
628
629 wxStopWatch chrono;
630 bool done = FALSE;
631
632 while (!done)
633 {
634 result = GSocket_Select(m_socket, flags | GSOCK_LOST_FLAG);
635
636 // Incoming connection (server) or connection established (client)
637 if (result & GSOCK_CONNECTION_FLAG)
638 {
639 m_connected = TRUE;
640 m_establishing = FALSE;
641 return TRUE;
642 }
643
644 // Data available or output buffer ready
645 if ((result & GSOCK_INPUT_FLAG) || (result & GSOCK_OUTPUT_FLAG))
646 {
647 return TRUE;
648 }
649
650 // Connection lost
651 if (result & GSOCK_LOST_FLAG)
652 {
653 m_connected = FALSE;
654 m_establishing = FALSE;
655 return (flags & GSOCK_LOST_FLAG) != 0;
656 }
657
658 // Wait more?
659 if ((!timeout) || (chrono.Time() > timeout) || (m_interrupt))
660 done = TRUE;
661 else
662 PROCESS_EVENTS();
663 }
664
665 return FALSE;
666 }
667
668 bool wxSocketBase::Wait(long seconds, long milliseconds)
669 {
670 return _Wait(seconds, milliseconds, GSOCK_INPUT_FLAG |
671 GSOCK_OUTPUT_FLAG |
672 GSOCK_CONNECTION_FLAG |
673 GSOCK_LOST_FLAG);
674 }
675
676 bool wxSocketBase::WaitForRead(long seconds, long milliseconds)
677 {
678 // Check pushback buffer before entering _Wait
679 if (m_unread)
680 return TRUE;
681
682 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
683 // _Wait becuase of the semantics of WaitForRead: a return
684 // value of TRUE means that a GSocket_Read call will return
685 // immediately, not that there is actually data to read.
686
687 return _Wait(seconds, milliseconds, GSOCK_INPUT_FLAG |
688 GSOCK_LOST_FLAG);
689 }
690
691 bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
692 {
693 return _Wait(seconds, milliseconds, GSOCK_OUTPUT_FLAG);
694 }
695
696 bool wxSocketBase::WaitForLost(long seconds, long milliseconds)
697 {
698 return _Wait(seconds, milliseconds, GSOCK_LOST_FLAG);
699 }
700
701 // --------------------------------------------------------------------------
702 // Miscellaneous
703 // --------------------------------------------------------------------------
704
705 //
706 // Get local or peer address
707 //
708
709 bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
710 {
711 GAddress *peer;
712
713 if (!m_socket)
714 return FALSE;
715
716 peer = GSocket_GetPeer(m_socket);
717 addr_man.SetAddress(peer);
718 GAddress_destroy(peer);
719
720 return TRUE;
721 }
722
723 bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
724 {
725 GAddress *local;
726
727 if (!m_socket)
728 return FALSE;
729
730 local = GSocket_GetLocal(m_socket);
731 addr_man.SetAddress(local);
732 GAddress_destroy(local);
733
734 return TRUE;
735 }
736
737 //
738 // Save and restore socket state
739 //
740
741 void wxSocketBase::SaveState()
742 {
743 wxSocketState *state;
744
745 state = new wxSocketState();
746
747 state->m_flags = m_flags;
748 state->m_notify = m_notify;
749 state->m_eventmask = m_eventmask;
750 state->m_clientData = m_clientData;
751 #if WXWIN_COMPATIBILITY
752 state->m_cbk = m_cbk;
753 state->m_cdata = m_cdata;
754 #endif // WXWIN_COMPATIBILITY
755
756 m_states.Append(state);
757 }
758
759 void wxSocketBase::RestoreState()
760 {
761 wxNode *node;
762 wxSocketState *state;
763
764 node = m_states.Last();
765 if (!node)
766 return;
767
768 state = (wxSocketState *)node->Data();
769
770 m_flags = state->m_flags;
771 m_notify = state->m_notify;
772 m_eventmask = state->m_eventmask;
773 m_clientData = state->m_clientData;
774 #if WXWIN_COMPATIBILITY
775 m_cbk = state->m_cbk;
776 m_cdata = state->m_cdata;
777 #endif // WXWIN_COMPATIBILITY
778
779 delete node;
780 delete state;
781 }
782
783 //
784 // Timeout and flags
785 //
786
787 void wxSocketBase::SetTimeout(long seconds)
788 {
789 m_timeout = seconds;
790
791 if (m_socket)
792 GSocket_SetTimeout(m_socket, m_timeout * 1000);
793 }
794
795 void wxSocketBase::SetFlags(wxSocketFlags flags)
796 {
797 m_flags = flags;
798 }
799
800
801 // --------------------------------------------------------------------------
802 // Callbacks (now obsolete - use events instead)
803 // --------------------------------------------------------------------------
804
805 #if WXWIN_COMPATIBILITY
806
807 wxSocketBase::wxSockCbk wxSocketBase::Callback(wxSockCbk cbk_)
808 {
809 wxSockCbk old_cbk = cbk_;
810
811 m_cbk = cbk_;
812 return old_cbk;
813 }
814
815 char *wxSocketBase::CallbackData(char *data)
816 {
817 char *old_data = m_cdata;
818
819 m_cdata = data;
820 return old_data;
821 }
822
823 #endif // WXWIN_COMPATIBILITY
824
825 // --------------------------------------------------------------------------
826 // Event handling
827 // --------------------------------------------------------------------------
828
829 // A note on how events are processed, which is probably the most
830 // difficult thing to get working right while keeping the same API
831 // and functionality for all platforms.
832 //
833 // When GSocket detects an event, it calls wx_socket_callback, which in
834 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
835 // object. OnRequest does some housekeeping, and if the event is to be
836 // propagated to the user, it creates a new wxSocketEvent object and
837 // posts it. The event is not processed immediately, but delayed with
838 // AddPendingEvent instead. This is necessary in order to decouple the
839 // event processing from wx_socket_callback; otherwise, subsequent IO
840 // calls made from the user event handler would fail, as gtk callbacks
841 // are not reentrant.
842 //
843 // Note that, unlike events, user callbacks (now deprecated) are _not_
844 // decoupled from wx_socket_callback and thus they suffer from a variety
845 // of problems. Avoid them where possible and use events instead.
846
847 static void LINKAGEMODE wx_socket_callback(GSocket * WXUNUSED(socket),
848 GSocketEvent notification,
849 char *cdata)
850 {
851 wxSocketBase *sckobj = (wxSocketBase *)cdata;
852
853 sckobj->OnRequest((wxSocketNotify) notification);
854 }
855
856 void wxSocketBase::OnRequest(wxSocketNotify notification)
857 {
858 // NOTE: We duplicate some of the code in _Wait, but this doesn't
859 // hurt. It has to be here because the (GSocket) event might arrive
860 // a bit delayed, and it has to be in _Wait as well because we don't
861 // know whether the Wait functions are being used.
862
863 switch(notification)
864 {
865 case wxSOCKET_CONNECTION:
866 m_establishing = FALSE;
867 m_connected = TRUE;
868 break;
869
870 // If we are in the middle of a R/W operation, do not
871 // propagate events to users. Also, filter 'late' events
872 // which are no longer valid.
873
874 case wxSOCKET_INPUT:
875 if (m_reading || !GSocket_Select(m_socket, GSOCK_INPUT_FLAG))
876 return;
877 break;
878
879 case wxSOCKET_OUTPUT:
880 if (m_writing || !GSocket_Select(m_socket, GSOCK_OUTPUT_FLAG))
881 return;
882 break;
883
884 case wxSOCKET_LOST:
885 m_connected = FALSE;
886 m_establishing = FALSE;
887 break;
888
889 default:
890 break;
891 }
892
893 // Schedule the event
894
895 wxSocketEventFlags flag = 0;
896 switch (notification)
897 {
898 case GSOCK_INPUT: flag = GSOCK_INPUT_FLAG; break;
899 case GSOCK_OUTPUT: flag = GSOCK_OUTPUT_FLAG; break;
900 case GSOCK_CONNECTION: flag = GSOCK_CONNECTION_FLAG; break;
901 case GSOCK_LOST: flag = GSOCK_LOST_FLAG; break;
902 default:
903 wxLogWarning(_("wxSocket: unknown event!."));
904 return;
905 }
906
907 if (((m_eventmask & flag) == flag) && m_notify)
908 {
909 if (m_handler)
910 {
911 wxSocketEvent event(m_id);
912 event.m_event = notification;
913 event.m_clientData = m_clientData;
914 event.SetEventObject(this);
915
916 m_handler->AddPendingEvent(event);
917 }
918
919 #if WXWIN_COMPATIBILITY
920 if (m_cbk)
921 m_cbk(*this, notification, m_cdata);
922 #endif // WXWIN_COMPATIBILITY
923 }
924 }
925
926 void wxSocketBase::Notify(bool notify)
927 {
928 m_notify = notify;
929 }
930
931 void wxSocketBase::SetNotify(wxSocketEventFlags flags)
932 {
933 m_eventmask = flags;
934 }
935
936 void wxSocketBase::SetEventHandler(wxEvtHandler& handler, int id)
937 {
938 m_handler = &handler;
939 m_id = id;
940 }
941
942 // --------------------------------------------------------------------------
943 // Pushback buffer
944 // --------------------------------------------------------------------------
945
946 void wxSocketBase::Pushback(const void *buffer, wxUint32 size)
947 {
948 if (!size) return;
949
950 if (m_unread == NULL)
951 m_unread = malloc(size);
952 else
953 {
954 void *tmp;
955
956 tmp = malloc(m_unrd_size + size);
957 memcpy((char *)tmp + size, m_unread, m_unrd_size);
958 free(m_unread);
959
960 m_unread = tmp;
961 }
962
963 m_unrd_size += size;
964
965 memcpy(m_unread, buffer, size);
966 }
967
968 wxUint32 wxSocketBase::GetPushback(void *buffer, wxUint32 size, bool peek)
969 {
970 if (!m_unrd_size)
971 return 0;
972
973 if (size > (m_unrd_size-m_unrd_cur))
974 size = m_unrd_size-m_unrd_cur;
975
976 memcpy(buffer, (char *)m_unread + m_unrd_cur, size);
977
978 if (!peek)
979 {
980 m_unrd_cur += size;
981 if (m_unrd_size == m_unrd_cur)
982 {
983 free(m_unread);
984 m_unread = NULL;
985 m_unrd_size = 0;
986 m_unrd_cur = 0;
987 }
988 }
989
990 return size;
991 }
992
993
994 // ==========================================================================
995 // wxSocketServer
996 // ==========================================================================
997
998 // --------------------------------------------------------------------------
999 // Ctor
1000 // --------------------------------------------------------------------------
1001
1002 wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
1003 wxSocketFlags flags)
1004 : wxSocketBase(flags, wxSOCKET_SERVER)
1005 {
1006 // Create the socket
1007 m_socket = GSocket_new();
1008
1009 if (!m_socket)
1010 return;
1011
1012 // Setup the socket as server
1013 GSocket_SetLocal(m_socket, addr_man.GetAddress());
1014 if (GSocket_SetServer(m_socket) != GSOCK_NOERROR)
1015 {
1016 GSocket_destroy(m_socket);
1017 m_socket = NULL;
1018 return;
1019 }
1020
1021 GSocket_SetTimeout(m_socket, m_timeout * 1000);
1022 GSocket_SetCallback(m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1023 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1024 wx_socket_callback, (char *)this);
1025
1026 }
1027
1028 // --------------------------------------------------------------------------
1029 // Accept
1030 // --------------------------------------------------------------------------
1031
1032 bool wxSocketServer::AcceptWith(wxSocketBase& sock, bool wait)
1033 {
1034 GSocket *child_socket;
1035
1036 if (!m_socket)
1037 return FALSE;
1038
1039 // If wait == FALSE, then the call should be nonblocking.
1040 // When we are finished, we put the socket to blocking mode
1041 // again.
1042
1043 if (!wait)
1044 GSocket_SetNonBlocking(m_socket, 1);
1045
1046 child_socket = GSocket_WaitConnection(m_socket);
1047
1048 if (!wait)
1049 GSocket_SetNonBlocking(m_socket, 0);
1050
1051 if (!child_socket)
1052 return FALSE;
1053
1054 sock.m_type = wxSOCKET_BASE;
1055 sock.m_socket = child_socket;
1056 sock.m_connected = TRUE;
1057
1058 GSocket_SetTimeout(sock.m_socket, sock.m_timeout * 1000);
1059 GSocket_SetCallback(sock.m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1060 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1061 wx_socket_callback, (char *)&sock);
1062
1063 return TRUE;
1064 }
1065
1066 wxSocketBase *wxSocketServer::Accept(bool wait)
1067 {
1068 wxSocketBase* sock = new wxSocketBase();
1069
1070 sock->SetFlags(m_flags);
1071
1072 if (!AcceptWith(*sock, wait))
1073 return NULL;
1074
1075 return sock;
1076 }
1077
1078 bool wxSocketServer::WaitForAccept(long seconds, long milliseconds)
1079 {
1080 return _Wait(seconds, milliseconds, GSOCK_CONNECTION_FLAG);
1081 }
1082
1083 // ==========================================================================
1084 // wxSocketClient
1085 // ==========================================================================
1086
1087 // --------------------------------------------------------------------------
1088 // Ctor and dtor
1089 // --------------------------------------------------------------------------
1090
1091 wxSocketClient::wxSocketClient(wxSocketFlags flags)
1092 : wxSocketBase(flags, wxSOCKET_CLIENT)
1093 {
1094 }
1095
1096 wxSocketClient::~wxSocketClient()
1097 {
1098 }
1099
1100 // --------------------------------------------------------------------------
1101 // Connect
1102 // --------------------------------------------------------------------------
1103
1104 bool wxSocketClient::Connect(wxSockAddress& addr_man, bool wait)
1105 {
1106 GSocketError err;
1107
1108 if (m_socket)
1109 {
1110 // Shutdown and destroy the socket
1111 Close();
1112 GSocket_destroy(m_socket);
1113 }
1114
1115 m_socket = GSocket_new();
1116 m_connected = FALSE;
1117 m_establishing = FALSE;
1118
1119 if (!m_socket)
1120 return FALSE;
1121
1122 GSocket_SetTimeout(m_socket, m_timeout * 1000);
1123 GSocket_SetCallback(m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1124 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1125 wx_socket_callback, (char *)this);
1126
1127 // If wait == FALSE, then the call should be nonblocking.
1128 // When we are finished, we put the socket to blocking mode
1129 // again.
1130
1131 if (!wait)
1132 GSocket_SetNonBlocking(m_socket, 1);
1133
1134 GSocket_SetPeer(m_socket, addr_man.GetAddress());
1135 err = GSocket_Connect(m_socket, GSOCK_STREAMED);
1136
1137 if (!wait)
1138 GSocket_SetNonBlocking(m_socket, 0);
1139
1140 if (err != GSOCK_NOERROR)
1141 {
1142 if (err == GSOCK_WOULDBLOCK)
1143 m_establishing = TRUE;
1144
1145 return FALSE;
1146 }
1147
1148 m_connected = TRUE;
1149 return TRUE;
1150 }
1151
1152 bool wxSocketClient::WaitOnConnect(long seconds, long milliseconds)
1153 {
1154 if (m_connected) // Already connected
1155 return TRUE;
1156
1157 if (!m_establishing || !m_socket) // No connection in progress
1158 return FALSE;
1159
1160 return _Wait(seconds, milliseconds, GSOCK_CONNECTION_FLAG |
1161 GSOCK_LOST_FLAG);
1162 }
1163
1164 // ==========================================================================
1165 // wxDatagramSocket
1166 // ==========================================================================
1167
1168 /* NOTE: experimental stuff - might change */
1169
1170 wxDatagramSocket::wxDatagramSocket( wxSockAddress& addr,
1171 wxSocketFlags flags )
1172 : wxSocketBase( flags, wxSOCKET_DATAGRAM )
1173 {
1174 // Create the socket
1175 m_socket = GSocket_new();
1176
1177 if(!m_socket)
1178 return;
1179
1180 // Setup the socket as non connection oriented
1181 GSocket_SetLocal(m_socket, addr.GetAddress());
1182 if( GSocket_SetNonOriented(m_socket) != GSOCK_NOERROR )
1183 {
1184 GSocket_destroy(m_socket);
1185 m_socket = NULL;
1186 return;
1187 }
1188
1189 // Initialize all stuff
1190 m_connected = FALSE;
1191 m_establishing = FALSE;
1192 GSocket_SetTimeout( m_socket, m_timeout );
1193 GSocket_SetCallback( m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1194 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1195 wx_socket_callback, (char*)this );
1196
1197 }
1198
1199 wxDatagramSocket& wxDatagramSocket::RecvFrom( wxSockAddress& addr,
1200 void* buf,
1201 wxUint32 nBytes )
1202 {
1203 Read(buf, nBytes);
1204 GetPeer(addr);
1205 return (*this);
1206 }
1207
1208 wxDatagramSocket& wxDatagramSocket::SendTo( wxSockAddress& addr,
1209 const void* buf,
1210 wxUint32 nBytes )
1211 {
1212 GSocket_SetPeer(m_socket, addr.GetAddress());
1213 Write(buf, nBytes);
1214 return (*this);
1215 }
1216
1217 // ==========================================================================
1218 // wxSocketEvent
1219 // ==========================================================================
1220
1221 wxSocketEvent::wxSocketEvent(int id) : wxEvent(id)
1222 {
1223 SetEventType( (wxEventType)wxEVT_SOCKET );
1224 }
1225
1226 void wxSocketEvent::CopyObject(wxObject& object_dest) const
1227 {
1228 wxSocketEvent *event = (wxSocketEvent *)&object_dest;
1229
1230 wxEvent::CopyObject(object_dest);
1231
1232 event->m_event = m_event;
1233 event->m_clientData = m_clientData;
1234 }
1235
1236 // ==========================================================================
1237 // wxSocketModule
1238 // ==========================================================================
1239
1240 class WXDLLEXPORT wxSocketModule : public wxModule
1241 {
1242 DECLARE_DYNAMIC_CLASS(wxSocketModule)
1243
1244 public:
1245 bool OnInit() { return GSocket_Init() != 0; }
1246 void OnExit() { GSocket_Cleanup(); }
1247 };
1248
1249 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
1250
1251 #endif
1252 // wxUSE_SOCKETS