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