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