]> git.saurik.com Git - wxWidgets.git/blame - src/common/socket.cpp
Added (untested) support for sub-locales.
[wxWidgets.git] / src / common / socket.cpp
CommitLineData
f4ada568
GL
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////////////////////////////////////////////////////////////////////////////////
384b4373 12#ifdef __GNUG__
f4ada568 13#pragma implementation "socket.h"
0c32066b
JS
14// #pragma interface
15// #pragma implementation "socket.cpp"
f4ada568
GL
16#endif
17
17dff81c
SC
18#ifdef __MWERKS__
19typedef int socklen_t ;
20#endif
21
fcc6dddd
JS
22// For compilers that support precompilation, includes "wx.h".
23#include "wx/wxprec.h"
24
25#ifdef __BORLANDC__
26#pragma hdrstop
27#endif
28
f4ada568
GL
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
7f555861
JS
38// Not enough OS behaviour defined for wxStubs
39#ifndef __WXSTUBS__
40
f4ada568
GL
41#include <stdlib.h>
42#include <string.h>
43#include <ctype.h>
44
45/////////////////////////////////////////////////////////////////////////////
46// System specific headers
47/////////////////////////////////////////////////////////////////////////////
17dff81c
SC
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>
54extern GUSISpinFn GUSISpin;
55#define PROCESS_EVENTS() wxMacProcessEvents()
56const short kwxMacNetEventsMax = 1000 ;
57short wxMacNetEventsTop = 0 ;
58short wxMacNetEventsBottom = 0 ;
59short wxMacNetEventsEvents[kwxMacNetEventsMax] ;
60void *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
69extern "C" void wxMacSocketHandlerProc( void *refcon , short event ) ; // adds events
70extern "C" void wxMacSocketOnRequestProc( void *refcon , short event ) ; // consumes them
71extern "C" void GUSISetReference( short sock , short eventmask , void * data ) ;
72void wxMacProcessEvents() ;
73#endif
74
f4ada568
GL
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
384b4373
RD
91#ifdef sun
92#include <sys/filio.h>
93#endif
94
f4ada568
GL
95#endif // __UNIX__
96
97#include <signal.h>
98#include <errno.h>
99
fcc6dddd
JS
100#ifdef _MSC_VER
101#include <io.h>
102#endif
103
f4ada568
GL
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/////////////////////////////////////////////////////////////////////////////
3b4183d8 123#include "wx/module.h"
f4ada568
GL
124#define WXSOCK_INTERNAL
125#include "wx/sckaddr.h"
126#include "wx/socket.h"
127
f4ada568
GL
128/////////////////////////////////////////////////////////////////////////////
129// Some patch ///// BEGIN
130/////////////////////////////////////////////////////////////////////////////
131#ifdef __WINDOWS__
132#define close closesocket
133#define ioctl ioctlsocket
0c32066b
JS
134#ifdef errno
135#undef errno
136#endif
f4ada568
GL
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__
46ccb510 152#define wxAPP_CONTEXT ((XtAppContext)wxTheApp->GetAppContext())
f4ada568
GL
153#endif
154
155#ifdef __WINDOWS__
156// This is an MS TCP/IP routine and is not needed here. Some WinSock
157// implementations (such as PC-NFS) will require you to include this
158// or a similar routine (see appendix in WinSock doc or help file).
159
160#if defined( NEED_WSAFDIsSet ) || defined( _MSC_VER )
161int PASCAL FAR __WSAFDIsSet(SOCKET fd, fd_set FAR *set)
162{
17dff81c 163 int i = set->fd_count;
f4ada568 164
17dff81c
SC
165 while (i--)
166 {
167 if (set->fd_array[i] == fd)
168 return 1;
169 }
f4ada568 170
17dff81c 171 return 0;
f4ada568
GL
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__)
8c14576d 181#define PROCESS_EVENTS() gtk_main_iteration()
f4ada568
GL
182#endif
183
184/////////////////////////////////////////////////////////////////////////////
185// Some patch ///// END
186/////////////////////////////////////////////////////////////////////////////
187
ce3ed50d
JS
188#ifdef GetClassInfo
189#undef GetClassInfo
190#endif
191
3b4183d8
GL
192// --------------------------------------------------------------
193// Module
194// --------------------------------------------------------------
db131261
RR
195class wxSocketModule: public wxModule
196{
3b4183d8
GL
197 DECLARE_DYNAMIC_CLASS(wxSocketModule)
198public:
199 wxSocketModule() {}
200 bool OnInit();
201 void OnExit();
202};
203
f4ada568
GL
204// --------------------------------------------------------------
205// ClassInfos
206// --------------------------------------------------------------
207#if !USE_SHARED_LIBRARY
208IMPLEMENT_CLASS(wxSocketBase, wxObject)
209IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
210IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
211IMPLEMENT_CLASS(wxSocketHandler, wxObject)
212IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
3b4183d8 213IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
f4ada568
GL
214#endif
215
db131261
RR
216class wxSockWakeUp : public wxTimer
217{
f4ada568
GL
218public:
219 int *my_id;
220 int n_val;
221 wxSocketBase *sock;
222
db131261
RR
223 wxSockWakeUp(wxSocketBase *_sock, int *id, int new_val)
224 {
f4ada568
GL
225 my_id = id; n_val = new_val;
226 sock = _sock;
227 }
db131261
RR
228 virtual void Notify()
229 {
f4ada568
GL
230 *my_id = n_val;
231 if (sock) sock->Notify(FALSE);
232 }
233};
234
235/// Socket request
db131261
RR
236class SockRequest : public wxObject
237{
f4ada568
GL
238public:
239 char *buffer;
240 size_t size, nbytes;
241 bool done;
242 int error;
243 wxSockWakeUp *auto_wakeup;
244 wxSocketBase::wxRequestNotify type;
245};
384b4373 246
f4ada568
GL
247
248/////////////////////////////////////////////////////////////////////////////
249// Some internal define
250/////////////////////////////////////////////////////////////////////////////
251
252// --------------------------------------------------------------
253// --------- wxSocketBase CONSTRUCTOR ---------------------------
254// --------------------------------------------------------------
255wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags,
17dff81c 256 wxSocketBase::wxSockType _type) :
f4ada568
GL
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),
8c14576d 265 m_timeout(3600), m_wantbuf(0)
f4ada568
GL
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
278wxSocketBase::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),
8c14576d 288 m_timeout(3600), m_wantbuf(0)
f4ada568
GL
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// --------------------------------------------------------------
8c14576d 302// wxSocketBase
f4ada568 303// --------------------------------------------------------------
8c14576d 304
f4ada568
GL
305wxSocketBase::~wxSocketBase()
306{
307 DestroyCallbacks();
308 Close();
309
310 if (m_unread)
311 free(m_unread);
8c14576d
RR
312 if (m_handler)
313 {
f4ada568
GL
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
325bool wxSocketBase::Close()
326{
8c14576d
RR
327 if (m_fd != INVALID_SOCKET)
328 {
329 for (int i=0;i<3;i++)
330 {
f4ada568
GL
331 wxNode *n, *node = req_list[i].First();
332
8c14576d
RR
333 while (node)
334 {
f4ada568
GL
335 SockRequest *req = (SockRequest *)node->Data();
336 req->done = TRUE;
384b4373 337
f4ada568
GL
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// --------------------------------------------------------------
8c14576d 355// wxSocketBase base IO function
f4ada568 356// --------------------------------------------------------------
8c14576d 357
f4ada568
GL
358wxSocketBase& 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
372wxSocketBase& wxSocketBase::Peek(char* buffer, size_t nbytes)
373{
374 size_t nbytes_old = nbytes;
375
376 nbytes -= GetPushback(buffer, nbytes, TRUE);
8c14576d
RR
377 if (!nbytes)
378 {
f4ada568
GL
379 m_lcount = nbytes_old;
380 return *this;
381 }
382
383 WantBuffer(buffer, nbytes, EVT_PEEK);
384
385 return *this;
386}
387
388wxSocketBase& wxSocketBase::Write(const char *buffer, size_t nbytes)
389{
390 WantBuffer((char *)buffer, nbytes, EVT_WRITE);
391 return *this;
392}
393
394wxSocketBase& wxSocketBase::ReadMsg(char* buffer, size_t nbytes)
395{
396 SockMsg msg;
397 size_t len, len2, sig;
384b4373 398
f4ada568
GL
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
438wxSocketBase& wxSocketBase::WriteMsg(const char *buffer, size_t nbytes)
439{
440 SockMsg msg;
384b4373 441
ba681060
VZ
442 // warning about 'cast truncates constant value'
443#ifdef _MSC_VER
444 #pragma warning(disable: 4310)
445#endif // _MSC_VER
446
0c32066b
JS
447 msg.sig[0] = (char) 0xad;
448 msg.sig[1] = (char) 0xde;
449 msg.sig[2] = (char) 0xed;
450 msg.sig[3] = (char) 0xfe;
f4ada568 451
0c32066b
JS
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;
f4ada568
GL
456
457 if (Write((char *)&msg, sizeof(msg)).LastCount() < sizeof(msg))
458 return *this;
459 if (Write(buffer, nbytes).LastCount() < nbytes)
384b4373 460 return *this;
f4ada568 461
0c32066b
JS
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;
f4ada568
GL
467 Write((char *)&msg, sizeof(msg));
468
469 return *this;
ba681060
VZ
470
471#ifdef _MSC_VER
472 #pragma warning(default: 4310)
473#endif // _MSC_VER
f4ada568
GL
474}
475
476wxSocketBase& wxSocketBase::Unread(const char *buffer, size_t nbytes)
477{
478 CreatePushbackAfter(buffer, nbytes);
479 return *this;
480}
481
482bool 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);
0c32066b 497 return (FD_ISSET(m_fd, &sock_set) != 0);
f4ada568
GL
498}
499
500// ---------------------------------------------------------------------
501// --------- wxSocketBase Discard(): deletes all byte in the input queue
502// ---------------------------------------------------------------------
503void 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));
384b4373 511
8c14576d
RR
512 while (recv_size == MAX_BUFSIZE)
513 {
f4ada568
GL
514 recv_size = Read(my_data, MAX_BUFSIZE).LastCount();
515 }
516
517 RestoreState();
518 delete [] my_data;
519
520#undef MAX_BUFSIZE
521}
522
15ed4533
JS
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*.
bbe0af5b
RR
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
ee4c6942
JS
530// JACS - How can we detect this?
531// Meanwhile, if your compiler complains about socklen_t,
532// switch lines below.
533
6d5977df
KB
534#if wxHAVE_GLIBC2
535# define wxSOCKET_INT socklen_t
15ed4533 536#else
6d5977df 537# define wxSOCKET_INT int
15ed4533
JS
538#endif
539
f4ada568 540// --------------------------------------------------------------
8c14576d 541// wxSocketBase socket info functions
f4ada568 542// --------------------------------------------------------------
8c14576d 543
f4ada568
GL
544bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
545{
546 struct sockaddr my_addr;
15ed4533 547 wxSOCKET_INT len_addr = sizeof(my_addr);
f4ada568
GL
548
549 if (m_fd < 0)
550 return FALSE;
551
db131261 552 if (getpeername(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0)
384b4373 553 return FALSE;
f4ada568
GL
554
555 addr_man.Disassemble(&my_addr, len_addr);
556 return TRUE;
557}
558
559bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
560{
561 struct sockaddr my_addr;
15ed4533 562 wxSOCKET_INT len_addr = sizeof(my_addr);
f4ada568
GL
563
564 if (m_fd < 0)
565 return FALSE;
566
db131261 567 if (getsockname(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0)
62448488 568
f4ada568
GL
569 return FALSE;
570
571 addr_man.Disassemble(&my_addr, len_addr);
572 return TRUE;
573}
574
575// --------------------------------------------------------------
8c14576d 576// wxSocketBase wait functions
f4ada568 577// --------------------------------------------------------------
db131261 578
f4ada568
GL
579void 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
593void wxSocketBase::RestoreState()
594{
595 wxNode *node;
596
597 node = m_states.Last();
598 if (!node)
599 return;
600
601 wxSockState *state = (wxSockState *)node->Data();
384b4373 602
f4ada568
GL
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// --------------------------------------------------------------
db131261 620
f4ada568
GL
621bool 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);
384b4373 634
f4ada568
GL
635 m_waitflags = 0x80 | type;
636 while (m_waitflags & 0x80)
637 PROCESS_EVENTS();
638
639 RestoreState();
640
8c14576d
RR
641 if (m_waitflags & 0x40)
642 {
f4ada568
GL
643 m_waitflags = 0;
644 return TRUE;
645 }
646 m_waitflags = 0;
647
648 return FALSE;
649}
650
651bool 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
657bool wxSocketBase::WaitForRead(long seconds, long microseconds)
658{
659 return _Wait(seconds, microseconds, REQ_READ | REQ_LOST);
660}
661
662bool wxSocketBase::WaitForWrite(long seconds, long microseconds)
663{
664 return _Wait(seconds, microseconds, REQ_WRITE);
665}
666
667bool 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__)
678static void wx_socket_read(XtPointer client, int *fid,
17dff81c 679 XtInputId *WXUNUSED(id))
f4ada568
GL
680#define fd *fid
681#else
682static 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
8c14576d
RR
693 if (i == -1 && (sock->NeededReq() & wxSocketBase::REQ_ACCEPT))
694 {
f4ada568
GL
695 sock->OnRequest(wxSocketBase::EVT_ACCEPT);
696 return;
697 }
698
8c14576d
RR
699 if (i != 0)
700 {
f4ada568 701 if (!(sock->NeededReq() & wxSocketBase::REQ_READ))
8c14576d 702 {
f4ada568 703 return;
8c14576d 704 }
f4ada568
GL
705
706 sock->OnRequest(wxSocketBase::EVT_READ);
8c14576d
RR
707 }
708 else
709 {
710 if (!(sock->NeededReq() & wxSocketBase::REQ_LOST))
711 {
f4ada568
GL
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__)
722static void wx_socket_write(XtPointer client, int *WXUNUSED(fid),
17dff81c 723 XtInputId *WXUNUSED(id))
f4ada568
GL
724#else
725static void wx_socket_write(gpointer client, gint WXUNUSED(fd),
17dff81c 726 GdkInputCondition WXUNUSED(cond))
f4ada568
GL
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
739Notify_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
8c14576d
RR
747 if (i == -1 && (sock->NeededReq() & wxSocketBase::REQ_ACCEPT))
748 {
f4ada568
GL
749 sock->OnRequest(wxSocketBase::EVT_ACCEPT);
750 return;
751 }
752
753 /* Bytes arrived */
8c14576d
RR
754 if (i != 0)
755 {
f4ada568
GL
756 if (!(sock->NeededReq() & wxSocketBase::REQ_READ))
757 return (Notify_value) FALSE;
758
759 sock->OnRequest(wxSocketBase::EVT_READ);
8c14576d
RR
760 }
761 else
762 {
f4ada568
GL
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
772Notify_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
785wxSocketBase::wxRequestNotify wxSocketBase::EventToNotify(wxRequestEvent evt)
786{
db131261
RR
787 switch (evt)
788 {
f4ada568
GL
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
805void wxSocketBase::SetFlags(wxSockFlags _flags)
806{
807 m_flags = _flags;
db131261
RR
808 if (_flags & SPEED)
809 {
f4ada568
GL
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);
db131261
RR
817 }
818 else
819 {
f4ada568
GL
820 unsigned long flag = 1;
821 ioctl(m_fd, FIONBIO, &flag);
822 }
823}
824
825void wxSocketBase::SetNotify(wxRequestNotify flags)
826{
827 wxRequestNotify old_needed_req = m_neededreq;
db131261
RR
828 if (flags & REQ_ACCEPT)
829 {
f4ada568
GL
830 /* Check if server */
831 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer))))
832 flags &= ~REQ_ACCEPT;
833 }
834 m_neededreq = flags;
db131261
RR
835
836/*
837 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
838 SetupCallbacks();
839*/
840
8c14576d 841 if (old_needed_req != flags)
f4ada568
GL
842 SetupCallbacks();
843}
844
845void wxSocketBase::SetupCallbacks()
846{
847 if (m_fd == INVALID_SOCKET || !m_handler || (m_flags & SPEED))
848 return;
849
8c14576d
RR
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,
f4ada568
GL
856 (XtPointer *) XtInputReadMask,
857 (XtInputCallbackProc) wx_socket_read,
b412f9be 858 (XtPointer) this);
8c14576d 859 }
f4ada568 860 }
8c14576d
RR
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,
f4ada568
GL
875 (XtPointer *) XtInputWriteMask,
876 (XtInputCallbackProc) wx_socket_write,
877 (XtPointer) this);
8c14576d
RR
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 }
f4ada568 888#endif
8c14576d
RR
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 }
f4ada568
GL
928 }
929#endif
8c14576d
RR
930
931
932#ifdef __WXMSW__
f4ada568
GL
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);
17dff81c
SC
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);
f4ada568
GL
967#endif
968 m_cbkon = TRUE;
969 m_processing = FALSE;
970}
971
972void wxSocketBase::DestroyCallbacks()
973{
974 if (!m_cbkon || !m_handler)
975 return;
db131261 976
f4ada568
GL
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
17dff81c
SC
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
f4ada568
GL
1012}
1013
1014void 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
1025void wxSocketBase::OnRequest(wxRequestEvent req_evt)
1026{
1027 wxRequestNotify req_notif = EventToNotify(req_evt);
1028
1029 // Mask the current event
8c14576d
RR
1030 SetNotify(m_neededreq & ~req_notif);
1031
f4ada568
GL
1032 if (req_evt <= EVT_WRITE && DoRequests(req_evt))
1033 return;
1034
db131261
RR
1035 if (m_waitflags & 0xF0)
1036 {
f4ada568 1037 // Wake up
db131261
RR
1038 if ((m_waitflags & 0x0F) == req_evt)
1039 {
f4ada568
GL
1040 m_waitflags = 0x80;
1041#ifndef __WXGTK__
8c14576d 1042 DestroyCallbacks();
f4ada568
GL
1043#endif
1044 }
1045 return;
1046 }
1047
db131261
RR
1048 if (req_evt == EVT_LOST)
1049 {
f4ada568
GL
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
1060wxSocketEvent::wxSocketEvent(int id)
1061 : wxEvent(id)
1062{
1063 wxEventType type = (wxEventType)wxEVT_SOCKET;
1064
1065 SetEventType(type);
1066}
1067
1068void 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// --------------------------------------------------------------
db131261 1083
f4ada568
GL
1084wxSocketBase::wxSockCbk wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk)
1085{
1086 wxSockCbk old_cbk = m_cbk;
1087
1088 m_cbk = _cbk;
1089 return old_cbk;
1090}
1091
1092char *wxSocketBase::CallbackData(char *cdata_)
1093{
1094 char *old_cdata = m_cdata;
1095
1096 m_cdata = cdata_;
1097 return old_cdata;
1098}
1099
1100void wxSocketBase::SetEventHandler(wxEvtHandler& h_evt, int id)
1101{
1102 SetNextHandler(&h_evt);
1103 m_id = id;
1104}
1105
1106// --------------------------------------------------------------
1107// --------- wxSocketBase pushback library ----------------------
1108// --------------------------------------------------------------
db131261 1109
f4ada568
GL
1110void 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
1121void 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
1136size_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
1160bool 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
db131261
RR
1173 switch (req->type)
1174 {
f4ada568
GL
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);
8c14576d
RR
1179 if (ret < 0)
1180 {
f4ada568
GL
1181 req->error = errno;
1182 req->done = TRUE;
1183 break;
1184 }
1185 len = ret;
8c14576d
RR
1186 if ((len < req->size) && (m_flags & WAITALL))
1187 {
f4ada568
GL
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);
8c14576d
RR
1203 if (ret < 0)
1204 {
f4ada568
GL
1205 req->error = errno;
1206 req->done = TRUE;
1207 break;
1208 }
1209 len = ret;
8c14576d
RR
1210 if ((len < req->size) && (m_flags & WAITALL))
1211 {
f4ada568
GL
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
1231void wxSocketBase::WantSpeedBuffer(char *buffer, size_t nbytes,
1232 wxRequestEvent evt)
1233{
e22036dc 1234 int ret = 0;
f4ada568 1235
8c14576d
RR
1236 switch (evt)
1237 {
f4ada568
GL
1238 case EVT_PEEK:
1239 case EVT_READ:
c740f496
GL
1240 ret = recv(m_fd, buffer, nbytes,
1241 (evt == EVT_PEEK) ? MSG_PEEK : 0);
f4ada568
GL
1242 break;
1243 case EVT_WRITE:
c740f496 1244 ret = send(m_fd, buffer, nbytes, 0);
f4ada568
GL
1245 break;
1246 }
8c14576d
RR
1247 if (ret < 0)
1248 {
f4ada568
GL
1249 m_lcount = 0;
1250 m_error = errno;
8c14576d
RR
1251 }
1252 else
1253 {
f4ada568 1254 m_lcount = ret;
8ef6a930
GL
1255 m_error = 0;
1256 }
f4ada568
GL
1257}
1258
1259void wxSocketBase::WantBuffer(char *buffer, size_t nbytes,
17dff81c 1260 wxRequestEvent evt)
f4ada568
GL
1261{
1262 bool buf_timed_out;
1263
1264 if (m_fd == INVALID_SOCKET || !m_handler || !m_connected)
1265 return;
1266
8c14576d
RR
1267 if (m_flags & SPEED)
1268 {
f4ada568
GL
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);
384b4373 1275
f4ada568
GL
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);
db131261
RR
1292 if (m_flags & NOWAIT)
1293 {
f4ada568 1294 DoRequests(evt);
db131261
RR
1295 }
1296 else
1297 {
f4ada568
GL
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// --------------------------------------------------------------
8c14576d 1313// wxSocketServer
f4ada568
GL
1314// --------------------------------------------------------------
1315
f4ada568 1316wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
17dff81c 1317 wxSockFlags flags) :
f4ada568
GL
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;
384b4373 1324
f4ada568
GL
1325 int flag = 1;
1326 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int));
384b4373 1327
f4ada568
GL
1328 struct sockaddr *myaddr;
1329 size_t len;
384b4373 1330
f4ada568
GL
1331 addr_man.Build(myaddr, len);
1332 if (bind(m_fd, myaddr, addr_man.SockAddrLen()) < 0)
1333 return;
384b4373 1334
f4ada568
GL
1335 if (listen(m_fd, 5) < 0) {
1336 m_fd = INVALID_SOCKET;
1337 return;
1338 }
1339}
1340
1341// --------------------------------------------------------------
8c14576d 1342// wxSocketServer Accept
f4ada568 1343// --------------------------------------------------------------
8c14576d 1344
f4ada568
GL
1345bool wxSocketServer::AcceptWith(wxSocketBase& sock)
1346{
1347 int fd2;
384b4373 1348
f4ada568
GL
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;
384b4373 1355
f4ada568 1356 setsockopt(fd2, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
384b4373 1357
f4ada568
GL
1358 int flag = 0;
1359 setsockopt(fd2, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
384b4373 1360
8c14576d
RR
1361 if (!(sock.m_flags & SPEED))
1362 {
f4ada568
GL
1363 unsigned long flag2 = 1;
1364 ioctl(fd2, FIONBIO, &flag2);
1365 }
384b4373 1366
f4ada568
GL
1367 sock.m_type = SOCK_INTERNAL;
1368 sock.m_fd = fd2;
1369 sock.m_connected = TRUE;
1370
1371 return TRUE;
1372}
1373
1374wxSocketBase *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// --------------------------------------------------------------
8c14576d 1390// wxSocketServer callbacks
f4ada568 1391// --------------------------------------------------------------
8c14576d 1392
f4ada568
GL
1393void wxSocketServer::OnRequest(wxRequestEvent evt)
1394{
8c14576d
RR
1395 if (evt == EVT_ACCEPT)
1396 {
f4ada568
GL
1397 OldOnNotify(EVT_ACCEPT);
1398 }
1399}
1400
1401// --------------------------------------------------------------
8c14576d 1402// wxSocketClient
f4ada568
GL
1403// --------------------------------------------------------------
1404
1405// --------- wxSocketClient CONSTRUCTOR -------------------------
1406// --------------------------------------------------------------
1407wxSocketClient::wxSocketClient(wxSockFlags _flags) :
17dff81c 1408 wxSocketBase(_flags, SOCK_CLIENT)
f4ada568
GL
1409{
1410}
1411
1412// --------------------------------------------------------------
1413// --------- wxSocketClient DESTRUCTOR --------------------------
1414// --------------------------------------------------------------
1415wxSocketClient::~wxSocketClient()
1416{
1417}
1418
1419// --------------------------------------------------------------
1420// --------- wxSocketClient Connect functions -------------------
1421// --------------------------------------------------------------
e22036dc 1422bool wxSocketClient::Connect(wxSockAddress& addr_man, bool WXUNUSED(wait) )
f4ada568
GL
1423{
1424 struct linger linger;
1425
1426 if (IsConnected())
1427 Close();
1428
1429 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
384b4373 1430
f4ada568
GL
1431 if (m_fd < 0)
1432 return FALSE;
384b4373 1433
f4ada568
GL
1434 m_connected = FALSE;
1435
1436 linger.l_onoff = 1;
384b4373 1437 linger.l_linger = 5;
f4ada568 1438 setsockopt(m_fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
384b4373 1439
f4ada568 1440 // Stay in touch with the state of things...
384b4373 1441
f4ada568
GL
1442 unsigned long flag = 1;
1443 setsockopt(m_fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
384b4373 1444
f4ada568
GL
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
384b4373 1452
f4ada568
GL
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
8c14576d
RR
1461 if (!(m_flags & SPEED))
1462 {
f4ada568
GL
1463 flag = 1;
1464 ioctl(m_fd, FIONBIO, &flag);
1465 }
384b4373 1466
f4ada568
GL
1467 Notify(TRUE);
1468
1469 m_connected = TRUE;
1470 return TRUE;
1471}
1472
75ed1d15 1473bool wxSocketClient::WaitOnConnect(long seconds, long microseconds)
f4ada568 1474{
75ed1d15 1475 int ret = _Wait(seconds, microseconds, REQ_CONNECT | REQ_LOST);
384b4373 1476
f4ada568
GL
1477 if (ret)
1478 m_connected = TRUE;
384b4373
RD
1479
1480 return m_connected;
f4ada568
GL
1481}
1482
1483void wxSocketClient::OnRequest(wxRequestEvent evt)
1484{
8c14576d
RR
1485 if (evt == EVT_CONNECT)
1486 {
1487 if (m_connected)
1488 {
1489#ifndef __WXGTK__
f4ada568 1490 SetNotify(m_neededreq & ~REQ_CONNECT);
8c14576d 1491#endif
f4ada568
GL
1492 return;
1493 }
1494 m_waitflags = 0x40;
384b4373 1495 m_connected = TRUE;
f4ada568 1496 OldOnNotify(EVT_CONNECT);
8c14576d 1497#ifndef __WXGTK__
f4ada568 1498 DestroyCallbacks();
8c14576d 1499#endif
f4ada568
GL
1500 return;
1501 }
1502 wxSocketBase::OnRequest(evt);
1503}
1504
1505/////////////////////////////////////////////////////////////////
1506// wxSocketHandler ///////////////////////////////////////////////
1507/////////////////////////////////////////////////////////////////
1508
1509wxSocketHandler *wxSocketHandler::master = NULL;
1510#if defined(__WINDOWS__)
1511static int win_initialized = 0;
1512#endif
1513
1514// --------------------------------------------------------------
1515// --------- wxSocketHandler CONSTRUCTOR ------------------------
1516// --------------------------------------------------------------
17dff81c
SC
1517#ifdef __WXMAC__
1518
1519extern "C" int updatestatus(int s) ;
1520
1521void 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
1561void 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
f4ada568
GL
1575#ifdef __WINDOWS__
1576
1577extern char wxPanelClassName[];
1578
1579LRESULT APIENTRY _EXPORT wxSocketHandlerWndProc(HWND hWnd, UINT message,
1580 WPARAM wParam, LPARAM lParam)
1581{
1cff61de
UU
1582 if(message==WM_DESTROY)
1583 {
17dff81c
SC
1584 ::SetWindowLong(hWnd, GWL_WNDPROC, (LONG) DefWindowProc);
1585 return DefWindowProc(hWnd, message, wParam, lParam);
1cff61de 1586 }
f4ada568
GL
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;
ba681060
VZ
1614
1615 default:
1616 wxFAIL_MSG("invalid socket event");
1617 return (LRESULT)0;
f4ada568 1618 }
ba681060 1619
f4ada568
GL
1620 sock->OnRequest(sk_req);
1621
1622 return (LRESULT)0;
1623}
1624
1625FARPROC wxSocketSubClassProc = NULL;
1626
1627#endif
1628
1629wxSocketHandler::wxSocketHandler()
1630{
1631#if defined(__WINDOWS__)
8c14576d
RR
1632 if (!win_initialized)
1633 {
f4ada568
GL
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,
17dff81c
SC
1641 0, 0, 0, 0, NULL, (HMENU) NULL,
1642 wxhInstance, 0);
f4ada568
GL
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// --------------------------------------------------------------
1664wxSocketHandler::~wxSocketHandler()
1665{
1666 wxNode *next_node, *node = socks->First();
1667
8c14576d
RR
1668 while (node)
1669 {
f4ada568
GL
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// --------------------------------------------------------------
8c14576d 1694
f4ada568
GL
1695void wxSocketHandler::Register(wxSocketBase* sock)
1696{
1697 wxNode *node;
1698
8c14576d
RR
1699 for (node = socks->First(); node != NULL; node = node->Next())
1700 {
f4ada568
GL
1701 wxSocketBase* s = (wxSocketBase*)node->Data();
1702
1703 if (s == sock)
1704 return;
1705 }
1706
8c14576d
RR
1707 if (sock)
1708 {
f4ada568
GL
1709 socks->Append(sock);
1710 sock->SetHandler(this);
1711 sock->SetupCallbacks();
1712 }
1713}
1714
1715void wxSocketHandler::UnRegister(wxSocketBase* sock)
1716{
1717 wxNode *node;
1718
8c14576d
RR
1719 for (node = socks->First(); node; node = node->Next())
1720 {
f4ada568 1721 wxSocketBase* s = (wxSocketBase*)node->Data();
384b4373 1722
8c14576d
RR
1723 if (s == sock)
1724 {
f4ada568
GL
1725 delete node;
1726 sock->DestroyCallbacks();
1727 sock->SetHandler(NULL);
1728 return;
1729 }
1730 }
1731}
1732
1733unsigned long wxSocketHandler::Count() const
1734{
1735 return socks->Number();
1736}
1737
1738// --------------------------------------------------------------
1739// --------- wxSocketHandler "big" wait functions ---------------
1740// --------------------------------------------------------------
1741void handler_cbk(wxSocketBase& sock,
17dff81c
SC
1742 wxSocketBase::wxRequestEvent WXUNUSED(flags),
1743 char *cdata)
f4ada568
GL
1744{
1745 int *a_wait = (int *)cdata;
1746
1747 (*a_wait)++;
1748 sock.Notify(FALSE);
1749}
1750
1751int 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
8c14576d
RR
1758 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1759 {
f4ada568
GL
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
8c14576d
RR
1776 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1777 {
f4ada568
GL
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
1789void wxSocketHandler::YieldSock()
1790{
1791 wxNode *node;
1792
8c14576d
RR
1793 for (node = socks->First(); node; node = node->Next() )
1794 {
f4ada568
GL
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// --------------------------------------------------------------
1811wxSocketServer *wxSocketHandler::CreateServer(wxSockAddress& addr,
17dff81c 1812 wxSocketBase::wxSockFlags flags)
f4ada568
GL
1813{
1814 wxSocketServer *serv = new wxSocketServer(addr, flags);
1815
1816 Register(serv);
1817 return serv;
1818}
1819
1820wxSocketClient *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// --------------------------------------------------------------
8c14576d 1832
f4ada568
GL
1833UINT wxSocketHandler::NewMessage(wxSocketBase *sock)
1834{
1835 internal->firstAvailableMsg++;
1836 smsg_list->Append(internal->firstAvailableMsg, sock);
1837 return internal->firstAvailableMsg;
1838}
1839
1840void wxSocketHandler::DestroyMessage(UINT msg)
1841{
1842 wxNode *node = smsg_list->Find(msg);
1843 delete node;
1844}
1845
1846HWND wxSocketHandler::GetHWND() const
1847{
1848 return internal->sockWin;
1849}
1850
1851#endif
7f555861 1852
8c14576d
RR
1853bool wxSocketModule::OnInit()
1854{
3b4183d8
GL
1855 wxSocketHandler::master = new wxSocketHandler();
1856 return TRUE;
1857}
1858
8c14576d
RR
1859void wxSocketModule::OnExit()
1860{
3b4183d8
GL
1861 delete wxSocketHandler::master;
1862 wxSocketHandler::master = NULL;
1863}
1864
17dff81c
SC
1865#ifdef __WXMAC__
1866void wxMacProcessSocketEvents() ;
1867void wxMacProcessEvents()
1868{
1869 wxMacProcessSocketEvents() ;
1870 (*GUSISpin)(SP_MISC, 0) ;
1871}
1872
1873void 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
7f555861
JS
1886#endif
1887 // __WXSTUBS__