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