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