]> git.saurik.com Git - wxWidgets.git/blob - src/common/socket.cpp
124df439516c5b8ad987efe05f941d27086c389f
[wxWidgets.git] / src / common / socket.cpp
1 ////////////////////////////////////////////////////////////////////////////////
2 // Name: socket.cpp
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux (completely rewritten from a basic API of Andrew
5 // Davidson(1995) in wxWeb)
6 // Created: April 1997
7 // Updated: March 1998
8 // Copyright: (C) 1998, 1997, Guilhem Lavaux
9 // RCS_ID: $Id$
10 // License: see wxWindows license
11 ////////////////////////////////////////////////////////////////////////////////
12 #ifdef __GNUG__
13 #pragma implementation "socket.h"
14 // #pragma interface
15 // #pragma implementation "socket.cpp"
16 #endif
17
18 #ifdef __MWERKS__
19 typedef int socklen_t ;
20 #endif
21
22 // For compilers that support precompilation, includes "wx.h".
23 #include "wx/wxprec.h"
24
25 #ifdef __BORLANDC__
26 #pragma hdrstop
27 #endif
28
29 /////////////////////////////////////////////////////////////////////////////
30 // wxWindows headers
31 /////////////////////////////////////////////////////////////////////////////
32 #include <wx/defs.h>
33 #include <wx/object.h>
34 #include <wx/string.h>
35 #include <wx/timer.h>
36 #include <wx/utils.h>
37
38 // Not enough OS behaviour defined for wxStubs
39 #ifndef __WXSTUBS__
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44
45 /////////////////////////////////////////////////////////////////////////////
46 // System specific headers
47 /////////////////////////////////////////////////////////////////////////////
48 #ifdef __WXMAC__
49 // in order to avoid problems with our c library and double definitions
50 #define close closesocket
51 #define ioctl ioctlsocket
52
53 #include <wx/mac/macsock.h>
54 extern GUSISpinFn GUSISpin;
55 #define PROCESS_EVENTS() wxMacProcessEvents()
56 const short kwxMacNetEventsMax = 1000 ;
57 short wxMacNetEventsTop = 0 ;
58 short wxMacNetEventsBottom = 0 ;
59 short wxMacNetEventsEvents[kwxMacNetEventsMax] ;
60 void *wxMacNetEventsReferences[kwxMacNetEventsMax] ;
61
62 #define FD_READ 1
63 #define FD_WRITE 2
64 #define FD_CLOSE 4
65 #define FD_ACCEPT 8
66 #define FD_CONNECT 16
67 #define FD_READY 32
68
69 extern "C" void wxMacSocketHandlerProc( void *refcon , short event ) ; // adds events
70 extern "C" void wxMacSocketOnRequestProc( void *refcon , short event ) ; // consumes them
71 extern "C" void GUSISetReference( short sock , short eventmask , void * data ) ;
72 void wxMacProcessEvents() ;
73 #endif
74
75 #if defined(__WINDOWS__)
76 #include <winsock.h>
77 #endif // __WINDOWS__
78
79 #if defined(__UNIX__)
80
81 #ifdef VMS
82 #include <socket.h>
83 #else
84 #include <sys/socket.h>
85 #endif
86 #include <sys/ioctl.h>
87
88 #include <sys/time.h>
89 #include <unistd.h>
90
91 #ifdef sun
92 #include <sys/filio.h>
93 #endif
94
95 #endif // __UNIX__
96
97 #include <signal.h>
98 #include <errno.h>
99
100 #ifdef _MSC_VER
101 #include <io.h>
102 #endif
103
104 #if defined(__WXMOTIF__) || defined(__WXXT__)
105 #include <X11/Intrinsic.h>
106
107 /////////////////////////////
108 // Needs internal variables
109 /////////////////////////////
110 #ifdef __WXXT__
111 #define Uses_XtIntrinsic
112 #endif
113
114 #endif
115
116 #if defined(__WXGTK__)
117 #include <gtk/gtk.h>
118 #endif
119
120 /////////////////////////////////////////////////////////////////////////////
121 // wxSocket headers
122 /////////////////////////////////////////////////////////////////////////////
123 #include "wx/module.h"
124 #define WXSOCK_INTERNAL
125 #include "wx/sckaddr.h"
126 #include "wx/socket.h"
127
128 /////////////////////////////////////////////////////////////////////////////
129 // Some patch ///// BEGIN
130 /////////////////////////////////////////////////////////////////////////////
131 #ifdef __WINDOWS__
132 #define close closesocket
133 #define ioctl ioctlsocket
134 #ifdef errno
135 #undef errno
136 #endif
137 #define errno WSAGetLastError()
138 #ifdef EWOULDBLOCK
139 #undef EWOULDBLOCK
140 #endif
141 #define EWOULDBLOCK WSAEWOULDBLOCK
142 #define ETIMEDOUT WSAETIMEDOUT
143 #undef EINTR
144 #define EINTR WSAEINTR
145 #endif
146
147 #ifndef __WINDOWS__
148 #define INVALID_SOCKET -1
149 #endif
150
151 #ifdef __WXMOTIF__
152 #define wxAPP_CONTEXT ((XtAppContext)wxTheApp->GetAppContext())
153 #endif
154
155 #ifdef __WINDOWS__
156 // This is an MS TCP/IP routine and is not needed here. Some WinSock
157 // implementations (such as PC-NFS) will require you to include this
158 // or a similar routine (see appendix in WinSock doc or help file).
159
160 #if defined( NEED_WSAFDIsSet ) || defined( _MSC_VER )
161 int PASCAL FAR __WSAFDIsSet(SOCKET fd, fd_set FAR *set)
162 {
163 int i = set->fd_count;
164
165 while (i--)
166 {
167 if (set->fd_array[i] == fd)
168 return 1;
169 }
170
171 return 0;
172 }
173 #endif
174 #endif
175
176 #if defined(__WINDOWS__)
177 #define PROCESS_EVENTS() wxYield()
178 #elif defined(__WXXT__) || defined(__WXMOTIF__)
179 #define PROCESS_EVENTS() XtAppProcessEvent(wxAPP_CONTEXT, XtIMAll)
180 #elif defined(__WXGTK__)
181 #define PROCESS_EVENTS() gtk_main_iteration()
182 #endif
183
184 /////////////////////////////////////////////////////////////////////////////
185 // Some patch ///// END
186 /////////////////////////////////////////////////////////////////////////////
187
188 // --------------------------------------------------------------
189 // Module
190 // --------------------------------------------------------------
191 class wxSocketModule: public wxModule
192 {
193 DECLARE_DYNAMIC_CLASS(wxSocketModule)
194 public:
195 wxSocketModule() {}
196 bool OnInit();
197 void OnExit();
198 };
199
200 // --------------------------------------------------------------
201 // ClassInfos
202 // --------------------------------------------------------------
203 #if !USE_SHARED_LIBRARY
204 IMPLEMENT_CLASS(wxSocketBase, wxObject)
205 IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
206 IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
207 IMPLEMENT_CLASS(wxSocketHandler, wxObject)
208 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
209 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
210 #endif
211
212 class wxSockWakeUp : public wxTimer
213 {
214 public:
215 int *my_id;
216 int n_val;
217 wxSocketBase *sock;
218
219 wxSockWakeUp(wxSocketBase *_sock, int *id, int new_val)
220 {
221 my_id = id; n_val = new_val;
222 sock = _sock;
223 }
224 virtual void Notify()
225 {
226 *my_id = n_val;
227 if (sock) sock->Notify(FALSE);
228 }
229 };
230
231 /// Socket request
232 class SockRequest : public wxObject
233 {
234 public:
235 char *buffer;
236 size_t size, nbytes;
237 bool done;
238 int error;
239 wxSockWakeUp *auto_wakeup;
240 wxSocketBase::wxRequestNotify type;
241 };
242
243
244 /////////////////////////////////////////////////////////////////////////////
245 // Some internal define
246 /////////////////////////////////////////////////////////////////////////////
247
248 // --------------------------------------------------------------
249 // --------- wxSocketBase CONSTRUCTOR ---------------------------
250 // --------------------------------------------------------------
251 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags,
252 wxSocketBase::wxSockType _type) :
253 wxEvtHandler(),
254 m_flags(_flags), m_type(_type), m_connected(FALSE), m_connecting(FALSE),
255 m_fd(INVALID_SOCKET), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
256 m_handler(0),
257 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
258 m_cbkon(FALSE),
259 m_unread(NULL), m_unrd_size(0),
260 m_processing(FALSE),
261 m_timeout(3600), m_wantbuf(0)
262 {
263 m_internal = new wxSockInternal;
264 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
265 m_internal->sock_inputid = 0;
266 m_internal->sock_outputid = 0;
267 m_internal->sock_exceptid = 0;
268 #endif
269 #ifdef __WINDOWS__
270 m_internal->my_msg = 0;
271 #endif
272 }
273
274 wxSocketBase::wxSocketBase() :
275 wxEvtHandler(),
276 m_flags(WAITALL), m_type(SOCK_UNINIT), m_connected(FALSE),
277 m_connecting(FALSE), m_fd(INVALID_SOCKET), m_waitflags(0),
278 m_cbk(0), m_cdata(0),
279 m_id(-1), m_handler(0),
280 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
281 m_cbkon(FALSE),
282 m_unread(NULL), m_unrd_size(0),
283 m_processing(FALSE),
284 m_timeout(3600), m_wantbuf(0)
285 {
286 m_internal = new wxSockInternal;
287 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
288 m_internal->sock_inputid = 0;
289 m_internal->sock_outputid = 0;
290 m_internal->sock_exceptid = 0;
291 #endif
292 #ifdef __WINDOWS__
293 m_internal->my_msg = 0;
294 #endif
295 }
296
297 // --------------------------------------------------------------
298 // wxSocketBase
299 // --------------------------------------------------------------
300
301 wxSocketBase::~wxSocketBase()
302 {
303 DestroyCallbacks();
304 Close();
305
306 if (m_unread)
307 free(m_unread);
308 if (m_handler)
309 {
310 #ifdef __WINDOWS__
311 if (m_internal->my_msg)
312 m_handler->DestroyMessage(m_internal->my_msg);
313 #endif
314 m_handler->UnRegister(this);
315 }
316 m_states.DeleteContents(TRUE);
317
318 delete m_internal;
319 }
320
321 bool wxSocketBase::Close()
322 {
323 if (m_fd != INVALID_SOCKET)
324 {
325 for (int i=0;i<3;i++)
326 {
327 wxNode *n, *node = req_list[i].First();
328
329 while (node)
330 {
331 SockRequest *req = (SockRequest *)node->Data();
332 req->done = TRUE;
333
334 n = node->Next();
335 delete node;
336 node = n;
337 }
338 }
339
340 DestroyCallbacks();
341 shutdown(m_fd, 2);
342 close(m_fd);
343 m_fd = INVALID_SOCKET;
344 m_connected = FALSE;
345 }
346
347 return TRUE;
348 }
349
350 // --------------------------------------------------------------
351 // wxSocketBase base IO function
352 // --------------------------------------------------------------
353
354 wxSocketBase& wxSocketBase::Read(char* buffer, size_t nbytes)
355 {
356 m_lcount = GetPushback(buffer, nbytes, FALSE);
357
358 // If we have got the whole needed buffer or if we don't want to
359 // wait then it returns immediately.
360 if (!nbytes || (m_lcount && !(m_flags & WAITALL)) )
361 return *this;
362
363 WantBuffer(buffer, nbytes, EVT_READ);
364
365 return *this;
366 }
367
368 wxSocketBase& wxSocketBase::Peek(char* buffer, size_t nbytes)
369 {
370 size_t nbytes_old = nbytes;
371
372 nbytes -= GetPushback(buffer, nbytes, TRUE);
373 if (!nbytes)
374 {
375 m_lcount = nbytes_old;
376 return *this;
377 }
378
379 WantBuffer(buffer, nbytes, EVT_PEEK);
380
381 return *this;
382 }
383
384 wxSocketBase& wxSocketBase::Write(const char *buffer, size_t nbytes)
385 {
386 WantBuffer((char *)buffer, nbytes, EVT_WRITE);
387 return *this;
388 }
389
390 wxSocketBase& wxSocketBase::ReadMsg(char* buffer, size_t nbytes)
391 {
392 SockMsg msg;
393 size_t len, len2, sig;
394
395 Read((char *)&msg, sizeof(msg));
396 if (m_lcount != sizeof(msg))
397 return *this;
398
399 sig = msg.sig[0] & 0xff;
400 sig |= (size_t)(msg.sig[1] & 0xff) << 8;
401 sig |= (size_t)(msg.sig[2] & 0xff) << 16;
402 sig |= (size_t)(msg.sig[3] & 0xff) << 24;
403
404 if (sig != 0xfeeddead)
405 return *this;
406 len = msg.len[0] & 0xff;
407 len |= (size_t)(msg.len[1] & 0xff) << 8;
408 len |= (size_t)(msg.len[2] & 0xff) << 16;
409 len |= (size_t)(msg.len[3] & 0xff) << 24;
410 len2 = len;
411 if (len > nbytes)
412 len = nbytes;
413 else
414 len2 = 0;
415
416 if (Read(buffer, len).LastCount() != len)
417 return *this;
418 if (len2 && (Read(NULL, len2).LastCount() != len2))
419 return *this;
420 if (Read((char *)&msg, sizeof(msg)).LastCount() != sizeof(msg))
421 return *this;
422
423 sig = msg.sig[0] & 0xff;
424 sig |= (size_t)(msg.sig[1] & 0xff) << 8;
425 sig |= (size_t)(msg.sig[2] & 0xff) << 16;
426 sig |= (size_t)(msg.sig[3] & 0xff) << 24;
427 // ERROR
428 if (sig != 0xdeadfeed)
429 return *this;
430
431 return *this;
432 }
433
434 wxSocketBase& wxSocketBase::WriteMsg(const char *buffer, size_t nbytes)
435 {
436 SockMsg msg;
437
438 msg.sig[0] = (char) 0xad;
439 msg.sig[1] = (char) 0xde;
440 msg.sig[2] = (char) 0xed;
441 msg.sig[3] = (char) 0xfe;
442
443 msg.len[0] = (char) nbytes & 0xff;
444 msg.len[1] = (char) (nbytes >> 8) & 0xff;
445 msg.len[2] = (char) (nbytes >> 16) & 0xff;
446 msg.len[3] = (char) (nbytes >> 24) & 0xff;
447
448 if (Write((char *)&msg, sizeof(msg)).LastCount() < sizeof(msg))
449 return *this;
450 if (Write(buffer, nbytes).LastCount() < nbytes)
451 return *this;
452
453 msg.sig[0] = (char) 0xed;
454 msg.sig[1] = (char) 0xfe;
455 msg.sig[2] = (char) 0xad;
456 msg.sig[3] = (char) 0xde;
457 msg.len[0] = msg.len[1] = msg.len[2] = msg.len[3] = (char) 0;
458 Write((char *)&msg, sizeof(msg));
459
460 return *this;
461 }
462
463 wxSocketBase& wxSocketBase::Unread(const char *buffer, size_t nbytes)
464 {
465 CreatePushbackAfter(buffer, nbytes);
466 return *this;
467 }
468
469 bool wxSocketBase::IsData() const
470 {
471 struct timeval tv;
472 fd_set sock_set;
473
474 if (m_fd < 0)
475 return FALSE;
476 if (m_unrd_size > 0)
477 return TRUE;
478
479 tv.tv_sec = 0;
480 tv.tv_usec = 0;
481 FD_ZERO(&sock_set);
482 FD_SET(m_fd, &sock_set);
483 select(FD_SETSIZE, &sock_set, NULL, NULL, &tv);
484 return (FD_ISSET(m_fd, &sock_set) != 0);
485 }
486
487 // ---------------------------------------------------------------------
488 // --------- wxSocketBase Discard(): deletes all byte in the input queue
489 // ---------------------------------------------------------------------
490 void wxSocketBase::Discard()
491 {
492 #define MAX_BUFSIZE (10*1024)
493 char *my_data = new char[MAX_BUFSIZE];
494 size_t recv_size = MAX_BUFSIZE;
495
496 SaveState();
497 SetFlags((wxSockFlags)(NOWAIT | SPEED));
498
499 while (recv_size == MAX_BUFSIZE)
500 {
501 recv_size = Read(my_data, MAX_BUFSIZE).LastCount();
502 }
503
504 RestoreState();
505 delete [] my_data;
506
507 #undef MAX_BUFSIZE
508 }
509
510 // If what? Who seems to need unsigned int?
511 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
512 // were, getpeername/getsockname don't take unsigned int*, they take int*.
513 #if 0
514 #define wxSOCKET_INT unsigned int
515 #else
516 #define wxSOCKET_INT int
517 #endif
518
519 // --------------------------------------------------------------
520 // wxSocketBase socket info functions
521 // --------------------------------------------------------------
522
523 bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
524 {
525 struct sockaddr my_addr;
526 wxSOCKET_INT len_addr = sizeof(my_addr);
527
528 if (m_fd < 0)
529 return FALSE;
530
531 if (getpeername(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0)
532 return FALSE;
533
534 addr_man.Disassemble(&my_addr, len_addr);
535 return TRUE;
536 }
537
538 bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
539 {
540 struct sockaddr my_addr;
541 wxSOCKET_INT len_addr = sizeof(my_addr);
542
543 if (m_fd < 0)
544 return FALSE;
545
546 if (getsockname(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0)
547
548 return FALSE;
549
550 addr_man.Disassemble(&my_addr, len_addr);
551 return TRUE;
552 }
553
554 // --------------------------------------------------------------
555 // wxSocketBase wait functions
556 // --------------------------------------------------------------
557
558 void wxSocketBase::SaveState()
559 {
560 wxSockState *state = new wxSockState;
561
562 state->cbk_on = m_cbkon;
563 state->cbk_set= m_neededreq;
564 state->cbk = m_cbk;
565 state->cdata = m_cdata;
566 state->flags = m_flags;
567 state->notif = m_notifyme;
568
569 m_states.Append(state);
570 }
571
572 void wxSocketBase::RestoreState()
573 {
574 wxNode *node;
575
576 node = m_states.Last();
577 if (!node)
578 return;
579
580 wxSockState *state = (wxSockState *)node->Data();
581
582 SetFlags(state->flags);
583 m_neededreq = state->cbk_set;
584 m_cbk = state->cbk;
585 m_cdata = state->cdata;
586 m_notifyme = state->notif;
587 if (state->cbk_on)
588 SetupCallbacks();
589 else
590 DestroyCallbacks();
591
592 delete node;
593 delete state;
594 }
595
596 // --------------------------------------------------------------
597 // --------- wxSocketBase wait functions ------------------------
598 // --------------------------------------------------------------
599
600 bool wxSocketBase::_Wait(long seconds, long microseconds, int type)
601 {
602 if ((!m_connected && !m_connecting) || m_fd < 0)
603 return FALSE;
604
605 wxSockWakeUp wakeup(this, &m_waitflags, 0);
606
607 SaveState();
608 SetNotify((wxRequestNotify)type);
609 SetupCallbacks();
610
611 if (seconds != -1)
612 wakeup.Start((int)(seconds*1000 + (microseconds / 1000)), TRUE);
613
614 m_waitflags = 0x80 | type;
615 while (m_waitflags & 0x80)
616 PROCESS_EVENTS();
617
618 RestoreState();
619
620 if (m_waitflags & 0x40)
621 {
622 m_waitflags = 0;
623 return TRUE;
624 }
625 m_waitflags = 0;
626
627 return FALSE;
628 }
629
630 bool wxSocketBase::Wait(long seconds, long microseconds)
631 {
632 return _Wait(seconds, microseconds, REQ_ACCEPT | REQ_CONNECT |
633 REQ_READ | REQ_WRITE | REQ_LOST);
634 }
635
636 bool wxSocketBase::WaitForRead(long seconds, long microseconds)
637 {
638 return _Wait(seconds, microseconds, REQ_READ | REQ_LOST);
639 }
640
641 bool wxSocketBase::WaitForWrite(long seconds, long microseconds)
642 {
643 return _Wait(seconds, microseconds, REQ_WRITE);
644 }
645
646 bool wxSocketBase::WaitForLost(long seconds, long microseconds)
647 {
648 return _Wait(seconds, microseconds, REQ_LOST);
649 }
650
651 // --------------------------------------------------------------
652 // --------- wxSocketBase callback management -------------------
653 // --------------------------------------------------------------
654
655 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
656 #if defined(__WXMOTIF__) || defined(__WXXT__)
657 static void wx_socket_read(XtPointer client, int *fid,
658 XtInputId *WXUNUSED(id))
659 #define fd *fid
660 #else
661 static void wx_socket_read(gpointer client, gint fd,
662 GdkInputCondition WXUNUSED(cond))
663 #define fd fd
664 #endif
665 {
666 wxSocketBase *sock = (wxSocketBase *)client;
667 char c;
668 int i;
669
670 i = recv(fd, &c, 1, MSG_PEEK);
671
672 if (i == -1 && (sock->NeededReq() & wxSocketBase::REQ_ACCEPT))
673 {
674 sock->OnRequest(wxSocketBase::EVT_ACCEPT);
675 return;
676 }
677
678 if (i != 0)
679 {
680 if (!(sock->NeededReq() & wxSocketBase::REQ_READ))
681 {
682 return;
683 }
684
685 sock->OnRequest(wxSocketBase::EVT_READ);
686 }
687 else
688 {
689 if (!(sock->NeededReq() & wxSocketBase::REQ_LOST))
690 {
691 sock->Close();
692 return;
693 }
694
695 sock->OnRequest(wxSocketBase::EVT_LOST);
696 }
697 }
698 #undef fd
699
700 #if defined(__WXMOTIF__) || defined(__WXXT__)
701 static void wx_socket_write(XtPointer client, int *WXUNUSED(fid),
702 XtInputId *WXUNUSED(id))
703 #else
704 static void wx_socket_write(gpointer client, gint WXUNUSED(fd),
705 GdkInputCondition WXUNUSED(cond))
706 #endif
707 {
708 wxSocketBase *sock = (wxSocketBase *)client;
709
710 if (!sock->IsConnected())
711 sock->OnRequest(wxSocketBase::EVT_CONNECT);
712 else
713 sock->OnRequest(wxSocketBase::EVT_WRITE);
714 }
715 #endif
716
717 #ifdef wx_xview
718 Notify_value wx_sock_read_xview (Notify_client client, int fd)
719 {
720 wxSocketBase *sock = (wxSocketBase *)client;
721 char c;
722 int i;
723
724 i = recv(fd, &c, 1, MSG_PEEK);
725
726 if (i == -1 && (sock->NeededReq() & wxSocketBase::REQ_ACCEPT))
727 {
728 sock->OnRequest(wxSocketBase::EVT_ACCEPT);
729 return;
730 }
731
732 /* Bytes arrived */
733 if (i != 0)
734 {
735 if (!(sock->NeededReq() & wxSocketBase::REQ_READ))
736 return (Notify_value) FALSE;
737
738 sock->OnRequest(wxSocketBase::EVT_READ);
739 }
740 else
741 {
742 if (!(sock->NeededReq() & wxSocketBase::REQ_LOST))
743 return;
744
745 sock->OnRequest(wxSocketBase::EVT_LOST);
746 }
747
748 return (Notify_value) FALSE;
749 }
750
751 Notify_value wx_sock_write_xview (Notify_client client, int fd)
752 {
753 wxSocketBase *sock = (wxSocketBase *)client;
754
755 if (!sock->IsConnected())
756 sock->OnRequest(wxSocketBase::EVT_CONNECT);
757 else
758 sock->OnRequest(wxSocketBase::EVT_WRITE);
759
760 return (Notify_value) TRUE;
761 }
762 #endif
763
764 wxSocketBase::wxRequestNotify wxSocketBase::EventToNotify(wxRequestEvent evt)
765 {
766 switch (evt)
767 {
768 case EVT_READ:
769 return REQ_READ;
770 case EVT_PEEK:
771 return REQ_PEEK;
772 case EVT_WRITE:
773 return REQ_WRITE;
774 case EVT_LOST:
775 return REQ_LOST;
776 case EVT_ACCEPT:
777 return REQ_ACCEPT;
778 case EVT_CONNECT:
779 return REQ_CONNECT;
780 }
781 return 0;
782 }
783
784 void wxSocketBase::SetFlags(wxSockFlags _flags)
785 {
786 m_flags = _flags;
787 if (_flags & SPEED)
788 {
789 unsigned long flag = 0;
790 ioctl(m_fd, FIONBIO, &flag);
791
792 // SPEED and WAITALL are antagonists.
793 m_flags = (wxSockFlags)(m_flags & ~WAITALL);
794
795 Notify(FALSE);
796 }
797 else
798 {
799 unsigned long flag = 1;
800 ioctl(m_fd, FIONBIO, &flag);
801 }
802 }
803
804 void wxSocketBase::SetNotify(wxRequestNotify flags)
805 {
806 wxRequestNotify old_needed_req = m_neededreq;
807 if (flags & REQ_ACCEPT)
808 {
809 /* Check if server */
810 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer))))
811 flags &= ~REQ_ACCEPT;
812 }
813 m_neededreq = flags;
814
815 /*
816 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
817 SetupCallbacks();
818 */
819
820 if (old_needed_req != flags)
821 SetupCallbacks();
822 }
823
824 void wxSocketBase::SetupCallbacks()
825 {
826 if (m_fd == INVALID_SOCKET || !m_handler || (m_flags & SPEED))
827 return;
828
829 #if defined(__WXMOTIF__) || defined(__WXXT__)
830 if (m_neededreq & (REQ_ACCEPT | REQ_READ | REQ_LOST))
831 {
832 if (m_internal->sock_inputid <= 0)
833 {
834 m_internal->sock_inputid = XtAppAddInput (wxAPP_CONTEXT, m_fd,
835 (XtPointer *) XtInputReadMask,
836 (XtInputCallbackProc) wx_socket_read,
837 }
838 }
839 else
840 {
841 if (m_internal->sock_inputid > 0)
842 {
843 XtRemoveInput(m_internal->sock_inputid);
844 m_internal->sock_inputid = 0;
845 }
846 }
847
848 if (m_neededreq & (REQ_CONNECT | REQ_WRITE))
849 {
850 if (m_internal->sock_outputid <= 0)
851 {
852 m_internal->sock_outputid = XtAppAddInput (wxAPP_CONTEXT, m_fd,
853 (XtPointer *) XtInputWriteMask,
854 (XtInputCallbackProc) wx_socket_write,
855 (XtPointer) this);
856 }
857 }
858 else
859 {
860 if (m_internal->sock_outputid > 0)
861 {
862 XtRemoveInput(m_internal->sock_outputid);
863 m_internal->sock_outputid = 0;
864 }
865 }
866 #endif
867
868
869 #ifdef __WXGTK__
870 if (m_neededreq & (REQ_ACCEPT | REQ_READ | REQ_LOST))
871 {
872 if (m_internal->sock_inputid <= 0)
873 {
874 m_internal->sock_inputid = gdk_input_add(m_fd, GDK_INPUT_READ,
875 wx_socket_read, (gpointer)this);
876 }
877 }
878 else
879 {
880 if (m_internal->sock_inputid > 0)
881 {
882 /*
883 gdk_input_remove(m_internal->sock_inputid);
884 m_internal->sock_inputid = 0;
885 */
886 }
887 }
888
889 if (m_neededreq & (REQ_CONNECT | REQ_WRITE))
890 {
891 if (m_internal->sock_outputid <= 0)
892 {
893 m_internal->sock_outputid = gdk_input_add(m_fd, GDK_INPUT_WRITE,
894 wx_socket_write, (gpointer)this);
895 }
896 }
897 else
898 {
899 if (m_internal->sock_outputid > 0)
900 {
901 /*
902 gdk_input_remove(m_internal->sock_outputid);
903 m_internal->sock_outputid = 0;
904 */
905 }
906 }
907 #endif
908
909
910 #ifdef __WXMSW__
911 WORD mask = 0;
912
913 if (m_neededreq & REQ_READ)
914 mask |= FD_READ;
915 if (m_neededreq & REQ_WRITE)
916 mask |= FD_WRITE;
917 if (m_neededreq & REQ_LOST)
918 mask |= FD_CLOSE;
919 if (m_neededreq & REQ_ACCEPT)
920 mask |= FD_ACCEPT;
921 if (m_neededreq & REQ_CONNECT)
922 mask |= FD_CONNECT;
923
924 if (!m_internal->my_msg)
925 m_internal->my_msg = m_handler->NewMessage(this);
926 WSAAsyncSelect(m_fd, m_handler->GetHWND(), m_internal->my_msg, mask);
927 #endif
928 #ifdef __WXMAC__
929 short mask = 0;
930
931 if (m_neededreq & REQ_READ)
932 mask |= FD_READ;
933 if (m_neededreq & REQ_WRITE)
934 mask |= FD_WRITE;
935 if (m_neededreq & REQ_LOST)
936 mask |= FD_CLOSE;
937 if (m_neededreq & REQ_ACCEPT)
938 mask |= FD_ACCEPT;
939 if (m_neededreq & REQ_CONNECT)
940 mask |= FD_CONNECT;
941
942 GUSISetReference( m_fd ,mask, this ) ;
943 unsigned long flag = 1;
944 ioctl(m_fd, FIONBIO, &flag);
945 #endif
946 m_cbkon = TRUE;
947 m_processing = FALSE;
948 }
949
950 void wxSocketBase::DestroyCallbacks()
951 {
952 if (!m_cbkon || !m_handler)
953 return;
954
955 m_cbkon = FALSE;
956 m_processing = FALSE;
957 #if defined(__WXMOTIF__) || defined(__WXXT__)
958 if (m_internal->sock_inputid > 0)
959 XtRemoveInput(m_internal->sock_inputid);
960 m_internal->sock_inputid = 0;
961 if (m_internal->sock_outputid > 0)
962 XtRemoveInput(m_internal->sock_outputid);
963 m_internal->sock_outputid = 0;
964 #endif
965 #ifdef __WXGTK__
966 if (m_internal->sock_inputid > 0)
967 gdk_input_remove(m_internal->sock_inputid);
968 m_internal->sock_inputid = 0;
969 if (m_internal->sock_outputid > 0)
970 gdk_input_remove(m_internal->sock_outputid);
971 m_internal->sock_outputid = 0;
972 #endif
973 #ifdef __WINDOWS__
974 WSAAsyncSelect(m_fd, m_handler->GetHWND(), 0, 0);
975 #endif
976 #ifdef __WXMAC__
977 GUSISetReference( m_fd , 0 , 0 ) ;
978 int bottom = wxMacNetEventsBottom ;
979 while ( wxMacNetEventsTop != bottom )
980 {
981 // set all events that reference this socket to nil
982 if ( wxMacNetEventsReferences[bottom] == (void*) this )
983 wxMacNetEventsReferences[bottom] = NULL ;
984 bottom++ ;
985 if ( bottom == kwxMacNetEventsMax )
986 bottom = 0 ;
987 }
988 SetFlags( m_flags ) ;
989 #endif
990 }
991
992 void wxSocketBase::Notify(bool notify)
993 {
994 if (m_notifyme == notify)
995 return;
996 if (notify)
997 SetupCallbacks();
998 else
999 DestroyCallbacks();
1000 m_notifyme = notify;
1001 }
1002
1003 void wxSocketBase::OnRequest(wxRequestEvent req_evt)
1004 {
1005 wxRequestNotify req_notif = EventToNotify(req_evt);
1006
1007 // Mask the current event
1008 SetNotify(m_neededreq & ~req_notif);
1009
1010 if (req_evt <= EVT_WRITE && DoRequests(req_evt))
1011 return;
1012
1013 if (m_waitflags & 0xF0)
1014 {
1015 // Wake up
1016 if ((m_waitflags & 0x0F) == req_evt)
1017 {
1018 m_waitflags = 0x80;
1019 #ifndef __WXGTK__
1020 DestroyCallbacks();
1021 #endif
1022 }
1023 return;
1024 }
1025
1026 if (req_evt == EVT_LOST)
1027 {
1028 m_connected = FALSE;
1029 Close();
1030 }
1031 if (m_notifyme)
1032 OldOnNotify(req_evt);
1033
1034 // Unmask
1035 SetNotify(m_neededreq | req_notif);
1036 }
1037
1038 wxSocketEvent::wxSocketEvent(int id)
1039 : wxEvent(id)
1040 {
1041 wxEventType type = (wxEventType)wxEVT_SOCKET;
1042
1043 SetEventType(type);
1044 }
1045
1046 void wxSocketBase::OldOnNotify(wxRequestEvent evt)
1047 {
1048 wxSocketEvent event(m_id);
1049
1050 event.SetEventObject(this);
1051 event.m_skevt = evt;
1052 ProcessEvent(event);
1053
1054 if (m_cbk)
1055 m_cbk(*this, evt, m_cdata);
1056 }
1057
1058 // --------------------------------------------------------------
1059 // --------- wxSocketBase functions [Callback, CallbackData] ----
1060 // --------------------------------------------------------------
1061
1062 wxSocketBase::wxSockCbk wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk)
1063 {
1064 wxSockCbk old_cbk = m_cbk;
1065
1066 m_cbk = _cbk;
1067 return old_cbk;
1068 }
1069
1070 char *wxSocketBase::CallbackData(char *cdata_)
1071 {
1072 char *old_cdata = m_cdata;
1073
1074 m_cdata = cdata_;
1075 return old_cdata;
1076 }
1077
1078 void wxSocketBase::SetEventHandler(wxEvtHandler& h_evt, int id)
1079 {
1080 SetNextHandler(&h_evt);
1081 m_id = id;
1082 }
1083
1084 // --------------------------------------------------------------
1085 // --------- wxSocketBase pushback library ----------------------
1086 // --------------------------------------------------------------
1087
1088 void wxSocketBase::CreatePushbackAfter(const char *buffer, size_t size)
1089 {
1090 char *curr_pos;
1091
1092 m_unread = (char *) realloc(m_unread, m_unrd_size+size);
1093 curr_pos = m_unread + m_unrd_size;
1094
1095 memcpy(curr_pos, buffer, size);
1096 m_unrd_size += size;
1097 }
1098
1099 void wxSocketBase::CreatePushbackBefore(const char *buffer, size_t size)
1100 {
1101 char *curr_pos, *new_buf;
1102
1103 new_buf = (char *) malloc(m_unrd_size+size);
1104 curr_pos = new_buf + size;
1105
1106 memcpy(new_buf, buffer, size);
1107 memcpy(curr_pos, m_unread, m_unrd_size);
1108
1109 free(m_unread);
1110 m_unread = new_buf;
1111 m_unrd_size += size;
1112 }
1113
1114 size_t wxSocketBase::GetPushback(char *buffer, size_t size, bool peek)
1115 {
1116 if (!m_unrd_size)
1117 return 0;
1118
1119 if (size > m_unrd_size)
1120 size = m_unrd_size;
1121 memcpy(buffer, m_unread, size);
1122
1123 if (!peek) {
1124 m_unrd_size -= size;
1125 if (!m_unrd_size) {
1126 free(m_unread);
1127 m_unread = NULL;
1128 }
1129 }
1130
1131 return size;
1132 }
1133
1134 // --------------------------------------------------------------
1135 // --------- wxSocketBase "multi-thread" core -------------------
1136 // --------------------------------------------------------------
1137
1138 bool wxSocketBase::DoRequests(wxRequestEvent req_flag)
1139 {
1140 wxNode *node = req_list[req_flag].First();
1141 size_t len;
1142 int ret;
1143
1144 if (!node)
1145 return FALSE;
1146
1147 SockRequest *req = (SockRequest *)node->Data();
1148
1149 delete node;
1150
1151 switch (req->type)
1152 {
1153 case EVT_READ:
1154 case EVT_PEEK:
1155 ret = recv(m_fd, req->buffer, req->size,
1156 (req->type == EVT_PEEK) ? MSG_PEEK : 0);
1157 if (ret < 0)
1158 {
1159 req->error = errno;
1160 req->done = TRUE;
1161 break;
1162 }
1163 len = ret;
1164 if ((len < req->size) && (m_flags & WAITALL))
1165 {
1166 req->size -= len;
1167 req->nbytes += len;
1168 req->buffer += len;
1169 req->auto_wakeup->Start(m_timeout*1000, TRUE);
1170 req_list[req_flag].Insert(req);
1171 break;
1172 }
1173 req->done = TRUE;
1174 req->nbytes += len;
1175 #ifndef __WXGTK__
1176 DestroyCallbacks();
1177 #endif
1178 break;
1179 case EVT_WRITE:
1180 ret = send(m_fd, req->buffer, req->size, 0);
1181 if (ret < 0)
1182 {
1183 req->error = errno;
1184 req->done = TRUE;
1185 break;
1186 }
1187 len = ret;
1188 if ((len < req->size) && (m_flags & WAITALL))
1189 {
1190 req->size -= len;
1191 req->nbytes += len;
1192 req->buffer += len;
1193 req->auto_wakeup->Start(m_timeout*1000, TRUE);
1194 req_list[req_flag].Insert(req);
1195 break;
1196 }
1197 req->done = TRUE;
1198 req->nbytes += len;
1199 #ifndef __WXGTK__
1200 DestroyCallbacks();
1201 #endif
1202 break;
1203 default:
1204 return FALSE;
1205 }
1206 return TRUE;
1207 }
1208
1209 void wxSocketBase::WantSpeedBuffer(char *buffer, size_t nbytes,
1210 wxRequestEvent evt)
1211 {
1212 int ret = 0;
1213
1214 switch (evt)
1215 {
1216 case EVT_PEEK:
1217 case EVT_READ:
1218 ret = recv(m_fd, buffer, nbytes,
1219 (evt == EVT_PEEK) ? MSG_PEEK : 0);
1220 break;
1221 case EVT_WRITE:
1222 ret = send(m_fd, buffer, nbytes, 0);
1223 break;
1224 }
1225 if (ret < 0)
1226 {
1227 m_lcount = 0;
1228 m_error = errno;
1229 }
1230 else
1231 {
1232 m_lcount = ret;
1233 m_error = 0;
1234 }
1235 }
1236
1237 void wxSocketBase::WantBuffer(char *buffer, size_t nbytes,
1238 wxRequestEvent evt)
1239 {
1240 bool buf_timed_out;
1241
1242 if (m_fd == INVALID_SOCKET || !m_handler || !m_connected)
1243 return;
1244
1245 if (m_flags & SPEED)
1246 {
1247 WantSpeedBuffer(buffer, nbytes, evt);
1248 return;
1249 }
1250
1251 SockRequest *buf = new SockRequest;
1252 wxSockWakeUp s_wake(NULL, (int *)&buf_timed_out, (int)TRUE);
1253
1254 m_wantbuf++;
1255 req_list[evt].Append(buf);
1256
1257 SaveState();
1258 SetNotify(REQ_LOST | EventToNotify(evt));
1259 SetupCallbacks();
1260 buf->buffer = buffer;
1261 buf->size = nbytes;
1262 buf->done = FALSE;
1263 buf->type = evt;
1264 buf->nbytes = 0;
1265 buf->auto_wakeup = &s_wake;
1266 buf->error = 0;
1267 buf_timed_out = FALSE;
1268
1269 s_wake.Start(m_timeout*1000, TRUE);
1270 if (m_flags & NOWAIT)
1271 {
1272 DoRequests(evt);
1273 }
1274 else
1275 {
1276 while (!buf->done && !buf_timed_out)
1277 PROCESS_EVENTS();
1278 }
1279 m_wantbuf--;
1280 m_lcount = buf->nbytes;
1281 if (buf_timed_out)
1282 m_error = ETIMEDOUT;
1283 else
1284 m_error = buf->error;
1285
1286 delete buf;
1287 RestoreState();
1288 }
1289
1290 // --------------------------------------------------------------
1291 // wxSocketServer
1292 // --------------------------------------------------------------
1293
1294 wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
1295 wxSockFlags flags) :
1296 wxSocketBase(flags, SOCK_SERVER)
1297 {
1298 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
1299
1300 if (m_fd == INVALID_SOCKET)
1301 return;
1302
1303 int flag = 1;
1304 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int));
1305
1306 struct sockaddr *myaddr;
1307 size_t len;
1308
1309 addr_man.Build(myaddr, len);
1310 if (bind(m_fd, myaddr, addr_man.SockAddrLen()) < 0)
1311 return;
1312
1313 if (listen(m_fd, 5) < 0) {
1314 m_fd = INVALID_SOCKET;
1315 return;
1316 }
1317 }
1318
1319 // --------------------------------------------------------------
1320 // wxSocketServer Accept
1321 // --------------------------------------------------------------
1322
1323 bool wxSocketServer::AcceptWith(wxSocketBase& sock)
1324 {
1325 int fd2;
1326
1327 if ((fd2 = accept(m_fd, 0, 0)) < 0)
1328 return FALSE;
1329
1330 struct linger linger;
1331 linger.l_onoff = 0;
1332 linger.l_linger = 1;
1333
1334 setsockopt(fd2, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
1335
1336 int flag = 0;
1337 setsockopt(fd2, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
1338
1339 if (!(sock.m_flags & SPEED))
1340 {
1341 unsigned long flag2 = 1;
1342 ioctl(fd2, FIONBIO, &flag2);
1343 }
1344
1345 sock.m_type = SOCK_INTERNAL;
1346 sock.m_fd = fd2;
1347 sock.m_connected = TRUE;
1348
1349 return TRUE;
1350 }
1351
1352 wxSocketBase *wxSocketServer::Accept()
1353 {
1354 wxSocketBase* sock = new wxSocketBase();
1355
1356 sock->SetFlags((wxSockFlags)m_flags);
1357
1358 if (!AcceptWith(*sock))
1359 return NULL;
1360
1361 if (m_handler)
1362 m_handler->Register(sock);
1363
1364 return sock;
1365 }
1366
1367 // --------------------------------------------------------------
1368 // wxSocketServer callbacks
1369 // --------------------------------------------------------------
1370
1371 void wxSocketServer::OnRequest(wxRequestEvent evt)
1372 {
1373 if (evt == EVT_ACCEPT)
1374 {
1375 OldOnNotify(EVT_ACCEPT);
1376 }
1377 }
1378
1379 // --------------------------------------------------------------
1380 // wxSocketClient
1381 // --------------------------------------------------------------
1382
1383 // --------- wxSocketClient CONSTRUCTOR -------------------------
1384 // --------------------------------------------------------------
1385 wxSocketClient::wxSocketClient(wxSockFlags _flags) :
1386 wxSocketBase(_flags, SOCK_CLIENT)
1387 {
1388 }
1389
1390 // --------------------------------------------------------------
1391 // --------- wxSocketClient DESTRUCTOR --------------------------
1392 // --------------------------------------------------------------
1393 wxSocketClient::~wxSocketClient()
1394 {
1395 }
1396
1397 // --------------------------------------------------------------
1398 // --------- wxSocketClient Connect functions -------------------
1399 // --------------------------------------------------------------
1400 bool wxSocketClient::Connect(wxSockAddress& addr_man, bool WXUNUSED(wait) )
1401 {
1402 struct linger linger;
1403
1404 if (IsConnected())
1405 Close();
1406
1407 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
1408
1409 if (m_fd < 0)
1410 return FALSE;
1411
1412 m_connected = FALSE;
1413
1414 linger.l_onoff = 1;
1415 linger.l_linger = 5;
1416 setsockopt(m_fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
1417
1418 // Stay in touch with the state of things...
1419
1420 unsigned long flag = 1;
1421 setsockopt(m_fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
1422
1423 // Disable the nagle algorithm, which delays sends till the
1424 // buffer is full (or a certain time period has passed?)...
1425
1426 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1427 flag = 1;
1428 setsockopt(m_fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int));
1429 #endif
1430
1431 struct sockaddr *remote;
1432 size_t len;
1433
1434 addr_man.Build(remote, len);
1435
1436 if (connect(m_fd, remote, len) != 0)
1437 return FALSE;
1438
1439 if (!(m_flags & SPEED))
1440 {
1441 flag = 1;
1442 ioctl(m_fd, FIONBIO, &flag);
1443 }
1444
1445 Notify(TRUE);
1446
1447 m_connected = TRUE;
1448 return TRUE;
1449 }
1450
1451 bool wxSocketClient::WaitOnConnect(long seconds, long microseconds)
1452 {
1453 int ret = _Wait(seconds, microseconds, REQ_CONNECT | REQ_LOST);
1454
1455 if (ret)
1456 m_connected = TRUE;
1457
1458 return m_connected;
1459 }
1460
1461 void wxSocketClient::OnRequest(wxRequestEvent evt)
1462 {
1463 if (evt == EVT_CONNECT)
1464 {
1465 if (m_connected)
1466 {
1467 #ifndef __WXGTK__
1468 SetNotify(m_neededreq & ~REQ_CONNECT);
1469 #endif
1470 return;
1471 }
1472 m_waitflags = 0x40;
1473 m_connected = TRUE;
1474 OldOnNotify(EVT_CONNECT);
1475 #ifndef __WXGTK__
1476 DestroyCallbacks();
1477 #endif
1478 return;
1479 }
1480 wxSocketBase::OnRequest(evt);
1481 }
1482
1483 /////////////////////////////////////////////////////////////////
1484 // wxSocketHandler ///////////////////////////////////////////////
1485 /////////////////////////////////////////////////////////////////
1486
1487 wxSocketHandler *wxSocketHandler::master = NULL;
1488 #if defined(__WINDOWS__)
1489 static int win_initialized = 0;
1490 #endif
1491
1492 // --------------------------------------------------------------
1493 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1494 // --------------------------------------------------------------
1495 #ifdef __WXMAC__
1496
1497 extern "C" int updatestatus(int s) ;
1498
1499 void wxMacSocketOnRequestProc( void *refcon , short event )
1500 {
1501 if ( refcon )
1502 {
1503 wxSocketBase *sock = (wxSocketBase *) refcon ;
1504
1505 wxSocketBase::wxRequestEvent sk_req;
1506
1507 int canRead ;
1508 int canWrite ;
1509 int exception ;
1510
1511 switch (event) {
1512 case FD_READ:
1513 sk_req = wxSocketBase::EVT_READ;
1514 sock->OnRequest(sk_req);
1515 break;
1516 case FD_WRITE:
1517 sk_req = wxSocketBase::EVT_WRITE;
1518 sock->OnRequest(sk_req);
1519 break;
1520 case FD_CLOSE:
1521 sk_req = wxSocketBase::EVT_LOST;
1522 sock->OnRequest(sk_req);
1523 break;
1524 case FD_ACCEPT:
1525 sk_req = wxSocketBase::EVT_ACCEPT;
1526 sock->OnRequest(sk_req);
1527 break;
1528 case FD_CONNECT:
1529 sk_req = wxSocketBase::EVT_CONNECT;
1530 sock->OnRequest(sk_req);
1531 break;
1532 case FD_READY :
1533 break ;
1534 }
1535 updatestatus ( sock->m_fd ) ;
1536 }
1537 }
1538
1539 void wxMacSocketHandlerProc( void *refcon , short event )
1540 {
1541 wxMacNetEventsReferences[wxMacNetEventsTop] = refcon ;
1542 wxMacNetEventsEvents[wxMacNetEventsTop] = event ;
1543
1544 // clumsy construct in order to never have a incorrect wxMacNetEventsTop (above limits)
1545
1546 if ( wxMacNetEventsTop + 1 == kwxMacNetEventsMax )
1547 wxMacNetEventsTop = 0 ;
1548 else
1549 wxMacNetEventsTop++ ;
1550 }
1551
1552 #endif
1553 #ifdef __WINDOWS__
1554
1555 extern char wxPanelClassName[];
1556
1557 LRESULT APIENTRY _EXPORT wxSocketHandlerWndProc(HWND hWnd, UINT message,
1558 WPARAM wParam, LPARAM lParam)
1559 {
1560 if(message==WM_DESTROY)
1561 {
1562 ::SetWindowLong(hWnd, GWL_WNDPROC, (LONG) DefWindowProc);
1563 return DefWindowProc(hWnd, message, wParam, lParam);
1564 }
1565 wxSocketHandler *h_sock = (wxSocketHandler *)GetWindowLong(hWnd, GWL_USERDATA);
1566 wxNode *node = h_sock->smsg_list->Find(message);
1567 wxSocketBase *sock;
1568 wxSocketBase::wxRequestEvent sk_req;
1569 UINT event = WSAGETSELECTEVENT(lParam);
1570
1571 if (!node)
1572 return DefWindowProc(hWnd, message, wParam, lParam);
1573
1574 sock = (wxSocketBase *)node->Data();
1575
1576 switch (event) {
1577 case FD_READ:
1578 sk_req = wxSocketBase::EVT_READ;
1579 break;
1580 case FD_WRITE:
1581 sk_req = wxSocketBase::EVT_WRITE;
1582 break;
1583 case FD_CLOSE:
1584 sk_req = wxSocketBase::EVT_LOST;
1585 break;
1586 case FD_ACCEPT:
1587 sk_req = wxSocketBase::EVT_ACCEPT;
1588 break;
1589 case FD_CONNECT:
1590 sk_req = wxSocketBase::EVT_CONNECT;
1591 break;
1592 }
1593 sock->OnRequest(sk_req);
1594
1595 return (LRESULT)0;
1596 }
1597
1598 FARPROC wxSocketSubClassProc = NULL;
1599
1600 #endif
1601
1602 wxSocketHandler::wxSocketHandler()
1603 {
1604 #if defined(__WINDOWS__)
1605 if (!win_initialized)
1606 {
1607 WSADATA wsaData;
1608
1609 WSAStartup((1 << 8) | 1, &wsaData);
1610 win_initialized = 1;
1611 }
1612 internal = new wxSockHandlerInternal;
1613 internal->sockWin = ::CreateWindow(wxPanelClassName, NULL, 0,
1614 0, 0, 0, 0, NULL, (HMENU) NULL,
1615 wxhInstance, 0);
1616
1617 // Subclass the window
1618 if (!wxSocketSubClassProc)
1619 wxSocketSubClassProc = MakeProcInstance((FARPROC) wxSocketHandlerWndProc, wxhInstance);
1620 ::SetWindowLong(internal->sockWin, GWL_WNDPROC, (LONG) wxSocketSubClassProc);
1621 ::SetWindowLong(internal->sockWin, GWL_USERDATA, (LONG) this);
1622
1623 internal->firstAvailableMsg = 5000;
1624 smsg_list = new wxList(wxKEY_INTEGER);
1625 #endif
1626
1627 socks = new wxList;
1628
1629 #ifndef __WINDOWS__
1630 signal(SIGPIPE, SIG_IGN);
1631 #endif
1632 }
1633
1634 // --------------------------------------------------------------
1635 // --------- wxSocketHandler DESTRUCTOR -------------------------
1636 // --------------------------------------------------------------
1637 wxSocketHandler::~wxSocketHandler()
1638 {
1639 wxNode *next_node, *node = socks->First();
1640
1641 while (node)
1642 {
1643 wxSocketBase* sock = (wxSocketBase*)node->Data();
1644
1645 delete sock;
1646 next_node = node->Next();
1647 delete node;
1648 node = next_node;
1649 }
1650
1651 delete socks;
1652
1653 #ifdef __WINDOWS__
1654 delete smsg_list;
1655
1656 ::DestroyWindow(internal->sockWin);
1657 WSACleanup();
1658 win_initialized = 0;
1659
1660 delete internal;
1661 #endif
1662 }
1663
1664 // --------------------------------------------------------------
1665 // --------- wxSocketHandler registering functions --------------
1666 // --------------------------------------------------------------
1667
1668 void wxSocketHandler::Register(wxSocketBase* sock)
1669 {
1670 wxNode *node;
1671
1672 for (node = socks->First(); node != NULL; node = node->Next())
1673 {
1674 wxSocketBase* s = (wxSocketBase*)node->Data();
1675
1676 if (s == sock)
1677 return;
1678 }
1679
1680 if (sock)
1681 {
1682 socks->Append(sock);
1683 sock->SetHandler(this);
1684 sock->SetupCallbacks();
1685 }
1686 }
1687
1688 void wxSocketHandler::UnRegister(wxSocketBase* sock)
1689 {
1690 wxNode *node;
1691
1692 for (node = socks->First(); node; node = node->Next())
1693 {
1694 wxSocketBase* s = (wxSocketBase*)node->Data();
1695
1696 if (s == sock)
1697 {
1698 delete node;
1699 sock->DestroyCallbacks();
1700 sock->SetHandler(NULL);
1701 return;
1702 }
1703 }
1704 }
1705
1706 unsigned long wxSocketHandler::Count() const
1707 {
1708 return socks->Number();
1709 }
1710
1711 // --------------------------------------------------------------
1712 // --------- wxSocketHandler "big" wait functions ---------------
1713 // --------------------------------------------------------------
1714 void handler_cbk(wxSocketBase& sock,
1715 wxSocketBase::wxRequestEvent WXUNUSED(flags),
1716 char *cdata)
1717 {
1718 int *a_wait = (int *)cdata;
1719
1720 (*a_wait)++;
1721 sock.Notify(FALSE);
1722 }
1723
1724 int wxSocketHandler::Wait(long seconds, long microseconds)
1725 {
1726 int i;
1727 int on_wait;
1728 wxSockWakeUp s_wake(NULL, &on_wait, -2);
1729 wxNode *node;
1730
1731 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1732 {
1733 wxSocketBase *sock = (wxSocketBase *)node->Data();
1734
1735 sock->SaveState();
1736
1737 sock->SetupCallbacks();
1738
1739 sock->Callback(handler_cbk);
1740 sock->CallbackData((char *)&on_wait);
1741 }
1742 on_wait = 0;
1743 if (seconds != -1)
1744 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1745
1746 while (!on_wait)
1747 PROCESS_EVENTS();
1748
1749 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1750 {
1751 wxSocketBase *sock = (wxSocketBase *)node->Data();
1752
1753 sock->RestoreState();
1754 }
1755
1756 if (on_wait == -2)
1757 return 0;
1758
1759 return on_wait;
1760 }
1761
1762 void wxSocketHandler::YieldSock()
1763 {
1764 wxNode *node;
1765
1766 for (node = socks->First(); node; node = node->Next() )
1767 {
1768 wxSocketBase *sock = (wxSocketBase *)node->Data();
1769
1770 sock->SaveState();
1771
1772 sock->SetFlags(wxSocketBase::SPEED);
1773 if (sock->IsData())
1774 sock->DoRequests(wxSocketBase::EVT_READ);
1775 sock->DoRequests(wxSocketBase::EVT_WRITE);
1776
1777 sock->RestoreState();
1778 }
1779 }
1780
1781 // --------------------------------------------------------------
1782 // --------- wxSocketHandler: create and register the socket ----
1783 // --------------------------------------------------------------
1784 wxSocketServer *wxSocketHandler::CreateServer(wxSockAddress& addr,
1785 wxSocketBase::wxSockFlags flags)
1786 {
1787 wxSocketServer *serv = new wxSocketServer(addr, flags);
1788
1789 Register(serv);
1790 return serv;
1791 }
1792
1793 wxSocketClient *wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags)
1794 {
1795 wxSocketClient *client = new wxSocketClient(flags);
1796
1797 Register(client);
1798 return client;
1799 }
1800
1801 #ifdef __WINDOWS__
1802 // --------------------------------------------------------------
1803 // --------- wxSocketHandler: Windows specific methods ----------
1804 // --------------------------------------------------------------
1805
1806 UINT wxSocketHandler::NewMessage(wxSocketBase *sock)
1807 {
1808 internal->firstAvailableMsg++;
1809 smsg_list->Append(internal->firstAvailableMsg, sock);
1810 return internal->firstAvailableMsg;
1811 }
1812
1813 void wxSocketHandler::DestroyMessage(UINT msg)
1814 {
1815 wxNode *node = smsg_list->Find(msg);
1816 delete node;
1817 }
1818
1819 HWND wxSocketHandler::GetHWND() const
1820 {
1821 return internal->sockWin;
1822 }
1823
1824 #endif
1825
1826 bool wxSocketModule::OnInit()
1827 {
1828 wxSocketHandler::master = new wxSocketHandler();
1829 return TRUE;
1830 }
1831
1832 void wxSocketModule::OnExit()
1833 {
1834 delete wxSocketHandler::master;
1835 wxSocketHandler::master = NULL;
1836 }
1837
1838 #ifdef __WXMAC__
1839 void wxMacProcessSocketEvents() ;
1840 void wxMacProcessEvents()
1841 {
1842 wxMacProcessSocketEvents() ;
1843 (*GUSISpin)(SP_MISC, 0) ;
1844 }
1845
1846 void wxMacProcessSocketEvents()
1847 {
1848 while ( wxMacNetEventsTop != wxMacNetEventsBottom )
1849 {
1850 // consume event at wxMacNetEventsBottom
1851 wxMacSocketOnRequestProc(wxMacNetEventsReferences[wxMacNetEventsBottom] , wxMacNetEventsEvents[wxMacNetEventsBottom] ) ;
1852 wxMacNetEventsBottom++ ;
1853 if ( wxMacNetEventsBottom == kwxMacNetEventsMax )
1854 wxMacNetEventsBottom = 0 ;
1855 }
1856 }
1857 #endif
1858
1859 #endif
1860 // __WXSTUBS__