]> git.saurik.com Git - wxWidgets.git/blame - src/unix/gsocket.cpp
cleanup - heavy reformatting
[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
302#if defined(HAVE_GETHOSTBYNAME)
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)
b082b524 694 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(u_long));
97e6ee04
DE
695
696 /* Bind to the local address,
697 * retrieve the actual address bound,
698 * and listen up to 5 connections.
699 */
09e6e5ec
DE
700 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
701 (getsockname(m_fd,
702 m_local->m_addr,
9e03e02d 703 (WX_SOCKLEN_T *) &m_local->m_len) != 0) ||
09e6e5ec 704 (listen(m_fd, 5) != 0))
97e6ee04 705 {
09e6e5ec
DE
706 Close();
707 m_error = GSOCK_IOERR;
97e6ee04
DE
708 return GSOCK_IOERR;
709 }
710
711 return GSOCK_NOERROR;
712}
713
714/* GSocket_WaitConnection:
715 * Waits for an incoming client connection. Returns a pointer to
716 * a GSocket object, or NULL if there was an error, in which case
717 * the last error field will be updated for the calling GSocket.
718 *
719 * Error codes (set in the calling GSocket)
720 * GSOCK_INVSOCK - the socket is not valid or not a server.
721 * GSOCK_TIMEDOUT - timeout, no incoming connections.
722 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
723 * GSOCK_MEMERR - couldn't allocate memory.
b082b524 724 * GSOCK_IOERR - low-level error.
97e6ee04 725 */
ba2a81d7 726GSocket *GSocket::WaitConnection()
97e6ee04
DE
727{
728 struct sockaddr from;
9e03e02d 729 WX_SOCKLEN_T fromlen = sizeof(from);
97e6ee04
DE
730 GSocket *connection;
731 GSocketError err;
732 int arg = 1;
733
09e6e5ec 734 assert(this);
97e6ee04 735
97e6ee04 736 /* If the socket has already been created, we exit immediately */
09e6e5ec 737 if (m_fd == INVALID_SOCKET || !m_server)
97e6ee04 738 {
09e6e5ec 739 m_error = GSOCK_INVSOCK;
97e6ee04
DE
740 return NULL;
741 }
742
743 /* Create a GSocket object for the new connection */
444cb1fd 744 connection = GSocket_new();
97e6ee04 745
444cb1fd 746 if (!connection)
97e6ee04 747 {
09e6e5ec 748 m_error = GSOCK_MEMERR;
97e6ee04
DE
749 return NULL;
750 }
751
752 /* Wait for a connection (with timeout) */
09e6e5ec 753 if (Input_Timeout() == GSOCK_TIMEDOUT)
97e6ee04 754 {
85431efa 755 delete connection;
09e6e5ec 756 /* m_error set by _GSocket_Input_Timeout */
97e6ee04
DE
757 return NULL;
758 }
759
9e03e02d 760 connection->m_fd = accept(m_fd, &from, (WX_SOCKLEN_T *) &fromlen);
97e6ee04 761
bb154f79
KH
762 /* Reenable CONNECTION events */
763 Enable(GSOCK_CONNECTION);
bb154f79 764
97e6ee04
DE
765 if (connection->m_fd == INVALID_SOCKET)
766 {
767 if (errno == EWOULDBLOCK)
09e6e5ec 768 m_error = GSOCK_WOULDBLOCK;
97e6ee04 769 else
09e6e5ec 770 m_error = GSOCK_IOERR;
97e6ee04 771
85431efa 772 delete connection;
97e6ee04
DE
773 return NULL;
774 }
775
776 /* Initialize all fields */
948c96ef
DE
777 connection->m_server = false;
778 connection->m_stream = true;
97e6ee04
DE
779
780 /* Setup the peer address field */
781 connection->m_peer = GAddress_new();
782 if (!connection->m_peer)
783 {
85431efa 784 delete connection;
09e6e5ec 785 m_error = GSOCK_MEMERR;
97e6ee04
DE
786 return NULL;
787 }
1aa7b427 788
97e6ee04
DE
789 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
790 if (err != GSOCK_NOERROR)
791 {
85431efa 792 delete connection;
09e6e5ec 793 m_error = err;
97e6ee04
DE
794 return NULL;
795 }
1aa7b427 796
97e6ee04
DE
797#if defined(__EMX__) || defined(__VISAGECPP__)
798 ioctl(connection->m_fd, FIONBIO, (char*)&arg, sizeof(arg));
799#else
800 ioctl(connection->m_fd, FIONBIO, &arg);
801#endif
ba2a81d7 802 gs_gui_functions->Enable_Events(connection);
97e6ee04
DE
803
804 return connection;
805}
806
948c96ef 807bool GSocket::SetReusable()
b082b524
DE
808{
809 /* socket must not be null, and must not be in use/already bound */
1aa7b427
DS
810 if (this && m_fd == INVALID_SOCKET)
811 {
948c96ef 812 m_reusable = true;
1aa7b427 813
948c96ef 814 return true;
b082b524 815 }
1aa7b427 816
948c96ef 817 return false;
b082b524
DE
818}
819
97e6ee04
DE
820/* Client specific parts */
821
822/* GSocket_Connect:
823 * For stream (connection oriented) sockets, GSocket_Connect() tries
824 * to establish a client connection to a server using the peer address
825 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
d6922577 826 * connection has been successfully established, or one of the error
97e6ee04
DE
827 * codes listed below. Note that for nonblocking sockets, a return
828 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
829 * request can be completed later; you should use GSocket_Select()
830 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
831 * corresponding asynchronous events.
832 *
833 * For datagram (non connection oriented) sockets, GSocket_Connect()
834 * just sets the peer address established with GSocket_SetPeer() as
835 * default destination.
836 *
837 * Error codes:
838 * GSOCK_INVSOCK - the socket is in use or not valid.
839 * GSOCK_INVADDR - the peer address has not been established.
840 * GSOCK_TIMEDOUT - timeout, the connection failed.
841 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
842 * GSOCK_MEMERR - couldn't allocate memory.
b082b524 843 * GSOCK_IOERR - low-level error.
97e6ee04 844 */
ba2a81d7 845GSocketError GSocket::Connect(GSocketStream stream)
97e6ee04
DE
846{
847 int err, ret;
848 int arg = 1;
849
09e6e5ec 850 assert(this);
97e6ee04
DE
851
852 /* Enable CONNECTION events (needed for nonblocking connections) */
09e6e5ec 853 Enable(GSOCK_CONNECTION);
97e6ee04 854
09e6e5ec 855 if (m_fd != INVALID_SOCKET)
97e6ee04 856 {
09e6e5ec 857 m_error = GSOCK_INVSOCK;
97e6ee04
DE
858 return GSOCK_INVSOCK;
859 }
860
09e6e5ec 861 if (!m_peer)
97e6ee04 862 {
09e6e5ec 863 m_error = GSOCK_INVADDR;
97e6ee04
DE
864 return GSOCK_INVADDR;
865 }
866
867 /* Streamed or dgram socket? */
09e6e5ec 868 m_stream = (stream == GSOCK_STREAMED);
948c96ef
DE
869 m_server = false;
870 m_establishing = false;
97e6ee04
DE
871
872 /* Create the socket */
09e6e5ec
DE
873 m_fd = socket(m_peer->m_realfamily,
874 m_stream? SOCK_STREAM : SOCK_DGRAM, 0);
97e6ee04 875
09e6e5ec 876 if (m_fd == INVALID_SOCKET)
97e6ee04 877 {
09e6e5ec 878 m_error = GSOCK_IOERR;
97e6ee04
DE
879 return GSOCK_IOERR;
880 }
bb154f79
KH
881
882 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
883#ifdef SO_NOSIGPIPE
884 setsockopt(m_fd, SOL_SOCKET, SO_NOSIGPIPE, (const char*)&arg, sizeof(u_long));
885#endif
886
97e6ee04 887#if defined(__EMX__) || defined(__VISAGECPP__)
09e6e5ec 888 ioctl(m_fd, FIONBIO, (char*)&arg, sizeof(arg));
97e6ee04 889#else
09e6e5ec 890 ioctl(m_fd, FIONBIO, &arg);
97e6ee04 891#endif
97e6ee04
DE
892
893 /* Connect it to the peer address, with a timeout (see below) */
09e6e5ec 894 ret = connect(m_fd, m_peer->m_addr, m_peer->m_len);
97e6ee04 895
0d34c30e
KH
896 /* We only call Enable_Events if we know we aren't shutting down the socket.
897 * NB: Enable_Events needs to be called whether the socket is blocking or
898 * non-blocking, it just shouldn't be called prior to knowing there is a
899 * connection _if_ blocking sockets are being used.
900 * If connect above returns 0, we are already connected and need to make the
17a1ebd1 901 * call to Enable_Events now.
a3687636 902 */
17a1ebd1 903
0d34c30e 904 if (m_non_blocking || ret == 0)
bb154f79 905 gs_gui_functions->Enable_Events(this);
bb154f79 906
97e6ee04
DE
907 if (ret == -1)
908 {
909 err = errno;
910
911 /* If connect failed with EINPROGRESS and the GSocket object
912 * is in blocking mode, we select() for the specified timeout
913 * checking for writability to see if the connection request
914 * completes.
915 */
09e6e5ec 916 if ((err == EINPROGRESS) && (!m_non_blocking))
97e6ee04 917 {
09e6e5ec 918 if (Output_Timeout() == GSOCK_TIMEDOUT)
97e6ee04 919 {
09e6e5ec
DE
920 Close();
921 /* m_error is set in _GSocket_Output_Timeout */
97e6ee04
DE
922 return GSOCK_TIMEDOUT;
923 }
924 else
925 {
926 int error;
ddc1a35f 927 SOCKOPTLEN_T len = sizeof(error);
97e6ee04 928
f71bb8ef 929 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*) &error, &len);
97e6ee04 930
bb154f79
KH
931 gs_gui_functions->Enable_Events(this);
932
97e6ee04
DE
933 if (!error)
934 return GSOCK_NOERROR;
935 }
936 }
937
938 /* If connect failed with EINPROGRESS and the GSocket object
939 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
940 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
941 * this way if the connection completes, a GSOCK_CONNECTION
942 * event will be generated, if enabled.
943 */
09e6e5ec 944 if ((err == EINPROGRESS) && (m_non_blocking))
97e6ee04 945 {
948c96ef 946 m_establishing = true;
09e6e5ec 947 m_error = GSOCK_WOULDBLOCK;
97e6ee04
DE
948 return GSOCK_WOULDBLOCK;
949 }
950
951 /* If connect failed with an error other than EINPROGRESS,
952 * then the call to GSocket_Connect has failed.
953 */
09e6e5ec
DE
954 Close();
955 m_error = GSOCK_IOERR;
1aa7b427 956
97e6ee04
DE
957 return GSOCK_IOERR;
958 }
959
960 return GSOCK_NOERROR;
961}
962
963/* Datagram sockets */
964
965/* GSocket_SetNonOriented:
966 * Sets up this socket as a non-connection oriented (datagram) socket.
967 * Before using this function, the local address must have been set
968 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
969 * on success, or one of the following otherwise.
970 *
971 * Error codes:
972 * GSOCK_INVSOCK - the socket is in use.
973 * GSOCK_INVADDR - the local address has not been set.
974 * GSOCK_IOERR - low-level error.
975 */
ba2a81d7 976GSocketError GSocket::SetNonOriented()
97e6ee04
DE
977{
978 int arg = 1;
979
09e6e5ec 980 assert(this);
97e6ee04 981
09e6e5ec 982 if (m_fd != INVALID_SOCKET)
97e6ee04 983 {
09e6e5ec 984 m_error = GSOCK_INVSOCK;
97e6ee04
DE
985 return GSOCK_INVSOCK;
986 }
987
09e6e5ec 988 if (!m_local)
97e6ee04 989 {
09e6e5ec 990 m_error = GSOCK_INVADDR;
97e6ee04
DE
991 return GSOCK_INVADDR;
992 }
993
994 /* Initialize all fields */
948c96ef
DE
995 m_stream = false;
996 m_server = false;
97e6ee04
DE
997
998 /* Create the socket */
09e6e5ec 999 m_fd = socket(m_local->m_realfamily, SOCK_DGRAM, 0);
97e6ee04 1000
09e6e5ec 1001 if (m_fd == INVALID_SOCKET)
97e6ee04 1002 {
09e6e5ec 1003 m_error = GSOCK_IOERR;
97e6ee04
DE
1004 return GSOCK_IOERR;
1005 }
1006#if defined(__EMX__) || defined(__VISAGECPP__)
09e6e5ec 1007 ioctl(m_fd, FIONBIO, (char*)&arg, sizeof(arg));
97e6ee04 1008#else
09e6e5ec 1009 ioctl(m_fd, FIONBIO, &arg);
97e6ee04 1010#endif
ba2a81d7 1011 gs_gui_functions->Enable_Events(this);
97e6ee04
DE
1012
1013 /* Bind to the local address,
1014 * and retrieve the actual address bound.
1015 */
09e6e5ec
DE
1016 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
1017 (getsockname(m_fd,
1018 m_local->m_addr,
9e03e02d 1019 (WX_SOCKLEN_T *) &m_local->m_len) != 0))
97e6ee04 1020 {
09e6e5ec
DE
1021 Close();
1022 m_error = GSOCK_IOERR;
97e6ee04
DE
1023 return GSOCK_IOERR;
1024 }
1025
1026 return GSOCK_NOERROR;
1027}
1028
1029/* Generic IO */
1030
1031/* Like recv(), send(), ... */
ba2a81d7 1032int GSocket::Read(char *buffer, int size)
97e6ee04
DE
1033{
1034 int ret;
1035
09e6e5ec 1036 assert(this);
97e6ee04 1037
09e6e5ec 1038 if (m_fd == INVALID_SOCKET || m_server)
97e6ee04 1039 {
09e6e5ec 1040 m_error = GSOCK_INVSOCK;
97e6ee04
DE
1041 return -1;
1042 }
1043
9d715960
DE
1044 /* Disable events during query of socket status */
1045 Disable(GSOCK_INPUT);
b082b524 1046
97e6ee04 1047 /* If the socket is blocking, wait for data (with a timeout) */
976abb72
VZ
1048 if (Input_Timeout() == GSOCK_TIMEDOUT) {
1049 m_error = GSOCK_TIMEDOUT;
1050 /* Don't return here immediately, otherwise socket events would not be
1051 * re-enabled! */
9d715960 1052 ret = -1;
976abb72 1053 }
1aa7b427
DS
1054 else
1055 {
9d715960
DE
1056 /* Read the data */
1057 if (m_stream)
1058 ret = Recv_Stream(buffer, size);
1059 else
1060 ret = Recv_Dgram(buffer, size);
b082b524 1061
9b67181b
KH
1062 /* If recv returned zero, then the connection is lost, and errno is not set.
1063 * Otherwise, recv has returned an error (-1), in which case we have lost the
1064 * socket only if errno does _not_ indicate that there may be more data to read.
1065 */
1066 if (ret == 0)
1067 m_error = GSOCK_IOERR;
1aa7b427
DS
1068 else if (ret == -1)
1069 {
976abb72
VZ
1070 if ((errno == EWOULDBLOCK) || (errno == EAGAIN))
1071 m_error = GSOCK_WOULDBLOCK;
1072 else
1073 m_error = GSOCK_IOERR;
1074 }
97e6ee04 1075 }
b082b524 1076
9d715960 1077 /* Enable events again now that we are done processing */
09e6e5ec 1078 Enable(GSOCK_INPUT);
97e6ee04
DE
1079
1080 return ret;
1081}
1082
ba2a81d7 1083int GSocket::Write(const char *buffer, int size)
b082b524 1084{
97e6ee04
DE
1085 int ret;
1086
09e6e5ec 1087 assert(this);
b082b524 1088
97e6ee04
DE
1089 GSocket_Debug(( "GSocket_Write #1, size %d\n", size ));
1090
09e6e5ec 1091 if (m_fd == INVALID_SOCKET || m_server)
97e6ee04 1092 {
09e6e5ec 1093 m_error = GSOCK_INVSOCK;
97e6ee04
DE
1094 return -1;
1095 }
1096
1097 GSocket_Debug(( "GSocket_Write #2, size %d\n", size ));
1098
1099 /* If the socket is blocking, wait for writability (with a timeout) */
09e6e5ec 1100 if (Output_Timeout() == GSOCK_TIMEDOUT)
97e6ee04
DE
1101 return -1;
1102
1103 GSocket_Debug(( "GSocket_Write #3, size %d\n", size ));
1104
1105 /* Write the data */
09e6e5ec
DE
1106 if (m_stream)
1107 ret = Send_Stream(buffer, size);
97e6ee04 1108 else
09e6e5ec 1109 ret = Send_Dgram(buffer, size);
b082b524 1110
97e6ee04
DE
1111 GSocket_Debug(( "GSocket_Write #4, size %d\n", size ));
1112
1113 if (ret == -1)
1114 {
7e1e6965 1115 if ((errno == EWOULDBLOCK) || (errno == EAGAIN))
97e6ee04 1116 {
09e6e5ec 1117 m_error = GSOCK_WOULDBLOCK;
97e6ee04
DE
1118 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
1119 }
1120 else
1121 {
09e6e5ec 1122 m_error = GSOCK_IOERR;
97e6ee04
DE
1123 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
1124 }
1125
1126 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
1127 * in MSW). Once the first OUTPUT event is received, users can assume
1128 * that the socket is writable until a read operation fails. Only then
1129 * will further OUTPUT events be posted.
1130 */
09e6e5ec 1131 Enable(GSOCK_OUTPUT);
1aa7b427 1132
97e6ee04
DE
1133 return -1;
1134 }
b082b524 1135
97e6ee04
DE
1136 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size, ret ));
1137
1138 return ret;
1139}
1140
1141/* GSocket_Select:
1142 * Polls the socket to determine its status. This function will
1143 * check for the events specified in the 'flags' parameter, and
1144 * it will return a mask indicating which operations can be
1145 * performed. This function won't block, regardless of the
1146 * mode (blocking | nonblocking) of the socket.
1147 */
ba2a81d7 1148GSocketEventFlags GSocket::Select(GSocketEventFlags flags)
97e6ee04 1149{
ba2a81d7 1150 if (!gs_gui_functions->CanUseEventLoop())
97e6ee04
DE
1151 {
1152
1153 GSocketEventFlags result = 0;
1154 fd_set readfds;
1155 fd_set writefds;
1156 fd_set exceptfds;
1157 struct timeval tv;
1158
9d715960
DE
1159 assert(this);
1160
60b0bd1d
JS
1161 if (m_fd == -1)
1162 return (GSOCK_LOST_FLAG & flags);
17a1ebd1 1163
97e6ee04 1164 /* Do not use a static struct, Linux can garble it */
09e6e5ec 1165 tv.tv_sec = m_timeout / 1000;
7488a05e 1166 tv.tv_usec = (m_timeout % 1000) * 1000;
97e6ee04 1167
17a1ebd1
VZ
1168 wxFD_ZERO(&readfds);
1169 wxFD_ZERO(&writefds);
1170 wxFD_ZERO(&exceptfds);
1171 wxFD_SET(m_fd, &readfds);
9d715960 1172 if (flags & GSOCK_OUTPUT_FLAG || flags & GSOCK_CONNECTION_FLAG)
17a1ebd1
VZ
1173 wxFD_SET(m_fd, &writefds);
1174 wxFD_SET(m_fd, &exceptfds);
97e6ee04
DE
1175
1176 /* Check 'sticky' CONNECTION flag first */
09e6e5ec 1177 result |= (GSOCK_CONNECTION_FLAG & m_detected);
97e6ee04
DE
1178
1179 /* If we have already detected a LOST event, then don't try
1180 * to do any further processing.
1181 */
09e6e5ec 1182 if ((m_detected & GSOCK_LOST_FLAG) != 0)
97e6ee04 1183 {
948c96ef 1184 m_establishing = false;
97e6ee04
DE
1185
1186 return (GSOCK_LOST_FLAG & flags);
1187 }
1188
1189 /* Try select now */
09e6e5ec 1190 if (select(m_fd + 1, &readfds, &writefds, &exceptfds, &tv) <= 0)
97e6ee04
DE
1191 {
1192 /* What to do here? */
1193 return (result & flags);
1194 }
1195
1196 /* Check for readability */
17a1ebd1 1197 if (wxFD_ISSET(m_fd, &readfds))
97e6ee04
DE
1198 {
1199 char c;
1200
bb154f79
KH
1201 int num = recv(m_fd, &c, 1, MSG_PEEK | GSOCKET_MSG_NOSIGNAL);
1202
1203 if (num > 0)
97e6ee04
DE
1204 {
1205 result |= GSOCK_INPUT_FLAG;
1206 }
1207 else
1208 {
09e6e5ec 1209 if (m_server && m_stream)
97e6ee04
DE
1210 {
1211 result |= GSOCK_CONNECTION_FLAG;
09e6e5ec 1212 m_detected |= GSOCK_CONNECTION_FLAG;
97e6ee04 1213 }
9b67181b
KH
1214 /* If recv returned zero, then the connection is lost, and errno is not set.
1215 * Otherwise, recv has returned an error (-1), in which case we have lost the
1216 * socket only if errno does _not_ indicate that there may be more data to read.
1217 */
1218 else if (num == 0 ||
1219 (errno != EWOULDBLOCK) && (errno != EAGAIN) && (errno != EINTR))
97e6ee04 1220 {
09e6e5ec 1221 m_detected = GSOCK_LOST_FLAG;
948c96ef 1222 m_establishing = false;
b082b524 1223
97e6ee04
DE
1224 /* LOST event: Abort any further processing */
1225 return (GSOCK_LOST_FLAG & flags);
1226 }
1227 }
1228 }
1229
1230 /* Check for writability */
17a1ebd1 1231 if (wxFD_ISSET(m_fd, &writefds))
97e6ee04 1232 {
09e6e5ec 1233 if (m_establishing && !m_server)
97e6ee04
DE
1234 {
1235 int error;
ddc1a35f 1236 SOCKOPTLEN_T len = sizeof(error);
97e6ee04 1237
948c96ef 1238 m_establishing = false;
97e6ee04 1239
f71bb8ef 1240 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
97e6ee04
DE
1241
1242 if (error)
1243 {
09e6e5ec 1244 m_detected = GSOCK_LOST_FLAG;
97e6ee04
DE
1245
1246 /* LOST event: Abort any further processing */
1247 return (GSOCK_LOST_FLAG & flags);
1248 }
1249 else
1250 {
1251 result |= GSOCK_CONNECTION_FLAG;
09e6e5ec 1252 m_detected |= GSOCK_CONNECTION_FLAG;
97e6ee04
DE
1253 }
1254 }
1255 else
1256 {
1257 result |= GSOCK_OUTPUT_FLAG;
1258 }
1259 }
1260
1261 /* Check for exceptions and errors (is this useful in Unices?) */
17a1ebd1 1262 if (wxFD_ISSET(m_fd, &exceptfds))
97e6ee04 1263 {
948c96ef 1264 m_establishing = false;
09e6e5ec 1265 m_detected = GSOCK_LOST_FLAG;
97e6ee04
DE
1266
1267 /* LOST event: Abort any further processing */
1268 return (GSOCK_LOST_FLAG & flags);
1269 }
1270
1271 return (result & flags);
1272
1273 }
1274 else
1275 {
09e6e5ec
DE
1276 assert(this);
1277 return flags & m_detected;
97e6ee04
DE
1278 }
1279}
1280
1281/* Flags */
1282
1283/* GSocket_SetNonBlocking:
1284 * Sets the socket to non-blocking mode. All IO calls will return
1285 * immediately.
1286 */
948c96ef 1287void GSocket::SetNonBlocking(bool non_block)
97e6ee04 1288{
09e6e5ec 1289 assert(this);
97e6ee04
DE
1290
1291 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
1292
09e6e5ec 1293 m_non_blocking = non_block;
97e6ee04
DE
1294}
1295
1296/* GSocket_SetTimeout:
1297 * Sets the timeout for blocking calls. Time is expressed in
1298 * milliseconds.
1299 */
ba2a81d7 1300void GSocket::SetTimeout(unsigned long millisec)
97e6ee04 1301{
09e6e5ec 1302 assert(this);
97e6ee04 1303
09e6e5ec 1304 m_timeout = millisec;
97e6ee04
DE
1305}
1306
1307/* GSocket_GetError:
d6922577 1308 * Returns the last error occurred for this socket. Note that successful
97e6ee04
DE
1309 * operations do not clear this back to GSOCK_NOERROR, so use it only
1310 * after an error.
1311 */
ba2a81d7 1312GSocketError WXDLLIMPEXP_NET GSocket::GetError()
97e6ee04 1313{
09e6e5ec 1314 assert(this);
97e6ee04 1315
09e6e5ec 1316 return m_error;
97e6ee04
DE
1317}
1318
1319/* Callbacks */
1320
1321/* GSOCK_INPUT:
1322 * There is data to be read in the input buffer. If, after a read
1323 * operation, there is still data available, the callback function will
1324 * be called again.
1325 * GSOCK_OUTPUT:
b082b524 1326 * The socket is available for writing. That is, the next write call
97e6ee04
DE
1327 * won't block. This event is generated only once, when the connection is
1328 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1329 * when the output buffer empties again. This means that the app should
1330 * assume that it can write since the first OUTPUT event, and no more
1331 * OUTPUT events will be generated unless an error occurs.
1332 * GSOCK_CONNECTION:
d6922577 1333 * Connection successfully established, for client sockets, or incoming
97e6ee04
DE
1334 * client connection, for server sockets. Wait for this event (also watch
1335 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1336 * GSOCK_LOST:
1337 * The connection is lost (or a connection request failed); this could
1338 * be due to a failure, or due to the peer closing it gracefully.
1339 */
1340
1341/* GSocket_SetCallback:
1342 * Enables the callbacks specified by 'flags'. Note that 'flags'
1343 * may be a combination of flags OR'ed toghether, so the same
1344 * callback function can be made to accept different events.
1345 * The callback function must have the following prototype:
1346 *
1347 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1348 */
ba2a81d7 1349void GSocket::SetCallback(GSocketEventFlags flags,
97e6ee04
DE
1350 GSocketCallback callback, char *cdata)
1351{
1352 int count;
1353
09e6e5ec 1354 assert(this);
97e6ee04
DE
1355
1356 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1357 {
1358 if ((flags & (1 << count)) != 0)
1359 {
09e6e5ec
DE
1360 m_cbacks[count] = callback;
1361 m_data[count] = cdata;
97e6ee04
DE
1362 }
1363 }
1364}
1365
1366/* GSocket_UnsetCallback:
1367 * Disables all callbacks specified by 'flags', which may be a
1368 * combination of flags OR'ed toghether.
1369 */
ba2a81d7 1370void GSocket::UnsetCallback(GSocketEventFlags flags)
97e6ee04
DE
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] = NULL;
1381 m_data[count] = NULL;
97e6ee04
DE
1382 }
1383 }
1384}
1385
ba2a81d7 1386GSocketError GSocket::GetSockOpt(int level, int optname,
b082b524
DE
1387 void *optval, int *optlen)
1388{
ddc1a35f 1389 if (getsockopt(m_fd, level, optname, (char*)optval, (SOCKOPTLEN_T*)optlen) == 0)
b082b524 1390 return GSOCK_NOERROR;
1aa7b427 1391
b082b524
DE
1392 return GSOCK_OPTERR;
1393}
1394
ba2a81d7 1395GSocketError GSocket::SetSockOpt(int level, int optname,
b082b524
DE
1396 const void *optval, int optlen)
1397{
f71bb8ef 1398 if (setsockopt(m_fd, level, optname, (const char*)optval, optlen) == 0)
b082b524 1399 return GSOCK_NOERROR;
1aa7b427 1400
b082b524
DE
1401 return GSOCK_OPTERR;
1402}
1403
ba2a81d7 1404#define CALL_CALLBACK(socket, event) { \
9a7e4a56 1405 socket->Disable(event); \
ba2a81d7
DE
1406 if (socket->m_cbacks[event]) \
1407 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
97e6ee04
DE
1408}
1409
1410
ba2a81d7 1411void GSocket::Enable(GSocketEvent event)
97e6ee04 1412{
09e6e5ec 1413 m_detected &= ~(1 << event);
ba2a81d7 1414 gs_gui_functions->Install_Callback(this, event);
97e6ee04
DE
1415}
1416
ba2a81d7 1417void GSocket::Disable(GSocketEvent event)
97e6ee04 1418{
09e6e5ec 1419 m_detected |= (1 << event);
ba2a81d7 1420 gs_gui_functions->Uninstall_Callback(this, event);
97e6ee04
DE
1421}
1422
1423/* _GSocket_Input_Timeout:
1424 * For blocking sockets, wait until data is available or
1425 * until timeout ellapses.
1426 */
ba2a81d7 1427GSocketError GSocket::Input_Timeout()
97e6ee04
DE
1428{
1429 struct timeval tv;
1430 fd_set readfds;
1431 int ret;
1432
1433 /* Linux select() will overwrite the struct on return */
09e6e5ec
DE
1434 tv.tv_sec = (m_timeout / 1000);
1435 tv.tv_usec = (m_timeout % 1000) * 1000;
97e6ee04 1436
09e6e5ec 1437 if (!m_non_blocking)
97e6ee04 1438 {
17a1ebd1
VZ
1439 wxFD_ZERO(&readfds);
1440 wxFD_SET(m_fd, &readfds);
09e6e5ec 1441 ret = select(m_fd + 1, &readfds, NULL, NULL, &tv);
97e6ee04
DE
1442 if (ret == 0)
1443 {
1444 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
09e6e5ec 1445 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1446 return GSOCK_TIMEDOUT;
1447 }
1aa7b427 1448
97e6ee04
DE
1449 if (ret == -1)
1450 {
1451 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1452 if (errno == EBADF) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1453 if (errno == EINTR) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1454 if (errno == EINVAL) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1455 if (errno == ENOMEM) { GSocket_Debug(( "Not enough memory\n" )); }
09e6e5ec 1456 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1457 return GSOCK_TIMEDOUT;
1458 }
1459 }
1aa7b427 1460
97e6ee04
DE
1461 return GSOCK_NOERROR;
1462}
1463
1464/* _GSocket_Output_Timeout:
1465 * For blocking sockets, wait until data can be sent without
1466 * blocking or until timeout ellapses.
1467 */
ba2a81d7 1468GSocketError GSocket::Output_Timeout()
97e6ee04
DE
1469{
1470 struct timeval tv;
1471 fd_set writefds;
1472 int ret;
1473
1474 /* Linux select() will overwrite the struct on return */
09e6e5ec
DE
1475 tv.tv_sec = (m_timeout / 1000);
1476 tv.tv_usec = (m_timeout % 1000) * 1000;
97e6ee04 1477
09e6e5ec 1478 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking) );
97e6ee04 1479
09e6e5ec 1480 if (!m_non_blocking)
97e6ee04 1481 {
17a1ebd1
VZ
1482 wxFD_ZERO(&writefds);
1483 wxFD_SET(m_fd, &writefds);
09e6e5ec 1484 ret = select(m_fd + 1, NULL, &writefds, NULL, &tv);
97e6ee04
DE
1485 if (ret == 0)
1486 {
1487 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
09e6e5ec 1488 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1489 return GSOCK_TIMEDOUT;
1490 }
1aa7b427 1491
97e6ee04
DE
1492 if (ret == -1)
1493 {
1494 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1495 if (errno == EBADF) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1496 if (errno == EINTR) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1497 if (errno == EINVAL) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1498 if (errno == ENOMEM) { GSocket_Debug(( "Not enough memory\n" )); }
09e6e5ec 1499 m_error = GSOCK_TIMEDOUT;
97e6ee04
DE
1500 return GSOCK_TIMEDOUT;
1501 }
1aa7b427
DS
1502
1503 if ( ! wxFD_ISSET(m_fd, &writefds) )
1504 {
97e6ee04
DE
1505 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1506 }
1aa7b427
DS
1507 else
1508 {
97e6ee04
DE
1509 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1510 }
1511 }
1512 else
1513 {
1514 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1515 }
1516
1517 return GSOCK_NOERROR;
1518}
1519
ba2a81d7 1520int GSocket::Recv_Stream(char *buffer, int size)
97e6ee04 1521{
bb154f79 1522 int ret;
7e1e6965 1523 do
bb154f79
KH
1524 {
1525 ret = recv(m_fd, buffer, size, GSOCKET_MSG_NOSIGNAL);
1aa7b427
DS
1526 }
1527 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
1528
bb154f79 1529 return ret;
97e6ee04
DE
1530}
1531
ba2a81d7 1532int GSocket::Recv_Dgram(char *buffer, int size)
97e6ee04
DE
1533{
1534 struct sockaddr from;
9e03e02d 1535 WX_SOCKLEN_T fromlen = sizeof(from);
97e6ee04
DE
1536 int ret;
1537 GSocketError err;
1538
1539 fromlen = sizeof(from);
1540
7e1e6965 1541 do
bb154f79 1542 {
9e03e02d 1543 ret = recvfrom(m_fd, buffer, size, 0, &from, (WX_SOCKLEN_T *) &fromlen);
1aa7b427
DS
1544 }
1545 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
97e6ee04
DE
1546
1547 if (ret == -1)
1548 return -1;
1549
1550 /* Translate a system address into a GSocket address */
09e6e5ec 1551 if (!m_peer)
97e6ee04 1552 {
09e6e5ec
DE
1553 m_peer = GAddress_new();
1554 if (!m_peer)
97e6ee04 1555 {
09e6e5ec 1556 m_error = GSOCK_MEMERR;
97e6ee04
DE
1557 return -1;
1558 }
1559 }
1aa7b427 1560
09e6e5ec 1561 err = _GAddress_translate_from(m_peer, &from, fromlen);
97e6ee04
DE
1562 if (err != GSOCK_NOERROR)
1563 {
09e6e5ec
DE
1564 GAddress_destroy(m_peer);
1565 m_peer = NULL;
1566 m_error = err;
97e6ee04
DE
1567 return -1;
1568 }
1569
1570 return ret;
1571}
1572
ba2a81d7 1573int GSocket::Send_Stream(const char *buffer, int size)
97e6ee04
DE
1574{
1575 int ret;
1576
7e1e6965
WS
1577 MASK_SIGNAL();
1578
1579 do
bb154f79
KH
1580 {
1581 ret = send(m_fd, (char *)buffer, size, GSOCKET_MSG_NOSIGNAL);
1aa7b427
DS
1582 }
1583 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
7e1e6965 1584
97e6ee04 1585 UNMASK_SIGNAL();
97e6ee04
DE
1586
1587 return ret;
1588}
1589
ba2a81d7 1590int GSocket::Send_Dgram(const char *buffer, int size)
97e6ee04
DE
1591{
1592 struct sockaddr *addr;
1593 int len, ret;
1594 GSocketError err;
1595
09e6e5ec 1596 if (!m_peer)
97e6ee04 1597 {
09e6e5ec 1598 m_error = GSOCK_INVADDR;
97e6ee04
DE
1599 return -1;
1600 }
1601
09e6e5ec 1602 err = _GAddress_translate_to(m_peer, &addr, &len);
97e6ee04
DE
1603 if (err != GSOCK_NOERROR)
1604 {
09e6e5ec 1605 m_error = err;
97e6ee04
DE
1606 return -1;
1607 }
1608
97e6ee04 1609 MASK_SIGNAL();
7e1e6965
WS
1610
1611 do
bb154f79
KH
1612 {
1613 ret = sendto(m_fd, (char *)buffer, size, 0, addr, len);
1aa7b427
DS
1614 }
1615 while (ret == -1 && errno == EINTR); /* Loop until not interrupted */
7e1e6965 1616
97e6ee04 1617 UNMASK_SIGNAL();
97e6ee04
DE
1618
1619 /* Frees memory allocated from _GAddress_translate_to */
1620 free(addr);
1621
1622 return ret;
1623}
1624
ba2a81d7 1625void GSocket::Detected_Read()
97e6ee04
DE
1626{
1627 char c;
1628
bb154f79
KH
1629 /* Safeguard against straggling call to Detected_Read */
1630 if (m_fd == INVALID_SOCKET)
1631 {
1632 return;
1633 }
1634
97e6ee04
DE
1635 /* If we have already detected a LOST event, then don't try
1636 * to do any further processing.
1637 */
09e6e5ec 1638 if ((m_detected & GSOCK_LOST_FLAG) != 0)
97e6ee04 1639 {
948c96ef 1640 m_establishing = false;
97e6ee04 1641
ba2a81d7 1642 CALL_CALLBACK(this, GSOCK_LOST);
09e6e5ec 1643 Shutdown();
97e6ee04
DE
1644 return;
1645 }
1646
bb154f79
KH
1647 int num = recv(m_fd, &c, 1, MSG_PEEK | GSOCKET_MSG_NOSIGNAL);
1648
1649 if (num > 0)
97e6ee04 1650 {
ba2a81d7 1651 CALL_CALLBACK(this, GSOCK_INPUT);
97e6ee04
DE
1652 }
1653 else
1654 {
09e6e5ec 1655 if (m_server && m_stream)
97e6ee04 1656 {
ba2a81d7 1657 CALL_CALLBACK(this, GSOCK_CONNECTION);
97e6ee04
DE
1658 }
1659 else
1660 {
e400d27d 1661 /* Do not throw a lost event in cases where the socket isn't really lost */
7e1e6965 1662 if ((errno == EWOULDBLOCK) || (errno == EAGAIN) || (errno == EINTR))
bb154f79
KH
1663 {
1664 CALL_CALLBACK(this, GSOCK_INPUT);
1665 }
7e1e6965 1666 else
bb154f79
KH
1667 {
1668 CALL_CALLBACK(this, GSOCK_LOST);
1669 Shutdown();
7e1e6965 1670 }
97e6ee04
DE
1671 }
1672 }
1673}
1674
ba2a81d7 1675void GSocket::Detected_Write()
97e6ee04
DE
1676{
1677 /* If we have already detected a LOST event, then don't try
1678 * to do any further processing.
1679 */
09e6e5ec 1680 if ((m_detected & GSOCK_LOST_FLAG) != 0)
97e6ee04 1681 {
948c96ef 1682 m_establishing = false;
97e6ee04 1683
ba2a81d7 1684 CALL_CALLBACK(this, GSOCK_LOST);
09e6e5ec 1685 Shutdown();
97e6ee04
DE
1686 return;
1687 }
1688
09e6e5ec 1689 if (m_establishing && !m_server)
97e6ee04
DE
1690 {
1691 int error;
ddc1a35f 1692 SOCKOPTLEN_T len = sizeof(error);
97e6ee04 1693
948c96ef 1694 m_establishing = false;
97e6ee04 1695
f71bb8ef 1696 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
97e6ee04
DE
1697
1698 if (error)
1699 {
ba2a81d7 1700 CALL_CALLBACK(this, GSOCK_LOST);
09e6e5ec 1701 Shutdown();
97e6ee04
DE
1702 }
1703 else
1704 {
ba2a81d7 1705 CALL_CALLBACK(this, GSOCK_CONNECTION);
97e6ee04
DE
1706 /* We have to fire this event by hand because CONNECTION (for clients)
1707 * and OUTPUT are internally the same and we just disabled CONNECTION
1708 * events with the above macro.
1709 */
ba2a81d7 1710 CALL_CALLBACK(this, GSOCK_OUTPUT);
97e6ee04
DE
1711 }
1712 }
1713 else
1714 {
ba2a81d7 1715 CALL_CALLBACK(this, GSOCK_OUTPUT);
97e6ee04
DE
1716 }
1717}
1718
09e6e5ec
DE
1719/* Compatibility functions for GSocket */
1720GSocket *GSocket_new(void)
1721{
ba2a81d7 1722 GSocket *newsocket = new GSocket();
1aa7b427 1723 if (newsocket->IsOk())
09e6e5ec 1724 return newsocket;
1aa7b427 1725
09e6e5ec 1726 delete newsocket;
1aa7b427 1727
09e6e5ec
DE
1728 return NULL;
1729}
1730
97e6ee04
DE
1731/*
1732 * -------------------------------------------------------------------------
1733 * GAddress
1734 * -------------------------------------------------------------------------
1735 */
1736
1737/* CHECK_ADDRESS verifies that the current address family is either
1738 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1739 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1740 * an appropiate error code.
1741 *
1742 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1743 */
1744#define CHECK_ADDRESS(address, family) \
1745{ \
1746 if (address->m_family == GSOCK_NOFAMILY) \
1747 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1748 return address->m_error; \
1749 if (address->m_family != GSOCK_##family) \
1750 { \
1751 address->m_error = GSOCK_INVADDR; \
1752 return GSOCK_INVADDR; \
1753 } \
1754}
1755
1756#define CHECK_ADDRESS_RETVAL(address, family, retval) \
1757{ \
1758 if (address->m_family == GSOCK_NOFAMILY) \
1759 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1760 return retval; \
1761 if (address->m_family != GSOCK_##family) \
1762 { \
1763 address->m_error = GSOCK_INVADDR; \
1764 return retval; \
1765 } \
1766}
1767
1768
1769GAddress *GAddress_new(void)
1770{
1771 GAddress *address;
1772
1773 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1774 return NULL;
1775
1776 address->m_family = GSOCK_NOFAMILY;
1777 address->m_addr = NULL;
1778 address->m_len = 0;
1779
1780 return address;
1781}
1782
1783GAddress *GAddress_copy(GAddress *address)
1784{
1785 GAddress *addr2;
1786
1787 assert(address != NULL);
1788
1789 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1790 return NULL;
1791
1792 memcpy(addr2, address, sizeof(GAddress));
1793
1794 if (address->m_addr && address->m_len > 0)
1795 {
1796 addr2->m_addr = (struct sockaddr *)malloc(addr2->m_len);
1797 if (addr2->m_addr == NULL)
1798 {
1799 free(addr2);
1800 return NULL;
1801 }
1802 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1803 }
1804
1805 return addr2;
1806}
1807
1808void GAddress_destroy(GAddress *address)
1809{
1810 assert(address != NULL);
1811
1812 if (address->m_addr)
1813 free(address->m_addr);
1814
1815 free(address);
1816}
1817
1818void GAddress_SetFamily(GAddress *address, GAddressType type)
1819{
1820 assert(address != NULL);
1821
1822 address->m_family = type;
1823}
1824
1825GAddressType GAddress_GetFamily(GAddress *address)
1826{
1827 assert(address != NULL);
1828
1829 return address->m_family;
1830}
1831
1832GSocketError _GAddress_translate_from(GAddress *address,
1833 struct sockaddr *addr, int len)
1834{
1835 address->m_realfamily = addr->sa_family;
1836 switch (addr->sa_family)
1837 {
1838 case AF_INET:
1839 address->m_family = GSOCK_INET;
1840 break;
1841 case AF_UNIX:
1842 address->m_family = GSOCK_UNIX;
1843 break;
1844#ifdef AF_INET6
1845 case AF_INET6:
1846 address->m_family = GSOCK_INET6;
1847 break;
1848#endif
1849 default:
1850 {
1851 address->m_error = GSOCK_INVOP;
1852 return GSOCK_INVOP;
1853 }
1854 }
1855
1856 if (address->m_addr)
1857 free(address->m_addr);
1858
1859 address->m_len = len;
1860 address->m_addr = (struct sockaddr *)malloc(len);
1861
1862 if (address->m_addr == NULL)
1863 {
1864 address->m_error = GSOCK_MEMERR;
1865 return GSOCK_MEMERR;
1866 }
1aa7b427 1867
97e6ee04
DE
1868 memcpy(address->m_addr, addr, len);
1869
1870 return GSOCK_NOERROR;
1871}
1872
1873GSocketError _GAddress_translate_to(GAddress *address,
1874 struct sockaddr **addr, int *len)
1875{
1876 if (!address->m_addr)
1877 {
1878 address->m_error = GSOCK_INVADDR;
1879 return GSOCK_INVADDR;
1880 }
1881
1882 *len = address->m_len;
1883 *addr = (struct sockaddr *)malloc(address->m_len);
1884 if (*addr == NULL)
1885 {
1886 address->m_error = GSOCK_MEMERR;
1887 return GSOCK_MEMERR;
1888 }
1889
1890 memcpy(*addr, address->m_addr, address->m_len);
1891 return GSOCK_NOERROR;
1892}
1893
1894/*
1895 * -------------------------------------------------------------------------
1896 * Internet address family
1897 * -------------------------------------------------------------------------
1898 */
1899
1900GSocketError _GAddress_Init_INET(GAddress *address)
1901{
1902 address->m_len = sizeof(struct sockaddr_in);
1903 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1904 if (address->m_addr == NULL)
1905 {
1906 address->m_error = GSOCK_MEMERR;
1907 return GSOCK_MEMERR;
1908 }
1909
1910 address->m_family = GSOCK_INET;
1911 address->m_realfamily = PF_INET;
1912 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
1913 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
1914
1915 return GSOCK_NOERROR;
1916}
1917
1918GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1919{
1920 struct hostent *he;
1921 struct in_addr *addr;
1922
1923 assert(address != NULL);
1924
1925 CHECK_ADDRESS(address, INET);
1926
1927 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1928
1929 /* If it is a numeric host name, convert it now */
1930#if defined(HAVE_INET_ATON)
1931 if (inet_aton(hostname, addr) == 0)
1932 {
1933#elif defined(HAVE_INET_ADDR)
8c0f8906 1934 if ( (addr->s_addr = inet_addr(hostname)) == (unsigned)-1 )
97e6ee04
DE
1935 {
1936#else
1937 /* Use gethostbyname by default */
9d715960 1938#ifndef __WXMAC__
ba2a81d7 1939 int val = 1; /* VA doesn't like constants in conditional expressions */
97e6ee04 1940 if (val)
9d715960 1941#endif
97e6ee04
DE
1942 {
1943#endif
1944 struct in_addr *array_addr;
1945
1946 /* It is a real name, we solve it */
127189eb
SN
1947 struct hostent h;
1948#if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
1949 struct hostent_data buffer;
1950#else
1951 char buffer[1024];
1952#endif
1953 int err;
1954 he = wxGethostbyname_r(hostname, &h, (void*)&buffer, sizeof(buffer), &err);
1955 if (he == NULL)
97e6ee04
DE
1956 {
1957 /* Reset to invalid address */
1958 addr->s_addr = INADDR_NONE;
1959 address->m_error = GSOCK_NOHOST;
1960 return GSOCK_NOHOST;
1961 }
1aa7b427 1962
97e6ee04
DE
1963 array_addr = (struct in_addr *) *(he->h_addr_list);
1964 addr->s_addr = array_addr[0].s_addr;
1965 }
1aa7b427 1966
97e6ee04
DE
1967 return GSOCK_NOERROR;
1968}
1969
1970GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1971{
1972 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1973}
1974
1975GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1976 unsigned long hostaddr)
1977{
1978 struct in_addr *addr;
1979
1980 assert(address != NULL);
1981
1982 CHECK_ADDRESS(address, INET);
1983
1984 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
9d715960 1985 addr->s_addr = htonl(hostaddr);
97e6ee04
DE
1986
1987 return GSOCK_NOERROR;
1988}
1989
1990GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1991 const char *protocol)
1992{
1993 struct servent *se;
1994 struct sockaddr_in *addr;
1995
1996 assert(address != NULL);
1997 CHECK_ADDRESS(address, INET);
1998
1999 if (!port)
2000 {
2001 address->m_error = GSOCK_INVPORT;
2002 return GSOCK_INVPORT;
2003 }
b082b524 2004
127189eb
SN
2005#if defined(HAVE_FUNC_GETSERVBYNAME_R_4)
2006 struct servent_data buffer;
f6bc1c74 2007#else
127189eb 2008 char buffer[1024];
f6bc1c74 2009#endif
127189eb
SN
2010 struct servent serv;
2011 se = wxGetservbyname_r(port, protocol, &serv,
2012 (void*)&buffer, sizeof(buffer));
97e6ee04
DE
2013 if (!se)
2014 {
2015 /* the cast to int suppresses compiler warnings about subscript having the
2016 type char */
2017 if (isdigit((int)port[0]))
2018 {
2019 int port_int;
2020
2021 port_int = atoi(port);
2022 addr = (struct sockaddr_in *)address->m_addr;
2023 addr->sin_port = htons(port_int);
2024 return GSOCK_NOERROR;
2025 }
2026
2027 address->m_error = GSOCK_INVPORT;
2028 return GSOCK_INVPORT;
2029 }
2030
2031 addr = (struct sockaddr_in *)address->m_addr;
2032 addr->sin_port = se->s_port;
2033
2034 return GSOCK_NOERROR;
2035}
2036
2037GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
2038{
2039 struct sockaddr_in *addr;
2040
2041 assert(address != NULL);
2042 CHECK_ADDRESS(address, INET);
b082b524 2043
97e6ee04
DE
2044 addr = (struct sockaddr_in *)address->m_addr;
2045 addr->sin_port = htons(port);
2046
2047 return GSOCK_NOERROR;
2048}
2049
2050GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
2051{
2052 struct hostent *he;
2053 char *addr_buf;
2054 struct sockaddr_in *addr;
2055
b082b524 2056 assert(address != NULL);
97e6ee04
DE
2057 CHECK_ADDRESS(address, INET);
2058
2059 addr = (struct sockaddr_in *)address->m_addr;
2060 addr_buf = (char *)&(addr->sin_addr);
2061
127189eb
SN
2062 struct hostent temphost;
2063#if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2064 struct hostent_data buffer;
2065#else
2066 char buffer[1024];
2067#endif
2068 int err;
2069 he = wxGethostbyaddr_r(addr_buf, sizeof(addr->sin_addr), AF_INET, &temphost,
2070 (void*)&buffer, sizeof(buffer), &err);
97e6ee04
DE
2071 if (he == NULL)
2072 {
2073 address->m_error = GSOCK_NOHOST;
2074 return GSOCK_NOHOST;
2075 }
2076
2077 strncpy(hostname, he->h_name, sbuf);
2078
2079 return GSOCK_NOERROR;
2080}
2081
2082unsigned long GAddress_INET_GetHostAddress(GAddress *address)
2083{
2084 struct sockaddr_in *addr;
2085
b082b524
DE
2086 assert(address != NULL);
2087 CHECK_ADDRESS_RETVAL(address, INET, 0);
97e6ee04
DE
2088
2089 addr = (struct sockaddr_in *)address->m_addr;
2090
9d715960 2091 return ntohl(addr->sin_addr.s_addr);
97e6ee04
DE
2092}
2093
2094unsigned short GAddress_INET_GetPort(GAddress *address)
2095{
2096 struct sockaddr_in *addr;
2097
b082b524
DE
2098 assert(address != NULL);
2099 CHECK_ADDRESS_RETVAL(address, INET, 0);
97e6ee04
DE
2100
2101 addr = (struct sockaddr_in *)address->m_addr;
2102 return ntohs(addr->sin_port);
2103}
2104
2105/*
2106 * -------------------------------------------------------------------------
2107 * Unix address family
2108 * -------------------------------------------------------------------------
2109 */
2110
2111#ifndef __VISAGECPP__
2112GSocketError _GAddress_Init_UNIX(GAddress *address)
2113{
2114 address->m_len = sizeof(struct sockaddr_un);
2115 address->m_addr = (struct sockaddr *)malloc(address->m_len);
2116 if (address->m_addr == NULL)
2117 {
2118 address->m_error = GSOCK_MEMERR;
2119 return GSOCK_MEMERR;
2120 }
2121
2122 address->m_family = GSOCK_UNIX;
2123 address->m_realfamily = PF_UNIX;
2124 ((struct sockaddr_un *)address->m_addr)->sun_family = AF_UNIX;
2125 ((struct sockaddr_un *)address->m_addr)->sun_path[0] = 0;
2126
2127 return GSOCK_NOERROR;
2128}
2129
2130#define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
2131
2132GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *path)
2133{
2134 struct sockaddr_un *addr;
2135
b082b524 2136 assert(address != NULL);
97e6ee04 2137
b082b524 2138 CHECK_ADDRESS(address, UNIX);
97e6ee04
DE
2139
2140 addr = ((struct sockaddr_un *)address->m_addr);
2141 strncpy(addr->sun_path, path, UNIX_SOCK_PATHLEN);
2142 addr->sun_path[UNIX_SOCK_PATHLEN - 1] = '\0';
2143
2144 return GSOCK_NOERROR;
2145}
2146
2147GSocketError GAddress_UNIX_GetPath(GAddress *address, char *path, size_t sbuf)
2148{
2149 struct sockaddr_un *addr;
2150
2151 assert(address != NULL);
2152 CHECK_ADDRESS(address, UNIX);
2153
2154 addr = (struct sockaddr_un *)address->m_addr;
2155
2156 strncpy(path, addr->sun_path, sbuf);
2157
2158 return GSOCK_NOERROR;
2159}
2160#endif /* !defined(__VISAGECPP__) */
2161#endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */