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