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