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