]> git.saurik.com Git - wxWidgets.git/blame - src/common/socket.cpp
1. wxWindow::IsTopLevel() added and documented
[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
a737331d
GL
7// Updated: April 1999
8// Copyright: (C) 1999 1998, 1997, Guilhem Lavaux
f4ada568
GL
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>
a737331d 54
17dff81c
SC
55#endif
56
f4ada568 57#if defined(__WINDOWS__)
a737331d 58#include <winsock.h>
f4ada568
GL
59#endif // __WINDOWS__
60
61#if defined(__UNIX__)
62
63#ifdef VMS
a737331d
GL
64#include <socket.h>
65#else
66#include <sys/socket.h>
67#endif
f4ada568
GL
68#include <sys/ioctl.h>
69
70#include <sys/time.h>
71#include <unistd.h>
72
384b4373 73#ifdef sun
a737331d 74#include <sys/filio.h>
384b4373
RD
75#endif
76
f4ada568
GL
77#endif // __UNIX__
78
79#include <signal.h>
80#include <errno.h>
81
3f4a0c5b 82#ifdef __VISUALC__
a737331d 83#include <io.h>
f4ada568
GL
84#endif
85
86/////////////////////////////////////////////////////////////////////////////
87// wxSocket headers
88/////////////////////////////////////////////////////////////////////////////
a737331d 89#include <wx/module.h>
f4ada568 90#define WXSOCK_INTERNAL
a737331d
GL
91#include <wx/sckaddr.h>
92#include <wx/socket.h>
93#include <wx/sckint.h>
57493f9f 94
a737331d
GL
95// ----------------------
96// Some patch ----- BEGIN
97// ----------------------
f4ada568
GL
98#ifdef __WINDOWS__
99#define close closesocket
100#define ioctl ioctlsocket
0c32066b
JS
101#ifdef errno
102#undef errno
103#endif
f4ada568
GL
104#define errno WSAGetLastError()
105#ifdef EWOULDBLOCK
106#undef EWOULDBLOCK
107#endif
108#define EWOULDBLOCK WSAEWOULDBLOCK
109#define ETIMEDOUT WSAETIMEDOUT
110#undef EINTR
111#define EINTR WSAEINTR
112#endif
113
114#ifndef __WINDOWS__
115#define INVALID_SOCKET -1
116#endif
117
f4ada568
GL
118#ifdef __WINDOWS__
119// This is an MS TCP/IP routine and is not needed here. Some WinSock
120// implementations (such as PC-NFS) will require you to include this
121// or a similar routine (see appendix in WinSock doc or help file).
122
3f4a0c5b 123#if defined( NEED_WSAFDIsSet ) || defined( __VISUALC__ )
f4ada568
GL
124int PASCAL FAR __WSAFDIsSet(SOCKET fd, fd_set FAR *set)
125{
17dff81c 126 int i = set->fd_count;
f4ada568 127
17dff81c
SC
128 while (i--)
129 {
130 if (set->fd_array[i] == fd)
131 return 1;
132 }
f4ada568 133
17dff81c 134 return 0;
f4ada568
GL
135}
136#endif
137#endif
138
a737331d
GL
139// -------------------
140// Some patch ---- END
141// -------------------
f4ada568 142
ce3ed50d
JS
143#ifdef GetClassInfo
144#undef GetClassInfo
145#endif
146
3b4183d8
GL
147// --------------------------------------------------------------
148// Module
149// --------------------------------------------------------------
db131261
RR
150class wxSocketModule: public wxModule
151{
3b4183d8
GL
152 DECLARE_DYNAMIC_CLASS(wxSocketModule)
153public:
154 wxSocketModule() {}
155 bool OnInit();
156 void OnExit();
157};
158
f4ada568
GL
159// --------------------------------------------------------------
160// ClassInfos
161// --------------------------------------------------------------
162#if !USE_SHARED_LIBRARY
a737331d
GL
163IMPLEMENT_CLASS(wxSocketBase, wxObject)
164IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
165IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
166IMPLEMENT_CLASS(wxSocketHandler, wxObject)
167IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
168IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
f4ada568
GL
169#endif
170
f4ada568
GL
171// --------------------------------------------------------------
172// --------- wxSocketBase CONSTRUCTOR ---------------------------
173// --------------------------------------------------------------
174wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags,
17dff81c 175 wxSocketBase::wxSockType _type) :
f4ada568
GL
176 wxEvtHandler(),
177 m_flags(_flags), m_type(_type), m_connected(FALSE), m_connecting(FALSE),
a737331d 178 m_fd(INVALID_SOCKET), m_id(-1),
f4ada568
GL
179 m_handler(0),
180 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
a737331d 181 m_timeout(3600),
f4ada568 182 m_unread(NULL), m_unrd_size(0),
a737331d
GL
183 m_cbk(NULL), m_cdata(NULL),
184 m_notify_state(FALSE)
f4ada568 185{
a737331d 186 m_internal = new wxSocketInternal(this);
f4ada568
GL
187}
188
189wxSocketBase::wxSocketBase() :
190 wxEvtHandler(),
191 m_flags(WAITALL), m_type(SOCK_UNINIT), m_connected(FALSE),
a737331d 192 m_connecting(FALSE), m_fd(INVALID_SOCKET),
f4ada568
GL
193 m_id(-1), m_handler(0),
194 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
a737331d 195 m_timeout(3600),
f4ada568 196 m_unread(NULL), m_unrd_size(0),
a737331d
GL
197 m_cbk(NULL), m_cdata(NULL),
198 m_notify_state(FALSE)
f4ada568 199{
a737331d 200 m_internal = new wxSocketInternal(this);
f4ada568
GL
201}
202
203// --------------------------------------------------------------
8c14576d 204// wxSocketBase
f4ada568 205// --------------------------------------------------------------
8c14576d 206
f4ada568
GL
207wxSocketBase::~wxSocketBase()
208{
a737331d 209 // First, close the file descriptor.
f4ada568
GL
210 Close();
211
212 if (m_unread)
213 free(m_unread);
a737331d 214 // Unregister from the handler database.
8c14576d 215 if (m_handler)
f4ada568 216 m_handler->UnRegister(this);
a737331d
GL
217
218 // Destroy all saved states.
f4ada568
GL
219 m_states.DeleteContents(TRUE);
220
a737331d 221 // Destroy the socket manager.
f4ada568
GL
222 delete m_internal;
223}
224
225bool wxSocketBase::Close()
226{
8c14576d
RR
227 if (m_fd != INVALID_SOCKET)
228 {
2a4f27f2
GL
229 if (m_notify_state == TRUE)
230 Notify(FALSE);
f4ada568 231
a737331d 232 // Shutdown the connection.
f4ada568
GL
233 shutdown(m_fd, 2);
234 close(m_fd);
235 m_fd = INVALID_SOCKET;
236 m_connected = FALSE;
237 }
238
239 return TRUE;
240}
241
242// --------------------------------------------------------------
8c14576d 243// wxSocketBase base IO function
f4ada568 244// --------------------------------------------------------------
8c14576d 245
f4ada568
GL
246wxSocketBase& wxSocketBase::Read(char* buffer, size_t nbytes)
247{
a737331d
GL
248 m_lcount = GetPushback(buffer, nbytes, FALSE);
249 nbytes -= m_lcount;
250 buffer += m_lcount;
f4ada568
GL
251
252 // If we have got the whole needed buffer or if we don't want to
253 // wait then it returns immediately.
a737331d 254 if (!nbytes || (m_lcount && !(m_flags & WAITALL)) ) {
f4ada568 255 return *this;
375abe3d 256 }
f4ada568
GL
257
258 WantBuffer(buffer, nbytes, EVT_READ);
259
260 return *this;
261}
262
062c4861
GL
263wxSocketBase& wxSocketBase::ReadMsg(char* buffer, size_t nbytes)
264{
265 unsigned long len, len2, sig;
266 struct {
267 char sig[4];
268 char len[4];
269 } msg;
270
271 // sig should be an explicit 32-bit unsigned integer; I've seen
272 // compilers in which size_t was actually a 16-bit unsigned integer
273
274 Read((char *)&msg, sizeof(msg));
275 if (m_lcount != sizeof(msg))
276 return *this;
277
278 sig = msg.sig[0] & 0xff;
279 sig |= (size_t)(msg.sig[1] & 0xff) << 8;
280 sig |= (size_t)(msg.sig[2] & 0xff) << 16;
281 sig |= (size_t)(msg.sig[3] & 0xff) << 24;
282
283 if (sig != 0xfeeddead)
284 return *this;
285 len = msg.len[0] & 0xff;
286 len |= (size_t)(msg.len[1] & 0xff) << 8;
287 len |= (size_t)(msg.len[2] & 0xff) << 16;
288 len |= (size_t)(msg.len[3] & 0xff) << 24;
289
290 // len2 is incorrectly computed in the original; this sequence is
291 // the fix
292 if (len > nbytes) {
293 len2 = len - nbytes;
294 len = nbytes;
295 }
296 else
297 len2 = 0;
298
299 // the "len &&" in the following statement is necessary so that
300 // we don't attempt to read (and possibly hang the system)
301 // if the message was zero bytes long
302 if (len && Read(buffer, len).LastCount() != len)
303 return *this;
304 if (len2 && (Read(NULL, len2).LastCount() != len2))
305 return *this;
306 if (Read((char *)&msg, sizeof(msg)).LastCount() != sizeof(msg))
307 return *this;
308
309 sig = msg.sig[0] & 0xff;
310 sig |= (size_t)(msg.sig[1] & 0xff) << 8;
311 sig |= (size_t)(msg.sig[2] & 0xff) << 16;
312 sig |= (size_t)(msg.sig[3] & 0xff) << 24;
313// ERROR
314// we return *this either way, so a smart optimizer will
315// optimize the following sequence out; I'm leaving it in anyway
316 if (sig != 0xdeadfeed)
317 return *this;
318
319 return *this;
320}
321
f4ada568
GL
322wxSocketBase& wxSocketBase::Peek(char* buffer, size_t nbytes)
323{
a737331d
GL
324 m_lcount = GetPushback(buffer, nbytes, TRUE);
325 if (nbytes-m_lcount == 0)
8c14576d 326 {
f4ada568
GL
327 return *this;
328 }
a737331d
GL
329 buffer += m_lcount;
330 nbytes -= m_lcount;
f4ada568
GL
331
332 WantBuffer(buffer, nbytes, EVT_PEEK);
333
334 return *this;
335}
336
337wxSocketBase& wxSocketBase::Write(const char *buffer, size_t nbytes)
338{
a737331d 339 m_lcount = 0;
f4ada568
GL
340 WantBuffer((char *)buffer, nbytes, EVT_WRITE);
341 return *this;
342}
343
062c4861
GL
344wxSocketBase& wxSocketBase::WriteMsg(const char *buffer, size_t nbytes)
345{
346 struct {
347 char sig[4];
348 char len[4];
349 } msg;
350
351 // warning about 'cast truncates constant value'
352#ifdef __VISUALC__
353 #pragma warning(disable: 4310)
354#endif // __VISUALC__
355
356 msg.sig[0] = (char) 0xad;
357 msg.sig[1] = (char) 0xde;
358 msg.sig[2] = (char) 0xed;
359 msg.sig[3] = (char) 0xfe;
360
361 msg.len[0] = (char) nbytes & 0xff;
362 msg.len[1] = (char) (nbytes >> 8) & 0xff;
363 msg.len[2] = (char) (nbytes >> 16) & 0xff;
364 msg.len[3] = (char) (nbytes >> 24) & 0xff;
365
366 if (Write((char *)&msg, sizeof(msg)).LastCount() < sizeof(msg))
367 return *this;
368 if (Write(buffer, nbytes).LastCount() < nbytes)
369 return *this;
370
371 msg.sig[0] = (char) 0xed;
372 msg.sig[1] = (char) 0xfe;
373 msg.sig[2] = (char) 0xad;
374 msg.sig[3] = (char) 0xde;
375 msg.len[0] = msg.len[1] = msg.len[2] = msg.len[3] = (char) 0;
376 Write((char *)&msg, sizeof(msg));
377
378 return *this;
379
380#ifdef __VISUALC__
381 #pragma warning(default: 4310)
382#endif // __VISUALC__
383}
384
f4ada568
GL
385wxSocketBase& wxSocketBase::Unread(const char *buffer, size_t nbytes)
386{
062c4861
GL
387 m_lcount = 0;
388 if (nbytes != 0) {
389 CreatePushbackAfter(buffer, nbytes);
390 m_lcount = nbytes;
391 }
f4ada568
GL
392 return *this;
393}
394
395bool wxSocketBase::IsData() const
396{
397 struct timeval tv;
398 fd_set sock_set;
399
400 if (m_fd < 0)
401 return FALSE;
402 if (m_unrd_size > 0)
403 return TRUE;
404
a737331d
GL
405 m_internal->AcquireFD();
406
f4ada568
GL
407 tv.tv_sec = 0;
408 tv.tv_usec = 0;
409 FD_ZERO(&sock_set);
410 FD_SET(m_fd, &sock_set);
062c4861 411 select(m_fd+1, &sock_set, NULL, NULL, &tv);
a737331d
GL
412
413 m_internal->ReleaseFD();
414
0c32066b 415 return (FD_ISSET(m_fd, &sock_set) != 0);
f4ada568
GL
416}
417
418// ---------------------------------------------------------------------
419// --------- wxSocketBase Discard(): deletes all byte in the input queue
420// ---------------------------------------------------------------------
421void wxSocketBase::Discard()
422{
423#define MAX_BUFSIZE (10*1024)
424 char *my_data = new char[MAX_BUFSIZE];
425 size_t recv_size = MAX_BUFSIZE;
426
427 SaveState();
428 SetFlags((wxSockFlags)(NOWAIT | SPEED));
384b4373 429
8c14576d
RR
430 while (recv_size == MAX_BUFSIZE)
431 {
f4ada568
GL
432 recv_size = Read(my_data, MAX_BUFSIZE).LastCount();
433 }
434
435 RestoreState();
436 delete [] my_data;
437
438#undef MAX_BUFSIZE
439}
440
a737331d
GL
441// If what? Who seems to need unsigned int?
442// BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
443// were, getpeername/getsockname don't take unsigned int*, they take int*.
444//
445// Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
446// and it uses *socklen_t as the 3rd parameter. Robert.
447
448// JACS - How can we detect this?
449// Meanwhile, if your compiler complains about socklen_t,
450// switch lines below.
451
452#if wxHAVE_GLIBC2
453# define wxSOCKET_INT socklen_t
454#else
455# define wxSOCKET_INT int
456#endif
15ed4533 457
f4ada568 458// --------------------------------------------------------------
8c14576d 459// wxSocketBase socket info functions
f4ada568 460// --------------------------------------------------------------
8c14576d 461
f4ada568
GL
462bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
463{
464 struct sockaddr my_addr;
a737331d 465 wxSOCKET_INT len_addr = sizeof(my_addr);
f4ada568
GL
466
467 if (m_fd < 0)
468 return FALSE;
469
a737331d
GL
470 m_internal->AcquireFD();
471
472 if (getpeername(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
473 m_internal->ReleaseFD();
384b4373 474 return FALSE;
a737331d 475 }
f4ada568 476
a737331d 477 m_internal->ReleaseFD();
f4ada568
GL
478 addr_man.Disassemble(&my_addr, len_addr);
479 return TRUE;
480}
481
482bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
483{
484 struct sockaddr my_addr;
a737331d 485 wxSOCKET_INT len_addr = sizeof(my_addr);
f4ada568
GL
486
487 if (m_fd < 0)
488 return FALSE;
489
a737331d
GL
490 m_internal->AcquireFD();
491
492 if (getsockname(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
493 m_internal->ReleaseFD();
f4ada568 494 return FALSE;
a737331d
GL
495 }
496 m_internal->ReleaseFD();
f4ada568
GL
497
498 addr_man.Disassemble(&my_addr, len_addr);
499 return TRUE;
500}
501
502// --------------------------------------------------------------
8c14576d 503// wxSocketBase wait functions
f4ada568 504// --------------------------------------------------------------
db131261 505
f4ada568
GL
506void wxSocketBase::SaveState()
507{
a737331d 508 SocketState *state = new SocketState;
f4ada568 509
a737331d
GL
510 state->notify_state = m_notify_state;
511 state->evt_notify_state = m_neededreq;
512 state->socket_flags = m_flags;
513 state->c_callback = m_cbk;
514 state->c_callback_data = m_cdata;
f4ada568 515
a737331d 516 m_states.Append((wxObject *)state);
f4ada568
GL
517}
518
519void wxSocketBase::RestoreState()
520{
521 wxNode *node;
a737331d 522 SocketState *state;
f4ada568
GL
523
524 node = m_states.Last();
525 if (!node)
526 return;
527
a737331d 528 state = (SocketState *)node->Data();
384b4373 529
a737331d 530 SetFlags(state->socket_flags);
062c4861 531 m_internal->AcquireData();
a737331d 532 m_neededreq = state->evt_notify_state;
062c4861 533 m_internal->ReleaseData();
a737331d
GL
534 m_cbk = state->c_callback;
535 m_cdata = state->c_callback_data;
536 Notify(state->notify_state);
f4ada568
GL
537
538 delete node;
539 delete state;
540}
541
542// --------------------------------------------------------------
a737331d 543// --------- wxSocketBase callback functions --------------------
f4ada568 544// --------------------------------------------------------------
db131261 545
a737331d 546wxSocketBase::wxSockCbk wxSocketBase::Callback(wxSockCbk cbk_)
f4ada568 547{
a737331d 548 wxSockCbk old_cbk = cbk_;
f4ada568 549
a737331d
GL
550 m_cbk = cbk_;
551 return old_cbk;
f4ada568
GL
552}
553
a737331d 554char *wxSocketBase::CallbackData(char *data)
f4ada568 555{
a737331d 556 char *old_data = m_cdata;
f4ada568 557
a737331d
GL
558 m_cdata = data;
559 return old_data;
f4ada568
GL
560}
561
562// --------------------------------------------------------------
a737331d 563// --------- wxSocketBase wait functions ------------------------
f4ada568
GL
564// --------------------------------------------------------------
565
a737331d 566bool wxSocketBase::_Wait(long seconds, long milliseconds, int type)
375abe3d 567{
a737331d 568 SockRequest *req;
375abe3d 569
a737331d
GL
570 if ((!m_connected && !m_connecting) || m_fd < 0)
571 return FALSE;
f4ada568 572
a737331d 573 req = new SockRequest;
f4ada568 574
a737331d
GL
575 req->type = REQ_WAIT | type;
576 req->timeout = seconds * 1000 + milliseconds;
577 req->done = FALSE;
578 req->buffer = NULL;
579 req->size = 0;
580 req->error = 0;
581 req->wait = TRUE;
582 m_internal->QueueRequest(req, TRUE);
f4ada568 583
a737331d 584 return (req->io_nbytes != 0);
f4ada568 585}
f4ada568 586
a737331d 587bool wxSocketBase::Wait(long seconds, long milliseconds)
f4ada568 588{
a737331d
GL
589 return _Wait(seconds, milliseconds, REQ_ACCEPT | REQ_CONNECT |
590 REQ_READ | REQ_WRITE | REQ_LOST);
f4ada568 591}
f4ada568 592
a737331d 593bool wxSocketBase::WaitForRead(long seconds, long milliseconds)
f4ada568 594{
a737331d 595 return _Wait(seconds, milliseconds, REQ_READ | REQ_LOST);
f4ada568
GL
596}
597
a737331d 598bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
f4ada568 599{
a737331d
GL
600 return _Wait(seconds, milliseconds, REQ_WRITE);
601}
f4ada568 602
a737331d
GL
603bool wxSocketBase::WaitForLost(long seconds, long milliseconds)
604{
605 return _Wait(seconds, milliseconds, REQ_LOST);
f4ada568 606}
a737331d
GL
607
608// --------------------------------------------------------------
609// --------- wxSocketBase callback management -------------------
610// --------------------------------------------------------------
f4ada568
GL
611
612wxSocketBase::wxRequestNotify wxSocketBase::EventToNotify(wxRequestEvent evt)
613{
db131261
RR
614 switch (evt)
615 {
f4ada568
GL
616 case EVT_READ:
617 return REQ_READ;
618 case EVT_PEEK:
619 return REQ_PEEK;
620 case EVT_WRITE:
621 return REQ_WRITE;
622 case EVT_LOST:
623 return REQ_LOST;
624 case EVT_ACCEPT:
625 return REQ_ACCEPT;
626 case EVT_CONNECT:
627 return REQ_CONNECT;
628 }
629 return 0;
630}
631
632void wxSocketBase::SetFlags(wxSockFlags _flags)
633{
634 m_flags = _flags;
a737331d 635 if (_flags & SPEED) {
f4ada568
GL
636 // SPEED and WAITALL are antagonists.
637 m_flags = (wxSockFlags)(m_flags & ~WAITALL);
f4ada568
GL
638 }
639}
640
a737331d 641wxSocketBase::wxSockFlags wxSocketBase::GetFlags() const
f4ada568 642{
a737331d 643 return m_flags;
f4ada568
GL
644}
645
a737331d 646void wxSocketBase::SetNotify(wxRequestNotify flags)
f4ada568 647{
a737331d
GL
648 /* Check if server */
649 if (m_type != SOCK_SERVER)
650 flags &= ~REQ_ACCEPT;
f4ada568 651
48da7d0b 652 m_internal->AcquireData();
a737331d 653 m_neededreq = flags;
48da7d0b 654 m_internal->ReleaseData();
a737331d 655 if (m_neededreq == 0)
2a4f27f2 656 m_internal->StopWaiter();
8c14576d 657 else
a737331d 658 Notify(m_notify_state);
f4ada568
GL
659}
660
661void wxSocketBase::Notify(bool notify)
662{
aadbdf11
GL
663 m_notify_state = notify;
664 if (m_fd == INVALID_SOCKET)
665 return;
666
f4ada568 667 if (notify)
2a4f27f2 668 m_internal->ResumeWaiter();
f4ada568 669 else
2a4f27f2 670 m_internal->StopWaiter();
f4ada568
GL
671}
672
673void wxSocketBase::OnRequest(wxRequestEvent req_evt)
674{
a737331d
GL
675 wxSocketEvent event(m_id);
676 wxRequestNotify notify = EventToNotify(req_evt);
f4ada568 677
a737331d
GL
678 if ((m_neededreq & notify) == notify) {
679 event.m_socket = this;
680 event.m_skevt = req_evt;
681 ProcessEvent(event);
682 // TODOTODO
683 // OldOnNotify(req_evt);
f4ada568 684
a737331d 685 // We disable the event reporting.
2a4f27f2 686 m_neededreq &= ~notify;
f4ada568 687 }
f4ada568
GL
688}
689
690wxSocketEvent::wxSocketEvent(int id)
691 : wxEvent(id)
692{
693 wxEventType type = (wxEventType)wxEVT_SOCKET;
694
695 SetEventType(type);
696}
697
aadbdf11 698void wxSocketEvent::CopyObject(wxObject& obj_d) const
f4ada568 699{
aadbdf11
GL
700 wxSocketEvent *event = (wxSocketEvent *)&obj_d;
701
702 wxEvent::CopyObject(obj_d);
f4ada568 703
a737331d
GL
704 event->m_skevt = m_skevt;
705 event->m_socket = m_socket;
f4ada568
GL
706}
707
a737331d 708void wxSocketBase::OldOnNotify(wxRequestEvent evt)
f4ada568 709{
f4ada568
GL
710}
711
a737331d
GL
712// --------------------------------------------------------------
713// --------- wxSocketBase functions [Callback, CallbackData] ----
714// --------------------------------------------------------------
f4ada568
GL
715
716void wxSocketBase::SetEventHandler(wxEvtHandler& h_evt, int id)
717{
718 SetNextHandler(&h_evt);
719 m_id = id;
720}
721
722// --------------------------------------------------------------
723// --------- wxSocketBase pushback library ----------------------
724// --------------------------------------------------------------
db131261 725
f4ada568
GL
726void wxSocketBase::CreatePushbackAfter(const char *buffer, size_t size)
727{
728 char *curr_pos;
729
375abe3d
GL
730 if (m_unread != NULL)
731 m_unread = (char *) realloc(m_unread, m_unrd_size+size);
732 else
733 m_unread = (char *) malloc(size);
f4ada568
GL
734 curr_pos = m_unread + m_unrd_size;
735
736 memcpy(curr_pos, buffer, size);
737 m_unrd_size += size;
738}
739
740void wxSocketBase::CreatePushbackBefore(const char *buffer, size_t size)
741{
742 char *curr_pos, *new_buf;
743
744 new_buf = (char *) malloc(m_unrd_size+size);
745 curr_pos = new_buf + size;
746
747 memcpy(new_buf, buffer, size);
41895a05
GL
748 if (m_unrd_size != 0) {
749 memcpy(curr_pos, m_unread, m_unrd_size);
750 free(m_unread);
751 }
f4ada568
GL
752 m_unread = new_buf;
753 m_unrd_size += size;
754}
755
756size_t wxSocketBase::GetPushback(char *buffer, size_t size, bool peek)
757{
758 if (!m_unrd_size)
759 return 0;
760
761 if (size > m_unrd_size)
762 size = m_unrd_size;
763 memcpy(buffer, m_unread, size);
764
765 if (!peek) {
766 m_unrd_size -= size;
41895a05 767 if (m_unrd_size == 0) {
f4ada568
GL
768 free(m_unread);
769 m_unread = NULL;
770 }
771 }
772
773 return size;
774}
775
776// --------------------------------------------------------------
a737331d 777// --------- wxSocketBase buffer core requester -----------------
f4ada568
GL
778// --------------------------------------------------------------
779
f4ada568 780void wxSocketBase::WantBuffer(char *buffer, size_t nbytes,
17dff81c 781 wxRequestEvent evt)
f4ada568
GL
782{
783 bool buf_timed_out;
784
785 if (m_fd == INVALID_SOCKET || !m_handler || !m_connected)
786 return;
787
f4ada568 788 SockRequest *buf = new SockRequest;
f4ada568
GL
789
790 SaveState();
f4ada568
GL
791 buf->buffer = buffer;
792 buf->size = nbytes;
793 buf->done = FALSE;
a737331d
GL
794 buf->type = EventToNotify(evt);
795 buf->io_nbytes = 0;
f4ada568 796 buf->error = 0;
a737331d
GL
797 buf->wait = TRUE;
798 buf->timeout = 1000;
f4ada568
GL
799 buf_timed_out = FALSE;
800
48da7d0b 801 if ((m_flags & SPEED) != 0)
a737331d
GL
802 m_internal->QueueRequest(buf, FALSE);
803 else
48da7d0b 804 if ((m_flags & NOWAIT) != 0)
a737331d
GL
805 m_internal->QueueRequest(buf, TRUE);
806 else
807 m_internal->QueueRequest(buf, TRUE);
808 m_lcount += buf->io_nbytes;
f4ada568
GL
809 if (buf_timed_out)
810 m_error = ETIMEDOUT;
811 else
812 m_error = buf->error;
813
814 delete buf;
815 RestoreState();
816}
817
818// --------------------------------------------------------------
8c14576d 819// wxSocketServer
f4ada568
GL
820// --------------------------------------------------------------
821
f4ada568 822wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
17dff81c 823 wxSockFlags flags) :
f4ada568
GL
824 wxSocketBase(flags, SOCK_SERVER)
825{
826 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
827
828 if (m_fd == INVALID_SOCKET)
829 return;
384b4373 830
f4ada568
GL
831 int flag = 1;
832 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int));
384b4373 833
f4ada568
GL
834 struct sockaddr *myaddr;
835 size_t len;
384b4373 836
f4ada568
GL
837 addr_man.Build(myaddr, len);
838 if (bind(m_fd, myaddr, addr_man.SockAddrLen()) < 0)
839 return;
384b4373 840
f4ada568
GL
841 if (listen(m_fd, 5) < 0) {
842 m_fd = INVALID_SOCKET;
843 return;
844 }
a737331d 845
9111db68
GL
846 m_internal->SetFD(m_fd);
847
2a4f27f2 848 Notify(TRUE);
f4ada568
GL
849}
850
851// --------------------------------------------------------------
8c14576d 852// wxSocketServer Accept
f4ada568 853// --------------------------------------------------------------
8c14576d 854
f4ada568
GL
855bool wxSocketServer::AcceptWith(wxSocketBase& sock)
856{
857 int fd2;
384b4373 858
aadbdf11
GL
859 m_internal->AcquireFD();
860 if ((fd2 = accept(m_fd, 0, 0)) < 0) {
861 m_internal->ReleaseFD();
f4ada568 862 return FALSE;
aadbdf11
GL
863 }
864 m_internal->ReleaseFD();
f4ada568
GL
865
866 struct linger linger;
867 linger.l_onoff = 0;
868 linger.l_linger = 1;
384b4373 869
f4ada568 870 setsockopt(fd2, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
384b4373 871
f4ada568
GL
872 int flag = 0;
873 setsockopt(fd2, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
384b4373 874
f4ada568
GL
875 sock.m_type = SOCK_INTERNAL;
876 sock.m_fd = fd2;
877 sock.m_connected = TRUE;
878
9111db68
GL
879 sock.m_internal->SetFD(fd2);
880
2a4f27f2 881 sock.m_internal->ResumeWaiter();
a737331d 882
f4ada568
GL
883 return TRUE;
884}
885
886wxSocketBase *wxSocketServer::Accept()
887{
888 wxSocketBase* sock = new wxSocketBase();
889
890 sock->SetFlags((wxSockFlags)m_flags);
891
892 if (!AcceptWith(*sock))
893 return NULL;
894
895 if (m_handler)
896 m_handler->Register(sock);
897
898 return sock;
899}
900
f4ada568 901// --------------------------------------------------------------
8c14576d 902// wxSocketClient
f4ada568
GL
903// --------------------------------------------------------------
904
905// --------- wxSocketClient CONSTRUCTOR -------------------------
906// --------------------------------------------------------------
907wxSocketClient::wxSocketClient(wxSockFlags _flags) :
17dff81c 908 wxSocketBase(_flags, SOCK_CLIENT)
f4ada568
GL
909{
910}
911
912// --------------------------------------------------------------
913// --------- wxSocketClient DESTRUCTOR --------------------------
914// --------------------------------------------------------------
915wxSocketClient::~wxSocketClient()
916{
917}
918
919// --------------------------------------------------------------
920// --------- wxSocketClient Connect functions -------------------
921// --------------------------------------------------------------
e22036dc 922bool wxSocketClient::Connect(wxSockAddress& addr_man, bool WXUNUSED(wait) )
f4ada568
GL
923{
924 struct linger linger;
925
926 if (IsConnected())
927 Close();
928
a737331d
GL
929 // Initializes all socket stuff ...
930 // --------------------------------
f4ada568 931 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
384b4373 932
f4ada568
GL
933 if (m_fd < 0)
934 return FALSE;
384b4373 935
f4ada568
GL
936 m_connected = FALSE;
937
938 linger.l_onoff = 1;
384b4373 939 linger.l_linger = 5;
f4ada568 940 setsockopt(m_fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
384b4373 941
f4ada568 942 // Stay in touch with the state of things...
384b4373 943
f4ada568
GL
944 unsigned long flag = 1;
945 setsockopt(m_fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
384b4373 946
f4ada568
GL
947 // Disable the nagle algorithm, which delays sends till the
948 // buffer is full (or a certain time period has passed?)...
949
950#if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
951 flag = 1;
952 setsockopt(m_fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int));
953#endif
384b4373 954
f4ada568
GL
955 struct sockaddr *remote;
956 size_t len;
957
958 addr_man.Build(remote, len);
959
960 if (connect(m_fd, remote, len) != 0)
961 return FALSE;
962
9111db68
GL
963 m_internal->SetFD(m_fd);
964
a737331d
GL
965 // Enables bg events.
966 // ------------------
f4ada568
GL
967 Notify(TRUE);
968
969 m_connected = TRUE;
970 return TRUE;
971}
972
75ed1d15 973bool wxSocketClient::WaitOnConnect(long seconds, long microseconds)
f4ada568 974{
75ed1d15 975 int ret = _Wait(seconds, microseconds, REQ_CONNECT | REQ_LOST);
384b4373 976
f4ada568
GL
977 if (ret)
978 m_connected = TRUE;
384b4373
RD
979
980 return m_connected;
f4ada568
GL
981}
982
983void wxSocketClient::OnRequest(wxRequestEvent evt)
984{
8c14576d
RR
985 if (evt == EVT_CONNECT)
986 {
987 if (m_connected)
988 {
2a4f27f2 989 m_neededreq &= ~REQ_CONNECT;
f4ada568
GL
990 return;
991 }
384b4373 992 m_connected = TRUE;
f4ada568
GL
993 return;
994 }
995 wxSocketBase::OnRequest(evt);
996}
997
998/////////////////////////////////////////////////////////////////
999// wxSocketHandler ///////////////////////////////////////////////
1000/////////////////////////////////////////////////////////////////
1001
1002wxSocketHandler *wxSocketHandler::master = NULL;
1003#if defined(__WINDOWS__)
1004static int win_initialized = 0;
1005#endif
1006
1007// --------------------------------------------------------------
1008// --------- wxSocketHandler CONSTRUCTOR ------------------------
1009// --------------------------------------------------------------
f4ada568
GL
1010wxSocketHandler::wxSocketHandler()
1011{
1012#if defined(__WINDOWS__)
8c14576d
RR
1013 if (!win_initialized)
1014 {
f4ada568
GL
1015 WSADATA wsaData;
1016
1017 WSAStartup((1 << 8) | 1, &wsaData);
1018 win_initialized = 1;
1019 }
f4ada568
GL
1020#endif
1021
1022 socks = new wxList;
1023
1024#ifndef __WINDOWS__
1025 signal(SIGPIPE, SIG_IGN);
1026#endif
1027}
1028
1029// --------------------------------------------------------------
1030// --------- wxSocketHandler DESTRUCTOR -------------------------
1031// --------------------------------------------------------------
1032wxSocketHandler::~wxSocketHandler()
1033{
1034 wxNode *next_node, *node = socks->First();
1035
8c14576d
RR
1036 while (node)
1037 {
f4ada568
GL
1038 wxSocketBase* sock = (wxSocketBase*)node->Data();
1039
1040 delete sock;
1041 next_node = node->Next();
1042 delete node;
1043 node = next_node;
1044 }
1045
1046 delete socks;
1047
1048#ifdef __WINDOWS__
f4ada568
GL
1049 WSACleanup();
1050 win_initialized = 0;
f4ada568
GL
1051#endif
1052}
1053
1054// --------------------------------------------------------------
1055// --------- wxSocketHandler registering functions --------------
1056// --------------------------------------------------------------
8c14576d 1057
f4ada568
GL
1058void wxSocketHandler::Register(wxSocketBase* sock)
1059{
1060 wxNode *node;
1061
8c14576d
RR
1062 for (node = socks->First(); node != NULL; node = node->Next())
1063 {
f4ada568
GL
1064 wxSocketBase* s = (wxSocketBase*)node->Data();
1065
1066 if (s == sock)
1067 return;
1068 }
1069
8c14576d
RR
1070 if (sock)
1071 {
f4ada568
GL
1072 socks->Append(sock);
1073 sock->SetHandler(this);
f4ada568
GL
1074 }
1075}
1076
1077void wxSocketHandler::UnRegister(wxSocketBase* sock)
1078{
1079 wxNode *node;
1080
8c14576d
RR
1081 for (node = socks->First(); node; node = node->Next())
1082 {
f4ada568 1083 wxSocketBase* s = (wxSocketBase*)node->Data();
384b4373 1084
8c14576d
RR
1085 if (s == sock)
1086 {
f4ada568 1087 delete node;
f4ada568
GL
1088 sock->SetHandler(NULL);
1089 return;
1090 }
1091 }
1092}
1093
1094unsigned long wxSocketHandler::Count() const
1095{
1096 return socks->Number();
1097}
1098
1099// --------------------------------------------------------------
1100// --------- wxSocketHandler "big" wait functions ---------------
1101// --------------------------------------------------------------
f4ada568
GL
1102
1103int wxSocketHandler::Wait(long seconds, long microseconds)
1104{
a737331d
GL
1105 // TODO Needs the completely asynchronous notifier.
1106
1107 /*
f4ada568
GL
1108 int i;
1109 int on_wait;
f4ada568 1110 wxNode *node;
8c14576d
RR
1111 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1112 {
f4ada568
GL
1113 wxSocketBase *sock = (wxSocketBase *)node->Data();
1114
1115 sock->SaveState();
1116
1117 sock->SetupCallbacks();
1118
1119 sock->Callback(handler_cbk);
1120 sock->CallbackData((char *)&on_wait);
1121 }
1122 on_wait = 0;
1123 if (seconds != -1)
1124 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1125
1126 while (!on_wait)
1127 PROCESS_EVENTS();
1128
8c14576d
RR
1129 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1130 {
f4ada568
GL
1131 wxSocketBase *sock = (wxSocketBase *)node->Data();
1132
1133 sock->RestoreState();
1134 }
1135
1136 if (on_wait == -2)
1137 return 0;
1138
1139 return on_wait;
a737331d
GL
1140 */
1141 return 0;
f4ada568
GL
1142}
1143
1144void wxSocketHandler::YieldSock()
1145{
1146 wxNode *node;
1147
a737331d
GL
1148 // Nothing to do anymore here except waiting for the queue emptying.
1149 for (node = socks->First(); node; node=node->Next()) {
f4ada568
GL
1150 wxSocketBase *sock = (wxSocketBase *)node->Data();
1151
a737331d 1152 sock->m_internal->WaitForEnd(NULL);
f4ada568
GL
1153 }
1154}
1155
1156// --------------------------------------------------------------
1157// --------- wxSocketHandler: create and register the socket ----
1158// --------------------------------------------------------------
1159wxSocketServer *wxSocketHandler::CreateServer(wxSockAddress& addr,
17dff81c 1160 wxSocketBase::wxSockFlags flags)
f4ada568
GL
1161{
1162 wxSocketServer *serv = new wxSocketServer(addr, flags);
1163
1164 Register(serv);
1165 return serv;
1166}
1167
1168wxSocketClient *wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags)
1169{
1170 wxSocketClient *client = new wxSocketClient(flags);
1171
1172 Register(client);
1173 return client;
1174}
1175
8c14576d
RR
1176bool wxSocketModule::OnInit()
1177{
3b4183d8
GL
1178 wxSocketHandler::master = new wxSocketHandler();
1179 return TRUE;
1180}
1181
8c14576d
RR
1182void wxSocketModule::OnExit()
1183{
3b4183d8
GL
1184 delete wxSocketHandler::master;
1185 wxSocketHandler::master = NULL;
1186}
1187
7f555861
JS
1188#endif
1189 // __WXSTUBS__
35a4dab7
GL
1190
1191#endif
1192 // wxUSE_SOCKETS