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