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