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