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