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