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