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