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