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