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