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