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