]> git.saurik.com Git - wxWidgets.git/blob - src/mac/carbon/cfsocket.cpp
d32965130abb9b0a8398d923e50edafcff41640f
[wxWidgets.git] / src / mac / carbon / cfsocket.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/cfsocket.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 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 #if wxUSE_SOCKETS
19
20 #include "wx/app.h"
21 #include "wx/apptrait.h"
22 #include "wx/object.h"
23 #include "wx/string.h"
24 #include "wx/timer.h"
25 #include "wx/utils.h"
26 #include "wx/module.h"
27 #include "wx/log.h"
28 #include "wx/intl.h"
29 #include "wx/event.h"
30
31 #include "wx/sckaddr.h"
32 #include "wx/socket.h"
33 #include "wx/mac/carbon/private.h"
34
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <netdb.h>
39
40 #define HAVE_INET_ATON
41
42 // DLL options compatibility check:
43 #include "wx/build.h"
44
45 WX_CHECK_BUILD_OPTIONS("wxNet")
46
47
48 // discard buffer
49 #define MAX_DISCARD_SIZE (10 * 1024)
50
51 #ifndef INVALID_SOCKET
52 #define INVALID_SOCKET -1
53 #endif
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 wxWidgets) 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 IMPLEMENT_CLASS(wxSocketBase, wxObject)
78 IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
79 IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
80 IMPLEMENT_CLASS(wxDatagramSocket, wxSocketBase)
81 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
82
83 // --------------------------------------------------------------------------
84 // private classes
85 // --------------------------------------------------------------------------
86
87 class wxSocketState : public wxObject
88 {
89 public:
90 wxSocketFlags m_flags;
91 wxSocketEventFlags m_eventmask;
92 bool m_notify;
93 void *m_clientData;
94
95 public:
96 wxSocketState() : wxObject() {}
97
98 DECLARE_NO_COPY_CLASS(wxSocketState)
99 };
100
101 struct _GSocket
102 {
103 CFSocketNativeHandle m_fd;
104 GAddress *m_local;
105 GAddress *m_peer;
106 GSocketError m_error;
107
108 int m_non_blocking;
109 int m_server;
110 int m_stream;
111 int m_oriented;
112 int m_establishing;
113 unsigned long m_timeout;
114
115 // Callbacks
116 GSocketEventFlags m_detected;
117 GSocketCallback m_cbacks[GSOCK_MAX_EVENT];
118 char *m_data[GSOCK_MAX_EVENT];
119
120 CFSocketRef m_cfSocket;
121 CFRunLoopSourceRef m_runLoopSource;
122 CFReadStreamRef m_readStream ;
123 CFWriteStreamRef m_writeStream ;
124 };
125
126 struct _GAddress
127 {
128 struct sockaddr *m_addr;
129 size_t m_len;
130
131 GAddressType m_family;
132 int m_realfamily;
133
134 GSocketError m_error;
135 int somethingElse ;
136 };
137
138 void wxMacCFSocketCallback(CFSocketRef s, CFSocketCallBackType callbackType,
139 CFDataRef address, const void* data, void* info) ;
140 void _GSocket_Enable(GSocket *socket, GSocketEvent event) ;
141 void _GSocket_Disable(GSocket *socket, GSocketEvent event) ;
142
143 // ==========================================================================
144 // wxSocketBase
145 // ==========================================================================
146
147 // --------------------------------------------------------------------------
148 // Initialization and shutdown
149 // --------------------------------------------------------------------------
150
151 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
152 // to m_countInit with a crit section
153 size_t wxSocketBase::m_countInit = 0;
154
155 bool wxSocketBase::IsInitialized()
156 {
157 return m_countInit > 0;
158 }
159
160 bool wxSocketBase::Initialize()
161 {
162 if ( !m_countInit++ )
163 {
164 #if 0
165 wxAppTraits *traits = wxAppConsole::GetInstance() ?
166 wxAppConsole::GetInstance()->GetTraits() : NULL;
167 GSocketGUIFunctionsTable *functions =
168 traits ? traits->GetSocketGUIFunctionsTable() : NULL;
169 GSocket_SetGUIFunctions(functions);
170
171 if ( !GSocket_Init() )
172 {
173 m_countInit--;
174
175 return false;
176 }
177 #endif
178 }
179
180 return true;
181 }
182
183 void wxSocketBase::Shutdown()
184 {
185 // we should be initialized
186 wxASSERT_MSG( m_countInit, wxT("extra call to Shutdown()") );
187 if ( !--m_countInit )
188 {
189 #if 0
190 GSocket_Cleanup();
191 #endif
192 }
193 }
194
195 // --------------------------------------------------------------------------
196 // Ctor and dtor
197 // --------------------------------------------------------------------------
198
199 void wxSocketBase::Init()
200 {
201 m_socket = NULL;
202 m_type = wxSOCKET_UNINIT;
203
204 // state
205 m_flags = 0;
206 m_connected =
207 m_establishing =
208 m_reading =
209 m_writing =
210 m_error = false;
211 m_lcount = 0;
212 m_timeout = 600;
213 m_beingDeleted = false;
214
215 // pushback buffer
216 m_unread = NULL;
217 m_unrd_size = 0;
218 m_unrd_cur = 0;
219
220 // events
221 m_id = -1;
222 m_handler = NULL;
223 m_clientData = NULL;
224 m_notify = false;
225 m_eventmask = 0;
226
227 if ( !IsInitialized() )
228 {
229 // this Initialize() will be undone by wxSocketModule::OnExit(), all the
230 // other calls to it should be matched by a call to Shutdown()
231 Initialize();
232 }
233 }
234
235 wxSocketBase::wxSocketBase()
236 {
237 Init();
238 }
239
240 wxSocketBase::wxSocketBase( wxSocketFlags flags, wxSocketType type)
241 {
242 Init();
243
244 m_flags = flags;
245 m_type = type;
246 }
247
248 wxSocketBase::~wxSocketBase()
249 {
250 // Just in case the app called Destroy() *and* then deleted
251 // the socket immediately: don't leave dangling pointers.
252 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
253 if ( traits )
254 traits->RemoveFromPendingDelete(this);
255
256 // Shutdown and close the socket
257 if (!m_beingDeleted)
258 Close();
259
260 // Destroy the GSocket object
261 if (m_socket)
262 {
263 GSocket_destroy(m_socket);
264 }
265
266 // Free the pushback buffer
267 if (m_unread)
268 free(m_unread);
269 }
270
271 bool wxSocketBase::Destroy()
272 {
273 // Delayed destruction: the socket will be deleted during the next
274 // idle loop iteration. This ensures that all pending events have
275 // been processed.
276 m_beingDeleted = true;
277
278 // Shutdown and close the socket
279 Close();
280
281 // Supress events from now on
282 Notify(false);
283
284 // schedule this object for deletion
285 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
286 if ( traits )
287 {
288 // let the traits object decide what to do with us
289 traits->ScheduleForDestroy(this);
290 }
291 else // no app or no traits
292 {
293 // in wxBase we might have no app object at all, don't leak memory
294 delete this;
295 }
296
297 return true;
298 }
299
300 // --------------------------------------------------------------------------
301 // Basic IO calls
302 // --------------------------------------------------------------------------
303
304 // The following IO operations update m_error and m_lcount:
305 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
306 //
307 // TODO: Should Connect, Accept and AcceptWith update m_error?
308
309 bool wxSocketBase::Close()
310 {
311 // Interrupt pending waits
312 InterruptWait();
313
314 if (m_socket)
315 GSocket_Shutdown(m_socket);
316
317 m_connected = false;
318 m_establishing = false;
319
320 return true;
321 }
322
323 wxSocketBase& wxSocketBase::Read(void* buffer, wxUint32 nbytes)
324 {
325 // Mask read events
326 m_reading = true;
327
328 m_lcount = _Read(buffer, nbytes);
329
330 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
331 if (m_flags & wxSOCKET_WAITALL)
332 m_error = (m_lcount != nbytes);
333 else
334 m_error = (m_lcount == 0);
335
336 // Allow read events from now on
337 m_reading = false;
338
339 return *this;
340 }
341
342 wxUint32 wxSocketBase::_Read(void* buffer, wxUint32 nbytes)
343 {
344 int total = 0;
345
346 // Try the pushback buffer first
347 total = GetPushback(buffer, nbytes, false);
348 nbytes -= total;
349 buffer = (char *)buffer + total;
350
351 // Return now in one of the following cases:
352 // - the socket is invalid,
353 // - we got all the data,
354 // - we got *some* data and we are not using wxSOCKET_WAITALL.
355 if ( !m_socket ||
356 !nbytes ||
357 ((total != 0) && !(m_flags & wxSOCKET_WAITALL)) )
358 return total;
359
360 // Possible combinations (they are checked in this order)
361 // wxSOCKET_NOWAIT
362 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
363 // wxSOCKET_BLOCK
364 // wxSOCKET_NONE
365 //
366
367 int ret;
368 if (m_flags & wxSOCKET_NOWAIT)
369 {
370 GSocket_SetNonBlocking(m_socket, 1);
371 ret = GSocket_Read(m_socket, (char *)buffer, nbytes);
372 GSocket_SetNonBlocking(m_socket, 0);
373
374 if (ret > 0)
375 total += ret;
376 }
377 else
378 {
379 bool more = true;
380
381 while (more)
382 {
383 if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForRead() )
384 break;
385
386 ret = GSocket_Read(m_socket, (char *)buffer, nbytes);
387
388 if (ret > 0)
389 {
390 total += ret;
391 nbytes -= ret;
392 buffer = (char *)buffer + ret;
393 }
394
395 // If we got here and wxSOCKET_WAITALL is not set, we can leave
396 // now. Otherwise, wait until we recv all the data or until there
397 // is an error.
398 //
399 more = (ret > 0 && nbytes > 0 && (m_flags & wxSOCKET_WAITALL));
400 }
401 }
402
403 return total;
404 }
405
406 wxSocketBase& wxSocketBase::ReadMsg(void* buffer, wxUint32 nbytes)
407 {
408 wxUint32 len, len2, sig, total;
409 bool error;
410 int old_flags;
411 struct
412 {
413 unsigned char sig[4];
414 unsigned char len[4];
415 }
416 msg;
417
418 // Mask read events
419 m_reading = true;
420
421 total = 0;
422 error = true;
423 old_flags = m_flags;
424 SetFlags((m_flags & wxSOCKET_BLOCK) | wxSOCKET_WAITALL);
425
426 if (_Read(&msg, sizeof(msg)) != sizeof(msg))
427 goto exit;
428
429 sig = (wxUint32)msg.sig[0];
430 sig |= (wxUint32)(msg.sig[1] << 8);
431 sig |= (wxUint32)(msg.sig[2] << 16);
432 sig |= (wxUint32)(msg.sig[3] << 24);
433
434 if (sig != 0xfeeddead)
435 {
436 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
437 goto exit;
438 }
439
440 len = (wxUint32)msg.len[0];
441 len |= (wxUint32)(msg.len[1] << 8);
442 len |= (wxUint32)(msg.len[2] << 16);
443 len |= (wxUint32)(msg.len[3] << 24);
444
445 if (len > nbytes)
446 {
447 len2 = len - nbytes;
448 len = nbytes;
449 }
450 else
451 len2 = 0;
452
453 // Don't attemp to read if the msg was zero bytes long.
454 if (len)
455 {
456 total = _Read(buffer, len);
457
458 if (total != len)
459 goto exit;
460 }
461 if (len2)
462 {
463 char *discard_buffer = new char[MAX_DISCARD_SIZE];
464 long discard_len;
465
466 // NOTE: discarded bytes don't add to m_lcount.
467 do
468 {
469 discard_len = ((len2 > MAX_DISCARD_SIZE)? MAX_DISCARD_SIZE : len2);
470 discard_len = _Read(discard_buffer, (wxUint32)discard_len);
471 len2 -= (wxUint32)discard_len;
472 }
473 while ((discard_len > 0) && len2);
474
475 delete [] discard_buffer;
476
477 if (len2 != 0)
478 goto exit;
479 }
480 if (_Read(&msg, sizeof(msg)) != sizeof(msg))
481 goto exit;
482
483 sig = (wxUint32)msg.sig[0];
484 sig |= (wxUint32)(msg.sig[1] << 8);
485 sig |= (wxUint32)(msg.sig[2] << 16);
486 sig |= (wxUint32)(msg.sig[3] << 24);
487
488 if (sig != 0xdeadfeed)
489 {
490 wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
491 goto exit;
492 }
493
494 // everything was OK
495 error = false;
496
497 exit:
498 m_error = error;
499 m_lcount = total;
500 m_reading = false;
501 SetFlags(old_flags);
502
503 return *this;
504 }
505
506 wxSocketBase& wxSocketBase::Peek(void* buffer, wxUint32 nbytes)
507 {
508 // Mask read events
509 m_reading = true;
510
511 m_lcount = _Read(buffer, nbytes);
512 Pushback(buffer, m_lcount);
513
514 // If in wxSOCKET_WAITALL mode, all bytes should have been read.
515 if (m_flags & wxSOCKET_WAITALL)
516 m_error = (m_lcount != nbytes);
517 else
518 m_error = (m_lcount == 0);
519
520 // Allow read events again
521 m_reading = false;
522
523 return *this;
524 }
525
526 wxSocketBase& wxSocketBase::Write(const void *buffer, wxUint32 nbytes)
527 {
528 // Mask write events
529 m_writing = true;
530
531 m_lcount = _Write(buffer, nbytes);
532
533 // If in wxSOCKET_WAITALL mode, all bytes should have been written.
534 if (m_flags & wxSOCKET_WAITALL)
535 m_error = (m_lcount != nbytes);
536 else
537 m_error = (m_lcount == 0);
538
539 // Allow write events again
540 m_writing = false;
541
542 return *this;
543 }
544
545 wxUint32 wxSocketBase::_Write(const void *buffer, wxUint32 nbytes)
546 {
547 wxUint32 total = 0;
548
549 // If the socket is invalid or parameters are ill, return immediately
550 if (!m_socket || !buffer || !nbytes)
551 return 0;
552
553 // Possible combinations (they are checked in this order)
554 // wxSOCKET_NOWAIT
555 // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
556 // wxSOCKET_BLOCK
557 // wxSOCKET_NONE
558 //
559 int ret;
560 if (m_flags & wxSOCKET_NOWAIT)
561 {
562 GSocket_SetNonBlocking(m_socket, 1);
563 ret = GSocket_Write(m_socket, (const char *)buffer, nbytes);
564 GSocket_SetNonBlocking(m_socket, 0);
565
566 if (ret > 0)
567 total = ret;
568 }
569 else
570 {
571 bool more = true;
572
573 while (more)
574 {
575 if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForWrite() )
576 break;
577
578 ret = GSocket_Write(m_socket, (const char *)buffer, nbytes);
579
580 if (ret > 0)
581 {
582 total += ret;
583 nbytes -= ret;
584 buffer = (const char *)buffer + ret;
585 }
586
587 // If we got here and wxSOCKET_WAITALL is not set, we can leave
588 // now. Otherwise, wait until we send all the data or until there
589 // is an error.
590 //
591 more = (ret > 0 && nbytes > 0 && (m_flags & wxSOCKET_WAITALL));
592 }
593 }
594
595 return total;
596 }
597
598 wxSocketBase& wxSocketBase::WriteMsg(const void *buffer, wxUint32 nbytes)
599 {
600 wxUint32 total;
601 bool error;
602 struct
603 {
604 unsigned char sig[4];
605 unsigned char len[4];
606 }
607 msg;
608
609 // Mask write events
610 m_writing = true;
611
612 error = true;
613 total = 0;
614 SetFlags((m_flags & wxSOCKET_BLOCK) | wxSOCKET_WAITALL);
615
616 msg.sig[0] = (unsigned char) 0xad;
617 msg.sig[1] = (unsigned char) 0xde;
618 msg.sig[2] = (unsigned char) 0xed;
619 msg.sig[3] = (unsigned char) 0xfe;
620
621 msg.len[0] = (unsigned char) (nbytes & 0xff);
622 msg.len[1] = (unsigned char) ((nbytes >> 8) & 0xff);
623 msg.len[2] = (unsigned char) ((nbytes >> 16) & 0xff);
624 msg.len[3] = (unsigned char) ((nbytes >> 24) & 0xff);
625
626 if (_Write(&msg, sizeof(msg)) < sizeof(msg))
627 goto exit;
628
629 total = _Write(buffer, nbytes);
630
631 if (total < nbytes)
632 goto exit;
633
634 msg.sig[0] = (unsigned char) 0xed;
635 msg.sig[1] = (unsigned char) 0xfe;
636 msg.sig[2] = (unsigned char) 0xad;
637 msg.sig[3] = (unsigned char) 0xde;
638 msg.len[0] = msg.len[1] = msg.len[2] = msg.len[3] = (char) 0;
639
640 if ((_Write(&msg, sizeof(msg))) < sizeof(msg))
641 goto exit;
642
643 // everything was OK
644 error = false;
645
646 exit:
647 m_error = error;
648 m_lcount = total;
649 m_writing = false;
650
651 return *this;
652 }
653
654 wxSocketBase& wxSocketBase::Unread(const void *buffer, wxUint32 nbytes)
655 {
656 if (nbytes != 0)
657 Pushback(buffer, nbytes);
658
659 m_error = false;
660 m_lcount = nbytes;
661
662 return *this;
663 }
664
665 wxSocketBase& wxSocketBase::Discard()
666 {
667 char *buffer = new char[MAX_DISCARD_SIZE];
668 wxUint32 ret;
669 wxUint32 total = 0;
670
671 // Mask read events
672 m_reading = true;
673
674 SetFlags(wxSOCKET_NOWAIT);
675
676 do
677 {
678 ret = _Read(buffer, MAX_DISCARD_SIZE);
679 total += ret;
680 }
681 while (ret == MAX_DISCARD_SIZE);
682
683 delete[] buffer;
684 m_lcount = total;
685 m_error = false;
686
687 // Allow read events again
688 m_reading = false;
689
690 return *this;
691 }
692
693 // --------------------------------------------------------------------------
694 // Wait functions
695 // --------------------------------------------------------------------------
696
697 // All Wait functions poll the socket using GSocket_Select() to
698 // check for the specified combination of conditions, until one
699 // of these conditions become true, an error occurs, or the
700 // timeout elapses. The polling loop calls PROCESS_EVENTS(), so
701 // this won't block the GUI.
702
703 bool wxSocketBase::_Wait(long seconds,
704 long milliseconds,
705 wxSocketEventFlags flags)
706 {
707 GSocketEventFlags result;
708 long timeout;
709
710 // Set this to true to interrupt ongoing waits
711 m_interrupt = false;
712
713 // Check for valid socket
714 if (!m_socket)
715 return false;
716
717 // Check for valid timeout value.
718 if (seconds != -1)
719 timeout = seconds * 1000 + milliseconds;
720 else
721 timeout = m_timeout * 1000;
722
723 #if !defined(wxUSE_GUI) || !wxUSE_GUI
724 GSocket_SetTimeout(m_socket, timeout);
725 #endif
726
727 // Wait in an active polling loop.
728 //
729 // NOTE: We duplicate some of the code in OnRequest, but this doesn't
730 // hurt. It has to be here because the (GSocket) event might arrive
731 // a bit delayed, and it has to be in OnRequest as well because we
732 // don't know whether the Wait functions are being used.
733 //
734 // Do this at least once (important if timeout == 0, when
735 // we are just polling). Also, if just polling, do not yield.
736
737 wxStopWatch chrono;
738 bool done = false;
739
740 while (!done)
741 {
742 result = GSocket_Select(m_socket, flags | GSOCK_LOST_FLAG);
743
744 // Incoming connection (server) or connection established (client)
745 if (result & GSOCK_CONNECTION_FLAG)
746 {
747 m_connected = true;
748 m_establishing = false;
749
750 return true;
751 }
752
753 // Data available or output buffer ready
754 if ((result & GSOCK_INPUT_FLAG) || (result & GSOCK_OUTPUT_FLAG))
755 {
756 return true;
757 }
758
759 // Connection lost
760 if (result & GSOCK_LOST_FLAG)
761 {
762 m_connected = false;
763 m_establishing = false;
764
765 return (flags & GSOCK_LOST_FLAG) != 0;
766 }
767
768 // Wait more?
769 if ((!timeout) || (chrono.Time() > timeout) || (m_interrupt))
770 done = true;
771 else
772 PROCESS_EVENTS();
773 }
774
775 return false;
776 }
777
778 bool wxSocketBase::Wait(long seconds, long milliseconds)
779 {
780 return _Wait(seconds, milliseconds, GSOCK_INPUT_FLAG |
781 GSOCK_OUTPUT_FLAG |
782 GSOCK_CONNECTION_FLAG |
783 GSOCK_LOST_FLAG);
784 }
785
786 bool wxSocketBase::WaitForRead(long seconds, long milliseconds)
787 {
788 // Check pushback buffer before entering _Wait
789 if (m_unread)
790 return true;
791
792 // Note that GSOCK_INPUT_LOST has to be explicitly passed to
793 // _Wait becuase of the semantics of WaitForRead: a return
794 // value of true means that a GSocket_Read call will return
795 // immediately, not that there is actually data to read.
796
797 return _Wait(seconds, milliseconds, GSOCK_INPUT_FLAG | GSOCK_LOST_FLAG);
798 }
799
800 bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
801 {
802 return _Wait(seconds, milliseconds, GSOCK_OUTPUT_FLAG);
803 }
804
805 bool wxSocketBase::WaitForLost(long seconds, long milliseconds)
806 {
807 return _Wait(seconds, milliseconds, GSOCK_LOST_FLAG);
808 }
809
810 // --------------------------------------------------------------------------
811 // Miscellaneous
812 // --------------------------------------------------------------------------
813
814 //
815 // Get local or peer address
816 //
817
818 bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
819 {
820 GAddress *peer;
821
822 if (!m_socket)
823 return false;
824
825 peer = GSocket_GetPeer(m_socket);
826
827 // copying a null address would just trigger an assert anyway
828
829 if (!peer)
830 return false;
831
832 addr_man.SetAddress(peer);
833 GAddress_destroy(peer);
834
835 return true;
836 }
837
838 bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
839 {
840 #if 0
841 GAddress *local;
842
843 if (!m_socket)
844 return false;
845
846 local = GSocket_GetLocal(m_socket);
847 addr_man.SetAddress(local);
848 GAddress_destroy(local);
849 #endif
850
851 return true;
852 }
853
854 //
855 // Save and restore socket state
856 //
857
858 void wxSocketBase::SaveState()
859 {
860 wxSocketState *state;
861
862 state = new wxSocketState();
863
864 state->m_flags = m_flags;
865 state->m_notify = m_notify;
866 state->m_eventmask = m_eventmask;
867 state->m_clientData = m_clientData;
868
869 m_states.Append(state);
870 }
871
872 void wxSocketBase::RestoreState()
873 {
874 wxList::compatibility_iterator node;
875 wxSocketState *state;
876
877 node = m_states.GetLast();
878 if (!node)
879 return;
880
881 state = (wxSocketState *)node->GetData();
882
883 m_flags = state->m_flags;
884 m_notify = state->m_notify;
885 m_eventmask = state->m_eventmask;
886 m_clientData = state->m_clientData;
887
888 m_states.Erase(node);
889 delete state;
890 }
891
892 //
893 // Timeout and flags
894 //
895
896 void wxSocketBase::SetTimeout(long seconds)
897 {
898 m_timeout = seconds;
899
900 #if 0
901 if (m_socket)
902 GSocket_SetTimeout(m_socket, m_timeout * 1000);
903 #endif
904 }
905
906 void wxSocketBase::SetFlags(wxSocketFlags flags)
907 {
908 m_flags = flags;
909 }
910
911
912 // --------------------------------------------------------------------------
913 // Event handling
914 // --------------------------------------------------------------------------
915
916 // A note on how events are processed, which is probably the most
917 // difficult thing to get working right while keeping the same API
918 // and functionality for all platforms.
919 //
920 // When GSocket detects an event, it calls wx_socket_callback, which in
921 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
922 // object. OnRequest does some housekeeping, and if the event is to be
923 // propagated to the user, it creates a new wxSocketEvent object and
924 // posts it. The event is not processed immediately, but delayed with
925 // AddPendingEvent instead. This is necessary in order to decouple the
926 // event processing from wx_socket_callback; otherwise, subsequent IO
927 // calls made from the user event handler would fail, as gtk callbacks
928 // are not reentrant.
929 //
930 // Note that, unlike events, user callbacks (now deprecated) are _not_
931 // decoupled from wx_socket_callback and thus they suffer from a variety
932 // of problems. Avoid them where possible and use events instead.
933
934 extern "C"
935 void LINKAGEMODE wx_socket_callback(GSocket * WXUNUSED(socket),
936 GSocketEvent notification,
937 char *cdata)
938 {
939 wxSocketBase *sckobj = (wxSocketBase *)cdata;
940
941 sckobj->OnRequest((wxSocketNotify) notification);
942 }
943
944 void wxSocketBase::OnRequest(wxSocketNotify notification)
945 {
946 // NOTE: We duplicate some of the code in _Wait, but this doesn't
947 // hurt. It has to be here because the (GSocket) event might arrive
948 // a bit delayed, and it has to be in _Wait as well because we don't
949 // know whether the Wait functions are being used.
950
951 switch (notification)
952 {
953 case wxSOCKET_CONNECTION:
954 m_establishing = false;
955 m_connected = true;
956 break;
957
958 // If we are in the middle of a R/W operation, do not
959 // propagate events to users. Also, filter 'late' events
960 // which are no longer valid.
961
962 case wxSOCKET_INPUT:
963 if (m_reading || !GSocket_Select(m_socket, GSOCK_INPUT_FLAG))
964 return;
965 break;
966
967 case wxSOCKET_OUTPUT:
968 if (m_writing || !GSocket_Select(m_socket, GSOCK_OUTPUT_FLAG))
969 return;
970 break;
971
972 case wxSOCKET_LOST:
973 m_connected = false;
974 m_establishing = false;
975 break;
976
977 default:
978 break;
979 }
980
981 // Schedule the event
982
983 wxSocketEventFlags flag = 0;
984 wxUnusedVar(flag);
985 switch (notification)
986 {
987 case GSOCK_INPUT:
988 flag = GSOCK_INPUT_FLAG;
989 break;
990
991 case GSOCK_OUTPUT:
992 flag = GSOCK_OUTPUT_FLAG;
993 break;
994
995 case GSOCK_CONNECTION:
996 flag = GSOCK_CONNECTION_FLAG;
997 break;
998
999 case GSOCK_LOST:
1000 flag = GSOCK_LOST_FLAG;
1001 break;
1002
1003 default:
1004 wxLogWarning( wxT("wxSocket: unknown event!") );
1005 return;
1006 }
1007
1008 if (((m_eventmask & flag) == flag) && m_notify)
1009 {
1010 if (m_handler)
1011 {
1012 wxSocketEvent event(m_id);
1013 event.m_event = notification;
1014 event.m_clientData = m_clientData;
1015 event.SetEventObject(this);
1016
1017 m_handler->AddPendingEvent(event);
1018 }
1019 }
1020 }
1021
1022 void wxSocketBase::Notify(bool notify)
1023 {
1024 m_notify = notify;
1025 }
1026
1027 void wxSocketBase::SetNotify(wxSocketEventFlags flags)
1028 {
1029 m_eventmask = flags;
1030 }
1031
1032 void wxSocketBase::SetEventHandler(wxEvtHandler& handler, int id)
1033 {
1034 m_handler = &handler;
1035 m_id = id;
1036 }
1037
1038 // --------------------------------------------------------------------------
1039 // Pushback buffer
1040 // --------------------------------------------------------------------------
1041
1042 void wxSocketBase::Pushback(const void *buffer, wxUint32 size)
1043 {
1044 if (!size)
1045 return;
1046
1047 if (m_unread == NULL)
1048 m_unread = malloc(size);
1049 else
1050 {
1051 void *tmp;
1052
1053 tmp = malloc(m_unrd_size + size);
1054 memcpy((char *)tmp + size, m_unread, m_unrd_size);
1055 free(m_unread);
1056
1057 m_unread = tmp;
1058 }
1059
1060 m_unrd_size += size;
1061
1062 memcpy(m_unread, buffer, size);
1063 }
1064
1065 wxUint32 wxSocketBase::GetPushback(void *buffer, wxUint32 size, bool peek)
1066 {
1067 if (!m_unrd_size)
1068 return 0;
1069
1070 if (size > (m_unrd_size-m_unrd_cur))
1071 size = m_unrd_size-m_unrd_cur;
1072
1073 memcpy(buffer, (char *)m_unread + m_unrd_cur, size);
1074
1075 if (!peek)
1076 {
1077 m_unrd_cur += size;
1078 if (m_unrd_size == m_unrd_cur)
1079 {
1080 free(m_unread);
1081 m_unread = NULL;
1082 m_unrd_size = 0;
1083 m_unrd_cur = 0;
1084 }
1085 }
1086
1087 return size;
1088 }
1089
1090
1091 // ==========================================================================
1092 // wxSocketServer
1093 // ==========================================================================
1094
1095 // --------------------------------------------------------------------------
1096 // Ctor
1097 // --------------------------------------------------------------------------
1098
1099 wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
1100 wxSocketFlags flags)
1101 : wxSocketBase(flags, wxSOCKET_SERVER)
1102 {
1103 wxLogTrace( wxTRACE_Socket, wxT("Opening wxSocketServer") );
1104
1105 m_socket = GSocket_new();
1106
1107 if (!m_socket)
1108 {
1109 wxLogTrace( wxTRACE_Socket, wxT("*** GSocket_new failed") );
1110 return;
1111 }
1112
1113 // Setup the socket as server
1114
1115 #if 0
1116 GSocket_SetLocal(m_socket, addr_man.GetAddress());
1117 if (GSocket_SetServer(m_socket) != GSOCK_NOERROR)
1118 {
1119 GSocket_destroy(m_socket);
1120 m_socket = NULL;
1121
1122 wxLogTrace( wxTRACE_Socket, wxT("*** GSocket_SetServer failed") );
1123 return;
1124 }
1125
1126 GSocket_SetTimeout(m_socket, m_timeout * 1000);
1127 GSocket_SetCallback(m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1128 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1129 wx_socket_callback, (char *)this);
1130 #endif
1131 }
1132
1133 // --------------------------------------------------------------------------
1134 // Accept
1135 // --------------------------------------------------------------------------
1136
1137 bool wxSocketServer::AcceptWith(wxSocketBase& sock, bool wait)
1138 {
1139 GSocket *child_socket;
1140
1141 if (!m_socket)
1142 return false;
1143
1144 // If wait == false, then the call should be nonblocking.
1145 // When we are finished, we put the socket to blocking mode
1146 // again.
1147
1148 #if 0
1149 if (!wait)
1150 GSocket_SetNonBlocking(m_socket, 1);
1151
1152 child_socket = GSocket_WaitConnection(m_socket);
1153
1154 if (!wait)
1155 GSocket_SetNonBlocking(m_socket, 0);
1156
1157 if (!child_socket)
1158 return false;
1159
1160 sock.m_type = wxSOCKET_BASE;
1161 sock.m_socket = child_socket;
1162 sock.m_connected = true;
1163
1164 GSocket_SetTimeout(sock.m_socket, sock.m_timeout * 1000);
1165 GSocket_SetCallback(sock.m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1166 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1167 wx_socket_callback, (char *)&sock);
1168 #endif
1169
1170 return true;
1171 }
1172
1173 wxSocketBase *wxSocketServer::Accept(bool wait)
1174 {
1175 wxSocketBase* sock = new wxSocketBase();
1176
1177 sock->SetFlags(m_flags);
1178
1179 if (!AcceptWith(*sock, wait))
1180 {
1181 sock->Destroy();
1182 sock = NULL;
1183 }
1184
1185 return sock;
1186 }
1187
1188 bool wxSocketServer::WaitForAccept(long seconds, long milliseconds)
1189 {
1190 return _Wait(seconds, milliseconds, GSOCK_CONNECTION_FLAG);
1191 }
1192
1193 // ==========================================================================
1194 // wxSocketClient
1195 // ==========================================================================
1196
1197 // --------------------------------------------------------------------------
1198 // Ctor and dtor
1199 // --------------------------------------------------------------------------
1200
1201 wxSocketClient::wxSocketClient(wxSocketFlags flags)
1202 : wxSocketBase(flags, wxSOCKET_CLIENT)
1203 {
1204 }
1205
1206 wxSocketClient::~wxSocketClient()
1207 {
1208 }
1209
1210 // --------------------------------------------------------------------------
1211 // Connect
1212 // --------------------------------------------------------------------------
1213
1214 bool wxSocketClient::Connect(wxSockAddress& addr_man, bool wait)
1215 {
1216 GSocketError err;
1217
1218 if (m_socket)
1219 {
1220 // Shutdown and destroy the socket
1221 Close();
1222 GSocket_destroy(m_socket);
1223 }
1224
1225 m_socket = GSocket_new();
1226 m_connected = false;
1227 m_establishing = false;
1228
1229 if (!m_socket)
1230 return false;
1231
1232 GSocket_SetTimeout(m_socket, m_timeout * 1000);
1233 GSocket_SetCallback(m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1234 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1235 wx_socket_callback, (char *)this);
1236
1237 // If wait == false, then the call should be nonblocking.
1238 // When we are finished, we put the socket to blocking mode
1239 // again.
1240
1241 if (!wait)
1242 GSocket_SetNonBlocking(m_socket, 1);
1243
1244 GSocket_SetPeer(m_socket, addr_man.GetAddress());
1245 err = GSocket_Connect(m_socket, GSOCK_STREAMED);
1246
1247 if (!wait)
1248 GSocket_SetNonBlocking(m_socket, 0);
1249
1250 if (err != GSOCK_NOERROR)
1251 {
1252 if (err == GSOCK_WOULDBLOCK)
1253 m_establishing = true;
1254
1255 return false;
1256 }
1257
1258 m_connected = true;
1259 return true;
1260 }
1261
1262 bool wxSocketClient::WaitOnConnect(long seconds, long milliseconds)
1263 {
1264 if (m_connected) // Already connected
1265 return true;
1266
1267 if (!m_establishing || !m_socket) // No connection in progress
1268 return false;
1269
1270 return _Wait(seconds, milliseconds, GSOCK_CONNECTION_FLAG | GSOCK_LOST_FLAG);
1271 }
1272
1273 // ==========================================================================
1274 // wxDatagramSocket
1275 // ==========================================================================
1276
1277 /* NOTE: experimental stuff - might change */
1278
1279 wxDatagramSocket::wxDatagramSocket( wxSockAddress& addr,
1280 wxSocketFlags flags )
1281 : wxSocketBase( flags, wxSOCKET_DATAGRAM )
1282 {
1283 #if 0
1284 // Create the socket
1285 m_socket = GSocket_new();
1286
1287 if (!m_socket)
1288 return;
1289
1290 // Setup the socket as non connection oriented
1291 GSocket_SetLocal(m_socket, addr.GetAddress());
1292 if( GSocket_SetNonOriented(m_socket) != GSOCK_NOERROR )
1293 {
1294 GSocket_destroy(m_socket);
1295 m_socket = NULL;
1296 return;
1297 }
1298
1299 // Initialize all stuff
1300 m_connected = false;
1301 m_establishing = false;
1302 GSocket_SetTimeout( m_socket, m_timeout );
1303 GSocket_SetCallback( m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
1304 GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
1305 wx_socket_callback, (char*)this );
1306 #endif
1307 }
1308
1309 wxDatagramSocket& wxDatagramSocket::RecvFrom( wxSockAddress& addr,
1310 void* buf,
1311 wxUint32 nBytes )
1312 {
1313 Read(buf, nBytes);
1314 GetPeer(addr);
1315 return (*this);
1316 }
1317
1318 wxDatagramSocket& wxDatagramSocket::SendTo( wxSockAddress& addr,
1319 const void* buf,
1320 wxUint32 nBytes )
1321 {
1322 GSocket_SetPeer(m_socket, addr.GetAddress());
1323 Write(buf, nBytes);
1324 return (*this);
1325 }
1326
1327 /*
1328 * -------------------------------------------------------------------------
1329 * GAddress
1330 * -------------------------------------------------------------------------
1331 */
1332
1333 /* CHECK_ADDRESS verifies that the current address family is either
1334 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1335 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1336 * an appropiate error code.
1337 *
1338 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1339 */
1340 #define CHECK_ADDRESS(address, family) \
1341 { \
1342 if (address->m_family == GSOCK_NOFAMILY) \
1343 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1344 return address->m_error; \
1345 if (address->m_family != GSOCK_##family) \
1346 { \
1347 address->m_error = GSOCK_INVADDR; \
1348 return GSOCK_INVADDR; \
1349 } \
1350 }
1351
1352 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1353 { \
1354 if (address->m_family == GSOCK_NOFAMILY) \
1355 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1356 return retval; \
1357 if (address->m_family != GSOCK_##family) \
1358 { \
1359 address->m_error = GSOCK_INVADDR; \
1360 return retval; \
1361 } \
1362 }
1363
1364
1365 GAddress *GAddress_new(void)
1366 {
1367 GAddress *address;
1368
1369 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1370 return NULL;
1371
1372 address->m_family = GSOCK_NOFAMILY;
1373 address->m_addr = NULL;
1374 address->m_len = 0;
1375
1376 return address;
1377 }
1378
1379 GAddress *GAddress_copy(GAddress *address)
1380 {
1381 GAddress *addr2;
1382
1383 assert(address != NULL);
1384
1385 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1386 return NULL;
1387
1388 memcpy(addr2, address, sizeof(GAddress));
1389
1390 if (address->m_addr && address->m_len > 0)
1391 {
1392 addr2->m_addr = (struct sockaddr *)malloc(addr2->m_len);
1393 if (addr2->m_addr == NULL)
1394 {
1395 free(addr2);
1396 return NULL;
1397 }
1398
1399 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1400 }
1401
1402 return addr2;
1403 }
1404
1405 void GAddress_destroy(GAddress *address)
1406 {
1407 assert( address != NULL );
1408
1409 if (address->m_addr)
1410 free(address->m_addr);
1411
1412 free(address);
1413 }
1414
1415 void GAddress_SetFamily(GAddress *address, GAddressType type)
1416 {
1417 assert(address != NULL);
1418
1419 address->m_family = type;
1420 }
1421
1422 GAddressType GAddress_GetFamily(GAddress *address)
1423 {
1424 assert( address != NULL );
1425
1426 return address->m_family;
1427 }
1428
1429 GSocketError _GAddress_translate_from(GAddress *address,
1430 struct sockaddr *addr, int len)
1431 {
1432 address->m_realfamily = addr->sa_family;
1433 switch (addr->sa_family)
1434 {
1435 case AF_INET:
1436 address->m_family = GSOCK_INET;
1437 break;
1438
1439 case AF_UNIX:
1440 address->m_family = GSOCK_UNIX;
1441 break;
1442
1443 #ifdef AF_INET6
1444 case AF_INET6:
1445 address->m_family = GSOCK_INET6;
1446 break;
1447 #endif
1448
1449 default:
1450 {
1451 address->m_error = GSOCK_INVOP;
1452 return GSOCK_INVOP;
1453 }
1454 }
1455
1456 if (address->m_addr)
1457 free(address->m_addr);
1458
1459 address->m_len = len;
1460 address->m_addr = (struct sockaddr *)malloc(len);
1461
1462 if (address->m_addr == NULL)
1463 {
1464 address->m_error = GSOCK_MEMERR;
1465 return GSOCK_MEMERR;
1466 }
1467
1468 memcpy(address->m_addr, addr, len);
1469
1470 return GSOCK_NOERROR;
1471 }
1472
1473 GSocketError _GAddress_translate_to(GAddress *address,
1474 struct sockaddr **addr, int *len)
1475 {
1476 if (!address->m_addr)
1477 {
1478 address->m_error = GSOCK_INVADDR;
1479 return GSOCK_INVADDR;
1480 }
1481
1482 *len = address->m_len;
1483 *addr = (struct sockaddr *)malloc(address->m_len);
1484 if (*addr == NULL)
1485 {
1486 address->m_error = GSOCK_MEMERR;
1487 return GSOCK_MEMERR;
1488 }
1489
1490 memcpy(*addr, address->m_addr, address->m_len);
1491 return GSOCK_NOERROR;
1492 }
1493
1494 /*
1495 * -------------------------------------------------------------------------
1496 * Internet address family
1497 * -------------------------------------------------------------------------
1498 */
1499
1500 GSocketError _GAddress_Init_INET(GAddress *address)
1501 {
1502 address->m_len = sizeof(struct sockaddr_in);
1503 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1504 if (address->m_addr == NULL)
1505 {
1506 address->m_error = GSOCK_MEMERR;
1507 return GSOCK_MEMERR;
1508 }
1509
1510 memset( address->m_addr , 0 , address->m_len ) ;
1511 address->m_family = GSOCK_INET;
1512 address->m_realfamily = PF_INET;
1513 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
1514 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
1515
1516 return GSOCK_NOERROR;
1517 }
1518
1519 GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1520 {
1521 struct hostent *he;
1522 struct in_addr *addr;
1523
1524 assert( address != NULL );
1525 CHECK_ADDRESS( address, INET );
1526
1527 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1528
1529 // If it is a numeric host name, convert it now
1530 #if defined(HAVE_INET_ATON)
1531 if (inet_aton(hostname, addr) == 0)
1532 {
1533 #elif defined(HAVE_INET_ADDR)
1534 if ( (addr->s_addr = inet_addr(hostname)) == -1 )
1535 {
1536 #else
1537 // Use gethostbyname by default
1538 #ifndef __WXMAC__
1539 int val = 1; // VA doesn't like constants in conditional expressions
1540 if (val)
1541 #endif
1542 {
1543 #endif
1544 struct in_addr *array_addr;
1545
1546 // It is a real name, we solve it
1547 if ((he = gethostbyname(hostname)) == NULL)
1548 {
1549 // Reset to invalid address
1550 addr->s_addr = INADDR_NONE;
1551 address->m_error = GSOCK_NOHOST;
1552 return GSOCK_NOHOST;
1553 }
1554 array_addr = (struct in_addr *) *(he->h_addr_list);
1555 addr->s_addr = array_addr[0].s_addr;
1556 }
1557
1558 return GSOCK_NOERROR;
1559 }
1560
1561 GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1562 {
1563 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1564 }
1565
1566 GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1567 unsigned long hostaddr)
1568 {
1569 struct in_addr *addr;
1570
1571 assert( address != NULL );
1572 CHECK_ADDRESS( address, INET );
1573
1574 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1575 addr->s_addr = htonl(hostaddr) ;
1576
1577 return GSOCK_NOERROR;
1578 }
1579
1580 GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1581 const char *protocol)
1582 {
1583 struct servent *se;
1584 struct sockaddr_in *addr;
1585
1586 assert( address != NULL );
1587 CHECK_ADDRESS( address, INET );
1588
1589 if (!port)
1590 {
1591 address->m_error = GSOCK_INVPORT;
1592 return GSOCK_INVPORT;
1593 }
1594
1595 se = getservbyname(port, protocol);
1596 if (!se)
1597 {
1598 // the cast to int suppresses compiler warnings
1599 // about subscript having the type char
1600 if (isdigit((int)port[0]))
1601 {
1602 int port_int;
1603
1604 port_int = atoi(port);
1605 addr = (struct sockaddr_in *)address->m_addr;
1606 addr->sin_port = htons(port_int);
1607 return GSOCK_NOERROR;
1608 }
1609
1610 address->m_error = GSOCK_INVPORT;
1611 return GSOCK_INVPORT;
1612 }
1613
1614 addr = (struct sockaddr_in *)address->m_addr;
1615 addr->sin_port = se->s_port;
1616
1617 return GSOCK_NOERROR;
1618 }
1619
1620 GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
1621 {
1622 struct sockaddr_in *addr;
1623
1624 assert( address != NULL );
1625 CHECK_ADDRESS( address, INET );
1626
1627 addr = (struct sockaddr_in *)address->m_addr;
1628 addr->sin_port = htons(port);
1629
1630 return GSOCK_NOERROR;
1631 }
1632
1633 GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
1634 {
1635 struct hostent *he;
1636 char *addr_buf;
1637 struct sockaddr_in *addr;
1638
1639 assert( address != NULL );
1640 CHECK_ADDRESS( address, INET );
1641
1642 addr = (struct sockaddr_in *)address->m_addr;
1643 addr_buf = (char *)&(addr->sin_addr);
1644
1645 he = gethostbyaddr(addr_buf, sizeof(addr->sin_addr), AF_INET);
1646 if (he == NULL)
1647 {
1648 address->m_error = GSOCK_NOHOST;
1649 return GSOCK_NOHOST;
1650 }
1651
1652 strncpy(hostname, he->h_name, sbuf);
1653
1654 return GSOCK_NOERROR;
1655 }
1656
1657 unsigned long GAddress_INET_GetHostAddress(GAddress *address)
1658 {
1659 struct sockaddr_in *addr;
1660
1661 assert( address != NULL );
1662 CHECK_ADDRESS_RETVAL( address, INET, 0 );
1663
1664 addr = (struct sockaddr_in *)address->m_addr;
1665
1666 return ntohl(addr->sin_addr.s_addr) ;
1667 }
1668
1669 unsigned short GAddress_INET_GetPort(GAddress *address)
1670 {
1671 struct sockaddr_in *addr;
1672
1673 assert( address != NULL );
1674 CHECK_ADDRESS_RETVAL( address, INET, 0 );
1675
1676 addr = (struct sockaddr_in *)address->m_addr;
1677
1678 return ntohs(addr->sin_port);
1679 }
1680
1681 /*
1682 * -------------------------------------------------------------------------
1683 * Unix address family
1684 * -------------------------------------------------------------------------
1685 */
1686
1687 GSocketError _GAddress_Init_UNIX(GAddress *address)
1688 {
1689 address->m_len = sizeof(struct sockaddr_un);
1690 address->m_addr = (struct sockaddr *)malloc(address->m_len);
1691 if (address->m_addr == NULL)
1692 {
1693 address->m_error = GSOCK_MEMERR;
1694 return GSOCK_MEMERR;
1695 }
1696
1697 address->m_family = GSOCK_UNIX;
1698 address->m_realfamily = PF_UNIX;
1699 ((struct sockaddr_un *)address->m_addr)->sun_family = AF_UNIX;
1700 ((struct sockaddr_un *)address->m_addr)->sun_path[0] = 0;
1701
1702 return GSOCK_NOERROR;
1703 }
1704
1705 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1706
1707 GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *path)
1708 {
1709 struct sockaddr_un *addr;
1710
1711 assert( address != NULL );
1712 CHECK_ADDRESS( address, UNIX );
1713
1714 addr = ((struct sockaddr_un *)address->m_addr);
1715 strncpy(addr->sun_path, path, UNIX_SOCK_PATHLEN);
1716 addr->sun_path[UNIX_SOCK_PATHLEN - 1] = '\0';
1717
1718 return GSOCK_NOERROR;
1719 }
1720
1721 GSocketError GAddress_UNIX_GetPath(GAddress *address, char *path, size_t sbuf)
1722 {
1723 struct sockaddr_un *addr;
1724
1725 assert( address != NULL );
1726 CHECK_ADDRESS( address, UNIX );
1727
1728 addr = (struct sockaddr_un *)address->m_addr;
1729
1730 strncpy(path, addr->sun_path, sbuf);
1731
1732 return GSOCK_NOERROR;
1733 }
1734
1735 /* Address handling */
1736
1737 /* GSocket_SetLocal:
1738 * GSocket_GetLocal:
1739 * GSocket_SetPeer:
1740 * GSocket_GetPeer:
1741 * Set or get the local or peer address for this socket. The 'set'
1742 * functions return GSOCK_NOERROR on success, an error code otherwise.
1743 * The 'get' functions return a pointer to a GAddress object on success,
1744 * or NULL otherwise, in which case they set the error code of the
1745 * corresponding GSocket.
1746 *
1747 * Error codes:
1748 * GSOCK_INVSOCK - the socket is not valid.
1749 * GSOCK_INVADDR - the address is not valid.
1750 */
1751
1752 GSocketError GSocket_SetLocal(GSocket *socket, GAddress *address)
1753 {
1754 assert( socket != NULL );
1755
1756 // the socket must be initialized, or it must be a server
1757 if ((socket->m_fd != INVALID_SOCKET && !socket->m_server))
1758 {
1759 socket->m_error = GSOCK_INVSOCK;
1760 return GSOCK_INVSOCK;
1761 }
1762
1763 // check address
1764 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
1765 {
1766 socket->m_error = GSOCK_INVADDR;
1767 return GSOCK_INVADDR;
1768 }
1769
1770 if (socket->m_local)
1771 GAddress_destroy(socket->m_local);
1772
1773 socket->m_local = GAddress_copy(address);
1774
1775 return GSOCK_NOERROR;
1776 }
1777
1778 GSocketError GSocket_SetPeer(GSocket *socket, GAddress *address)
1779 {
1780 assert(socket != NULL);
1781
1782 // check address
1783 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
1784 {
1785 socket->m_error = GSOCK_INVADDR;
1786 return GSOCK_INVADDR;
1787 }
1788
1789 if (socket->m_peer)
1790 GAddress_destroy(socket->m_peer);
1791
1792 socket->m_peer = GAddress_copy(address);
1793
1794 return GSOCK_NOERROR;
1795 }
1796
1797 GAddress *GSocket_GetLocal(GSocket *socket)
1798 {
1799 GAddress *address;
1800 struct sockaddr addr;
1801 socklen_t size = sizeof(addr);
1802 GSocketError err;
1803
1804 assert( socket != NULL );
1805
1806 // try to get it from the m_local var first
1807 if (socket->m_local)
1808 return GAddress_copy(socket->m_local);
1809
1810 // else, if the socket is initialized, try getsockname
1811 if (socket->m_fd == INVALID_SOCKET)
1812 {
1813 socket->m_error = GSOCK_INVSOCK;
1814 return NULL;
1815 }
1816
1817 if (getsockname(socket->m_fd, &addr, (socklen_t *) &size) < 0)
1818 {
1819 socket->m_error = GSOCK_IOERR;
1820 return NULL;
1821 }
1822
1823 // got a valid address from getsockname, create a GAddress object
1824 address = GAddress_new();
1825 if (address == NULL)
1826 {
1827 socket->m_error = GSOCK_MEMERR;
1828 return NULL;
1829 }
1830
1831 err = _GAddress_translate_from(address, &addr, size);
1832 if (err != GSOCK_NOERROR)
1833 {
1834 GAddress_destroy(address);
1835 socket->m_error = err;
1836 return NULL;
1837 }
1838
1839 return address;
1840 }
1841
1842 GAddress *GSocket_GetPeer(GSocket *socket)
1843 {
1844 assert(socket != NULL);
1845
1846 // try to get it from the m_peer var
1847 if (socket->m_peer)
1848 return GAddress_copy(socket->m_peer);
1849
1850 return NULL;
1851 }
1852
1853
1854 GSocket *GSocket_new(void)
1855 {
1856 GSocket *socket;
1857 socket = (GSocket *)malloc(sizeof(GSocket));
1858
1859 if (socket == NULL)
1860 return NULL;
1861
1862 socket->m_fd = INVALID_SOCKET;
1863
1864 for (int i=0;i<GSOCK_MAX_EVENT;i++)
1865 {
1866 socket->m_cbacks[i] = NULL;
1867 }
1868
1869 socket->m_detected = 0;
1870
1871 socket->m_local = NULL;
1872 socket->m_peer = NULL;
1873 socket->m_error = GSOCK_NOERROR;
1874
1875 socket->m_non_blocking = false ;
1876 socket->m_stream = true;
1877 // socket->m_oriented = true;
1878 socket->m_server = false;
1879 socket->m_establishing = false;
1880 socket->m_timeout = 10 * 60 * 1000;
1881 // 10 minutes * 60 sec * 1000 millisec
1882
1883 socket->m_cfSocket = NULL ;
1884 socket->m_runLoopSource = NULL ;
1885 socket->m_readStream = NULL;
1886 socket->m_writeStream = NULL;
1887
1888 return socket ;
1889 }
1890
1891 void GSocket_close(GSocket *socket)
1892 {
1893 if ( socket->m_cfSocket != NULL )
1894 {
1895 if ( socket->m_readStream )
1896 {
1897 CFReadStreamClose(socket->m_readStream);
1898 CFRelease( socket->m_readStream ) ;
1899 socket->m_readStream = NULL ;
1900 }
1901
1902 if ( socket->m_writeStream )
1903 {
1904 CFWriteStreamClose(socket->m_writeStream);
1905 CFRelease( socket->m_writeStream ) ;
1906 socket->m_writeStream = NULL ;
1907 }
1908
1909 CFSocketInvalidate( socket->m_cfSocket ) ;
1910 CFRelease( socket->m_cfSocket ) ;
1911 socket->m_cfSocket = NULL ;
1912 socket->m_fd = INVALID_SOCKET ;
1913 }
1914 }
1915
1916 void GSocket_Shutdown(GSocket *socket)
1917 {
1918 GSocket_close( socket );
1919
1920 // Disable GUI callbacks
1921 for (int evt = 0; evt < GSOCK_MAX_EVENT; evt++)
1922 socket->m_cbacks[evt] = NULL;
1923
1924 socket->m_detected = GSOCK_LOST_FLAG;
1925 }
1926
1927 void GSocket_destroy(GSocket *socket)
1928 {
1929 assert( socket != NULL );
1930
1931 // Check that the socket is really shut down
1932 if (socket->m_fd != INVALID_SOCKET)
1933 GSocket_Shutdown(socket);
1934
1935 // Destroy private addresses
1936 if (socket->m_local)
1937 GAddress_destroy(socket->m_local);
1938
1939 if (socket->m_peer)
1940 GAddress_destroy(socket->m_peer);
1941
1942 // Destroy the socket itself
1943 free(socket);
1944 }
1945
1946 GSocketError GSocket_Connect(GSocket *socket, GSocketStream stream)
1947 {
1948 assert( socket != NULL );
1949
1950 if (socket->m_fd != INVALID_SOCKET)
1951 {
1952 socket->m_error = GSOCK_INVSOCK;
1953 return GSOCK_INVSOCK;
1954 }
1955
1956 if (!socket->m_peer)
1957 {
1958 socket->m_error = GSOCK_INVADDR;
1959 return GSOCK_INVADDR;
1960 }
1961
1962 // Streamed or dgram socket?
1963 socket->m_stream = (stream == GSOCK_STREAMED);
1964 socket->m_oriented = true;
1965 socket->m_server = false;
1966 socket->m_establishing = false;
1967
1968 GSocketError returnErr = GSOCK_NOERROR ;
1969 CFSocketError err ;
1970
1971 CFAllocatorRef alloc = kCFAllocatorDefault ;
1972 CFSocketContext ctx ;
1973 memset( &ctx , 0 , sizeof( ctx ) ) ;
1974 ctx.info = socket ;
1975 socket->m_cfSocket = CFSocketCreate( alloc , socket->m_peer->m_realfamily ,
1976 stream == GSOCK_STREAMED ? SOCK_STREAM : SOCK_DGRAM , 0 ,
1977 kCFSocketReadCallBack | kCFSocketWriteCallBack | kCFSocketConnectCallBack , wxMacCFSocketCallback , &ctx ) ;
1978 _GSocket_Enable(socket, GSOCK_CONNECTION);
1979
1980 socket->m_fd = CFSocketGetNative( socket->m_cfSocket ) ;
1981
1982 CFStreamCreatePairWithSocket ( alloc , socket->m_fd , &socket->m_readStream , &socket->m_writeStream );
1983 if ((socket->m_readStream == NULL) || (socket->m_writeStream == NULL))
1984 {
1985 GSocket_close(socket);
1986 socket->m_error = GSOCK_IOERR;
1987 return GSOCK_IOERR;
1988 }
1989
1990 if ( !CFReadStreamOpen( socket->m_readStream ) || !CFWriteStreamOpen( socket->m_writeStream ) )
1991 {
1992 GSocket_close(socket);
1993 socket->m_error = GSOCK_IOERR;
1994 return GSOCK_IOERR;
1995 }
1996
1997 CFRunLoopSourceRef rls = CFSocketCreateRunLoopSource(alloc , socket->m_cfSocket , 0);
1998 CFRunLoopAddSource(CFRunLoopGetCurrent() , rls, kCFRunLoopCommonModes);
1999 CFRelease(rls);
2000
2001 CFDataRef address = CFDataCreateWithBytesNoCopy(alloc, (const UInt8*) socket->m_peer->m_addr, socket->m_peer->m_len , kCFAllocatorNull);
2002 if ( !address )
2003 return GSOCK_MEMERR ;
2004
2005 err = CFSocketConnectToAddress( socket->m_cfSocket , address, socket->m_non_blocking ? -1 : socket->m_timeout / 1000 ) ;
2006 CFRelease(address);
2007
2008 if (err != kCFSocketSuccess)
2009 {
2010 if ( err == kCFSocketTimeout )
2011 {
2012 GSocket_close(socket);
2013 socket->m_error = GSOCK_TIMEDOUT ;
2014 return GSOCK_TIMEDOUT ;
2015 }
2016
2017 // we don't know whether a connect in progress will be issued like this
2018 if ( err != kCFSocketTimeout && socket->m_non_blocking )
2019 {
2020 socket->m_establishing = true;
2021 socket->m_error = GSOCK_WOULDBLOCK;
2022 return GSOCK_WOULDBLOCK;
2023 }
2024
2025 GSocket_close(socket);
2026 socket->m_error = GSOCK_IOERR;
2027 return GSOCK_IOERR;
2028 }
2029
2030 return GSOCK_NOERROR;
2031 }
2032
2033 /* Flags */
2034
2035 /* GSocket_SetNonBlocking:
2036 * Sets the socket to non-blocking mode.
2037 * All IO calls will return immediately.
2038 */
2039 void GSocket_SetNonBlocking(GSocket *socket, int non_block)
2040 {
2041 assert( socket != NULL );
2042
2043 // GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
2044
2045 socket->m_non_blocking = non_block;
2046 }
2047
2048 /*
2049 * GSocket_SetTimeout:
2050 * Sets the timeout for blocking calls. Time is expressed in
2051 * milliseconds.
2052 */
2053 void GSocket_SetTimeout(GSocket *socket, unsigned long millisec)
2054 {
2055 assert( socket != NULL );
2056
2057 socket->m_timeout = millisec;
2058 }
2059
2060 /* GSocket_GetError:
2061 * Returns the last error which occurred for this socket. Note that successful
2062 * operations do not clear this back to GSOCK_NOERROR, so use it only
2063 * after an error.
2064 */
2065 GSocketError GSocket_GetError(GSocket *socket)
2066 {
2067 assert( socket != NULL );
2068
2069 return socket->m_error;
2070 }
2071
2072 /* Callbacks */
2073
2074 /* GSOCK_INPUT:
2075 * There is data to be read in the input buffer. If, after a read
2076 * operation, there is still data available, the callback function will
2077 * be called again.
2078 * GSOCK_OUTPUT:
2079 * The socket is available for writing. That is, the next write call
2080 * won't block. This event is generated only once, when the connection is
2081 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
2082 * when the output buffer empties again. This means that the app should
2083 * assume that it can write since the first OUTPUT event, and no more
2084 * OUTPUT events will be generated unless an error occurs.
2085 * GSOCK_CONNECTION:
2086 * Connection successfully established, for client sockets, or incoming
2087 * client connection, for server sockets. Wait for this event (also watch
2088 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
2089 * GSOCK_LOST:
2090 * The connection is lost (or a connection request failed); this could
2091 * be due to a failure, or due to the peer closing it gracefully.
2092 */
2093
2094 /* GSocket_SetCallback:
2095 * Enables the callbacks specified by 'flags'. Note that 'flags'
2096 * may be a combination of flags OR'ed toghether, so the same
2097 * callback function can be made to accept different events.
2098 * The callback function must have the following prototype:
2099 *
2100 * void function(GSocket *socket, GSocketEvent event, char *cdata)
2101 */
2102 void GSocket_SetCallback(GSocket *socket, GSocketEventFlags flags,
2103 GSocketCallback callback, char *cdata)
2104 {
2105 int count;
2106
2107 assert( socket != NULL );
2108
2109 for (count = 0; count < GSOCK_MAX_EVENT; count++)
2110 {
2111 if ((flags & (1 << count)) != 0)
2112 {
2113 socket->m_cbacks[count] = callback;
2114 socket->m_data[count] = cdata;
2115 }
2116 }
2117 }
2118
2119 /* GSocket_UnsetCallback:
2120 * Disables all callbacks specified by 'flags', which may be a
2121 * combination of flags OR'ed toghether.
2122 */
2123 void GSocket_UnsetCallback(GSocket *socket, GSocketEventFlags flags)
2124 {
2125 int count;
2126
2127 assert(socket != NULL);
2128
2129 for (count = 0; count < GSOCK_MAX_EVENT; count++)
2130 {
2131 if ((flags & (1 << count)) != 0)
2132 {
2133 socket->m_cbacks[count] = NULL;
2134 socket->m_data[count] = NULL;
2135 }
2136 }
2137 }
2138
2139
2140 #define CALL_CALLBACK(socket, event) { \
2141 _GSocket_Disable(socket, event); \
2142 if (socket->m_cbacks[event]) \
2143 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
2144 }
2145
2146 void _GSocket_Install_Callback(GSocket *socket, GSocketEvent event)
2147 {
2148 int c;
2149 switch (event)
2150 {
2151 case GSOCK_CONNECTION:
2152 if (socket->m_server)
2153 c = kCFSocketReadCallBack;
2154 else
2155 c = kCFSocketConnectCallBack;
2156 break;
2157
2158 case GSOCK_LOST:
2159 case GSOCK_INPUT:
2160 c = kCFSocketReadCallBack;
2161 break;
2162
2163 case GSOCK_OUTPUT:
2164 c = kCFSocketWriteCallBack;
2165 break;
2166
2167 default:
2168 c = 0;
2169 }
2170
2171 CFSocketEnableCallBacks(socket->m_cfSocket, c);
2172 }
2173
2174 void _GSocket_Uninstall_Callback(GSocket *socket, GSocketEvent event)
2175 {
2176 int c;
2177 switch (event)
2178 {
2179 case GSOCK_CONNECTION:
2180 if (socket->m_server)
2181 c = kCFSocketReadCallBack;
2182 else
2183 c = kCFSocketConnectCallBack;
2184 break;
2185
2186 case GSOCK_LOST:
2187 case GSOCK_INPUT:
2188 c = kCFSocketReadCallBack;
2189 break;
2190
2191 case GSOCK_OUTPUT:
2192 c = kCFSocketWriteCallBack;
2193 break;
2194
2195 default:
2196 c = 0;
2197 break;
2198 }
2199
2200 CFSocketDisableCallBacks(socket->m_cfSocket, c);
2201 }
2202
2203 void _GSocket_Enable(GSocket *socket, GSocketEvent event)
2204 {
2205 socket->m_detected &= ~(1 << event);
2206 _GSocket_Install_Callback(socket, event);
2207 }
2208
2209 void _GSocket_Disable(GSocket *socket, GSocketEvent event)
2210 {
2211 socket->m_detected |= (1 << event);
2212 _GSocket_Uninstall_Callback(socket, event);
2213 }
2214
2215 void wxMacCFSocketCallback(CFSocketRef s, CFSocketCallBackType callbackType,
2216 CFDataRef address, const void* data, void* info)
2217 {
2218 GSocket* socket = (GSocket*)info;
2219
2220 switch (callbackType)
2221 {
2222 case kCFSocketConnectCallBack:
2223 if ( data )
2224 {
2225 SInt32 error = *((SInt32*)data) ;
2226 CALL_CALLBACK( socket , GSOCK_LOST ) ;
2227 GSocket_Shutdown(socket);
2228 }
2229 else
2230 {
2231 CALL_CALLBACK( socket , GSOCK_CONNECTION ) ;
2232 }
2233 break;
2234
2235 case kCFSocketReadCallBack:
2236 CALL_CALLBACK( socket , GSOCK_INPUT ) ;
2237 break;
2238
2239 case kCFSocketWriteCallBack:
2240 CALL_CALLBACK( socket , GSOCK_OUTPUT ) ;
2241 break;
2242
2243 default:
2244 break; // We shouldn't get here.
2245 }
2246 }
2247
2248 int GSocket_Read(GSocket *socket, char *buffer, int size)
2249 {
2250 int ret = 0 ;
2251
2252 assert(socket != NULL);
2253 // if ( !CFReadStreamHasBytesAvailable() )
2254 ret = CFReadStreamRead( socket->m_readStream , (UInt8*) buffer , size ) ;
2255
2256 return ret;
2257 }
2258
2259 int GSocket_Write(GSocket *socket, const char *buffer, int size)
2260 {
2261 int ret;
2262
2263 assert(socket != NULL);
2264 ret = CFWriteStreamWrite( socket->m_writeStream , (UInt8*) buffer , size ) ;
2265
2266 return ret;
2267 }
2268
2269 GSocketEventFlags GSocket_Select(GSocket *socket, GSocketEventFlags flags)
2270 {
2271 assert( socket != NULL );
2272
2273 return flags & socket->m_detected;
2274 }
2275
2276 // ==========================================================================
2277 // wxSocketModule
2278 // ==========================================================================
2279
2280 class wxSocketModule : public wxModule
2281 {
2282 public:
2283 virtual bool OnInit()
2284 {
2285 // wxSocketBase will call GSocket_Init() itself when/if needed
2286 return true;
2287 }
2288
2289 virtual void OnExit()
2290 {
2291 if ( wxSocketBase::IsInitialized() )
2292 wxSocketBase::Shutdown();
2293 }
2294
2295 private:
2296 DECLARE_DYNAMIC_CLASS(wxSocketModule)
2297 };
2298
2299 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
2300
2301 #endif
2302 // wxUSE_SOCKETS