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