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