]> git.saurik.com Git - wxWidgets.git/blob - src/common/socket.cpp
1. wxWindow::IsTopLevel() added and documented
[wxWidgets.git] / src / common / socket.cpp
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: April 1999
8 // Copyright: (C) 1999 1998, 1997, Guilhem Lavaux
9 // RCS_ID: $Id$
10 // License: see wxWindows license
11 ////////////////////////////////////////////////////////////////////////////////
12 #ifdef __GNUG__
13 #pragma implementation "socket.h"
14 #endif
15
16 #ifdef __MWERKS__
17 typedef int socklen_t ;
18 #endif
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_SOCKETS
28
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
38 // Not enough OS behaviour defined for wxStubs
39 #ifndef __WXSTUBS__
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44
45 /////////////////////////////////////////////////////////////////////////////
46 // System specific headers
47 /////////////////////////////////////////////////////////////////////////////
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>
54
55 #endif
56
57 #if defined(__WINDOWS__)
58 #include <winsock.h>
59 #endif // __WINDOWS__
60
61 #if defined(__UNIX__)
62
63 #ifdef VMS
64 #include <socket.h>
65 #else
66 #include <sys/socket.h>
67 #endif
68 #include <sys/ioctl.h>
69
70 #include <sys/time.h>
71 #include <unistd.h>
72
73 #ifdef sun
74 #include <sys/filio.h>
75 #endif
76
77 #endif // __UNIX__
78
79 #include <signal.h>
80 #include <errno.h>
81
82 #ifdef __VISUALC__
83 #include <io.h>
84 #endif
85
86 /////////////////////////////////////////////////////////////////////////////
87 // wxSocket headers
88 /////////////////////////////////////////////////////////////////////////////
89 #include <wx/module.h>
90 #define WXSOCK_INTERNAL
91 #include <wx/sckaddr.h>
92 #include <wx/socket.h>
93 #include <wx/sckint.h>
94
95 // ----------------------
96 // Some patch ----- BEGIN
97 // ----------------------
98 #ifdef __WINDOWS__
99 #define close closesocket
100 #define ioctl ioctlsocket
101 #ifdef errno
102 #undef errno
103 #endif
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
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
123 #if defined( NEED_WSAFDIsSet ) || defined( __VISUALC__ )
124 int PASCAL FAR __WSAFDIsSet(SOCKET fd, fd_set FAR *set)
125 {
126 int i = set->fd_count;
127
128 while (i--)
129 {
130 if (set->fd_array[i] == fd)
131 return 1;
132 }
133
134 return 0;
135 }
136 #endif
137 #endif
138
139 // -------------------
140 // Some patch ---- END
141 // -------------------
142
143 #ifdef GetClassInfo
144 #undef GetClassInfo
145 #endif
146
147 // --------------------------------------------------------------
148 // Module
149 // --------------------------------------------------------------
150 class wxSocketModule: public wxModule
151 {
152 DECLARE_DYNAMIC_CLASS(wxSocketModule)
153 public:
154 wxSocketModule() {}
155 bool OnInit();
156 void OnExit();
157 };
158
159 // --------------------------------------------------------------
160 // ClassInfos
161 // --------------------------------------------------------------
162 #if !USE_SHARED_LIBRARY
163 IMPLEMENT_CLASS(wxSocketBase, wxObject)
164 IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
165 IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
166 IMPLEMENT_CLASS(wxSocketHandler, wxObject)
167 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
168 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
169 #endif
170
171 // --------------------------------------------------------------
172 // --------- wxSocketBase CONSTRUCTOR ---------------------------
173 // --------------------------------------------------------------
174 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags,
175 wxSocketBase::wxSockType _type) :
176 wxEvtHandler(),
177 m_flags(_flags), m_type(_type), m_connected(FALSE), m_connecting(FALSE),
178 m_fd(INVALID_SOCKET), m_id(-1),
179 m_handler(0),
180 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
181 m_timeout(3600),
182 m_unread(NULL), m_unrd_size(0),
183 m_cbk(NULL), m_cdata(NULL),
184 m_notify_state(FALSE)
185 {
186 m_internal = new wxSocketInternal(this);
187 }
188
189 wxSocketBase::wxSocketBase() :
190 wxEvtHandler(),
191 m_flags(WAITALL), m_type(SOCK_UNINIT), m_connected(FALSE),
192 m_connecting(FALSE), m_fd(INVALID_SOCKET),
193 m_id(-1), m_handler(0),
194 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
195 m_timeout(3600),
196 m_unread(NULL), m_unrd_size(0),
197 m_cbk(NULL), m_cdata(NULL),
198 m_notify_state(FALSE)
199 {
200 m_internal = new wxSocketInternal(this);
201 }
202
203 // --------------------------------------------------------------
204 // wxSocketBase
205 // --------------------------------------------------------------
206
207 wxSocketBase::~wxSocketBase()
208 {
209 // First, close the file descriptor.
210 Close();
211
212 if (m_unread)
213 free(m_unread);
214 // Unregister from the handler database.
215 if (m_handler)
216 m_handler->UnRegister(this);
217
218 // Destroy all saved states.
219 m_states.DeleteContents(TRUE);
220
221 // Destroy the socket manager.
222 delete m_internal;
223 }
224
225 bool wxSocketBase::Close()
226 {
227 if (m_fd != INVALID_SOCKET)
228 {
229 if (m_notify_state == TRUE)
230 Notify(FALSE);
231
232 // Shutdown the connection.
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 // --------------------------------------------------------------
243 // wxSocketBase base IO function
244 // --------------------------------------------------------------
245
246 wxSocketBase& wxSocketBase::Read(char* buffer, size_t nbytes)
247 {
248 m_lcount = GetPushback(buffer, nbytes, FALSE);
249 nbytes -= m_lcount;
250 buffer += m_lcount;
251
252 // If we have got the whole needed buffer or if we don't want to
253 // wait then it returns immediately.
254 if (!nbytes || (m_lcount && !(m_flags & WAITALL)) ) {
255 return *this;
256 }
257
258 WantBuffer(buffer, nbytes, EVT_READ);
259
260 return *this;
261 }
262
263 wxSocketBase& 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
322 wxSocketBase& wxSocketBase::Peek(char* buffer, size_t nbytes)
323 {
324 m_lcount = GetPushback(buffer, nbytes, TRUE);
325 if (nbytes-m_lcount == 0)
326 {
327 return *this;
328 }
329 buffer += m_lcount;
330 nbytes -= m_lcount;
331
332 WantBuffer(buffer, nbytes, EVT_PEEK);
333
334 return *this;
335 }
336
337 wxSocketBase& wxSocketBase::Write(const char *buffer, size_t nbytes)
338 {
339 m_lcount = 0;
340 WantBuffer((char *)buffer, nbytes, EVT_WRITE);
341 return *this;
342 }
343
344 wxSocketBase& 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
385 wxSocketBase& wxSocketBase::Unread(const char *buffer, size_t nbytes)
386 {
387 m_lcount = 0;
388 if (nbytes != 0) {
389 CreatePushbackAfter(buffer, nbytes);
390 m_lcount = nbytes;
391 }
392 return *this;
393 }
394
395 bool 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
405 m_internal->AcquireFD();
406
407 tv.tv_sec = 0;
408 tv.tv_usec = 0;
409 FD_ZERO(&sock_set);
410 FD_SET(m_fd, &sock_set);
411 select(m_fd+1, &sock_set, NULL, NULL, &tv);
412
413 m_internal->ReleaseFD();
414
415 return (FD_ISSET(m_fd, &sock_set) != 0);
416 }
417
418 // ---------------------------------------------------------------------
419 // --------- wxSocketBase Discard(): deletes all byte in the input queue
420 // ---------------------------------------------------------------------
421 void 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));
429
430 while (recv_size == MAX_BUFSIZE)
431 {
432 recv_size = Read(my_data, MAX_BUFSIZE).LastCount();
433 }
434
435 RestoreState();
436 delete [] my_data;
437
438 #undef MAX_BUFSIZE
439 }
440
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
457
458 // --------------------------------------------------------------
459 // wxSocketBase socket info functions
460 // --------------------------------------------------------------
461
462 bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
463 {
464 struct sockaddr my_addr;
465 wxSOCKET_INT len_addr = sizeof(my_addr);
466
467 if (m_fd < 0)
468 return FALSE;
469
470 m_internal->AcquireFD();
471
472 if (getpeername(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
473 m_internal->ReleaseFD();
474 return FALSE;
475 }
476
477 m_internal->ReleaseFD();
478 addr_man.Disassemble(&my_addr, len_addr);
479 return TRUE;
480 }
481
482 bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
483 {
484 struct sockaddr my_addr;
485 wxSOCKET_INT len_addr = sizeof(my_addr);
486
487 if (m_fd < 0)
488 return FALSE;
489
490 m_internal->AcquireFD();
491
492 if (getsockname(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
493 m_internal->ReleaseFD();
494 return FALSE;
495 }
496 m_internal->ReleaseFD();
497
498 addr_man.Disassemble(&my_addr, len_addr);
499 return TRUE;
500 }
501
502 // --------------------------------------------------------------
503 // wxSocketBase wait functions
504 // --------------------------------------------------------------
505
506 void wxSocketBase::SaveState()
507 {
508 SocketState *state = new SocketState;
509
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;
515
516 m_states.Append((wxObject *)state);
517 }
518
519 void wxSocketBase::RestoreState()
520 {
521 wxNode *node;
522 SocketState *state;
523
524 node = m_states.Last();
525 if (!node)
526 return;
527
528 state = (SocketState *)node->Data();
529
530 SetFlags(state->socket_flags);
531 m_internal->AcquireData();
532 m_neededreq = state->evt_notify_state;
533 m_internal->ReleaseData();
534 m_cbk = state->c_callback;
535 m_cdata = state->c_callback_data;
536 Notify(state->notify_state);
537
538 delete node;
539 delete state;
540 }
541
542 // --------------------------------------------------------------
543 // --------- wxSocketBase callback functions --------------------
544 // --------------------------------------------------------------
545
546 wxSocketBase::wxSockCbk wxSocketBase::Callback(wxSockCbk cbk_)
547 {
548 wxSockCbk old_cbk = cbk_;
549
550 m_cbk = cbk_;
551 return old_cbk;
552 }
553
554 char *wxSocketBase::CallbackData(char *data)
555 {
556 char *old_data = m_cdata;
557
558 m_cdata = data;
559 return old_data;
560 }
561
562 // --------------------------------------------------------------
563 // --------- wxSocketBase wait functions ------------------------
564 // --------------------------------------------------------------
565
566 bool wxSocketBase::_Wait(long seconds, long milliseconds, int type)
567 {
568 SockRequest *req;
569
570 if ((!m_connected && !m_connecting) || m_fd < 0)
571 return FALSE;
572
573 req = new SockRequest;
574
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);
583
584 return (req->io_nbytes != 0);
585 }
586
587 bool wxSocketBase::Wait(long seconds, long milliseconds)
588 {
589 return _Wait(seconds, milliseconds, REQ_ACCEPT | REQ_CONNECT |
590 REQ_READ | REQ_WRITE | REQ_LOST);
591 }
592
593 bool wxSocketBase::WaitForRead(long seconds, long milliseconds)
594 {
595 return _Wait(seconds, milliseconds, REQ_READ | REQ_LOST);
596 }
597
598 bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
599 {
600 return _Wait(seconds, milliseconds, REQ_WRITE);
601 }
602
603 bool wxSocketBase::WaitForLost(long seconds, long milliseconds)
604 {
605 return _Wait(seconds, milliseconds, REQ_LOST);
606 }
607
608 // --------------------------------------------------------------
609 // --------- wxSocketBase callback management -------------------
610 // --------------------------------------------------------------
611
612 wxSocketBase::wxRequestNotify wxSocketBase::EventToNotify(wxRequestEvent evt)
613 {
614 switch (evt)
615 {
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
632 void wxSocketBase::SetFlags(wxSockFlags _flags)
633 {
634 m_flags = _flags;
635 if (_flags & SPEED) {
636 // SPEED and WAITALL are antagonists.
637 m_flags = (wxSockFlags)(m_flags & ~WAITALL);
638 }
639 }
640
641 wxSocketBase::wxSockFlags wxSocketBase::GetFlags() const
642 {
643 return m_flags;
644 }
645
646 void wxSocketBase::SetNotify(wxRequestNotify flags)
647 {
648 /* Check if server */
649 if (m_type != SOCK_SERVER)
650 flags &= ~REQ_ACCEPT;
651
652 m_internal->AcquireData();
653 m_neededreq = flags;
654 m_internal->ReleaseData();
655 if (m_neededreq == 0)
656 m_internal->StopWaiter();
657 else
658 Notify(m_notify_state);
659 }
660
661 void wxSocketBase::Notify(bool notify)
662 {
663 m_notify_state = notify;
664 if (m_fd == INVALID_SOCKET)
665 return;
666
667 if (notify)
668 m_internal->ResumeWaiter();
669 else
670 m_internal->StopWaiter();
671 }
672
673 void wxSocketBase::OnRequest(wxRequestEvent req_evt)
674 {
675 wxSocketEvent event(m_id);
676 wxRequestNotify notify = EventToNotify(req_evt);
677
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);
684
685 // We disable the event reporting.
686 m_neededreq &= ~notify;
687 }
688 }
689
690 wxSocketEvent::wxSocketEvent(int id)
691 : wxEvent(id)
692 {
693 wxEventType type = (wxEventType)wxEVT_SOCKET;
694
695 SetEventType(type);
696 }
697
698 void wxSocketEvent::CopyObject(wxObject& obj_d) const
699 {
700 wxSocketEvent *event = (wxSocketEvent *)&obj_d;
701
702 wxEvent::CopyObject(obj_d);
703
704 event->m_skevt = m_skevt;
705 event->m_socket = m_socket;
706 }
707
708 void wxSocketBase::OldOnNotify(wxRequestEvent evt)
709 {
710 }
711
712 // --------------------------------------------------------------
713 // --------- wxSocketBase functions [Callback, CallbackData] ----
714 // --------------------------------------------------------------
715
716 void wxSocketBase::SetEventHandler(wxEvtHandler& h_evt, int id)
717 {
718 SetNextHandler(&h_evt);
719 m_id = id;
720 }
721
722 // --------------------------------------------------------------
723 // --------- wxSocketBase pushback library ----------------------
724 // --------------------------------------------------------------
725
726 void wxSocketBase::CreatePushbackAfter(const char *buffer, size_t size)
727 {
728 char *curr_pos;
729
730 if (m_unread != NULL)
731 m_unread = (char *) realloc(m_unread, m_unrd_size+size);
732 else
733 m_unread = (char *) malloc(size);
734 curr_pos = m_unread + m_unrd_size;
735
736 memcpy(curr_pos, buffer, size);
737 m_unrd_size += size;
738 }
739
740 void 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);
748 if (m_unrd_size != 0) {
749 memcpy(curr_pos, m_unread, m_unrd_size);
750 free(m_unread);
751 }
752 m_unread = new_buf;
753 m_unrd_size += size;
754 }
755
756 size_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;
767 if (m_unrd_size == 0) {
768 free(m_unread);
769 m_unread = NULL;
770 }
771 }
772
773 return size;
774 }
775
776 // --------------------------------------------------------------
777 // --------- wxSocketBase buffer core requester -----------------
778 // --------------------------------------------------------------
779
780 void wxSocketBase::WantBuffer(char *buffer, size_t nbytes,
781 wxRequestEvent evt)
782 {
783 bool buf_timed_out;
784
785 if (m_fd == INVALID_SOCKET || !m_handler || !m_connected)
786 return;
787
788 SockRequest *buf = new SockRequest;
789
790 SaveState();
791 buf->buffer = buffer;
792 buf->size = nbytes;
793 buf->done = FALSE;
794 buf->type = EventToNotify(evt);
795 buf->io_nbytes = 0;
796 buf->error = 0;
797 buf->wait = TRUE;
798 buf->timeout = 1000;
799 buf_timed_out = FALSE;
800
801 if ((m_flags & SPEED) != 0)
802 m_internal->QueueRequest(buf, FALSE);
803 else
804 if ((m_flags & NOWAIT) != 0)
805 m_internal->QueueRequest(buf, TRUE);
806 else
807 m_internal->QueueRequest(buf, TRUE);
808 m_lcount += buf->io_nbytes;
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 // --------------------------------------------------------------
819 // wxSocketServer
820 // --------------------------------------------------------------
821
822 wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
823 wxSockFlags flags) :
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;
830
831 int flag = 1;
832 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int));
833
834 struct sockaddr *myaddr;
835 size_t len;
836
837 addr_man.Build(myaddr, len);
838 if (bind(m_fd, myaddr, addr_man.SockAddrLen()) < 0)
839 return;
840
841 if (listen(m_fd, 5) < 0) {
842 m_fd = INVALID_SOCKET;
843 return;
844 }
845
846 m_internal->SetFD(m_fd);
847
848 Notify(TRUE);
849 }
850
851 // --------------------------------------------------------------
852 // wxSocketServer Accept
853 // --------------------------------------------------------------
854
855 bool wxSocketServer::AcceptWith(wxSocketBase& sock)
856 {
857 int fd2;
858
859 m_internal->AcquireFD();
860 if ((fd2 = accept(m_fd, 0, 0)) < 0) {
861 m_internal->ReleaseFD();
862 return FALSE;
863 }
864 m_internal->ReleaseFD();
865
866 struct linger linger;
867 linger.l_onoff = 0;
868 linger.l_linger = 1;
869
870 setsockopt(fd2, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
871
872 int flag = 0;
873 setsockopt(fd2, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
874
875 sock.m_type = SOCK_INTERNAL;
876 sock.m_fd = fd2;
877 sock.m_connected = TRUE;
878
879 sock.m_internal->SetFD(fd2);
880
881 sock.m_internal->ResumeWaiter();
882
883 return TRUE;
884 }
885
886 wxSocketBase *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
901 // --------------------------------------------------------------
902 // wxSocketClient
903 // --------------------------------------------------------------
904
905 // --------- wxSocketClient CONSTRUCTOR -------------------------
906 // --------------------------------------------------------------
907 wxSocketClient::wxSocketClient(wxSockFlags _flags) :
908 wxSocketBase(_flags, SOCK_CLIENT)
909 {
910 }
911
912 // --------------------------------------------------------------
913 // --------- wxSocketClient DESTRUCTOR --------------------------
914 // --------------------------------------------------------------
915 wxSocketClient::~wxSocketClient()
916 {
917 }
918
919 // --------------------------------------------------------------
920 // --------- wxSocketClient Connect functions -------------------
921 // --------------------------------------------------------------
922 bool wxSocketClient::Connect(wxSockAddress& addr_man, bool WXUNUSED(wait) )
923 {
924 struct linger linger;
925
926 if (IsConnected())
927 Close();
928
929 // Initializes all socket stuff ...
930 // --------------------------------
931 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
932
933 if (m_fd < 0)
934 return FALSE;
935
936 m_connected = FALSE;
937
938 linger.l_onoff = 1;
939 linger.l_linger = 5;
940 setsockopt(m_fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
941
942 // Stay in touch with the state of things...
943
944 unsigned long flag = 1;
945 setsockopt(m_fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
946
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
954
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
963 m_internal->SetFD(m_fd);
964
965 // Enables bg events.
966 // ------------------
967 Notify(TRUE);
968
969 m_connected = TRUE;
970 return TRUE;
971 }
972
973 bool wxSocketClient::WaitOnConnect(long seconds, long microseconds)
974 {
975 int ret = _Wait(seconds, microseconds, REQ_CONNECT | REQ_LOST);
976
977 if (ret)
978 m_connected = TRUE;
979
980 return m_connected;
981 }
982
983 void wxSocketClient::OnRequest(wxRequestEvent evt)
984 {
985 if (evt == EVT_CONNECT)
986 {
987 if (m_connected)
988 {
989 m_neededreq &= ~REQ_CONNECT;
990 return;
991 }
992 m_connected = TRUE;
993 return;
994 }
995 wxSocketBase::OnRequest(evt);
996 }
997
998 /////////////////////////////////////////////////////////////////
999 // wxSocketHandler ///////////////////////////////////////////////
1000 /////////////////////////////////////////////////////////////////
1001
1002 wxSocketHandler *wxSocketHandler::master = NULL;
1003 #if defined(__WINDOWS__)
1004 static int win_initialized = 0;
1005 #endif
1006
1007 // --------------------------------------------------------------
1008 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1009 // --------------------------------------------------------------
1010 wxSocketHandler::wxSocketHandler()
1011 {
1012 #if defined(__WINDOWS__)
1013 if (!win_initialized)
1014 {
1015 WSADATA wsaData;
1016
1017 WSAStartup((1 << 8) | 1, &wsaData);
1018 win_initialized = 1;
1019 }
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 // --------------------------------------------------------------
1032 wxSocketHandler::~wxSocketHandler()
1033 {
1034 wxNode *next_node, *node = socks->First();
1035
1036 while (node)
1037 {
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__
1049 WSACleanup();
1050 win_initialized = 0;
1051 #endif
1052 }
1053
1054 // --------------------------------------------------------------
1055 // --------- wxSocketHandler registering functions --------------
1056 // --------------------------------------------------------------
1057
1058 void wxSocketHandler::Register(wxSocketBase* sock)
1059 {
1060 wxNode *node;
1061
1062 for (node = socks->First(); node != NULL; node = node->Next())
1063 {
1064 wxSocketBase* s = (wxSocketBase*)node->Data();
1065
1066 if (s == sock)
1067 return;
1068 }
1069
1070 if (sock)
1071 {
1072 socks->Append(sock);
1073 sock->SetHandler(this);
1074 }
1075 }
1076
1077 void wxSocketHandler::UnRegister(wxSocketBase* sock)
1078 {
1079 wxNode *node;
1080
1081 for (node = socks->First(); node; node = node->Next())
1082 {
1083 wxSocketBase* s = (wxSocketBase*)node->Data();
1084
1085 if (s == sock)
1086 {
1087 delete node;
1088 sock->SetHandler(NULL);
1089 return;
1090 }
1091 }
1092 }
1093
1094 unsigned long wxSocketHandler::Count() const
1095 {
1096 return socks->Number();
1097 }
1098
1099 // --------------------------------------------------------------
1100 // --------- wxSocketHandler "big" wait functions ---------------
1101 // --------------------------------------------------------------
1102
1103 int wxSocketHandler::Wait(long seconds, long microseconds)
1104 {
1105 // TODO Needs the completely asynchronous notifier.
1106
1107 /*
1108 int i;
1109 int on_wait;
1110 wxNode *node;
1111 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1112 {
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
1129 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1130 {
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;
1140 */
1141 return 0;
1142 }
1143
1144 void wxSocketHandler::YieldSock()
1145 {
1146 wxNode *node;
1147
1148 // Nothing to do anymore here except waiting for the queue emptying.
1149 for (node = socks->First(); node; node=node->Next()) {
1150 wxSocketBase *sock = (wxSocketBase *)node->Data();
1151
1152 sock->m_internal->WaitForEnd(NULL);
1153 }
1154 }
1155
1156 // --------------------------------------------------------------
1157 // --------- wxSocketHandler: create and register the socket ----
1158 // --------------------------------------------------------------
1159 wxSocketServer *wxSocketHandler::CreateServer(wxSockAddress& addr,
1160 wxSocketBase::wxSockFlags flags)
1161 {
1162 wxSocketServer *serv = new wxSocketServer(addr, flags);
1163
1164 Register(serv);
1165 return serv;
1166 }
1167
1168 wxSocketClient *wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags)
1169 {
1170 wxSocketClient *client = new wxSocketClient(flags);
1171
1172 Register(client);
1173 return client;
1174 }
1175
1176 bool wxSocketModule::OnInit()
1177 {
1178 wxSocketHandler::master = new wxSocketHandler();
1179 return TRUE;
1180 }
1181
1182 void wxSocketModule::OnExit()
1183 {
1184 delete wxSocketHandler::master;
1185 wxSocketHandler::master = NULL;
1186 }
1187
1188 #endif
1189 // __WXSTUBS__
1190
1191 #endif
1192 // wxUSE_SOCKETS