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