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