]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/unix/gsocket.cpp
fixed broken link and use \backslash instead of literal backslash which has special...
[wxWidgets.git] / src / unix / gsocket.cpp
... / ...
CommitLineData
1/* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
3 * Name: gsocket.c
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Authors: David Elliott (C++ conversion, maintainer)
7 * Guilhem Lavaux,
8 * Guillermo Rodriguez Garcia <guille@iies.es>
9 * Purpose: GSocket main Unix and OS/2 file
10 * Licence: The wxWindows licence
11 * CVSID: $Id$
12 * -------------------------------------------------------------------------
13 */
14
15#if defined(__WATCOMC__)
16#include "wx/wxprec.h"
17#include <errno.h>
18#include <nerrno.h>
19#endif
20
21#ifndef __GSOCKET_STANDALONE__
22#include "wx/defs.h"
23#endif
24
25#if defined(__VISAGECPP__)
26#define BSD_SELECT /* use Berkeley Sockets select */
27#endif
28
29#if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
30
31#include <assert.h>
32#include <sys/types.h>
33#ifdef __VISAGECPP__
34#include <string.h>
35#include <sys/time.h>
36#include <types.h>
37#include <netinet/in.h>
38#endif
39#include <netdb.h>
40#include <sys/ioctl.h>
41
42#ifdef HAVE_SYS_SELECT_H
43# include <sys/select.h>
44#endif
45
46#ifdef __VMS__
47#include <socket.h>
48struct sockaddr_un
49{
50 u_char sun_len; /* sockaddr len including null */
51 u_char sun_family; /* AF_UNIX */
52 char sun_path[108]; /* path name (gag) */
53};
54#else
55#include <sys/socket.h>
56#include <sys/un.h>
57#endif
58
59#ifndef __VISAGECPP__
60#include <sys/time.h>
61#include <netinet/in.h>
62#include <arpa/inet.h>
63#include <errno.h>
64#include <string.h>
65#include <unistd.h>
66#else
67#include <nerrno.h>
68# if __IBMCPP__ < 400
69#include <machine/endian.h>
70#include <socket.h>
71#include <ioctl.h>
72#include <select.h>
73#include <unistd.h>
74
75#define EBADF SOCEBADF
76
77# ifdef min
78# undef min
79# endif
80# else
81#include <sys/socket.h>
82#include <sys/ioctl.h>
83#include <sys/select.h>
84
85#define close(a) soclose(a)
86#define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
87int _System bsdselect(int,
88 struct fd_set *,
89 struct fd_set *,
90 struct fd_set *,
91 struct timeval *);
92int _System soclose(int);
93# endif
94#endif
95#ifdef __EMX__
96#include <sys/select.h>
97#endif
98
99#include <stdio.h>
100#include <stdlib.h>
101#include <stddef.h>
102#include <ctype.h>
103#ifdef sun
104# include <sys/filio.h>
105#endif
106#ifdef sgi
107# include <bstring.h>
108#endif
109#ifdef _AIX
110# include <strings.h>
111#endif
112#include <signal.h>
113
114#ifndef WX_SOCKLEN_T
115
116#ifdef VMS
117# define WX_SOCKLEN_T unsigned int
118#else
119# ifdef __GLIBC__
120# if __GLIBC__ == 2
121# define WX_SOCKLEN_T socklen_t
122# endif
123# elif defined(__WXMAC__)
124# define WX_SOCKLEN_T socklen_t
125# else
126# define WX_SOCKLEN_T int
127# endif
128#endif
129
130#endif /* SOCKLEN_T */
131
132#ifndef SOCKOPTLEN_T
133#define SOCKOPTLEN_T WX_SOCKLEN_T
134#endif
135
136/*
137 * MSW defines this, Unices don't.
138 */
139#ifndef INVALID_SOCKET
140#define INVALID_SOCKET -1
141#endif
142
143/* UnixWare reportedly needs this for FIONBIO definition */
144#ifdef __UNIXWARE__
145#include <sys/filio.h>
146#endif
147
148/*
149 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
150 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
151 */
152#ifndef INADDR_NONE
153#define INADDR_NONE INADDR_BROADCAST
154#endif
155
156#if defined(__VISAGECPP__) || defined(__WATCOMC__)
157
158 #define MASK_SIGNAL() {
159 #define UNMASK_SIGNAL() }
160
161#else
162 extern "C" { typedef void (*wxSigHandler)(int); }
163
164 #define MASK_SIGNAL() \
165 { \
166 wxSigHandler old_handler = signal(SIGPIPE, SIG_IGN);
167
168 #define UNMASK_SIGNAL() \
169 signal(SIGPIPE, old_handler); \
170 }
171
172#endif
173
174/* If a SIGPIPE is issued by a socket call on a remotely closed socket,
175 the program will "crash" unless it explicitly handles the SIGPIPE.
176 By using MSG_NOSIGNAL, the SIGPIPE is suppressed. Later, we will
177 use SO_NOSIGPIPE (if available), the BSD equivalent. */
178#ifdef MSG_NOSIGNAL
179# define GSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
180#else /* MSG_NOSIGNAL not available (FreeBSD including OS X) */
181# define GSOCKET_MSG_NOSIGNAL 0
182#endif /* MSG_NOSIGNAL */
183
184#ifndef __GSOCKET_STANDALONE__
185# include "wx/unix/gsockunx.h"
186# include "wx/unix/private.h"
187# include "wx/gsocket.h"
188#if wxUSE_THREADS && (defined(HAVE_GETHOSTBYNAME) || defined(HAVE_GETSERVBYNAME))
189# include "wx/thread.h"
190#endif
191#else
192# include "gsockunx.h"
193# include "gsocket.h"
194# ifndef WXUNUSED
195# define WXUNUSED(x)
196# endif
197#endif /* __GSOCKET_STANDALONE__ */
198
199#if defined(HAVE_GETHOSTBYNAME)
200static struct hostent * deepCopyHostent(struct hostent *h,
201 const struct hostent *he,
202 char *buffer, int size, int *err)
203{
204 /* copy old structure */
205 memcpy(h, he, sizeof(struct hostent));
206
207 /* copy name */
208 int len = strlen(h->h_name);
209 if (len > size)
210 {
211 *err = ENOMEM;
212 return NULL;
213 }
214 memcpy(buffer, h->h_name, len);
215 buffer[len] = '\0';
216 h->h_name = buffer;
217
218 /* track position in the buffer */
219 int pos = len + 1;
220
221 /* reuse len to store address length */
222 len = h->h_length;
223
224 /* ensure pointer alignment */
225 unsigned int misalign = sizeof(char *) - pos%sizeof(char *);
226 if(misalign < sizeof(char *))
227 pos += misalign;
228
229 /* leave space for pointer list */
230 char **p = h->h_addr_list, **q;
231 char **h_addr_list = (char **)(buffer + pos);
232 while(*(p++) != 0)
233 pos += sizeof(char *);
234
235 /* copy addresses and fill new pointer list */
236 for (p = h->h_addr_list, q = h_addr_list; *p != 0; p++, q++)
237 {
238 if (size < pos + len)
239 {
240 *err = ENOMEM;
241 return NULL;
242 }
243 memcpy(buffer + pos, *p, len); /* copy content */
244 *q = buffer + pos; /* set copied pointer to copied content */
245 pos += len;
246 }
247 *++q = 0; /* null terminate the pointer list */
248 h->h_addr_list = h_addr_list; /* copy pointer to pointers */
249
250 /* ensure word alignment of pointers */
251 misalign = sizeof(char *) - pos%sizeof(char *);
252 if(misalign < sizeof(char *))
253 pos += misalign;
254
255 /* leave space for pointer list */
256 p = h->h_aliases;
257 char **h_aliases = (char **)(buffer + pos);
258 while(*(p++) != 0)
259 pos += sizeof(char *);
260
261 /* copy aliases and fill new pointer list */
262 for (p = h->h_aliases, q = h_aliases; *p != 0; p++, q++)
263 {
264 len = strlen(*p);
265 if (size <= pos + len)
266 {
267 *err = ENOMEM;
268 return NULL;
269 }
270 memcpy(buffer + pos, *p, len); /* copy content */
271 buffer[pos + len] = '\0';
272 *q = buffer + pos; /* set copied pointer to copied content */
273 pos += len + 1;
274 }
275 *++q = 0; /* null terminate the pointer list */
276 h->h_aliases = h_aliases; /* copy pointer to pointers */
277
278 return h;
279}
280#endif
281
282#if defined(HAVE_GETHOSTBYNAME) && wxUSE_THREADS
283static wxMutex nameLock;
284#endif
285struct hostent * wxGethostbyname_r(const char *hostname, struct hostent *h,
286 void *buffer, int size, int *err)
287
288{
289 struct hostent *he = NULL;
290 *err = 0;
291#if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
292 if (gethostbyname_r(hostname, h, (char*)buffer, size, &he, err))
293 he = NULL;
294#elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
295 he = gethostbyname_r(hostname, h, (char*)buffer, size, err);
296#elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
297 if (gethostbyname_r(hostname, h, (struct hostent_data*) buffer))
298 {
299 he = NULL;
300 *err = h_errno;
301 }
302 else
303 he = h;
304#elif defined(HAVE_GETHOSTBYNAME)
305#if wxUSE_THREADS
306 wxMutexLocker locker(nameLock);
307#endif
308 he = gethostbyname(hostname);
309 if (!he)
310 *err = h_errno;
311 else
312 he = deepCopyHostent(h, he, (char*)buffer, size, err);
313#endif
314 return he;
315}
316
317#if defined(HAVE_GETHOSTBYNAME) && wxUSE_THREADS
318static wxMutex addrLock;
319#endif
320struct hostent * wxGethostbyaddr_r(const char *addr_buf, int buf_size,
321 int proto, struct hostent *h,
322 void *buffer, int size, int *err)
323{
324 struct hostent *he = NULL;
325 *err = 0;
326#if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
327 if (gethostbyaddr_r(addr_buf, buf_size, proto, h,
328 (char*)buffer, size, &he, err))
329 he = NULL;
330#elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
331 he = gethostbyaddr_r(addr_buf, buf_size, proto, h, (char*)buffer, size, err);
332#elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
333 if (gethostbyaddr_r(addr_buf, buf_size, proto, h,
334 (struct hostent_data*) buffer))
335 {
336 he = NULL;
337 *err = h_errno;
338 }
339 else
340 he = h;
341#elif defined(HAVE_GETHOSTBYNAME)
342#if wxUSE_THREADS
343 wxMutexLocker locker(addrLock);
344#endif
345 he = gethostbyaddr(addr_buf, buf_size, proto);
346 if (!he)
347 *err = h_errno;
348 else
349 he = deepCopyHostent(h, he, (char*)buffer, size, err);
350#endif
351 return he;
352}
353
354#if defined(HAVE_GETSERVBYNAME)
355static struct servent * deepCopyServent(struct servent *s,
356 const struct servent *se,
357 char *buffer, int size)
358{
359 /* copy plain old structure */
360 memcpy(s, se, sizeof(struct servent));
361
362 /* copy name */
363 int len = strlen(s->s_name);
364 if (len >= size)
365 {
366 return NULL;
367 }
368 memcpy(buffer, s->s_name, len);
369 buffer[len] = '\0';
370 s->s_name = buffer;
371
372 /* track position in the buffer */
373 int pos = len + 1;
374
375 /* copy protocol */
376 len = strlen(s->s_proto);
377 if (pos + len >= size)
378 {
379 return NULL;
380 }
381 memcpy(buffer + pos, s->s_proto, len);
382 buffer[pos + len] = '\0';
383 s->s_proto = buffer + pos;
384
385 /* track position in the buffer */
386 pos += len + 1;
387
388 /* ensure pointer alignment */
389 unsigned int misalign = sizeof(char *) - pos%sizeof(char *);
390 if(misalign < sizeof(char *))
391 pos += misalign;
392
393 /* leave space for pointer list */
394 char **p = s->s_aliases, **q;
395 char **s_aliases = (char **)(buffer + pos);
396 while(*(p++) != 0)
397 pos += sizeof(char *);
398
399 /* copy addresses and fill new pointer list */
400 for (p = s->s_aliases, q = s_aliases; *p != 0; p++, q++){
401 len = strlen(*p);
402 if (size <= pos + len)
403 {
404 return NULL;
405 }
406 memcpy(buffer + pos, *p, len); /* copy content */
407 buffer[pos + len] = '\0';
408 *q = buffer + pos; /* set copied pointer to copied content */
409 pos += len + 1;
410 }
411 *++q = 0; /* null terminate the pointer list */
412 s->s_aliases = s_aliases; /* copy pointer to pointers */
413 return s;
414}
415#endif
416
417#if defined(HAVE_GETSERVBYNAME) && wxUSE_THREADS
418static wxMutex servLock;
419#endif
420struct servent *wxGetservbyname_r(const char *port, const char *protocol,
421 struct servent *serv, void *buffer, int size)
422{
423 struct servent *se = NULL;
424#if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
425 if (getservbyname_r(port, protocol, serv, (char*)buffer, size, &se))
426 se = NULL;
427#elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
428 se = getservbyname_r(port, protocol, serv, (char*)buffer, size);
429#elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
430 if (getservbyname_r(port, protocol, serv, (struct servent_data*) buffer))
431 se = NULL;
432 else
433 se = serv;
434#elif defined(HAVE_GETSERVBYNAME)
435#if wxUSE_THREADS
436 wxMutexLocker locker(servLock);
437#endif
438 se = getservbyname(port, protocol);
439 if (se)
440 se = deepCopyServent(serv, se, (char*)buffer, size);
441#endif
442 return se;
443}
444
445/* debugging helpers */
446#ifdef __GSOCKET_DEBUG__
447# define GSocket_Debug(args) printf args
448#else
449# define GSocket_Debug(args)
450#endif /* __GSOCKET_DEBUG__ */
451
452/* Table of GUI-related functions. We must call them indirectly because
453 * of wxBase and GUI separation: */
454
455static GSocketGUIFunctionsTable *gs_gui_functions;
456
457class GSocketGUIFunctionsTableNull: public GSocketGUIFunctionsTable
458{
459public:
460 virtual bool OnInit();
461 virtual void OnExit();
462 virtual bool CanUseEventLoop();
463 virtual bool Init_Socket(GSocket *socket);
464 virtual void Destroy_Socket(GSocket *socket);
465 virtual void Install_Callback(GSocket *socket, GSocketEvent event);
466 virtual void Uninstall_Callback(GSocket *socket, GSocketEvent event);
467 virtual void Enable_Events(GSocket *socket);
468 virtual void Disable_Events(GSocket *socket);
469};
470
471bool GSocketGUIFunctionsTableNull::OnInit()
472{ return true; }
473void GSocketGUIFunctionsTableNull::OnExit()
474{}
475bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
476{ return false; }
477bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket *WXUNUSED(socket))
478{ return true; }
479void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket *WXUNUSED(socket))
480{}
481void GSocketGUIFunctionsTableNull::Install_Callback(GSocket *WXUNUSED(socket), GSocketEvent WXUNUSED(event))
482{}
483void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket *WXUNUSED(socket), GSocketEvent WXUNUSED(event))
484{}
485void GSocketGUIFunctionsTableNull::Enable_Events(GSocket *WXUNUSED(socket))
486{}
487void GSocketGUIFunctionsTableNull::Disable_Events(GSocket *WXUNUSED(socket))
488{}
489/* Global initialisers */
490
491void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable *guifunc)
492{
493 gs_gui_functions = guifunc;
494}
495
496int GSocket_Init(void)
497{
498 if (!gs_gui_functions)
499 {
500 static GSocketGUIFunctionsTableNull table;
501 gs_gui_functions = &table;
502 }
503 if ( !gs_gui_functions->OnInit() )
504 return 0;
505 return 1;
506}
507
508void GSocket_Cleanup(void)
509{
510 if (gs_gui_functions)
511 {
512 gs_gui_functions->OnExit();
513 }
514}
515
516/* Constructors / Destructors for GSocket */
517
518GSocket::GSocket()
519{
520 int i;
521
522 m_fd = INVALID_SOCKET;
523 for (i=0;i<GSOCK_MAX_EVENT;i++)
524 {
525 m_cbacks[i] = NULL;
526 }
527 m_detected = 0;
528 m_local = NULL;
529 m_peer = NULL;
530 m_error = GSOCK_NOERROR;
531 m_server = false;
532 m_stream = true;
533 m_gui_dependent = NULL;
534 m_non_blocking = false;
535 m_reusable = false;
536 m_timeout = 10*60*1000;
537 /* 10 minutes * 60 sec * 1000 millisec */
538 m_establishing = false;
539
540 assert(gs_gui_functions);
541 /* Per-socket GUI-specific initialization */
542 m_ok = gs_gui_functions->Init_Socket(this);
543}
544
545void GSocket::Close()
546{
547 gs_gui_functions->Disable_Events(this);
548 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
549#if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
550 close(m_fd);
551#endif
552 m_fd = INVALID_SOCKET;
553}
554
555GSocket::~GSocket()
556{
557 assert(this);
558
559 /* Check that the socket is really shutdowned */
560 if (m_fd != INVALID_SOCKET)
561 Shutdown();
562
563 /* Per-socket GUI-specific cleanup */
564 gs_gui_functions->Destroy_Socket(this);
565
566 /* Destroy private addresses */
567 if (m_local)
568 GAddress_destroy(m_local);
569
570 if (m_peer)
571 GAddress_destroy(m_peer);
572}
573
574/* GSocket_Shutdown:
575 * Disallow further read/write operations on this socket, close
576 * the fd and disable all callbacks.
577 */
578void GSocket::Shutdown()
579{
580 int evt;
581
582 assert(this);
583
584 /* Don't allow events to fire after socket has been closed */
585 gs_gui_functions->Disable_Events(this);
586
587 /* If socket has been created, shutdown it */
588 if (m_fd != INVALID_SOCKET)
589 {
590 shutdown(m_fd, 1);
591 Close();
592 }
593
594 /* Disable GUI callbacks */
595 for (evt = 0; evt < GSOCK_MAX_EVENT; evt++)
596 m_cbacks[evt] = NULL;
597
598 m_detected = GSOCK_LOST_FLAG;
599}
600
601/* Address handling */
602
603/* GSocket_SetLocal:
604 * GSocket_GetLocal:
605 * GSocket_SetPeer:
606 * GSocket_GetPeer:
607 * Set or get the local or peer address for this socket. The 'set'
608 * functions return GSOCK_NOERROR on success, an error code otherwise.
609 * The 'get' functions return a pointer to a GAddress object on success,
610 * or NULL otherwise, in which case they set the error code of the
611 * corresponding GSocket.
612 *
613 * Error codes:
614 * GSOCK_INVSOCK - the socket is not valid.
615 * GSOCK_INVADDR - the address is not valid.
616 */
617GSocketError GSocket::SetLocal(GAddress *address)
618{
619 assert(this);
620
621 /* the socket must be initialized, or it must be a server */
622 if ((m_fd != INVALID_SOCKET && !m_server))
623 {
624 m_error = GSOCK_INVSOCK;
625 return GSOCK_INVSOCK;
626 }
627
628 /* check address */
629 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
630 {
631 m_error = GSOCK_INVADDR;
632 return GSOCK_INVADDR;
633 }
634
635 if (m_local)
636 GAddress_destroy(m_local);
637
638 m_local = GAddress_copy(address);
639
640 return GSOCK_NOERROR;
641}
642
643GSocketError GSocket::SetPeer(GAddress *address)
644{
645 assert(this);
646
647 /* check address */
648 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
649 {
650 m_error = GSOCK_INVADDR;
651 return GSOCK_INVADDR;
652 }
653
654 if (m_peer)
655 GAddress_destroy(m_peer);
656
657 m_peer = GAddress_copy(address);
658
659 return GSOCK_NOERROR;
660}
661
662GAddress *GSocket::GetLocal()
663{
664 GAddress *address;
665 struct sockaddr addr;
666 WX_SOCKLEN_T size = sizeof(addr);
667 GSocketError err;
668
669 assert(this);
670
671 /* try to get it from the m_local var first */
672 if (m_local)
673 return GAddress_copy(m_local);
674
675 /* else, if the socket is initialized, try getsockname */
676 if (m_fd == INVALID_SOCKET)
677 {
678 m_error = GSOCK_INVSOCK;
679 return NULL;
680 }
681
682 if (getsockname(m_fd, &addr, (WX_SOCKLEN_T *) &size) < 0)
683 {
684 m_error = GSOCK_IOERR;
685 return NULL;
686 }
687
688 /* got a valid address from getsockname, create a GAddress object */
689 address = GAddress_new();
690 if (address == NULL)
691 {
692 m_error = GSOCK_MEMERR;
693 return NULL;
694 }
695
696 err = _GAddress_translate_from(address, &addr, size);
697 if (err != GSOCK_NOERROR)
698 {
699 GAddress_destroy(address);
700 m_error = err;
701 return NULL;
702 }
703
704 return address;
705}
706
707GAddress *GSocket::GetPeer()
708{
709 assert(this);
710
711 /* try to get it from the m_peer var */
712 if (m_peer)
713 return GAddress_copy(m_peer);
714
715 return NULL;
716}
717
718/* Server specific parts */
719
720/* GSocket_SetServer:
721 * Sets up this socket as a server. The local address must have been
722 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
723 * Returns GSOCK_NOERROR on success, one of the following otherwise:
724 *
725 * Error codes:
726 * GSOCK_INVSOCK - the socket is in use.
727 * GSOCK_INVADDR - the local address has not been set.
728 * GSOCK_IOERR - low-level error.
729 */
730GSocketError GSocket::SetServer()
731{
732 int arg = 1;
733
734 assert(this);
735
736 /* must not be in use */
737 if (m_fd != INVALID_SOCKET)
738 {
739 m_error = GSOCK_INVSOCK;
740 return GSOCK_INVSOCK;
741 }
742
743 /* the local addr must have been set */
744 if (!m_local)
745 {
746 m_error = GSOCK_INVADDR;
747 return GSOCK_INVADDR;
748 }
749
750 /* Initialize all fields */
751 m_stream = true;
752 m_server = true;
753
754 /* Create the socket */
755 m_fd = socket(m_local->m_realfamily, SOCK_STREAM, 0);
756
757 if (m_fd == INVALID_SOCKET)
758 {
759 m_error = GSOCK_IOERR;
760 return GSOCK_IOERR;
761 }
762
763 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
764#ifdef SO_NOSIGPIPE
765 setsockopt(m_fd, SOL_SOCKET, SO_NOSIGPIPE, (const char*)&arg, sizeof(arg));
766#endif
767
768 ioctl(m_fd, FIONBIO, &arg);
769 gs_gui_functions->Enable_Events(this);
770
771 /* allow a socket to re-bind if the socket is in the TIME_WAIT
772 state after being previously closed.
773 */
774 if (m_reusable)
775 {
776 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(arg));
777#ifdef SO_REUSEPORT
778 setsockopt(m_fd, SOL_SOCKET, SO_REUSEPORT, (const char*)&arg, sizeof(arg));
779#endif
780 }
781
782 /* Bind to the local address,
783 * retrieve the actual address bound,
784 * and listen up to 5 connections.
785 */
786 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
787 (getsockname(m_fd,
788 m_local->m_addr,
789 (WX_SOCKLEN_T *) &m_local->m_len) != 0) ||
790 (listen(m_fd, 5) != 0))
791 {
792 Close();
793 m_error = GSOCK_IOERR;
794 return GSOCK_IOERR;
795 }
796
797 return GSOCK_NOERROR;
798}
799
800/* GSocket_WaitConnection:
801 * Waits for an incoming client connection. Returns a pointer to
802 * a GSocket object, or NULL if there was an error, in which case
803 * the last error field will be updated for the calling GSocket.
804 *
805 * Error codes (set in the calling GSocket)
806 * GSOCK_INVSOCK - the socket is not valid or not a server.
807 * GSOCK_TIMEDOUT - timeout, no incoming connections.
808 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
809 * GSOCK_MEMERR - couldn't allocate memory.
810 * GSOCK_IOERR - low-level error.
811 */
812GSocket *GSocket::WaitConnection()
813{
814 struct sockaddr from;
815 WX_SOCKLEN_T fromlen = sizeof(from);
816 GSocket *connection;
817 GSocketError err;
818 int arg = 1;
819
820 assert(this);
821
822 /* If the socket has already been created, we exit immediately */
823 if (m_fd == INVALID_SOCKET || !m_server)
824 {
825 m_error = GSOCK_INVSOCK;
826 return NULL;
827 }
828
829 /* Create a GSocket object for the new connection */
830 connection = GSocket_new();
831
832 if (!connection)
833 {
834 m_error = GSOCK_MEMERR;
835 return NULL;
836 }
837
838 /* Wait for a connection (with timeout) */
839 if (Input_Timeout() == GSOCK_TIMEDOUT)
840 {
841 delete connection;
842 /* m_error set by _GSocket_Input_Timeout */
843 return NULL;
844 }
845
846 connection->m_fd = accept(m_fd, &from, (WX_SOCKLEN_T *) &fromlen);
847
848 /* Reenable CONNECTION events */
849 Enable(GSOCK_CONNECTION);
850
851 if (connection->m_fd == INVALID_SOCKET)
852 {
853 if (errno == EWOULDBLOCK)
854 m_error = GSOCK_WOULDBLOCK;
855 else
856 m_error = GSOCK_IOERR;
857
858 delete connection;
859 return NULL;
860 }
861
862 /* Initialize all fields */
863 connection->m_server = false;
864 connection->m_stream = true;
865
866 /* Setup the peer address field */
867 connection->m_peer = GAddress_new();
868 if (!connection->m_peer)
869 {
870 delete connection;
871 m_error = GSOCK_MEMERR;
872 return NULL;
873 }
874
875 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
876 if (err != GSOCK_NOERROR)
877 {
878 delete connection;
879 m_error = err;
880 return NULL;
881 }
882
883#if defined(__EMX__) || defined(__VISAGECPP__)
884 ioctl(connection->m_fd, FIONBIO, (char*)&arg, sizeof(arg));
885#else
886 ioctl(connection->m_fd, FIONBIO, &arg);
887#endif
888 gs_gui_functions->Enable_Events(connection);
889
890 return connection;
891}
892
893bool GSocket::SetReusable()
894{
895 /* socket must not be null, and must not be in use/already bound */
896 if (this && m_fd == INVALID_SOCKET)
897 {
898 m_reusable = true;
899
900 return true;
901 }
902
903 return false;
904}
905
906/* Client specific parts */
907
908/* GSocket_Connect:
909 * For stream (connection oriented) sockets, GSocket_Connect() tries
910 * to establish a client connection to a server using the peer address
911 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
912 * connection has been successfully established, or one of the error
913 * codes listed below. Note that for nonblocking sockets, a return
914 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
915 * request can be completed later; you should use GSocket_Select()
916 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
917 * corresponding asynchronous events.
918 *
919 * For datagram (non connection oriented) sockets, GSocket_Connect()
920 * just sets the peer address established with GSocket_SetPeer() as
921 * default destination.
922 *
923 * Error codes:
924 * GSOCK_INVSOCK - the socket is in use or not valid.
925 * GSOCK_INVADDR - the peer address has not been established.
926 * GSOCK_TIMEDOUT - timeout, the connection failed.
927 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
928 * GSOCK_MEMERR - couldn't allocate memory.
929 * GSOCK_IOERR - low-level error.
930 */
931GSocketError GSocket::Connect(GSocketStream stream)
932{
933 int err, ret;
934 int arg = 1;
935
936 assert(this);
937
938 /* Enable CONNECTION events (needed for nonblocking connections) */
939 Enable(GSOCK_CONNECTION);
940
941 if (m_fd != INVALID_SOCKET)
942 {
943 m_error = GSOCK_INVSOCK;
944 return GSOCK_INVSOCK;
945 }
946
947 if (!m_peer)
948 {
949 m_error = GSOCK_INVADDR;
950 return GSOCK_INVADDR;
951 }
952
953 /* Streamed or dgram socket? */
954 m_stream = (stream == GSOCK_STREAMED);
955 m_server = false;
956 m_establishing = false;
957
958 /* Create the socket */
959 m_fd = socket(m_peer->m_realfamily,
960 m_stream? SOCK_STREAM : SOCK_DGRAM, 0);
961
962 if (m_fd == INVALID_SOCKET)
963 {
964 m_error = GSOCK_IOERR;
965 return GSOCK_IOERR;
966 }
967
968 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
969#ifdef SO_NOSIGPIPE
970 setsockopt(m_fd, SOL_SOCKET, SO_NOSIGPIPE, (const char*)&arg, sizeof(arg));
971#endif
972
973#if defined(__EMX__) || defined(__VISAGECPP__)
974 ioctl(m_fd, FIONBIO, (char*)&arg, sizeof(arg));
975#else
976 ioctl(m_fd, FIONBIO, &arg);
977#endif
978
979 // If the reuse flag is set, use the applicable socket reuse flags(s)
980 if (m_reusable)
981 {
982 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(arg));
983#ifdef SO_REUSEPORT
984 setsockopt(m_fd, SOL_SOCKET, SO_REUSEPORT, (const char*)&arg, sizeof(arg));
985#endif
986 }
987
988 // If a local address has been set, then we need to bind to it before calling connect
989 if (m_local && m_local->m_addr)
990 {
991 bind(m_fd, m_local->m_addr, m_local->m_len);
992 }
993
994 /* Connect it to the peer address, with a timeout (see below) */
995 ret = connect(m_fd, m_peer->m_addr, m_peer->m_len);
996
997 /* We only call Enable_Events if we know we aren't shutting down the socket.
998 * NB: Enable_Events needs to be called whether the socket is blocking or
999 * non-blocking, it just shouldn't be called prior to knowing there is a
1000 * connection _if_ blocking sockets are being used.
1001 * If connect above returns 0, we are already connected and need to make the
1002 * call to Enable_Events now.
1003 */
1004
1005 if (m_non_blocking || ret == 0)
1006 gs_gui_functions->Enable_Events(this);
1007
1008 if (ret == -1)
1009 {
1010 err = errno;
1011
1012 /* If connect failed with EINPROGRESS and the GSocket object
1013 * is in blocking mode, we select() for the specified timeout
1014 * checking for writability to see if the connection request
1015 * completes.
1016 */
1017 if ((err == EINPROGRESS) && (!m_non_blocking))
1018 {
1019 if (Output_Timeout() == GSOCK_TIMEDOUT)
1020 {
1021 Close();
1022 /* m_error is set in _GSocket_Output_Timeout */
1023 return GSOCK_TIMEDOUT;
1024 }
1025 else
1026 {
1027 int error;
1028 SOCKOPTLEN_T len = sizeof(error);
1029
1030 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*) &error, &len);
1031
1032 gs_gui_functions->Enable_Events(this);
1033
1034 if (!error)
1035 return GSOCK_NOERROR;
1036 }
1037 }
1038
1039 /* If connect failed with EINPROGRESS and the GSocket object
1040 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
1041 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
1042 * this way if the connection completes, a GSOCK_CONNECTION
1043 * event will be generated, if enabled.
1044 */
1045 if ((err == EINPROGRESS) && (m_non_blocking))
1046 {
1047 m_establishing = true;
1048 m_error = GSOCK_WOULDBLOCK;
1049 return GSOCK_WOULDBLOCK;
1050 }
1051
1052 /* If connect failed with an error other than EINPROGRESS,
1053 * then the call to GSocket_Connect has failed.
1054 */
1055 Close();
1056 m_error = GSOCK_IOERR;
1057
1058 return GSOCK_IOERR;
1059 }
1060
1061 return GSOCK_NOERROR;
1062}
1063
1064/* Datagram sockets */
1065
1066/* GSocket_SetNonOriented:
1067 * Sets up this socket as a non-connection oriented (datagram) socket.
1068 * Before using this function, the local address must have been set
1069 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
1070 * on success, or one of the following otherwise.
1071 *
1072 * Error codes:
1073 * GSOCK_INVSOCK - the socket is in use.
1074 * GSOCK_INVADDR - the local address has not been set.
1075 * GSOCK_IOERR - low-level error.
1076 */
1077GSocketError GSocket::SetNonOriented()
1078{
1079 int arg = 1;
1080
1081 assert(this);
1082
1083 if (m_fd != INVALID_SOCKET)
1084 {
1085 m_error = GSOCK_INVSOCK;
1086 return GSOCK_INVSOCK;
1087 }
1088
1089 if (!m_local)
1090 {
1091 m_error = GSOCK_INVADDR;
1092 return GSOCK_INVADDR;
1093 }
1094
1095 /* Initialize all fields */
1096 m_stream = false;
1097 m_server = false;
1098
1099 /* Create the socket */
1100 m_fd = socket(m_local->m_realfamily, SOCK_DGRAM, 0);
1101
1102 if (m_fd == INVALID_SOCKET)
1103 {
1104 m_error = GSOCK_IOERR;
1105 return GSOCK_IOERR;
1106 }
1107#if defined(__EMX__) || defined(__VISAGECPP__)
1108 ioctl(m_fd, FIONBIO, (char*)&arg, sizeof(arg));
1109#else
1110 ioctl(m_fd, FIONBIO, &arg);
1111#endif
1112 gs_gui_functions->Enable_Events(this);
1113
1114 if (m_reusable)
1115 {
1116 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(arg));
1117#ifdef SO_REUSEPORT
1118 setsockopt(m_fd, SOL_SOCKET, SO_REUSEPORT, (const char*)&arg, sizeof(arg));
1119#endif
1120 }
1121
1122 /* Bind to the local address,
1123 * and retrieve the actual address bound.
1124 */
1125 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
1126 (getsockname(m_fd,
1127 m_local->m_addr,
1128 (WX_SOCKLEN_T *) &m_local->m_len) != 0))
1129 {
1130 Close();
1131 m_error = GSOCK_IOERR;
1132 return GSOCK_IOERR;
1133 }
1134
1135 return GSOCK_NOERROR;
1136}
1137
1138/* Generic IO */
1139
1140/* Like recv(), send(), ... */
1141int GSocket::Read(char *buffer, int size)
1142{
1143 int ret;
1144
1145 assert(this);
1146
1147 if (m_fd == INVALID_SOCKET || m_server)
1148 {
1149 m_error = GSOCK_INVSOCK;
1150 return -1;
1151 }
1152
1153 /* Disable events during query of socket status */
1154 Disable(GSOCK_INPUT);
1155
1156 /* If the socket is blocking, wait for data (with a timeout) */
1157 if (Input_Timeout() == GSOCK_TIMEDOUT) {
1158 m_error = GSOCK_TIMEDOUT;
1159 /* Don't return here immediately, otherwise socket events would not be
1160 * re-enabled! */
1161 ret = -1;
1162 }
1163 else
1164 {
1165 /* Read the data */
1166 if (m_stream)
1167 ret = Recv_Stream(buffer, size);
1168 else
1169 ret = Recv_Dgram(buffer, size);
1170
1171 /* If recv returned zero, then the connection is lost, and errno is not set.
1172 * Otherwise, recv has returned an error (-1), in which case we have lost the
1173 * socket only if errno does _not_ indicate that there may be more data to read.
1174 */
1175 if (ret == 0)
1176 {
1177 m_error = GSOCK_IOERR;
1178 m_detected = GSOCK_LOST_FLAG;
1179 Close();
1180 // Signal an error for return
1181 return -1;
1182 }
1183 else if (ret == -1)
1184 {
1185 if ((errno == EWOULDBLOCK) || (errno == EAGAIN))
1186 m_error = GSOCK_WOULDBLOCK;
1187 else
1188 m_error = GSOCK_IOERR;
1189 }
1190 }
1191
1192 /* Enable events again now that we are done processing */
1193 Enable(GSOCK_INPUT);
1194
1195 return ret;
1196}
1197
1198int GSocket::Write(const char *buffer, int size)
1199{
1200 int ret;
1201
1202 assert(this);
1203
1204 GSocket_Debug(( "GSocket_Write #1, size %d\n", size ));
1205
1206 if (m_fd == INVALID_SOCKET || m_server)
1207 {
1208 m_error = GSOCK_INVSOCK;
1209 return -1;
1210 }
1211
1212 GSocket_Debug(( "GSocket_Write #2, size %d\n", size ));
1213
1214 /* If the socket is blocking, wait for writability (with a timeout) */
1215 if (Output_Timeout() == GSOCK_TIMEDOUT)
1216 return -1;
1217
1218 GSocket_Debug(( "GSocket_Write #3, size %d\n", size ));
1219
1220 /* Write the data */
1221 if (m_stream)
1222 ret = Send_Stream(buffer, size);
1223 else
1224 ret = Send_Dgram(buffer, size);
1225
1226 GSocket_Debug(( "GSocket_Write #4, size %d\n", size ));
1227
1228 if (ret == -1)
1229 {
1230 if ((errno == EWOULDBLOCK) || (errno == EAGAIN))
1231 {
1232 m_error = GSOCK_WOULDBLOCK;
1233 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
1234 }
1235 else
1236 {
1237 m_error = GSOCK_IOERR;
1238 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
1239 }
1240
1241 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
1242 * in MSW). Once the first OUTPUT event is received, users can assume
1243 * that the socket is writable until a read operation fails. Only then
1244 * will further OUTPUT events be posted.
1245 */
1246 Enable(GSOCK_OUTPUT);
1247
1248 return -1;
1249 }
1250
1251 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size, ret ));
1252
1253 return ret;
1254}
1255
1256/* GSocket_Select:
1257 * Polls the socket to determine its status. This function will
1258 * check for the events specified in the 'flags' parameter, and
1259 * it will return a mask indicating which operations can be
1260 * performed. This function won't block, regardless of the
1261 * mode (blocking | nonblocking) of the socket.
1262 */
1263GSocketEventFlags GSocket::Select(GSocketEventFlags flags)
1264{
1265 if (!gs_gui_functions->CanUseEventLoop())
1266 {
1267
1268 GSocketEventFlags result = 0;
1269 fd_set readfds;
1270 fd_set writefds;
1271 fd_set exceptfds;
1272 struct timeval tv;
1273
1274 assert(this);
1275
1276 if (m_fd == -1)
1277 return (GSOCK_LOST_FLAG & flags);
1278
1279 /* Do not use a static struct, Linux can garble it */
1280 tv.tv_sec = m_timeout / 1000;
1281 tv.tv_usec = (m_timeout % 1000) * 1000;
1282
1283 wxFD_ZERO(&readfds);
1284 wxFD_ZERO(&writefds);
1285 wxFD_ZERO(&exceptfds);
1286 wxFD_SET(m_fd, &readfds);
1287 if (flags & GSOCK_OUTPUT_FLAG || flags & GSOCK_CONNECTION_FLAG)
1288 wxFD_SET(m_fd, &writefds);
1289 wxFD_SET(m_fd, &exceptfds);
1290
1291 /* Check 'sticky' CONNECTION flag first */
1292 result |= (GSOCK_CONNECTION_FLAG & m_detected);
1293
1294 /* If we have already detected a LOST event, then don't try
1295 * to do any further processing.
1296 */
1297 if ((m_detected & GSOCK_LOST_FLAG) != 0)
1298 {
1299 m_establishing = false;
1300
1301 return (GSOCK_LOST_FLAG & flags);
1302 }
1303
1304 /* Try select now */
1305 if (select(m_fd + 1, &readfds, &writefds, &exceptfds, &tv) <= 0)
1306 {
1307 /* What to do here? */
1308 return (result & flags);
1309 }
1310
1311 /* Check for exceptions and errors */
1312 if (wxFD_ISSET(m_fd, &exceptfds))
1313 {
1314 m_establishing = false;
1315 m_detected = GSOCK_LOST_FLAG;
1316
1317 /* LOST event: Abort any further processing */
1318 return (GSOCK_LOST_FLAG & flags);
1319 }
1320
1321 /* Check for readability */
1322 if (wxFD_ISSET(m_fd, &readfds))
1323 {
1324 result |= GSOCK_INPUT_FLAG;
1325
1326 if (m_server && m_stream)
1327 {
1328 /* This is a TCP server socket that detected a connection.
1329 While the INPUT_FLAG is also set, it doesn't matter on
1330 this kind of sockets, as we can only Accept() from them. */
1331 result |= GSOCK_CONNECTION_FLAG;
1332 m_detected |= GSOCK_CONNECTION_FLAG;
1333 }
1334 }
1335
1336 /* Check for writability */
1337 if (wxFD_ISSET(m_fd, &writefds))
1338 {
1339 if (m_establishing && !m_server)
1340 {
1341 int error;
1342 SOCKOPTLEN_T len = sizeof(error);
1343
1344 m_establishing = false;
1345
1346 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
1347
1348 if (error)
1349 {
1350 m_detected = GSOCK_LOST_FLAG;
1351
1352 /* LOST event: Abort any further processing */
1353 return (GSOCK_LOST_FLAG & flags);
1354 }
1355 else
1356 {
1357 result |= GSOCK_CONNECTION_FLAG;
1358 m_detected |= GSOCK_CONNECTION_FLAG;
1359 }
1360 }
1361 else
1362 {
1363 result |= GSOCK_OUTPUT_FLAG;
1364 }
1365 }
1366
1367 return (result & flags);
1368
1369 }
1370 else
1371 {
1372 assert(this);
1373 return flags & m_detected;
1374 }
1375}
1376
1377/* Flags */
1378
1379/* GSocket_SetNonBlocking:
1380 * Sets the socket to non-blocking mode. All IO calls will return
1381 * immediately.
1382 */
1383void GSocket::SetNonBlocking(bool non_block)
1384{
1385 assert(this);
1386
1387 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
1388
1389 m_non_blocking = non_block;
1390}
1391
1392/* GSocket_SetTimeout:
1393 * Sets the timeout for blocking calls. Time is expressed in
1394 * milliseconds.
1395 */
1396void GSocket::SetTimeout(unsigned long millisec)
1397{
1398 assert(this);
1399
1400 m_timeout = millisec;
1401}
1402
1403/* GSocket_GetError:
1404 * Returns the last error occurred for this socket. Note that successful
1405 * operations do not clear this back to GSOCK_NOERROR, so use it only
1406 * after an error.
1407 */
1408GSocketError WXDLLIMPEXP_NET GSocket::GetError()
1409{
1410 assert(this);
1411
1412 return m_error;
1413}
1414
1415/* Callbacks */
1416
1417/* GSOCK_INPUT:
1418 * There is data to be read in the input buffer. If, after a read
1419 * operation, there is still data available, the callback function will
1420 * be called again.
1421 * GSOCK_OUTPUT:
1422 * The socket is available for writing. That is, the next write call
1423 * won't block. This event is generated only once, when the connection is
1424 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1425 * when the output buffer empties again. This means that the app should
1426 * assume that it can write since the first OUTPUT event, and no more
1427 * OUTPUT events will be generated unless an error occurs.
1428 * GSOCK_CONNECTION:
1429 * Connection successfully established, for client sockets, or incoming
1430 * client connection, for server sockets. Wait for this event (also watch
1431 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1432 * GSOCK_LOST:
1433 * The connection is lost (or a connection request failed); this could
1434 * be due to a failure, or due to the peer closing it gracefully.
1435 */
1436
1437/* GSocket_SetCallback:
1438 * Enables the callbacks specified by 'flags'. Note that 'flags'
1439 * may be a combination of flags OR'ed toghether, so the same
1440 * callback function can be made to accept different events.
1441 * The callback function must have the following prototype:
1442 *
1443 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1444 */
1445void GSocket::SetCallback(GSocketEventFlags flags,
1446 GSocketCallback callback, char *cdata)
1447{
1448 int count;
1449
1450 assert(this);
1451
1452 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1453 {
1454 if ((flags & (1 << count)) != 0)
1455 {
1456 m_cbacks[count] = callback;
1457 m_data[count] = cdata;
1458 }
1459 }
1460}
1461
1462/* GSocket_UnsetCallback:
1463 * Disables all callbacks specified by 'flags', which may be a
1464 * combination of flags OR'ed toghether.
1465 */
1466void GSocket::UnsetCallback(GSocketEventFlags flags)
1467{
1468 int count;
1469
1470 assert(this);
1471
1472 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1473 {
1474 if ((flags & (1 << count)) != 0)
1475 {
1476 m_cbacks[count] = NULL;
1477 m_data[count] = NULL;
1478 }
1479 }
1480}
1481
1482GSocketError GSocket::GetSockOpt(int level, int optname,
1483 void *optval, int *optlen)
1484{
1485 if (getsockopt(m_fd, level, optname, (char*)optval, (SOCKOPTLEN_T*)optlen) == 0)
1486 return GSOCK_NOERROR;
1487
1488 return GSOCK_OPTERR;
1489}
1490
1491GSocketError GSocket::SetSockOpt(int level, int optname,
1492 const void *optval, int optlen)
1493{
1494 if (setsockopt(m_fd, level, optname, (const char*)optval, optlen) == 0)
1495 return GSOCK_NOERROR;
1496
1497 return GSOCK_OPTERR;
1498}
1499
1500#define CALL_CALLBACK(socket, event) { \
1501 socket->Disable(event); \
1502 if (socket->m_cbacks[event]) \
1503 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1504}
1505
1506
1507void GSocket::Enable(GSocketEvent event)
1508{
1509 m_detected &= ~(1 << event);
1510 gs_gui_functions->Install_Callback(this, event);
1511}
1512
1513void GSocket::Disable(GSocketEvent event)
1514{
1515 m_detected |= (1 << event);
1516 gs_gui_functions->Uninstall_Callback(this, event);
1517}
1518
1519/* _GSocket_Input_Timeout:
1520 * For blocking sockets, wait until data is available or
1521 * until timeout ellapses.
1522 */
1523GSocketError GSocket::Input_Timeout()
1524{
1525 struct timeval tv;
1526 fd_set readfds;
1527 int ret;
1528
1529 /* Linux select() will overwrite the struct on return */
1530 tv.tv_sec = (m_timeout / 1000);
1531 tv.tv_usec = (m_timeout % 1000) * 1000;
1532
1533 if (!m_non_blocking)
1534 {
1535 wxFD_ZERO(&readfds);
1536 wxFD_SET(m_fd, &readfds);
1537 ret = select(m_fd + 1, &readfds, NULL, NULL, &tv);
1538 if (ret == 0)
1539 {
1540 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1541 m_error = GSOCK_TIMEDOUT;
1542 return GSOCK_TIMEDOUT;
1543 }
1544
1545 if (ret == -1)
1546 {
1547 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1548 if (errno == EBADF) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1549 if (errno == EINTR) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1550 if (errno == EINVAL) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1551 if (errno == ENOMEM) { GSocket_Debug(( "Not enough memory\n" )); }
1552 m_error = GSOCK_TIMEDOUT;
1553 return GSOCK_TIMEDOUT;
1554 }
1555 }
1556
1557 return GSOCK_NOERROR;
1558}
1559
1560/* _GSocket_Output_Timeout:
1561 * For blocking sockets, wait until data can be sent without
1562 * blocking or until timeout ellapses.
1563 */
1564GSocketError GSocket::Output_Timeout()
1565{
1566 struct timeval tv;
1567 fd_set writefds;
1568 int ret;
1569
1570 /* Linux select() will overwrite the struct on return */
1571 tv.tv_sec = (m_timeout / 1000);
1572 tv.tv_usec = (m_timeout % 1000) * 1000;
1573
1574 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking) );
1575
1576 if (!m_non_blocking)
1577 {
1578 wxFD_ZERO(&writefds);
1579 wxFD_SET(m_fd, &writefds);
1580 ret = select(m_fd + 1, NULL, &writefds, NULL, &tv);
1581 if (ret == 0)
1582 {
1583 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1584 m_error = GSOCK_TIMEDOUT;
1585 return GSOCK_TIMEDOUT;
1586 }
1587
1588 if (ret == -1)
1589 {
1590 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1591 if (errno == EBADF) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1592 if (errno == EINTR) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1593 if (errno == EINVAL) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1594 if (errno == ENOMEM) { GSocket_Debug(( "Not enough memory\n" )); }
1595 m_error = GSOCK_TIMEDOUT;
1596 return GSOCK_TIMEDOUT;
1597 }
1598
1599 if ( ! wxFD_ISSET(m_fd, &writefds) )
1600 {
1601 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1602 }
1603 else
1604 {
1605 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1606 }
1607 }
1608 else
1609 {
1610 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1611 }
1612
1613 return GSOCK_NOERROR;
1614}
1615
1616int GSocket::Recv_Stream(char *buffer, int size)
1617{
1618 int ret;
1619 do
1620 {
1621 ret = recv(m_fd, buffer, size, GSOCKET_MSG_NOSIGNAL);
1622 }
1623 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
1624
1625 return ret;
1626}
1627
1628int GSocket::Recv_Dgram(char *buffer, int size)
1629{
1630 struct sockaddr from;
1631 WX_SOCKLEN_T fromlen = sizeof(from);
1632 int ret;
1633 GSocketError err;
1634
1635 fromlen = sizeof(from);
1636
1637 do
1638 {
1639 ret = recvfrom(m_fd, buffer, size, 0, &from, (WX_SOCKLEN_T *) &fromlen);
1640 }
1641 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
1642
1643 if (ret == -1)
1644 return -1;
1645
1646 /* Translate a system address into a GSocket address */
1647 if (!m_peer)
1648 {
1649 m_peer = GAddress_new();
1650 if (!m_peer)
1651 {
1652 m_error = GSOCK_MEMERR;
1653 return -1;
1654 }
1655 }
1656
1657 err = _GAddress_translate_from(m_peer, &from, fromlen);
1658 if (err != GSOCK_NOERROR)
1659 {
1660 GAddress_destroy(m_peer);
1661 m_peer = NULL;
1662 m_error = err;
1663 return -1;
1664 }
1665
1666 return ret;
1667}
1668
1669int GSocket::Send_Stream(const char *buffer, int size)
1670{
1671 int ret;
1672
1673 MASK_SIGNAL();
1674
1675 do
1676 {
1677 ret = send(m_fd, (char *)buffer, size, GSOCKET_MSG_NOSIGNAL);
1678 }
1679 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
1680
1681 UNMASK_SIGNAL();
1682
1683 return ret;
1684}
1685
1686int GSocket::Send_Dgram(const char *buffer, int size)
1687{
1688 struct sockaddr *addr;
1689 int len, ret;
1690 GSocketError err;
1691
1692 if (!m_peer)
1693 {
1694 m_error = GSOCK_INVADDR;
1695 return -1;
1696 }
1697
1698 err = _GAddress_translate_to(m_peer, &addr, &len);
1699 if (err != GSOCK_NOERROR)
1700 {
1701 m_error = err;
1702 return -1;
1703 }
1704
1705 MASK_SIGNAL();
1706
1707 do
1708 {
1709 ret = sendto(m_fd, (char *)buffer, size, 0, addr, len);
1710 }
1711 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
1712
1713 UNMASK_SIGNAL();
1714
1715 /* Frees memory allocated from _GAddress_translate_to */
1716 free(addr);
1717
1718 return ret;
1719}
1720
1721void GSocket::Detected_Read()
1722{
1723 char c;
1724
1725 /* Safeguard against straggling call to Detected_Read */
1726 if (m_fd == INVALID_SOCKET)
1727 {
1728 return;
1729 }
1730
1731 /* If we have already detected a LOST event, then don't try
1732 * to do any further processing.
1733 */
1734 if ((m_detected & GSOCK_LOST_FLAG) != 0)
1735 {
1736 m_establishing = false;
1737
1738 CALL_CALLBACK(this, GSOCK_LOST);
1739 Shutdown();
1740 return;
1741 }
1742
1743 int num = recv(m_fd, &c, 1, MSG_PEEK | GSOCKET_MSG_NOSIGNAL);
1744
1745 if (num > 0)
1746 {
1747 CALL_CALLBACK(this, GSOCK_INPUT);
1748 }
1749 else
1750 {
1751 if (m_server && m_stream)
1752 {
1753 CALL_CALLBACK(this, GSOCK_CONNECTION);
1754 }
1755 else
1756 {
1757 /* Do not throw a lost event in cases where the socket isn't really lost */
1758 if ((errno == EWOULDBLOCK) || (errno == EAGAIN) || (errno == EINTR))
1759 {
1760 CALL_CALLBACK(this, GSOCK_INPUT);
1761 }
1762 else
1763 {
1764 CALL_CALLBACK(this, GSOCK_LOST);
1765 Shutdown();
1766 }
1767 }
1768 }
1769}
1770
1771void GSocket::Detected_Write()
1772{
1773 /* If we have already detected a LOST event, then don't try
1774 * to do any further processing.
1775 */
1776 if ((m_detected & GSOCK_LOST_FLAG) != 0)
1777 {
1778 m_establishing = false;
1779
1780 CALL_CALLBACK(this, GSOCK_LOST);
1781 Shutdown();
1782 return;
1783 }
1784
1785 if (m_establishing && !m_server)
1786 {
1787 int error;
1788 SOCKOPTLEN_T len = sizeof(error);
1789
1790 m_establishing = false;
1791
1792 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
1793
1794 if (error)
1795 {
1796 CALL_CALLBACK(this, GSOCK_LOST);
1797 Shutdown();
1798 }
1799 else
1800 {
1801 CALL_CALLBACK(this, GSOCK_CONNECTION);
1802 /* We have to fire this event by hand because CONNECTION (for clients)
1803 * and OUTPUT are internally the same and we just disabled CONNECTION
1804 * events with the above macro.
1805 */
1806 CALL_CALLBACK(this, GSOCK_OUTPUT);
1807 }
1808 }
1809 else
1810 {
1811 CALL_CALLBACK(this, GSOCK_OUTPUT);
1812 }
1813}
1814
1815/* Compatibility functions for GSocket */
1816GSocket *GSocket_new(void)
1817{
1818 GSocket *newsocket = new GSocket();
1819 if (newsocket->IsOk())
1820 return newsocket;
1821
1822 delete newsocket;
1823
1824 return NULL;
1825}
1826
1827/*
1828 * -------------------------------------------------------------------------
1829 * GAddress
1830 * -------------------------------------------------------------------------
1831 */
1832
1833/* CHECK_ADDRESS verifies that the current address family is either
1834 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1835 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1836 * an appropiate error code.
1837 *
1838 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1839 */
1840#define CHECK_ADDRESS(address, family) \
1841{ \
1842 if (address->m_family == GSOCK_NOFAMILY) \
1843 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1844 return address->m_error; \
1845 if (address->m_family != GSOCK_##family) \
1846 { \
1847 address->m_error = GSOCK_INVADDR; \
1848 return GSOCK_INVADDR; \
1849 } \
1850}
1851
1852#define CHECK_ADDRESS_RETVAL(address, family, retval) \
1853{ \
1854 if (address->m_family == GSOCK_NOFAMILY) \
1855 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1856 return retval; \
1857 if (address->m_family != GSOCK_##family) \
1858 { \
1859 address->m_error = GSOCK_INVADDR; \
1860 return retval; \
1861 } \
1862}
1863
1864
1865GAddress *GAddress_new(void)
1866{
1867 GAddress *address;
1868
1869 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1870 return NULL;
1871
1872 address->m_family = GSOCK_NOFAMILY;
1873 address->m_addr = NULL;
1874 address->m_len = 0;
1875
1876 return address;
1877}
1878
1879GAddress *GAddress_copy(GAddress *address)
1880{
1881 GAddress *addr2;
1882
1883 assert(address != NULL);
1884
1885 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1886 return NULL;
1887
1888 memcpy(addr2, address, sizeof(GAddress));
1889
1890 if (address->m_addr && address->m_len > 0)
1891 {
1892 addr2->m_addr = (struct sockaddr *)malloc(addr2->m_len);
1893 if (addr2->m_addr == NULL)
1894 {
1895 free(addr2);
1896 return NULL;
1897 }
1898 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1899 }
1900
1901 return addr2;
1902}
1903
1904void GAddress_destroy(GAddress *address)
1905{
1906 assert(address != NULL);
1907
1908 if (address->m_addr)
1909 free(address->m_addr);
1910
1911 free(address);
1912}
1913
1914void GAddress_SetFamily(GAddress *address, GAddressType type)
1915{
1916 assert(address != NULL);
1917
1918 address->m_family = type;
1919}
1920
1921GAddressType GAddress_GetFamily(GAddress *address)
1922{
1923 assert(address != NULL);
1924
1925 return address->m_family;
1926}
1927
1928GSocketError _GAddress_translate_from(GAddress *address,
1929 struct sockaddr *addr, int len)
1930{
1931 address->m_realfamily = addr->sa_family;
1932 switch (addr->sa_family)
1933 {
1934 case AF_INET:
1935 address->m_family = GSOCK_INET;
1936 break;
1937 case AF_UNIX:
1938 address->m_family = GSOCK_UNIX;
1939 break;
1940#ifdef AF_INET6
1941 case AF_INET6:
1942 address->m_family = GSOCK_INET6;
1943 break;
1944#endif
1945 default:
1946 {
1947 address->m_error = GSOCK_INVOP;
1948 return GSOCK_INVOP;
1949 }
1950 }
1951
1952 if (address->m_addr)
1953 free(address->m_addr);
1954
1955 address->m_len = len;
1956 address->m_addr = (struct sockaddr *)malloc(len);
1957
1958 if (address->m_addr == NULL)
1959 {
1960 address->m_error = GSOCK_MEMERR;
1961 return GSOCK_MEMERR;
1962 }
1963
1964 memcpy(address->m_addr, addr, len);
1965
1966 return GSOCK_NOERROR;
1967}
1968
1969GSocketError _GAddress_translate_to(GAddress *address,
1970 struct sockaddr **addr, int *len)
1971{
1972 if (!address->m_addr)
1973 {
1974 address->m_error = GSOCK_INVADDR;
1975 return GSOCK_INVADDR;
1976 }
1977
1978 *len = address->m_len;
1979 *addr = (struct sockaddr *)malloc(address->m_len);
1980 if (*addr == NULL)
1981 {
1982 address->m_error = GSOCK_MEMERR;
1983 return GSOCK_MEMERR;
1984 }
1985
1986 memcpy(*addr, address->m_addr, address->m_len);
1987 return GSOCK_NOERROR;
1988}
1989
1990/*
1991 * -------------------------------------------------------------------------
1992 * Internet address family
1993 * -------------------------------------------------------------------------
1994 */
1995
1996GSocketError _GAddress_Init_INET(GAddress *address)
1997{
1998 address->m_len = sizeof(struct sockaddr_in);
1999 address->m_addr = (struct sockaddr *) malloc(address->m_len);
2000 if (address->m_addr == NULL)
2001 {
2002 address->m_error = GSOCK_MEMERR;
2003 return GSOCK_MEMERR;
2004 }
2005
2006 address->m_family = GSOCK_INET;
2007 address->m_realfamily = PF_INET;
2008 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
2009 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
2010
2011 return GSOCK_NOERROR;
2012}
2013
2014GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
2015{
2016 struct hostent *he;
2017 struct in_addr *addr;
2018
2019 assert(address != NULL);
2020
2021 CHECK_ADDRESS(address, INET);
2022
2023 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
2024
2025 /* If it is a numeric host name, convert it now */
2026#if defined(HAVE_INET_ATON)
2027 if (inet_aton(hostname, addr) == 0)
2028 {
2029#elif defined(HAVE_INET_ADDR)
2030 if ( (addr->s_addr = inet_addr(hostname)) == (unsigned)-1 )
2031 {
2032#else
2033 /* Use gethostbyname by default */
2034#ifndef __WXMAC__
2035 int val = 1; /* VA doesn't like constants in conditional expressions */
2036 if (val)
2037#endif
2038 {
2039#endif
2040 struct in_addr *array_addr;
2041
2042 /* It is a real name, we solve it */
2043 struct hostent h;
2044#if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2045 struct hostent_data buffer;
2046#else
2047 char buffer[1024];
2048#endif
2049 int err;
2050 he = wxGethostbyname_r(hostname, &h, (void*)&buffer, sizeof(buffer), &err);
2051 if (he == NULL)
2052 {
2053 /* Reset to invalid address */
2054 addr->s_addr = INADDR_NONE;
2055 address->m_error = GSOCK_NOHOST;
2056 return GSOCK_NOHOST;
2057 }
2058
2059 array_addr = (struct in_addr *) *(he->h_addr_list);
2060 addr->s_addr = array_addr[0].s_addr;
2061 }
2062
2063 return GSOCK_NOERROR;
2064}
2065
2066GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
2067{
2068 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
2069}
2070
2071GSocketError GAddress_INET_SetHostAddress(GAddress *address,
2072 unsigned long hostaddr)
2073{
2074 struct in_addr *addr;
2075
2076 assert(address != NULL);
2077
2078 CHECK_ADDRESS(address, INET);
2079
2080 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
2081 addr->s_addr = htonl(hostaddr);
2082
2083 return GSOCK_NOERROR;
2084}
2085
2086GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
2087 const char *protocol)
2088{
2089 struct servent *se;
2090 struct sockaddr_in *addr;
2091
2092 assert(address != NULL);
2093 CHECK_ADDRESS(address, INET);
2094
2095 if (!port)
2096 {
2097 address->m_error = GSOCK_INVPORT;
2098 return GSOCK_INVPORT;
2099 }
2100
2101#if defined(HAVE_FUNC_GETSERVBYNAME_R_4)
2102 struct servent_data buffer;
2103#else
2104 char buffer[1024];
2105#endif
2106 struct servent serv;
2107 se = wxGetservbyname_r(port, protocol, &serv,
2108 (void*)&buffer, sizeof(buffer));
2109 if (!se)
2110 {
2111 /* the cast to int suppresses compiler warnings about subscript having the
2112 type char */
2113 if (isdigit((int)port[0]))
2114 {
2115 int port_int;
2116
2117 port_int = atoi(port);
2118 addr = (struct sockaddr_in *)address->m_addr;
2119 addr->sin_port = htons(port_int);
2120 return GSOCK_NOERROR;
2121 }
2122
2123 address->m_error = GSOCK_INVPORT;
2124 return GSOCK_INVPORT;
2125 }
2126
2127 addr = (struct sockaddr_in *)address->m_addr;
2128 addr->sin_port = se->s_port;
2129
2130 return GSOCK_NOERROR;
2131}
2132
2133GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
2134{
2135 struct sockaddr_in *addr;
2136
2137 assert(address != NULL);
2138 CHECK_ADDRESS(address, INET);
2139
2140 addr = (struct sockaddr_in *)address->m_addr;
2141 addr->sin_port = htons(port);
2142
2143 return GSOCK_NOERROR;
2144}
2145
2146GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
2147{
2148 struct hostent *he;
2149 char *addr_buf;
2150 struct sockaddr_in *addr;
2151
2152 assert(address != NULL);
2153 CHECK_ADDRESS(address, INET);
2154
2155 addr = (struct sockaddr_in *)address->m_addr;
2156 addr_buf = (char *)&(addr->sin_addr);
2157
2158 struct hostent temphost;
2159#if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2160 struct hostent_data buffer;
2161#else
2162 char buffer[1024];
2163#endif
2164 int err;
2165 he = wxGethostbyaddr_r(addr_buf, sizeof(addr->sin_addr), AF_INET, &temphost,
2166 (void*)&buffer, sizeof(buffer), &err);
2167 if (he == NULL)
2168 {
2169 address->m_error = GSOCK_NOHOST;
2170 return GSOCK_NOHOST;
2171 }
2172
2173 strncpy(hostname, he->h_name, sbuf);
2174
2175 return GSOCK_NOERROR;
2176}
2177
2178unsigned long GAddress_INET_GetHostAddress(GAddress *address)
2179{
2180 struct sockaddr_in *addr;
2181
2182 assert(address != NULL);
2183 CHECK_ADDRESS_RETVAL(address, INET, 0);
2184
2185 addr = (struct sockaddr_in *)address->m_addr;
2186
2187 return ntohl(addr->sin_addr.s_addr);
2188}
2189
2190unsigned short GAddress_INET_GetPort(GAddress *address)
2191{
2192 struct sockaddr_in *addr;
2193
2194 assert(address != NULL);
2195 CHECK_ADDRESS_RETVAL(address, INET, 0);
2196
2197 addr = (struct sockaddr_in *)address->m_addr;
2198 return ntohs(addr->sin_port);
2199}
2200
2201/*
2202 * -------------------------------------------------------------------------
2203 * Unix address family
2204 * -------------------------------------------------------------------------
2205 */
2206
2207#ifndef __VISAGECPP__
2208GSocketError _GAddress_Init_UNIX(GAddress *address)
2209{
2210 address->m_len = sizeof(struct sockaddr_un);
2211 address->m_addr = (struct sockaddr *)malloc(address->m_len);
2212 if (address->m_addr == NULL)
2213 {
2214 address->m_error = GSOCK_MEMERR;
2215 return GSOCK_MEMERR;
2216 }
2217
2218 address->m_family = GSOCK_UNIX;
2219 address->m_realfamily = PF_UNIX;
2220 ((struct sockaddr_un *)address->m_addr)->sun_family = AF_UNIX;
2221 ((struct sockaddr_un *)address->m_addr)->sun_path[0] = 0;
2222
2223 return GSOCK_NOERROR;
2224}
2225
2226#define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
2227
2228GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *path)
2229{
2230 struct sockaddr_un *addr;
2231
2232 assert(address != NULL);
2233
2234 CHECK_ADDRESS(address, UNIX);
2235
2236 addr = ((struct sockaddr_un *)address->m_addr);
2237 strncpy(addr->sun_path, path, UNIX_SOCK_PATHLEN);
2238 addr->sun_path[UNIX_SOCK_PATHLEN - 1] = '\0';
2239
2240 return GSOCK_NOERROR;
2241}
2242
2243GSocketError GAddress_UNIX_GetPath(GAddress *address, char *path, size_t sbuf)
2244{
2245 struct sockaddr_un *addr;
2246
2247 assert(address != NULL);
2248 CHECK_ADDRESS(address, UNIX);
2249
2250 addr = (struct sockaddr_un *)address->m_addr;
2251
2252 strncpy(path, addr->sun_path, sbuf);
2253
2254 return GSOCK_NOERROR;
2255}
2256#endif /* !defined(__VISAGECPP__) */
2257#endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */