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