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