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