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