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