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