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