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