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