]> git.saurik.com Git - wxWidgets.git/blame - src/unix/gsocket.cpp
wxchar.h doesn't have to be C file anymore, it's C++
[wxWidgets.git] / src / unix / gsocket.cpp
CommitLineData
97e6ee04 1/* -------------------------------------------------------------------------
99d80019
JS
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$
97e6ee04
DE
12 * -------------------------------------------------------------------------
13 */
14
7e1e6965
WS
15#if defined(__WATCOMC__)
16#include "wx/wxprec.h"
17#include <errno.h>
18#include <nerrno.h>
19#endif
20
ba2a81d7 21#ifndef __GSOCKET_STANDALONE__
0beb8735 22#include "wx/defs.h"
ba2a81d7 23#endif
97e6ee04
DE
24
25#if defined(__VISAGECPP__)
1aa7b427 26#define BSD_SELECT /* use Berkeley Sockets select */
97e6ee04
DE
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
bc023abb
MW
42#ifdef HAVE_SYS_SELECT_H
43# include <sys/select.h>
44#endif
45
97e6ee04
DE
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
ebdab982
SN
95#ifdef __EMX__
96#include <sys/select.h>
97#endif
98
97e6ee04
DE
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
d1f8e97b
SN
109#ifdef _AIX
110# include <strings.h>
111#endif
97e6ee04
DE
112#include <signal.h>
113
9e03e02d 114#ifndef WX_SOCKLEN_T
97e6ee04
DE
115
116#ifdef VMS
9e03e02d 117# define WX_SOCKLEN_T unsigned int
97e6ee04
DE
118#else
119# ifdef __GLIBC__
120# if __GLIBC__ == 2
9e03e02d 121# define WX_SOCKLEN_T socklen_t
97e6ee04 122# endif
fcbd7e5a 123# elif defined(__WXMAC__)
9e03e02d 124# define WX_SOCKLEN_T socklen_t
97e6ee04 125# else
9e03e02d 126# define WX_SOCKLEN_T int
97e6ee04
DE
127# endif
128#endif
129
130#endif /* SOCKLEN_T */
131
ddc1a35f 132#ifndef SOCKOPTLEN_T
9e03e02d 133#define SOCKOPTLEN_T WX_SOCKLEN_T
ddc1a35f
DE
134#endif
135
97e6ee04
DE
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
7e1e6965 156#if defined(__VISAGECPP__) || defined(__WATCOMC__)
97e6ee04 157
7e1e6965
WS
158 #define MASK_SIGNAL() {
159 #define UNMASK_SIGNAL() }
160
161#else
defbeca1 162 extern "C" { typedef void (*wxSigHandler)(int); }
7e1e6965
WS
163
164 #define MASK_SIGNAL() \
165 { \
defbeca1 166 wxSigHandler old_handler = signal(SIGPIPE, SIG_IGN);
7e1e6965
WS
167
168 #define UNMASK_SIGNAL() \
169 signal(SIGPIPE, old_handler); \
170 }
171
172#endif
97e6ee04 173
e400d27d
KH
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. */
bb154f79
KH
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 */
97e6ee04
DE
183
184#ifndef __GSOCKET_STANDALONE__
185# include "wx/unix/gsockunx.h"
17a1ebd1 186# include "wx/unix/private.h"
97e6ee04 187# include "wx/gsocket.h"
71b4a9b8
SN
188#if wxUSE_THREADS && (defined(HAVE_GETHOSTBYNAME) || defined(HAVE_GETSERVBYNAME))
189# include "wx/thread.h"
190#endif
97e6ee04
DE
191#else
192# include "gsockunx.h"
193# include "gsocket.h"
5fb9aa56
WS
194# ifndef WXUNUSED
195# define WXUNUSED(x)
196# endif
97e6ee04
DE
197#endif /* __GSOCKET_STANDALONE__ */
198
71b4a9b8
SN
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{
2887cb4e 204 /* copy old structure */
71b4a9b8 205 memcpy(h, he, sizeof(struct hostent));
2887cb4e
SN
206
207 /* copy name */
71b4a9b8
SN
208 int len = strlen(h->h_name);
209 if (len > size)
2887cb4e
SN
210 {
211 *err = ENOMEM;
212 return NULL;
213 }
71b4a9b8
SN
214 memcpy(buffer, h->h_name, len);
215 buffer[len] = '\0';
216 h->h_name = buffer;
2887cb4e
SN
217
218 /* track position in the buffer */
219 int pos = len + 1;
220
221 /* reuse len to store address length */
71b4a9b8 222 len = h->h_length;
2887cb4e
SN
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 {
71b4a9b8
SN
240 *err = ENOMEM;
241 return NULL;
242 }
2887cb4e
SN
243 memcpy(buffer + pos, *p, len); /* copy content */
244 *q = buffer + pos; /* set copied pointer to copied content */
245 pos += len;
71b4a9b8 246 }
2887cb4e
SN
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;
01ba4b67 254
2887cb4e
SN
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 *);
01ba4b67 260
2887cb4e
SN
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;
71b4a9b8 274 }
2887cb4e
SN
275 *++q = 0; /* null terminate the pointer list */
276 h->h_aliases = h_aliases; /* copy pointer to pointers */
277
71b4a9b8
SN
278 return h;
279}
280#endif
281
2887cb4e
SN
282#if defined(HAVE_GETHOSTBYNAME) && wxUSE_THREADS
283static wxMutex nameLock;
284#endif
71b4a9b8
SN
285struct hostent * wxGethostbyname_r(const char *hostname, struct hostent *h,
286 void *buffer, int size, int *err)
287
288{
539ae551 289 struct hostent *he = NULL;
71b4a9b8
SN
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
71b4a9b8
SN
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
2887cb4e
SN
317#if defined(HAVE_GETHOSTBYNAME) && wxUSE_THREADS
318static wxMutex addrLock;
319#endif
71b4a9b8
SN
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{
539ae551 324 struct hostent *he = NULL;
71b4a9b8
SN
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
71b4a9b8
SN
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
f0b805fa 354#if defined(HAVE_GETSERVBYNAME)
71b4a9b8
SN
355static struct servent * deepCopyServent(struct servent *s,
356 const struct servent *se,
357 char *buffer, int size)
358{
2887cb4e 359 /* copy plain old structure */
71b4a9b8 360 memcpy(s, se, sizeof(struct servent));
2887cb4e
SN
361
362 /* copy name */
71b4a9b8 363 int len = strlen(s->s_name);
2887cb4e
SN
364 if (len >= size)
365 {
366 return NULL;
367 }
71b4a9b8
SN
368 memcpy(buffer, s->s_name, len);
369 buffer[len] = '\0';
370 s->s_name = buffer;
2887cb4e
SN
371
372 /* track position in the buffer */
373 int pos = len + 1;
374
375 /* copy protocol */
71b4a9b8 376 len = strlen(s->s_proto);
2887cb4e
SN
377 if (pos + len >= size)
378 {
379 return NULL;
71b4a9b8 380 }
2887cb4e
SN
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;
01ba4b67 392
2887cb4e
SN
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 *);
01ba4b67 398
2887cb4e
SN
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 */
71b4a9b8
SN
413 return s;
414}
415#endif
416
2887cb4e
SN
417#if defined(HAVE_GETSERVBYNAME) && wxUSE_THREADS
418static wxMutex servLock;
419#endif
71b4a9b8
SN
420struct servent *wxGetservbyname_r(const char *port, const char *protocol,
421 struct servent *serv, void *buffer, int size)
422{
539ae551 423 struct servent *se = NULL;
71b4a9b8
SN
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
71b4a9b8
SN
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
97e6ee04
DE
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
ba2a81d7
DE
452/* Table of GUI-related functions. We must call them indirectly because
453 * of wxBase and GUI separation: */
444cb1fd 454
3e1400ac 455static GSocketGUIFunctionsTable *gs_gui_functions;
b082b524 456
ba2a81d7 457class GSocketGUIFunctionsTableNull: public GSocketGUIFunctionsTable
444cb1fd 458{
ba2a81d7
DE
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);
ba2a81d7
DE
466 virtual void Uninstall_Callback(GSocket *socket, GSocketEvent event);
467 virtual void Enable_Events(GSocket *socket);
468 virtual void Disable_Events(GSocket *socket);
469};
444cb1fd 470
ba2a81d7
DE
471bool GSocketGUIFunctionsTableNull::OnInit()
472{ return true; }
473void GSocketGUIFunctionsTableNull::OnExit()
474{}
475bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
476{ return false; }
c40158e4 477bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket *WXUNUSED(socket))
ba2a81d7 478{ return true; }
c40158e4 479void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket *WXUNUSED(socket))
ba2a81d7 480{}
c40158e4 481void GSocketGUIFunctionsTableNull::Install_Callback(GSocket *WXUNUSED(socket), GSocketEvent WXUNUSED(event))
ba2a81d7 482{}
c40158e4 483void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket *WXUNUSED(socket), GSocketEvent WXUNUSED(event))
ba2a81d7 484{}
c40158e4 485void GSocketGUIFunctionsTableNull::Enable_Events(GSocket *WXUNUSED(socket))
ba2a81d7 486{}
c40158e4 487void GSocketGUIFunctionsTableNull::Disable_Events(GSocket *WXUNUSED(socket))
ba2a81d7
DE
488{}
489/* Global initialisers */
444cb1fd 490
3e1400ac 491void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable *guifunc)
444cb1fd 492{
ba2a81d7 493 gs_gui_functions = guifunc;
444cb1fd
DE
494}
495
97e6ee04
DE
496int GSocket_Init(void)
497{
ba2a81d7
DE
498 if (!gs_gui_functions)
499 {
3e1400ac 500 static GSocketGUIFunctionsTableNull table;
ba2a81d7
DE
501 gs_gui_functions = &table;
502 }
503 if ( !gs_gui_functions->OnInit() )
504 return 0;
505 return 1;
97e6ee04
DE
506}
507
508void GSocket_Cleanup(void)
509{
ba2a81d7
DE
510 if (gs_gui_functions)
511 {
512 gs_gui_functions->OnExit();
513 }
97e6ee04
DE
514}
515
ba2a81d7
DE
516/* Constructors / Destructors for GSocket */
517
518GSocket::GSocket()
97e6ee04 519{
09e6e5ec 520 int i;
97e6ee04 521
09e6e5ec 522 m_fd = INVALID_SOCKET;
97e6ee04
DE
523 for (i=0;i<GSOCK_MAX_EVENT;i++)
524 {
09e6e5ec 525 m_cbacks[i] = NULL;
97e6ee04 526 }
09e6e5ec
DE
527 m_detected = 0;
528 m_local = NULL;
529 m_peer = NULL;
530 m_error = GSOCK_NOERROR;
948c96ef
DE
531 m_server = false;
532 m_stream = true;
09e6e5ec 533 m_gui_dependent = NULL;
948c96ef 534 m_non_blocking = false;
1eef64d8 535 m_reusable = false;
09e6e5ec 536 m_timeout = 10*60*1000;
97e6ee04 537 /* 10 minutes * 60 sec * 1000 millisec */
948c96ef 538 m_establishing = false;
97e6ee04 539
ba2a81d7
DE
540 assert(gs_gui_functions);
541 /* Per-socket GUI-specific initialization */
542 m_ok = gs_gui_functions->Init_Socket(this);
97e6ee04
DE
543}
544
ba2a81d7 545void GSocket::Close()
97e6ee04 546{
ba2a81d7
DE
547 gs_gui_functions->Disable_Events(this);
548 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
97e6ee04 549#if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
09e6e5ec 550 close(m_fd);
97e6ee04 551#endif
09e6e5ec 552 m_fd = INVALID_SOCKET;
97e6ee04
DE
553}
554
ba2a81d7 555GSocket::~GSocket()
97e6ee04 556{
ba2a81d7
DE
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
97e6ee04 566 /* Destroy private addresses */
09e6e5ec
DE
567 if (m_local)
568 GAddress_destroy(m_local);
97e6ee04 569
09e6e5ec
DE
570 if (m_peer)
571 GAddress_destroy(m_peer);
97e6ee04
DE
572}
573
574/* GSocket_Shutdown:
575 * Disallow further read/write operations on this socket, close
576 * the fd and disable all callbacks.
577 */
ba2a81d7 578void GSocket::Shutdown()
97e6ee04
DE
579{
580 int evt;
581
09e6e5ec 582 assert(this);
97e6ee04 583
c3b501e1
KH
584 /* Don't allow events to fire after socket has been closed */
585 gs_gui_functions->Disable_Events(this);
586
97e6ee04 587 /* If socket has been created, shutdown it */
09e6e5ec 588 if (m_fd != INVALID_SOCKET)
97e6ee04 589 {
cd632a86 590 shutdown(m_fd, 1);
09e6e5ec 591 Close();
97e6ee04
DE
592 }
593
594 /* Disable GUI callbacks */
595 for (evt = 0; evt < GSOCK_MAX_EVENT; evt++)
09e6e5ec 596 m_cbacks[evt] = NULL;
97e6ee04 597
09e6e5ec 598 m_detected = GSOCK_LOST_FLAG;
97e6ee04
DE
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 */
ba2a81d7 617GSocketError GSocket::SetLocal(GAddress *address)
97e6ee04 618{
09e6e5ec 619 assert(this);
97e6ee04
DE
620
621 /* the socket must be initialized, or it must be a server */
09e6e5ec 622 if ((m_fd != INVALID_SOCKET && !m_server))
97e6ee04 623 {
09e6e5ec 624 m_error = GSOCK_INVSOCK;
97e6ee04
DE
625 return GSOCK_INVSOCK;
626 }
627
628 /* check address */
629 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
630 {
09e6e5ec 631 m_error = GSOCK_INVADDR;
97e6ee04
DE
632 return GSOCK_INVADDR;
633 }
634
09e6e5ec
DE
635 if (m_local)
636 GAddress_destroy(m_local);
97e6ee04 637
09e6e5ec 638 m_local = GAddress_copy(address);
97e6ee04
DE
639
640 return GSOCK_NOERROR;
641}
642
ba2a81d7 643GSocketError GSocket::SetPeer(GAddress *address)
97e6ee04 644{
09e6e5ec 645 assert(this);
97e6ee04
DE
646
647 /* check address */
648 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
649 {
09e6e5ec 650 m_error = GSOCK_INVADDR;
97e6ee04
DE
651 return GSOCK_INVADDR;
652 }
653
09e6e5ec
DE
654 if (m_peer)
655 GAddress_destroy(m_peer);
97e6ee04 656
09e6e5ec 657 m_peer = GAddress_copy(address);
97e6ee04
DE
658
659 return GSOCK_NOERROR;
660}
661
ba2a81d7 662GAddress *GSocket::GetLocal()
97e6ee04
DE
663{
664 GAddress *address;
665 struct sockaddr addr;
9e03e02d 666 WX_SOCKLEN_T size = sizeof(addr);
97e6ee04
DE
667 GSocketError err;
668
09e6e5ec 669 assert(this);
97e6ee04
DE
670
671 /* try to get it from the m_local var first */
09e6e5ec
DE
672 if (m_local)
673 return GAddress_copy(m_local);
97e6ee04
DE
674
675 /* else, if the socket is initialized, try getsockname */
09e6e5ec 676 if (m_fd == INVALID_SOCKET)
97e6ee04 677 {
09e6e5ec 678 m_error = GSOCK_INVSOCK;
97e6ee04
DE
679 return NULL;
680 }
681
9e03e02d 682 if (getsockname(m_fd, &addr, (WX_SOCKLEN_T *) &size) < 0)
97e6ee04 683 {
09e6e5ec 684 m_error = GSOCK_IOERR;
97e6ee04
DE
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 {
09e6e5ec 692 m_error = GSOCK_MEMERR;
97e6ee04
DE
693 return NULL;
694 }
695
696 err = _GAddress_translate_from(address, &addr, size);
697 if (err != GSOCK_NOERROR)
698 {
699 GAddress_destroy(address);
09e6e5ec 700 m_error = err;
97e6ee04
DE
701 return NULL;
702 }
703
704 return address;
705}
706
ba2a81d7 707GAddress *GSocket::GetPeer()
97e6ee04 708{
09e6e5ec 709 assert(this);
97e6ee04
DE
710
711 /* try to get it from the m_peer var */
09e6e5ec
DE
712 if (m_peer)
713 return GAddress_copy(m_peer);
97e6ee04
DE
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:
b082b524 724 *
97e6ee04
DE
725 * Error codes:
726 * GSOCK_INVSOCK - the socket is in use.
727 * GSOCK_INVADDR - the local address has not been set.
b082b524 728 * GSOCK_IOERR - low-level error.
97e6ee04 729 */
ba2a81d7 730GSocketError GSocket::SetServer()
97e6ee04
DE
731{
732 int arg = 1;
733
09e6e5ec 734 assert(this);
97e6ee04
DE
735
736 /* must not be in use */
09e6e5ec 737 if (m_fd != INVALID_SOCKET)
97e6ee04 738 {
09e6e5ec 739 m_error = GSOCK_INVSOCK;
97e6ee04
DE
740 return GSOCK_INVSOCK;
741 }
742
743 /* the local addr must have been set */
09e6e5ec 744 if (!m_local)
97e6ee04 745 {
09e6e5ec 746 m_error = GSOCK_INVADDR;
97e6ee04
DE
747 return GSOCK_INVADDR;
748 }
749
750 /* Initialize all fields */
948c96ef
DE
751 m_stream = true;
752 m_server = true;
97e6ee04
DE
753
754 /* Create the socket */
09e6e5ec 755 m_fd = socket(m_local->m_realfamily, SOCK_STREAM, 0);
97e6ee04 756
09e6e5ec 757 if (m_fd == INVALID_SOCKET)
97e6ee04 758 {
09e6e5ec 759 m_error = GSOCK_IOERR;
97e6ee04
DE
760 return GSOCK_IOERR;
761 }
bb154f79
KH
762
763 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
764#ifdef SO_NOSIGPIPE
01ba4b67 765 setsockopt(m_fd, SOL_SOCKET, SO_NOSIGPIPE, (const char*)&arg, sizeof(arg));
bb154f79
KH
766#endif
767
09e6e5ec 768 ioctl(m_fd, FIONBIO, &arg);
ba2a81d7 769 gs_gui_functions->Enable_Events(this);
97e6ee04
DE
770
771 /* allow a socket to re-bind if the socket is in the TIME_WAIT
772 state after being previously closed.
773 */
ba2a81d7 774 if (m_reusable)
c232b3cd 775 {
01ba4b67 776 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(arg));
c232b3cd 777#ifdef SO_REUSEPORT
01ba4b67 778 setsockopt(m_fd, SOL_SOCKET, SO_REUSEPORT, (const char*)&arg, sizeof(arg));
c232b3cd
KH
779#endif
780 }
97e6ee04
DE
781
782 /* Bind to the local address,
783 * retrieve the actual address bound,
784 * and listen up to 5 connections.
785 */
09e6e5ec
DE
786 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
787 (getsockname(m_fd,
788 m_local->m_addr,
9e03e02d 789 (WX_SOCKLEN_T *) &m_local->m_len) != 0) ||
09e6e5ec 790 (listen(m_fd, 5) != 0))
97e6ee04 791 {
09e6e5ec
DE
792 Close();
793 m_error = GSOCK_IOERR;
97e6ee04
DE
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.
b082b524 810 * GSOCK_IOERR - low-level error.
97e6ee04 811 */
ba2a81d7 812GSocket *GSocket::WaitConnection()
97e6ee04
DE
813{
814 struct sockaddr from;
9e03e02d 815 WX_SOCKLEN_T fromlen = sizeof(from);
97e6ee04
DE
816 GSocket *connection;
817 GSocketError err;
818 int arg = 1;
819
09e6e5ec 820 assert(this);
97e6ee04 821
97e6ee04 822 /* If the socket has already been created, we exit immediately */
09e6e5ec 823 if (m_fd == INVALID_SOCKET || !m_server)
97e6ee04 824 {
09e6e5ec 825 m_error = GSOCK_INVSOCK;
97e6ee04
DE
826 return NULL;
827 }
828
829 /* Create a GSocket object for the new connection */
444cb1fd 830 connection = GSocket_new();
97e6ee04 831
444cb1fd 832 if (!connection)
97e6ee04 833 {
09e6e5ec 834 m_error = GSOCK_MEMERR;
97e6ee04
DE
835 return NULL;
836 }
837
838 /* Wait for a connection (with timeout) */
09e6e5ec 839 if (Input_Timeout() == GSOCK_TIMEDOUT)
97e6ee04 840 {
85431efa 841 delete connection;
09e6e5ec 842 /* m_error set by _GSocket_Input_Timeout */
97e6ee04
DE
843 return NULL;
844 }
845
9e03e02d 846 connection->m_fd = accept(m_fd, &from, (WX_SOCKLEN_T *) &fromlen);
97e6ee04 847
bb154f79
KH
848 /* Reenable CONNECTION events */
849 Enable(GSOCK_CONNECTION);
bb154f79 850
97e6ee04
DE
851 if (connection->m_fd == INVALID_SOCKET)
852 {
853 if (errno == EWOULDBLOCK)
09e6e5ec 854 m_error = GSOCK_WOULDBLOCK;
97e6ee04 855 else
09e6e5ec 856 m_error = GSOCK_IOERR;
97e6ee04 857
85431efa 858 delete connection;
97e6ee04
DE
859 return NULL;
860 }
861
862 /* Initialize all fields */
948c96ef
DE
863 connection->m_server = false;
864 connection->m_stream = true;
97e6ee04
DE
865
866 /* Setup the peer address field */
867 connection->m_peer = GAddress_new();
868 if (!connection->m_peer)
869 {
85431efa 870 delete connection;
09e6e5ec 871 m_error = GSOCK_MEMERR;
97e6ee04
DE
872 return NULL;
873 }
1aa7b427 874
97e6ee04
DE
875 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
876 if (err != GSOCK_NOERROR)
877 {
85431efa 878 delete connection;
09e6e5ec 879 m_error = err;
97e6ee04
DE
880 return NULL;
881 }
1aa7b427 882
97e6ee04
DE
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
ba2a81d7 888 gs_gui_functions->Enable_Events(connection);
97e6ee04
DE
889
890 return connection;
891}
892
948c96ef 893bool GSocket::SetReusable()
b082b524
DE
894{
895 /* socket must not be null, and must not be in use/already bound */
1aa7b427
DS
896 if (this && m_fd == INVALID_SOCKET)
897 {
948c96ef 898 m_reusable = true;
1aa7b427 899
948c96ef 900 return true;
b082b524 901 }
1aa7b427 902
948c96ef 903 return false;
b082b524
DE
904}
905
97e6ee04
DE
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
d6922577 912 * connection has been successfully established, or one of the error
97e6ee04
DE
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.
b082b524 929 * GSOCK_IOERR - low-level error.
97e6ee04 930 */
ba2a81d7 931GSocketError GSocket::Connect(GSocketStream stream)
97e6ee04
DE
932{
933 int err, ret;
934 int arg = 1;
935
09e6e5ec 936 assert(this);
97e6ee04
DE
937
938 /* Enable CONNECTION events (needed for nonblocking connections) */
09e6e5ec 939 Enable(GSOCK_CONNECTION);
97e6ee04 940
09e6e5ec 941 if (m_fd != INVALID_SOCKET)
97e6ee04 942 {
09e6e5ec 943 m_error = GSOCK_INVSOCK;
97e6ee04
DE
944 return GSOCK_INVSOCK;
945 }
946
09e6e5ec 947 if (!m_peer)
97e6ee04 948 {
09e6e5ec 949 m_error = GSOCK_INVADDR;
97e6ee04
DE
950 return GSOCK_INVADDR;
951 }
952
953 /* Streamed or dgram socket? */
09e6e5ec 954 m_stream = (stream == GSOCK_STREAMED);
948c96ef
DE
955 m_server = false;
956 m_establishing = false;
97e6ee04
DE
957
958 /* Create the socket */
09e6e5ec
DE
959 m_fd = socket(m_peer->m_realfamily,
960 m_stream? SOCK_STREAM : SOCK_DGRAM, 0);
97e6ee04 961
09e6e5ec 962 if (m_fd == INVALID_SOCKET)
97e6ee04 963 {
09e6e5ec 964 m_error = GSOCK_IOERR;
97e6ee04
DE
965 return GSOCK_IOERR;
966 }
bb154f79
KH
967
968 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
969#ifdef SO_NOSIGPIPE
01ba4b67 970 setsockopt(m_fd, SOL_SOCKET, SO_NOSIGPIPE, (const char*)&arg, sizeof(arg));
bb154f79
KH
971#endif
972
97e6ee04 973#if defined(__EMX__) || defined(__VISAGECPP__)
09e6e5ec 974 ioctl(m_fd, FIONBIO, (char*)&arg, sizeof(arg));
97e6ee04 975#else
09e6e5ec 976 ioctl(m_fd, FIONBIO, &arg);
97e6ee04 977#endif
97e6ee04 978
c232b3cd
KH
979 // If the reuse flag is set, use the applicable socket reuse flags(s)
980 if (m_reusable)
981 {
01ba4b67 982 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(arg));
c232b3cd 983#ifdef SO_REUSEPORT
01ba4b67 984 setsockopt(m_fd, SOL_SOCKET, SO_REUSEPORT, (const char*)&arg, sizeof(arg));
c232b3cd
KH
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
97e6ee04 994 /* Connect it to the peer address, with a timeout (see below) */
09e6e5ec 995 ret = connect(m_fd, m_peer->m_addr, m_peer->m_len);
97e6ee04 996
0d34c30e
KH
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
17a1ebd1 1002 * call to Enable_Events now.
a3687636 1003 */
17a1ebd1 1004
0d34c30e 1005 if (m_non_blocking || ret == 0)
bb154f79 1006 gs_gui_functions->Enable_Events(this);
bb154f79 1007
97e6ee04
DE
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 */
09e6e5ec 1017 if ((err == EINPROGRESS) && (!m_non_blocking))
97e6ee04 1018 {
09e6e5ec 1019 if (Output_Timeout() == GSOCK_TIMEDOUT)
97e6ee04 1020 {
09e6e5ec
DE
1021 Close();
1022 /* m_error is set in _GSocket_Output_Timeout */
97e6ee04
DE
1023 return GSOCK_TIMEDOUT;
1024 }
1025 else
1026 {
1027 int error;
ddc1a35f 1028 SOCKOPTLEN_T len = sizeof(error);
97e6ee04 1029
f71bb8ef 1030 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*) &error, &len);
97e6ee04 1031
bb154f79
KH
1032 gs_gui_functions->Enable_Events(this);
1033
97e6ee04
DE
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 */
09e6e5ec 1045 if ((err == EINPROGRESS) && (m_non_blocking))
97e6ee04 1046 {
948c96ef 1047 m_establishing = true;
09e6e5ec 1048 m_error = GSOCK_WOULDBLOCK;
97e6ee04
DE
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 */
09e6e5ec
DE
1055 Close();
1056 m_error = GSOCK_IOERR;
1aa7b427 1057
97e6ee04
DE
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 */
ba2a81d7 1077GSocketError GSocket::SetNonOriented()
97e6ee04
DE
1078{
1079 int arg = 1;
1080
09e6e5ec 1081 assert(this);
97e6ee04 1082
09e6e5ec 1083 if (m_fd != INVALID_SOCKET)
97e6ee04 1084 {
09e6e5ec 1085 m_error = GSOCK_INVSOCK;
97e6ee04
DE
1086 return GSOCK_INVSOCK;
1087 }
1088
09e6e5ec 1089 if (!m_local)
97e6ee04 1090 {
09e6e5ec 1091 m_error = GSOCK_INVADDR;
97e6ee04
DE
1092 return GSOCK_INVADDR;
1093 }
1094
1095 /* Initialize all fields */
948c96ef
DE
1096 m_stream = false;
1097 m_server = false;
97e6ee04
DE
1098
1099 /* Create the socket */
09e6e5ec 1100 m_fd = socket(m_local->m_realfamily, SOCK_DGRAM, 0);
97e6ee04 1101
09e6e5ec 1102 if (m_fd == INVALID_SOCKET)
97e6ee04 1103 {
09e6e5ec 1104 m_error = GSOCK_IOERR;
97e6ee04
DE
1105 return GSOCK_IOERR;
1106 }
1107#if defined(__EMX__) || defined(__VISAGECPP__)
09e6e5ec 1108 ioctl(m_fd, FIONBIO, (char*)&arg, sizeof(arg));
97e6ee04 1109#else
09e6e5ec 1110 ioctl(m_fd, FIONBIO, &arg);
97e6ee04 1111#endif
ba2a81d7 1112 gs_gui_functions->Enable_Events(this);
97e6ee04 1113
01ba4b67
VZ
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
97e6ee04
DE
1122 /* Bind to the local address,
1123 * and retrieve the actual address bound.
1124 */
09e6e5ec
DE
1125 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
1126 (getsockname(m_fd,
1127 m_local->m_addr,
9e03e02d 1128 (WX_SOCKLEN_T *) &m_local->m_len) != 0))
97e6ee04 1129 {
09e6e5ec
DE
1130 Close();
1131 m_error = GSOCK_IOERR;
97e6ee04
DE
1132 return GSOCK_IOERR;
1133 }
1134
1135 return GSOCK_NOERROR;
1136}
1137
1138/* Generic IO */
1139
1140/* Like recv(), send(), ... */
ba2a81d7 1141int GSocket::Read(char *buffer, int size)
97e6ee04
DE
1142{
1143 int ret;
1144
09e6e5ec 1145 assert(this);
97e6ee04 1146
09e6e5ec 1147 if (m_fd == INVALID_SOCKET || m_server)
97e6ee04 1148 {
09e6e5ec 1149 m_error = GSOCK_INVSOCK;
97e6ee04
DE
1150 return -1;
1151 }
1152
9d715960
DE
1153 /* Disable events during query of socket status */
1154 Disable(GSOCK_INPUT);
b082b524 1155
97e6ee04 1156 /* If the socket is blocking, wait for data (with a timeout) */
976abb72
VZ
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! */
9d715960 1161 ret = -1;
976abb72 1162 }
1aa7b427
DS
1163 else
1164 {
9d715960
DE
1165 /* Read the data */
1166 if (m_stream)
1167 ret = Recv_Stream(buffer, size);
1168 else
1169 ret = Recv_Dgram(buffer, size);
b082b524 1170
f4854380 1171 /* If recv returned zero, then the connection has been gracefully closed.
9b67181b
KH
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)
98e7a7f9 1176 {
f4854380 1177 /* Make sure wxSOCKET_LOST event gets sent and shut down the socket */
98e7a7f9 1178 m_detected = GSOCK_LOST_FLAG;
f4854380
VZ
1179 Detected_Read();
1180 return 0;
98e7a7f9 1181 }
1aa7b427
DS
1182 else if (ret == -1)
1183 {
976abb72
VZ
1184 if ((errno == EWOULDBLOCK) || (errno == EAGAIN))
1185 m_error = GSOCK_WOULDBLOCK;
1186 else
1187 m_error = GSOCK_IOERR;
1188 }
97e6ee04 1189 }
b082b524 1190
9d715960 1191 /* Enable events again now that we are done processing */
09e6e5ec 1192 Enable(GSOCK_INPUT);
97e6ee04
DE
1193
1194 return ret;
1195}
1196
ba2a81d7 1197int GSocket::Write(const char *buffer, int size)
b082b524 1198{
97e6ee04
DE
1199 int ret;
1200
09e6e5ec 1201 assert(this);
b082b524 1202
97e6ee04
DE
1203 GSocket_Debug(( "GSocket_Write #1, size %d\n", size ));
1204
09e6e5ec 1205 if (m_fd == INVALID_SOCKET || m_server)
97e6ee04 1206 {
09e6e5ec 1207 m_error = GSOCK_INVSOCK;
97e6ee04
DE
1208 return -1;
1209 }
1210
1211 GSocket_Debug(( "GSocket_Write #2, size %d\n", size ));
1212
1213 /* If the socket is blocking, wait for writability (with a timeout) */
09e6e5ec 1214 if (Output_Timeout() == GSOCK_TIMEDOUT)
97e6ee04
DE
1215 return -1;
1216
1217 GSocket_Debug(( "GSocket_Write #3, size %d\n", size ));
1218
1219 /* Write the data */
09e6e5ec
DE
1220 if (m_stream)
1221 ret = Send_Stream(buffer, size);
97e6ee04 1222 else
09e6e5ec 1223 ret = Send_Dgram(buffer, size);
b082b524 1224
97e6ee04
DE
1225 GSocket_Debug(( "GSocket_Write #4, size %d\n", size ));
1226
1227 if (ret == -1)
1228 {
7e1e6965 1229 if ((errno == EWOULDBLOCK) || (errno == EAGAIN))
97e6ee04 1230 {
09e6e5ec 1231 m_error = GSOCK_WOULDBLOCK;
97e6ee04
DE
1232 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
1233 }
1234 else
1235 {
09e6e5ec 1236 m_error = GSOCK_IOERR;
97e6ee04
DE
1237 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
1238 }
1239
1240 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
1241 * in MSW). Once the first OUTPUT event is received, users can assume
1242 * that the socket is writable until a read operation fails. Only then
1243 * will further OUTPUT events be posted.
1244 */
09e6e5ec 1245 Enable(GSOCK_OUTPUT);
1aa7b427 1246
97e6ee04
DE
1247 return -1;
1248 }
b082b524 1249
97e6ee04
DE
1250 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size, ret ));
1251
1252 return ret;
1253}
1254
1255/* GSocket_Select:
1256 * Polls the socket to determine its status. This function will
1257 * check for the events specified in the 'flags' parameter, and
1258 * it will return a mask indicating which operations can be
1259 * performed. This function won't block, regardless of the
1260 * mode (blocking | nonblocking) of the socket.
1261 */
ba2a81d7 1262GSocketEventFlags GSocket::Select(GSocketEventFlags flags)
97e6ee04 1263{
ba2a81d7 1264 if (!gs_gui_functions->CanUseEventLoop())
97e6ee04
DE
1265 {
1266
1267 GSocketEventFlags result = 0;
1268 fd_set readfds;
1269 fd_set writefds;
1270 fd_set exceptfds;
1271 struct timeval tv;
1272
9d715960
DE
1273 assert(this);
1274
60b0bd1d
JS
1275 if (m_fd == -1)
1276 return (GSOCK_LOST_FLAG & flags);
17a1ebd1 1277
97e6ee04 1278 /* Do not use a static struct, Linux can garble it */
09e6e5ec 1279 tv.tv_sec = m_timeout / 1000;
7488a05e 1280 tv.tv_usec = (m_timeout % 1000) * 1000;
97e6ee04 1281
17a1ebd1
VZ
1282 wxFD_ZERO(&readfds);
1283 wxFD_ZERO(&writefds);
1284 wxFD_ZERO(&exceptfds);
1285 wxFD_SET(m_fd, &readfds);
9d715960 1286 if (flags & GSOCK_OUTPUT_FLAG || flags & GSOCK_CONNECTION_FLAG)
17a1ebd1
VZ
1287 wxFD_SET(m_fd, &writefds);
1288 wxFD_SET(m_fd, &exceptfds);
97e6ee04
DE
1289
1290 /* Check 'sticky' CONNECTION flag first */
09e6e5ec 1291 result |= (GSOCK_CONNECTION_FLAG & m_detected);
97e6ee04
DE
1292
1293 /* If we have already detected a LOST event, then don't try
1294 * to do any further processing.
1295 */
09e6e5ec 1296 if ((m_detected & GSOCK_LOST_FLAG) != 0)
97e6ee04 1297 {
948c96ef 1298 m_establishing = false;
97e6ee04
DE
1299
1300 return (GSOCK_LOST_FLAG & flags);
1301 }
1302
1303 /* Try select now */
09e6e5ec 1304 if (select(m_fd + 1, &readfds, &writefds, &exceptfds, &tv) <= 0)
97e6ee04
DE
1305 {
1306 /* What to do here? */
1307 return (result & flags);
1308 }
1309
b74865fa
KH
1310 /* Check for exceptions and errors */
1311 if (wxFD_ISSET(m_fd, &exceptfds))
1312 {
1313 m_establishing = false;
1314 m_detected = GSOCK_LOST_FLAG;
1315
1316 /* LOST event: Abort any further processing */
1317 return (GSOCK_LOST_FLAG & flags);
1318 }
1319
97e6ee04 1320 /* Check for readability */
17a1ebd1 1321 if (wxFD_ISSET(m_fd, &readfds))
97e6ee04 1322 {
b74865fa 1323 result |= GSOCK_INPUT_FLAG;
bb154f79 1324
b74865fa 1325 if (m_server && m_stream)
97e6ee04 1326 {
b74865fa
KH
1327 /* This is a TCP server socket that detected a connection.
1328 While the INPUT_FLAG is also set, it doesn't matter on
01ba4b67 1329 this kind of sockets, as we can only Accept() from them. */
b74865fa
KH
1330 result |= GSOCK_CONNECTION_FLAG;
1331 m_detected |= GSOCK_CONNECTION_FLAG;
97e6ee04
DE
1332 }
1333 }
1334
1335 /* Check for writability */
17a1ebd1 1336 if (wxFD_ISSET(m_fd, &writefds))
97e6ee04 1337 {
09e6e5ec 1338 if (m_establishing && !m_server)
97e6ee04
DE
1339 {
1340 int error;
ddc1a35f 1341 SOCKOPTLEN_T len = sizeof(error);
97e6ee04 1342
948c96ef 1343 m_establishing = false;
97e6ee04 1344
f71bb8ef 1345 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
97e6ee04
DE
1346
1347 if (error)
1348 {
09e6e5ec 1349 m_detected = GSOCK_LOST_FLAG;
97e6ee04
DE
1350
1351 /* LOST event: Abort any further processing */
1352 return (GSOCK_LOST_FLAG & flags);
1353 }
1354 else
1355 {
1356 result |= GSOCK_CONNECTION_FLAG;
09e6e5ec 1357 m_detected |= GSOCK_CONNECTION_FLAG;
97e6ee04
DE
1358 }
1359 }
1360 else
1361 {
1362 result |= GSOCK_OUTPUT_FLAG;
1363 }
1364 }
97e6ee04
DE
1365
1366 return (result & flags);
1367
1368 }
1369 else
1370 {
09e6e5ec
DE
1371 assert(this);
1372 return flags & m_detected;
97e6ee04
DE
1373 }
1374}
1375
1376/* Flags */
1377
1378/* GSocket_SetNonBlocking:
1379 * Sets the socket to non-blocking mode. All IO calls will return
1380 * immediately.
1381 */
948c96ef 1382void GSocket::SetNonBlocking(bool non_block)
97e6ee04 1383{
09e6e5ec 1384 assert(this);
97e6ee04
DE
1385
1386 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
1387
09e6e5ec 1388 m_non_blocking = non_block;
97e6ee04
DE
1389}
1390
1391/* GSocket_SetTimeout:
1392 * Sets the timeout for blocking calls. Time is expressed in
1393 * milliseconds.
1394 */
ba2a81d7 1395void GSocket::SetTimeout(unsigned long millisec)
97e6ee04 1396{
09e6e5ec 1397 assert(this);
97e6ee04 1398
09e6e5ec 1399 m_timeout = millisec;
97e6ee04
DE
1400}
1401
1402/* GSocket_GetError:
d6922577 1403 * Returns the last error occurred for this socket. Note that successful
97e6ee04
DE
1404 * operations do not clear this back to GSOCK_NOERROR, so use it only
1405 * after an error.
1406 */
ba2a81d7 1407GSocketError WXDLLIMPEXP_NET GSocket::GetError()
97e6ee04 1408{
09e6e5ec 1409 assert(this);
97e6ee04 1410
09e6e5ec 1411 return m_error;
97e6ee04
DE
1412}
1413
1414/* Callbacks */
1415
1416/* GSOCK_INPUT:
1417 * There is data to be read in the input buffer. If, after a read
1418 * operation, there is still data available, the callback function will
1419 * be called again.
1420 * GSOCK_OUTPUT:
b082b524 1421 * The socket is available for writing. That is, the next write call
97e6ee04
DE
1422 * won't block. This event is generated only once, when the connection is
1423 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1424 * when the output buffer empties again. This means that the app should
1425 * assume that it can write since the first OUTPUT event, and no more
1426 * OUTPUT events will be generated unless an error occurs.
1427 * GSOCK_CONNECTION:
d6922577 1428 * Connection successfully established, for client sockets, or incoming
97e6ee04
DE
1429 * client connection, for server sockets. Wait for this event (also watch
1430 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1431 * GSOCK_LOST:
1432 * The connection is lost (or a connection request failed); this could
1433 * be due to a failure, or due to the peer closing it gracefully.
1434 */
1435
1436/* GSocket_SetCallback:
1437 * Enables the callbacks specified by 'flags'. Note that 'flags'
1438 * may be a combination of flags OR'ed toghether, so the same
1439 * callback function can be made to accept different events.
1440 * The callback function must have the following prototype:
1441 *
1442 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1443 */
ba2a81d7 1444void GSocket::SetCallback(GSocketEventFlags flags,
97e6ee04
DE
1445 GSocketCallback callback, char *cdata)
1446{
1447 int count;
1448
09e6e5ec 1449 assert(this);
97e6ee04
DE
1450
1451 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1452 {
1453 if ((flags & (1 << count)) != 0)
1454 {
09e6e5ec
DE
1455 m_cbacks[count] = callback;
1456 m_data[count] = cdata;
97e6ee04
DE
1457 }
1458 }
1459}
1460
1461/* GSocket_UnsetCallback:
1462 * Disables all callbacks specified by 'flags', which may be a
1463 * combination of flags OR'ed toghether.
1464 */
ba2a81d7 1465void GSocket::UnsetCallback(GSocketEventFlags flags)
97e6ee04
DE
1466{
1467 int count;
1468
09e6e5ec 1469 assert(this);
97e6ee04
DE
1470
1471 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1472 {
1473 if ((flags & (1 << count)) != 0)
1474 {
09e6e5ec
DE
1475 m_cbacks[count] = NULL;
1476 m_data[count] = NULL;
97e6ee04
DE
1477 }
1478 }
1479}
1480
ba2a81d7 1481GSocketError GSocket::GetSockOpt(int level, int optname,
b082b524
DE
1482 void *optval, int *optlen)
1483{
ddc1a35f 1484 if (getsockopt(m_fd, level, optname, (char*)optval, (SOCKOPTLEN_T*)optlen) == 0)
b082b524 1485 return GSOCK_NOERROR;
1aa7b427 1486
b082b524
DE
1487 return GSOCK_OPTERR;
1488}
1489
ba2a81d7 1490GSocketError GSocket::SetSockOpt(int level, int optname,
b082b524
DE
1491 const void *optval, int optlen)
1492{
f71bb8ef 1493 if (setsockopt(m_fd, level, optname, (const char*)optval, optlen) == 0)
b082b524 1494 return GSOCK_NOERROR;
1aa7b427 1495
b082b524
DE
1496 return GSOCK_OPTERR;
1497}
1498
ba2a81d7 1499#define CALL_CALLBACK(socket, event) { \
9a7e4a56 1500 socket->Disable(event); \
ba2a81d7
DE
1501 if (socket->m_cbacks[event]) \
1502 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
97e6ee04
DE
1503}
1504
1505
ba2a81d7 1506void GSocket::Enable(GSocketEvent event)
97e6ee04 1507{
09e6e5ec 1508 m_detected &= ~(1 << event);
ba2a81d7 1509 gs_gui_functions->Install_Callback(this, event);
97e6ee04
DE
1510}
1511
ba2a81d7 1512void GSocket::Disable(GSocketEvent event)
97e6ee04 1513{
09e6e5ec 1514 m_detected |= (1 << event);
ba2a81d7 1515 gs_gui_functions->Uninstall_Callback(this, event);
97e6ee04
DE
1516}
1517
1518/* _GSocket_Input_Timeout:
1519 * For blocking sockets, wait until data is available or
1520 * until timeout ellapses.
1521 */
ba2a81d7 1522GSocketError GSocket::Input_Timeout()
97e6ee04
DE
1523{
1524 struct timeval tv;
1525 fd_set readfds;
1526 int ret;
1527
1528 /* Linux select() will overwrite the struct on return */
09e6e5ec
DE
1529 tv.tv_sec = (m_timeout / 1000);
1530 tv.tv_usec = (m_timeout % 1000) * 1000;
97e6ee04 1531
09e6e5ec 1532 if (!m_non_blocking)
97e6ee04 1533 {
17a1ebd1
VZ
1534 wxFD_ZERO(&readfds);
1535 wxFD_SET(m_fd, &readfds);
09e6e5ec 1536 ret = select(m_fd + 1, &readfds, NULL, NULL, &tv);
97e6ee04
DE
1537 if (ret == 0)
1538 {
1539 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
09e6e5ec 1540 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1541 return GSOCK_TIMEDOUT;
1542 }
1aa7b427 1543
97e6ee04
DE
1544 if (ret == -1)
1545 {
1546 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1547 if (errno == EBADF) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1548 if (errno == EINTR) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1549 if (errno == EINVAL) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1550 if (errno == ENOMEM) { GSocket_Debug(( "Not enough memory\n" )); }
09e6e5ec 1551 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1552 return GSOCK_TIMEDOUT;
1553 }
1554 }
1aa7b427 1555
97e6ee04
DE
1556 return GSOCK_NOERROR;
1557}
1558
1559/* _GSocket_Output_Timeout:
1560 * For blocking sockets, wait until data can be sent without
1561 * blocking or until timeout ellapses.
1562 */
ba2a81d7 1563GSocketError GSocket::Output_Timeout()
97e6ee04
DE
1564{
1565 struct timeval tv;
1566 fd_set writefds;
1567 int ret;
1568
1569 /* Linux select() will overwrite the struct on return */
09e6e5ec
DE
1570 tv.tv_sec = (m_timeout / 1000);
1571 tv.tv_usec = (m_timeout % 1000) * 1000;
97e6ee04 1572
09e6e5ec 1573 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking) );
97e6ee04 1574
09e6e5ec 1575 if (!m_non_blocking)
97e6ee04 1576 {
17a1ebd1
VZ
1577 wxFD_ZERO(&writefds);
1578 wxFD_SET(m_fd, &writefds);
09e6e5ec 1579 ret = select(m_fd + 1, NULL, &writefds, NULL, &tv);
97e6ee04
DE
1580 if (ret == 0)
1581 {
1582 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
09e6e5ec 1583 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1584 return GSOCK_TIMEDOUT;
1585 }
1aa7b427 1586
97e6ee04
DE
1587 if (ret == -1)
1588 {
1589 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1590 if (errno == EBADF) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1591 if (errno == EINTR) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1592 if (errno == EINVAL) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1593 if (errno == ENOMEM) { GSocket_Debug(( "Not enough memory\n" )); }
09e6e5ec 1594 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1595 return GSOCK_TIMEDOUT;
1596 }
1aa7b427
DS
1597
1598 if ( ! wxFD_ISSET(m_fd, &writefds) )
1599 {
97e6ee04
DE
1600 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1601 }
1aa7b427
DS
1602 else
1603 {
97e6ee04
DE
1604 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1605 }
1606 }
1607 else
1608 {
1609 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1610 }
1611
1612 return GSOCK_NOERROR;
1613}
1614
ba2a81d7 1615int GSocket::Recv_Stream(char *buffer, int size)
97e6ee04 1616{
bb154f79 1617 int ret;
7e1e6965 1618 do
bb154f79
KH
1619 {
1620 ret = recv(m_fd, buffer, size, GSOCKET_MSG_NOSIGNAL);
1aa7b427
DS
1621 }
1622 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
1623
bb154f79 1624 return ret;
97e6ee04
DE
1625}
1626
ba2a81d7 1627int GSocket::Recv_Dgram(char *buffer, int size)
97e6ee04
DE
1628{
1629 struct sockaddr from;
9e03e02d 1630 WX_SOCKLEN_T fromlen = sizeof(from);
97e6ee04
DE
1631 int ret;
1632 GSocketError err;
1633
1634 fromlen = sizeof(from);
1635
7e1e6965 1636 do
bb154f79 1637 {
9e03e02d 1638 ret = recvfrom(m_fd, buffer, size, 0, &from, (WX_SOCKLEN_T *) &fromlen);
1aa7b427
DS
1639 }
1640 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
97e6ee04
DE
1641
1642 if (ret == -1)
1643 return -1;
1644
1645 /* Translate a system address into a GSocket address */
09e6e5ec 1646 if (!m_peer)
97e6ee04 1647 {
09e6e5ec
DE
1648 m_peer = GAddress_new();
1649 if (!m_peer)
97e6ee04 1650 {
09e6e5ec 1651 m_error = GSOCK_MEMERR;
97e6ee04
DE
1652 return -1;
1653 }
1654 }
1aa7b427 1655
09e6e5ec 1656 err = _GAddress_translate_from(m_peer, &from, fromlen);
97e6ee04
DE
1657 if (err != GSOCK_NOERROR)
1658 {
09e6e5ec
DE
1659 GAddress_destroy(m_peer);
1660 m_peer = NULL;
1661 m_error = err;
97e6ee04
DE
1662 return -1;
1663 }
1664
1665 return ret;
1666}
1667
ba2a81d7 1668int GSocket::Send_Stream(const char *buffer, int size)
97e6ee04
DE
1669{
1670 int ret;
1671
7e1e6965
WS
1672 MASK_SIGNAL();
1673
1674 do
bb154f79
KH
1675 {
1676 ret = send(m_fd, (char *)buffer, size, GSOCKET_MSG_NOSIGNAL);
1aa7b427
DS
1677 }
1678 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
7e1e6965 1679
97e6ee04 1680 UNMASK_SIGNAL();
97e6ee04
DE
1681
1682 return ret;
1683}
1684
ba2a81d7 1685int GSocket::Send_Dgram(const char *buffer, int size)
97e6ee04
DE
1686{
1687 struct sockaddr *addr;
1688 int len, ret;
1689 GSocketError err;
1690
09e6e5ec 1691 if (!m_peer)
97e6ee04 1692 {
09e6e5ec 1693 m_error = GSOCK_INVADDR;
97e6ee04
DE
1694 return -1;
1695 }
1696
09e6e5ec 1697 err = _GAddress_translate_to(m_peer, &addr, &len);
97e6ee04
DE
1698 if (err != GSOCK_NOERROR)
1699 {
09e6e5ec 1700 m_error = err;
97e6ee04
DE
1701 return -1;
1702 }
1703
97e6ee04 1704 MASK_SIGNAL();
7e1e6965
WS
1705
1706 do
bb154f79
KH
1707 {
1708 ret = sendto(m_fd, (char *)buffer, size, 0, addr, len);
1aa7b427
DS
1709 }
1710 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
7e1e6965 1711
97e6ee04 1712 UNMASK_SIGNAL();
97e6ee04
DE
1713
1714 /* Frees memory allocated from _GAddress_translate_to */
1715 free(addr);
1716
1717 return ret;
1718}
1719
ba2a81d7 1720void GSocket::Detected_Read()
97e6ee04
DE
1721{
1722 char c;
1723
bb154f79
KH
1724 /* Safeguard against straggling call to Detected_Read */
1725 if (m_fd == INVALID_SOCKET)
1726 {
1727 return;
1728 }
1729
97e6ee04
DE
1730 /* If we have already detected a LOST event, then don't try
1731 * to do any further processing.
1732 */
09e6e5ec 1733 if ((m_detected & GSOCK_LOST_FLAG) != 0)
97e6ee04 1734 {
948c96ef 1735 m_establishing = false;
97e6ee04 1736
ba2a81d7 1737 CALL_CALLBACK(this, GSOCK_LOST);
09e6e5ec 1738 Shutdown();
97e6ee04
DE
1739 return;
1740 }
1741
bb154f79
KH
1742 int num = recv(m_fd, &c, 1, MSG_PEEK | GSOCKET_MSG_NOSIGNAL);
1743
1744 if (num > 0)
97e6ee04 1745 {
ba2a81d7 1746 CALL_CALLBACK(this, GSOCK_INPUT);
97e6ee04
DE
1747 }
1748 else
1749 {
09e6e5ec 1750 if (m_server && m_stream)
97e6ee04 1751 {
ba2a81d7 1752 CALL_CALLBACK(this, GSOCK_CONNECTION);
97e6ee04
DE
1753 }
1754 else
1755 {
e400d27d 1756 /* Do not throw a lost event in cases where the socket isn't really lost */
7e1e6965 1757 if ((errno == EWOULDBLOCK) || (errno == EAGAIN) || (errno == EINTR))
bb154f79
KH
1758 {
1759 CALL_CALLBACK(this, GSOCK_INPUT);
1760 }
7e1e6965 1761 else
bb154f79
KH
1762 {
1763 CALL_CALLBACK(this, GSOCK_LOST);
1764 Shutdown();
7e1e6965 1765 }
97e6ee04
DE
1766 }
1767 }
1768}
1769
ba2a81d7 1770void GSocket::Detected_Write()
97e6ee04
DE
1771{
1772 /* If we have already detected a LOST event, then don't try
1773 * to do any further processing.
1774 */
09e6e5ec 1775 if ((m_detected & GSOCK_LOST_FLAG) != 0)
97e6ee04 1776 {
948c96ef 1777 m_establishing = false;
97e6ee04 1778
ba2a81d7 1779 CALL_CALLBACK(this, GSOCK_LOST);
09e6e5ec 1780 Shutdown();
97e6ee04
DE
1781 return;
1782 }
1783
09e6e5ec 1784 if (m_establishing && !m_server)
97e6ee04
DE
1785 {
1786 int error;
ddc1a35f 1787 SOCKOPTLEN_T len = sizeof(error);
97e6ee04 1788
948c96ef 1789 m_establishing = false;
97e6ee04 1790
f71bb8ef 1791 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
97e6ee04
DE
1792
1793 if (error)
1794 {
ba2a81d7 1795 CALL_CALLBACK(this, GSOCK_LOST);
09e6e5ec 1796 Shutdown();
97e6ee04
DE
1797 }
1798 else
1799 {
ba2a81d7 1800 CALL_CALLBACK(this, GSOCK_CONNECTION);
97e6ee04
DE
1801 /* We have to fire this event by hand because CONNECTION (for clients)
1802 * and OUTPUT are internally the same and we just disabled CONNECTION
1803 * events with the above macro.
1804 */
ba2a81d7 1805 CALL_CALLBACK(this, GSOCK_OUTPUT);
97e6ee04
DE
1806 }
1807 }
1808 else
1809 {
ba2a81d7 1810 CALL_CALLBACK(this, GSOCK_OUTPUT);
97e6ee04
DE
1811 }
1812}
1813
09e6e5ec
DE
1814/* Compatibility functions for GSocket */
1815GSocket *GSocket_new(void)
1816{
ba2a81d7 1817 GSocket *newsocket = new GSocket();
1aa7b427 1818 if (newsocket->IsOk())
09e6e5ec 1819 return newsocket;
1aa7b427 1820
09e6e5ec 1821 delete newsocket;
1aa7b427 1822
09e6e5ec
DE
1823 return NULL;
1824}
1825
97e6ee04
DE
1826/*
1827 * -------------------------------------------------------------------------
1828 * GAddress
1829 * -------------------------------------------------------------------------
1830 */
1831
1832/* CHECK_ADDRESS verifies that the current address family is either
1833 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1834 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1835 * an appropiate error code.
1836 *
1837 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1838 */
1839#define CHECK_ADDRESS(address, family) \
1840{ \
1841 if (address->m_family == GSOCK_NOFAMILY) \
1842 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1843 return address->m_error; \
1844 if (address->m_family != GSOCK_##family) \
1845 { \
1846 address->m_error = GSOCK_INVADDR; \
1847 return GSOCK_INVADDR; \
1848 } \
1849}
1850
1851#define CHECK_ADDRESS_RETVAL(address, family, retval) \
1852{ \
1853 if (address->m_family == GSOCK_NOFAMILY) \
1854 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1855 return retval; \
1856 if (address->m_family != GSOCK_##family) \
1857 { \
1858 address->m_error = GSOCK_INVADDR; \
1859 return retval; \
1860 } \
1861}
1862
1863
1864GAddress *GAddress_new(void)
1865{
1866 GAddress *address;
1867
1868 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1869 return NULL;
1870
1871 address->m_family = GSOCK_NOFAMILY;
1872 address->m_addr = NULL;
1873 address->m_len = 0;
1874
1875 return address;
1876}
1877
1878GAddress *GAddress_copy(GAddress *address)
1879{
1880 GAddress *addr2;
1881
1882 assert(address != NULL);
1883
1884 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1885 return NULL;
1886
1887 memcpy(addr2, address, sizeof(GAddress));
1888
1889 if (address->m_addr && address->m_len > 0)
1890 {
1891 addr2->m_addr = (struct sockaddr *)malloc(addr2->m_len);
1892 if (addr2->m_addr == NULL)
1893 {
1894 free(addr2);
1895 return NULL;
1896 }
1897 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1898 }
1899
1900 return addr2;
1901}
1902
1903void GAddress_destroy(GAddress *address)
1904{
1905 assert(address != NULL);
1906
1907 if (address->m_addr)
1908 free(address->m_addr);
1909
1910 free(address);
1911}
1912
1913void GAddress_SetFamily(GAddress *address, GAddressType type)
1914{
1915 assert(address != NULL);
1916
1917 address->m_family = type;
1918}
1919
1920GAddressType GAddress_GetFamily(GAddress *address)
1921{
1922 assert(address != NULL);
1923
1924 return address->m_family;
1925}
1926
1927GSocketError _GAddress_translate_from(GAddress *address,
1928 struct sockaddr *addr, int len)
1929{
1930 address->m_realfamily = addr->sa_family;
1931 switch (addr->sa_family)
1932 {
1933 case AF_INET:
1934 address->m_family = GSOCK_INET;
1935 break;
1936 case AF_UNIX:
1937 address->m_family = GSOCK_UNIX;
1938 break;
1939#ifdef AF_INET6
1940 case AF_INET6:
1941 address->m_family = GSOCK_INET6;
1942 break;
1943#endif
1944 default:
1945 {
1946 address->m_error = GSOCK_INVOP;
1947 return GSOCK_INVOP;
1948 }
1949 }
1950
1951 if (address->m_addr)
1952 free(address->m_addr);
1953
1954 address->m_len = len;
1955 address->m_addr = (struct sockaddr *)malloc(len);
1956
1957 if (address->m_addr == NULL)
1958 {
1959 address->m_error = GSOCK_MEMERR;
1960 return GSOCK_MEMERR;
1961 }
1aa7b427 1962
97e6ee04
DE
1963 memcpy(address->m_addr, addr, len);
1964
1965 return GSOCK_NOERROR;
1966}
1967
1968GSocketError _GAddress_translate_to(GAddress *address,
1969 struct sockaddr **addr, int *len)
1970{
1971 if (!address->m_addr)
1972 {
1973 address->m_error = GSOCK_INVADDR;
1974 return GSOCK_INVADDR;
1975 }
1976
1977 *len = address->m_len;
1978 *addr = (struct sockaddr *)malloc(address->m_len);
1979 if (*addr == NULL)
1980 {
1981 address->m_error = GSOCK_MEMERR;
1982 return GSOCK_MEMERR;
1983 }
1984
1985 memcpy(*addr, address->m_addr, address->m_len);
1986 return GSOCK_NOERROR;
1987}
1988
1989/*
1990 * -------------------------------------------------------------------------
1991 * Internet address family
1992 * -------------------------------------------------------------------------
1993 */
1994
1995GSocketError _GAddress_Init_INET(GAddress *address)
1996{
1997 address->m_len = sizeof(struct sockaddr_in);
1998 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1999 if (address->m_addr == NULL)
2000 {
2001 address->m_error = GSOCK_MEMERR;
2002 return GSOCK_MEMERR;
2003 }
2004
2005 address->m_family = GSOCK_INET;
2006 address->m_realfamily = PF_INET;
2007 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
2008 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
2009
2010 return GSOCK_NOERROR;
2011}
2012
2013GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
2014{
2015 struct hostent *he;
2016 struct in_addr *addr;
2017
2018 assert(address != NULL);
2019
2020 CHECK_ADDRESS(address, INET);
2021
2022 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
2023
2024 /* If it is a numeric host name, convert it now */
2025#if defined(HAVE_INET_ATON)
2026 if (inet_aton(hostname, addr) == 0)
2027 {
2028#elif defined(HAVE_INET_ADDR)
8c0f8906 2029 if ( (addr->s_addr = inet_addr(hostname)) == (unsigned)-1 )
97e6ee04
DE
2030 {
2031#else
2032 /* Use gethostbyname by default */
9d715960 2033#ifndef __WXMAC__
ba2a81d7 2034 int val = 1; /* VA doesn't like constants in conditional expressions */
97e6ee04 2035 if (val)
9d715960 2036#endif
97e6ee04
DE
2037 {
2038#endif
2039 struct in_addr *array_addr;
2040
2041 /* It is a real name, we solve it */
127189eb
SN
2042 struct hostent h;
2043#if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2044 struct hostent_data buffer;
2045#else
2046 char buffer[1024];
2047#endif
2048 int err;
2049 he = wxGethostbyname_r(hostname, &h, (void*)&buffer, sizeof(buffer), &err);
2050 if (he == NULL)
97e6ee04
DE
2051 {
2052 /* Reset to invalid address */
2053 addr->s_addr = INADDR_NONE;
2054 address->m_error = GSOCK_NOHOST;
2055 return GSOCK_NOHOST;
2056 }
1aa7b427 2057
97e6ee04
DE
2058 array_addr = (struct in_addr *) *(he->h_addr_list);
2059 addr->s_addr = array_addr[0].s_addr;
2060 }
1aa7b427 2061
97e6ee04
DE
2062 return GSOCK_NOERROR;
2063}
2064
2065GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
2066{
2067 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
2068}
2069
2070GSocketError GAddress_INET_SetHostAddress(GAddress *address,
2071 unsigned long hostaddr)
2072{
2073 struct in_addr *addr;
2074
2075 assert(address != NULL);
2076
2077 CHECK_ADDRESS(address, INET);
2078
2079 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
9d715960 2080 addr->s_addr = htonl(hostaddr);
97e6ee04
DE
2081
2082 return GSOCK_NOERROR;
2083}
2084
2085GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
2086 const char *protocol)
2087{
2088 struct servent *se;
2089 struct sockaddr_in *addr;
2090
2091 assert(address != NULL);
2092 CHECK_ADDRESS(address, INET);
2093
2094 if (!port)
2095 {
2096 address->m_error = GSOCK_INVPORT;
2097 return GSOCK_INVPORT;
2098 }
b082b524 2099
127189eb
SN
2100#if defined(HAVE_FUNC_GETSERVBYNAME_R_4)
2101 struct servent_data buffer;
f6bc1c74 2102#else
127189eb 2103 char buffer[1024];
f6bc1c74 2104#endif
127189eb
SN
2105 struct servent serv;
2106 se = wxGetservbyname_r(port, protocol, &serv,
2107 (void*)&buffer, sizeof(buffer));
97e6ee04
DE
2108 if (!se)
2109 {
2110 /* the cast to int suppresses compiler warnings about subscript having the
2111 type char */
2112 if (isdigit((int)port[0]))
2113 {
2114 int port_int;
2115
2116 port_int = atoi(port);
2117 addr = (struct sockaddr_in *)address->m_addr;
2118 addr->sin_port = htons(port_int);
2119 return GSOCK_NOERROR;
2120 }
2121
2122 address->m_error = GSOCK_INVPORT;
2123 return GSOCK_INVPORT;
2124 }
2125
2126 addr = (struct sockaddr_in *)address->m_addr;
2127 addr->sin_port = se->s_port;
2128
2129 return GSOCK_NOERROR;
2130}
2131
2132GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
2133{
2134 struct sockaddr_in *addr;
2135
2136 assert(address != NULL);
2137 CHECK_ADDRESS(address, INET);
b082b524 2138
97e6ee04
DE
2139 addr = (struct sockaddr_in *)address->m_addr;
2140 addr->sin_port = htons(port);
2141
2142 return GSOCK_NOERROR;
2143}
2144
2145GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
2146{
2147 struct hostent *he;
2148 char *addr_buf;
2149 struct sockaddr_in *addr;
2150
b082b524 2151 assert(address != NULL);
97e6ee04
DE
2152 CHECK_ADDRESS(address, INET);
2153
2154 addr = (struct sockaddr_in *)address->m_addr;
2155 addr_buf = (char *)&(addr->sin_addr);
2156
127189eb
SN
2157 struct hostent temphost;
2158#if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2159 struct hostent_data buffer;
2160#else
2161 char buffer[1024];
2162#endif
2163 int err;
2164 he = wxGethostbyaddr_r(addr_buf, sizeof(addr->sin_addr), AF_INET, &temphost,
2165 (void*)&buffer, sizeof(buffer), &err);
97e6ee04
DE
2166 if (he == NULL)
2167 {
2168 address->m_error = GSOCK_NOHOST;
2169 return GSOCK_NOHOST;
2170 }
2171
2172 strncpy(hostname, he->h_name, sbuf);
2173
2174 return GSOCK_NOERROR;
2175}
2176
2177unsigned long GAddress_INET_GetHostAddress(GAddress *address)
2178{
2179 struct sockaddr_in *addr;
2180
b082b524
DE
2181 assert(address != NULL);
2182 CHECK_ADDRESS_RETVAL(address, INET, 0);
97e6ee04
DE
2183
2184 addr = (struct sockaddr_in *)address->m_addr;
2185
9d715960 2186 return ntohl(addr->sin_addr.s_addr);
97e6ee04
DE
2187}
2188
2189unsigned short GAddress_INET_GetPort(GAddress *address)
2190{
2191 struct sockaddr_in *addr;
2192
b082b524
DE
2193 assert(address != NULL);
2194 CHECK_ADDRESS_RETVAL(address, INET, 0);
97e6ee04
DE
2195
2196 addr = (struct sockaddr_in *)address->m_addr;
2197 return ntohs(addr->sin_port);
2198}
2199
2200/*
2201 * -------------------------------------------------------------------------
2202 * Unix address family
2203 * -------------------------------------------------------------------------
2204 */
2205
2206#ifndef __VISAGECPP__
2207GSocketError _GAddress_Init_UNIX(GAddress *address)
2208{
2209 address->m_len = sizeof(struct sockaddr_un);
2210 address->m_addr = (struct sockaddr *)malloc(address->m_len);
2211 if (address->m_addr == NULL)
2212 {
2213 address->m_error = GSOCK_MEMERR;
2214 return GSOCK_MEMERR;
2215 }
2216
2217 address->m_family = GSOCK_UNIX;
2218 address->m_realfamily = PF_UNIX;
2219 ((struct sockaddr_un *)address->m_addr)->sun_family = AF_UNIX;
2220 ((struct sockaddr_un *)address->m_addr)->sun_path[0] = 0;
2221
2222 return GSOCK_NOERROR;
2223}
2224
2225#define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
2226
2227GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *path)
2228{
2229 struct sockaddr_un *addr;
2230
b082b524 2231 assert(address != NULL);
97e6ee04 2232
b082b524 2233 CHECK_ADDRESS(address, UNIX);
97e6ee04
DE
2234
2235 addr = ((struct sockaddr_un *)address->m_addr);
2236 strncpy(addr->sun_path, path, UNIX_SOCK_PATHLEN);
2237 addr->sun_path[UNIX_SOCK_PATHLEN - 1] = '\0';
2238
2239 return GSOCK_NOERROR;
2240}
2241
2242GSocketError GAddress_UNIX_GetPath(GAddress *address, char *path, size_t sbuf)
2243{
2244 struct sockaddr_un *addr;
2245
2246 assert(address != NULL);
2247 CHECK_ADDRESS(address, UNIX);
2248
2249 addr = (struct sockaddr_un *)address->m_addr;
2250
2251 strncpy(path, addr->sun_path, sbuf);
2252
2253 return GSOCK_NOERROR;
2254}
2255#endif /* !defined(__VISAGECPP__) */
2256#endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */