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