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