]> git.saurik.com Git - wxWidgets.git/blob - src/unix/gsocket.c
Reverted changes to grid line positioning that caused many problems
[wxWidgets.git] / src / unix / gsocket.c
1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
3 * Name: gsocket.c
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
6 * Purpose: GSocket main Unix file
7 * CVSID: $Id$
8 * -------------------------------------------------------------------------
9 */
10
11 /*
12 * PLEASE don't put C++ comments here - this is a C source file.
13 */
14
15 #ifndef __GSOCKET_STANDALONE__
16 #include "wx/setup.h"
17 #endif
18
19 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
20
21 #include <assert.h>
22 #include <sys/types.h>
23 #include <netdb.h>
24 #include <sys/ioctl.h>
25
26 #ifdef __VMS__
27 #include <socket.h>
28 struct sockaddr_un {
29 u_char sun_len; /* sockaddr len including null */
30 u_char sun_family; /* AF_UNIX */
31 char sun_path[108]; /* path name (gag) */
32 };
33 #else
34 #include <sys/socket.h>
35 #include <sys/un.h>
36 #endif
37
38 #include <sys/time.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <errno.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stddef.h>
47 #include <ctype.h>
48 #ifdef sun
49 # include <sys/filio.h>
50 #endif
51 #ifdef sgi
52 # include <bstring.h>
53 #endif
54 #include <signal.h>
55
56
57 #ifndef SOCKLEN_T
58
59 #ifdef VMS
60 # define SOCKLEN_T unsigned int
61 #else
62 # ifdef __GLIBC__
63 # if __GLIBC__ == 2
64 # define SOCKLEN_T socklen_t
65 # endif
66 # else
67 # define SOCKLEN_T int
68 # endif
69 #endif
70
71 #endif /* SOCKLEN_T */
72
73
74 /*
75 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
76 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
77 */
78 #ifndef INADDR_NONE
79 #define INADDR_NONE INADDR_BROADCAST
80 #endif
81
82 #define MASK_SIGNAL() \
83 { \
84 void (*old_handler)(int); \
85 \
86 old_handler = signal(SIGPIPE, SIG_IGN);
87
88 #define UNMASK_SIGNAL() \
89 signal(SIGPIPE, old_handler); \
90 }
91
92
93 #ifndef __GSOCKET_STANDALONE__
94
95 #include "wx/unix/gsockunx.h"
96 #include "wx/gsocket.h"
97
98 #else
99
100 #include "gsockunx.h"
101 #include "gsocket.h"
102
103 #endif /* __GSOCKET_STANDALONE__ */
104
105
106 /* Global initialisers */
107
108 bool GSocket_Init()
109 {
110 return TRUE;
111 }
112
113 void GSocket_Cleanup()
114 {
115 }
116
117 /* Constructors / Destructors for GSocket */
118
119 GSocket *GSocket_new()
120 {
121 int i;
122 GSocket *socket;
123
124 socket = (GSocket *)malloc(sizeof(GSocket));
125
126 if (socket == NULL)
127 return NULL;
128
129 socket->m_fd = -1;
130 for (i=0;i<GSOCK_MAX_EVENT;i++)
131 {
132 socket->m_cbacks[i] = NULL;
133 }
134 socket->m_detected = 0;
135 socket->m_local = NULL;
136 socket->m_peer = NULL;
137 socket->m_error = GSOCK_NOERROR;
138 socket->m_server = FALSE;
139 socket->m_stream = TRUE;
140 socket->m_gui_dependent = NULL;
141 socket->m_non_blocking = FALSE;
142 socket->m_timeout = 10*60*1000;
143 /* 10 minutes * 60 sec * 1000 millisec */
144 socket->m_establishing = FALSE;
145
146 /* We initialize the GUI specific entries here */
147 _GSocket_GUI_Init(socket);
148
149 return socket;
150 }
151
152 void GSocket_destroy(GSocket *socket)
153 {
154 assert(socket != NULL);
155
156 /* Check that the socket is really shutdowned */
157 if (socket->m_fd != -1)
158 GSocket_Shutdown(socket);
159
160 /* We destroy GUI specific variables */
161 _GSocket_GUI_Destroy(socket);
162
163 /* Destroy private addresses */
164 if (socket->m_local)
165 GAddress_destroy(socket->m_local);
166
167 if (socket->m_peer)
168 GAddress_destroy(socket->m_peer);
169
170 /* Destroy the socket itself */
171 free(socket);
172 }
173
174 /* GSocket_Shutdown:
175 * Disallow further read/write operations on this socket, close
176 * the fd and disable all callbacks.
177 */
178 void GSocket_Shutdown(GSocket *socket)
179 {
180 int evt;
181
182 assert(socket != NULL);
183
184 /* If socket has been created, shutdown it */
185 if (socket->m_fd != -1)
186 {
187 shutdown(socket->m_fd, 2);
188 close(socket->m_fd);
189 socket->m_fd = -1;
190 }
191
192 /* Disable GUI callbacks */
193 for (evt = 0; evt < GSOCK_MAX_EVENT; evt++)
194 socket->m_cbacks[evt] = NULL;
195
196 socket->m_detected = 0;
197 _GSocket_Disable_Events(socket);
198 }
199
200 /* Address handling */
201
202 /* GSocket_SetLocal:
203 * GSocket_GetLocal:
204 * GSocket_SetPeer:
205 * GSocket_GetPeer:
206 * Set or get the local or peer address for this socket. The 'set'
207 * functions return GSOCK_NOERROR on success, an error code otherwise.
208 * The 'get' functions return a pointer to a GAddress object on success,
209 * or NULL otherwise, in which case they set the error code of the
210 * corresponding GSocket.
211 *
212 * Error codes:
213 * GSOCK_INVSOCK - the socket is not valid.
214 * GSOCK_INVADDR - the address is not valid.
215 */
216 GSocketError GSocket_SetLocal(GSocket *socket, GAddress *address)
217 {
218 assert(socket != NULL);
219
220 /* the socket must be initialized, or it must be a server */
221 if ((socket->m_fd != -1 && !socket->m_server))
222 {
223 socket->m_error = GSOCK_INVSOCK;
224 return GSOCK_INVSOCK;
225 }
226
227 /* check address */
228 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
229 {
230 socket->m_error = GSOCK_INVADDR;
231 return GSOCK_INVADDR;
232 }
233
234 if (socket->m_local)
235 GAddress_destroy(socket->m_local);
236
237 socket->m_local = GAddress_copy(address);
238
239 return GSOCK_NOERROR;
240 }
241
242 GSocketError GSocket_SetPeer(GSocket *socket, GAddress *address)
243 {
244 assert(socket != NULL);
245
246 /* check address */
247 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
248 {
249 socket->m_error = GSOCK_INVADDR;
250 return GSOCK_INVADDR;
251 }
252
253 if (socket->m_peer)
254 GAddress_destroy(socket->m_peer);
255
256 socket->m_peer = GAddress_copy(address);
257
258 return GSOCK_NOERROR;
259 }
260
261 GAddress *GSocket_GetLocal(GSocket *socket)
262 {
263 GAddress *address;
264 struct sockaddr addr;
265 SOCKLEN_T size = sizeof(addr);
266 GSocketError err;
267
268 assert(socket != NULL);
269
270 /* try to get it from the m_local var first */
271 if (socket->m_local)
272 return GAddress_copy(socket->m_local);
273
274 /* else, if the socket is initialized, try getsockname */
275 if (socket->m_fd == -1)
276 {
277 socket->m_error = GSOCK_INVSOCK;
278 return NULL;
279 }
280
281 if (getsockname(socket->m_fd, &addr, (SOCKLEN_T *) &size) < 0)
282 {
283 socket->m_error = GSOCK_IOERR;
284 return NULL;
285 }
286
287 /* got a valid address from getsockname, create a GAddress object */
288 address = GAddress_new();
289 if (address == NULL)
290 {
291 socket->m_error = GSOCK_MEMERR;
292 return NULL;
293 }
294
295 err = _GAddress_translate_from(address, &addr, size);
296 if (err != GSOCK_NOERROR)
297 {
298 GAddress_destroy(address);
299 socket->m_error = err;
300 return NULL;
301 }
302
303 return address;
304 }
305
306 GAddress *GSocket_GetPeer(GSocket *socket)
307 {
308 assert(socket != NULL);
309
310 /* try to get it from the m_peer var */
311 if (socket->m_peer)
312 return GAddress_copy(socket->m_peer);
313
314 return NULL;
315 }
316
317 /* Server specific parts */
318
319 /* GSocket_SetServer:
320 * Sets up this socket as a server. The local address must have been
321 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
322 * Returns GSOCK_NOERROR on success, one of the following otherwise:
323 *
324 * Error codes:
325 * GSOCK_INVSOCK - the socket is in use.
326 * GSOCK_INVADDR - the local address has not been set.
327 * GSOCK_IOERR - low-level error.
328 */
329 GSocketError GSocket_SetServer(GSocket *sck)
330 {
331 int type;
332 int arg = 1;
333
334 assert(sck != NULL);
335
336 /* must not be in use */
337 if (sck->m_fd != -1)
338 {
339 sck->m_error = GSOCK_INVSOCK;
340 return GSOCK_INVSOCK;
341 }
342
343 /* the local addr must have been set */
344 if (!sck->m_local)
345 {
346 sck->m_error = GSOCK_INVADDR;
347 return GSOCK_INVADDR;
348 }
349
350 /* Initialize all fields */
351 sck->m_stream = TRUE;
352 sck->m_server = TRUE;
353 sck->m_oriented = TRUE;
354
355 /* Create the socket */
356 sck->m_fd = socket(sck->m_local->m_realfamily, SOCK_STREAM, 0);
357
358 if (sck->m_fd == -1)
359 {
360 sck->m_error = GSOCK_IOERR;
361 return GSOCK_IOERR;
362 }
363
364 ioctl(sck->m_fd, FIONBIO, &arg);
365 _GSocket_Enable_Events(sck);
366
367 /* Bind to the local address,
368 * retrieve the actual address bound,
369 * and listen up to 5 connections.
370 */
371 if ((bind(sck->m_fd, sck->m_local->m_addr, sck->m_local->m_len) != 0) ||
372 (getsockname(sck->m_fd,
373 sck->m_local->m_addr,
374 (SOCKLEN_T *) &sck->m_local->m_len) != 0) ||
375 (listen(sck->m_fd, 5) != 0))
376 {
377 close(sck->m_fd);
378 sck->m_fd = -1;
379 sck->m_error = GSOCK_IOERR;
380 return GSOCK_IOERR;
381 }
382
383 return GSOCK_NOERROR;
384 }
385
386 /* GSocket_WaitConnection:
387 * Waits for an incoming client connection. Returns a pointer to
388 * a GSocket object, or NULL if there was an error, in which case
389 * the last error field will be updated for the calling GSocket.
390 *
391 * Error codes (set in the calling GSocket)
392 * GSOCK_INVSOCK - the socket is not valid or not a server.
393 * GSOCK_TIMEDOUT - timeout, no incoming connections.
394 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
395 * GSOCK_MEMERR - couldn't allocate memory.
396 * GSOCK_IOERR - low-level error.
397 */
398 GSocket *GSocket_WaitConnection(GSocket *socket)
399 {
400 struct sockaddr from;
401 SOCKLEN_T fromlen = sizeof(from);
402 GSocket *connection;
403 GSocketError err;
404 int arg = 1;
405
406 assert(socket != NULL);
407
408 /* Reenable CONNECTION events */
409 _GSocket_Enable(socket, GSOCK_CONNECTION);
410
411 /* If the socket has already been created, we exit immediately */
412 if (socket->m_fd == -1 || !socket->m_server)
413 {
414 socket->m_error = GSOCK_INVSOCK;
415 return NULL;
416 }
417
418 /* Create a GSocket object for the new connection */
419 connection = GSocket_new();
420
421 if (!connection)
422 {
423 socket->m_error = GSOCK_MEMERR;
424 return NULL;
425 }
426
427 /* Wait for a connection (with timeout) */
428 if (_GSocket_Input_Timeout(socket) == GSOCK_TIMEDOUT)
429 {
430 GSocket_destroy(connection);
431 /* socket->m_error set by _GSocket_Input_Timeout */
432 return NULL;
433 }
434
435 connection->m_fd = accept(socket->m_fd, &from, (SOCKLEN_T *) &fromlen);
436
437 if (connection->m_fd == -1)
438 {
439 if (errno == EWOULDBLOCK)
440 socket->m_error = GSOCK_WOULDBLOCK;
441 else
442 socket->m_error = GSOCK_IOERR;
443
444 GSocket_destroy(connection);
445 return NULL;
446 }
447
448 /* Initialize all fields */
449 connection->m_server = FALSE;
450 connection->m_stream = TRUE;
451 connection->m_oriented = TRUE;
452
453 /* Setup the peer address field */
454 connection->m_peer = GAddress_new();
455 if (!connection->m_peer)
456 {
457 GSocket_destroy(connection);
458 socket->m_error = GSOCK_MEMERR;
459 return NULL;
460 }
461 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
462 if (err != GSOCK_NOERROR)
463 {
464 GAddress_destroy(connection->m_peer);
465 GSocket_destroy(connection);
466 socket->m_error = err;
467 return NULL;
468 }
469
470 ioctl(connection->m_fd, FIONBIO, &arg);
471 _GSocket_Enable_Events(connection);
472
473 return connection;
474 }
475
476 /* Datagram sockets */
477
478 /* GSocket_SetNonOriented:
479 * Sets up this socket as a non-connection oriented (datagram) socket.
480 * Before using this function, the local address must have been set
481 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
482 * on success, or one of the following otherwise.
483 *
484 * Error codes:
485 * GSOCK_INVSOCK - the socket is in use.
486 * GSOCK_INVADDR - the local address has not been set.
487 * GSOCK_IOERR - low-level error.
488 */
489 GSocketError GSocket_SetNonOriented(GSocket *sck)
490 {
491 int arg = 1;
492
493 assert(sck != NULL);
494
495 if (sck->m_fd != -1)
496 {
497 sck->m_error = GSOCK_INVSOCK;
498 return GSOCK_INVSOCK;
499 }
500
501 if (!sck->m_local)
502 {
503 sck->m_error = GSOCK_INVADDR;
504 return GSOCK_INVADDR;
505 }
506
507 /* Initialize all fields */
508 sck->m_stream = FALSE;
509 sck->m_server = FALSE;
510 sck->m_oriented = FALSE;
511
512 /* Create the socket */
513 sck->m_fd = socket(sck->m_local->m_realfamily, SOCK_DGRAM, 0);
514
515 if (sck->m_fd < 0)
516 {
517 sck->m_error = GSOCK_IOERR;
518 return GSOCK_IOERR;
519 }
520
521 ioctl(sck->m_fd, FIONBIO, &arg);
522 _GSocket_Enable_Events(sck);
523
524 /* Bind to the local address,
525 * and retrieve the actual address bound.
526 */
527 if ((bind(sck->m_fd, sck->m_local->m_addr, sck->m_local->m_len) != 0) ||
528 (getsockname(sck->m_fd,
529 sck->m_local->m_addr,
530 (SOCKLEN_T *) &sck->m_local->m_len) != 0))
531 {
532 close(sck->m_fd);
533 sck->m_fd = -1;
534 sck->m_error = GSOCK_IOERR;
535 return GSOCK_IOERR;
536 }
537
538 return GSOCK_NOERROR;
539 }
540
541 /* Client specific parts */
542
543 /* GSocket_Connect:
544 * For stream (connection oriented) sockets, GSocket_Connect() tries
545 * to establish a client connection to a server using the peer address
546 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
547 * connection has been succesfully established, or one of the error
548 * codes listed below. Note that for nonblocking sockets, a return
549 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
550 * request can be completed later; you should use GSocket_Select()
551 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
552 * corresponding asynchronous events.
553 *
554 * For datagram (non connection oriented) sockets, GSocket_Connect()
555 * just sets the peer address established with GSocket_SetPeer() as
556 * default destination.
557 *
558 * Error codes:
559 * GSOCK_INVSOCK - the socket is in use or not valid.
560 * GSOCK_INVADDR - the peer address has not been established.
561 * GSOCK_TIMEDOUT - timeout, the connection failed.
562 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
563 * GSOCK_MEMERR - couldn't allocate memory.
564 * GSOCK_IOERR - low-level error.
565 */
566 GSocketError GSocket_Connect(GSocket *sck, GSocketStream stream)
567 {
568 int err, ret;
569 int arg = 1;
570
571 assert(sck != NULL);
572
573 /* Enable CONNECTION events (needed for nonblocking connections) */
574 _GSocket_Enable(sck, GSOCK_CONNECTION);
575
576 if (sck->m_fd != -1)
577 {
578 sck->m_error = GSOCK_INVSOCK;
579 return GSOCK_INVSOCK;
580 }
581
582 if (!sck->m_peer)
583 {
584 sck->m_error = GSOCK_INVADDR;
585 return GSOCK_INVADDR;
586 }
587
588 /* Streamed or dgram socket? */
589 sck->m_stream = (stream == GSOCK_STREAMED);
590 sck->m_oriented = TRUE;
591 sck->m_server = FALSE;
592 sck->m_establishing = FALSE;
593
594 /* Create the socket */
595 sck->m_fd = socket(sck->m_peer->m_realfamily,
596 sck->m_stream? SOCK_STREAM : SOCK_DGRAM, 0);
597
598 if (sck->m_fd == -1)
599 {
600 sck->m_error = GSOCK_IOERR;
601 return GSOCK_IOERR;
602 }
603
604 ioctl(sck->m_fd, FIONBIO, &arg);
605 _GSocket_Enable_Events(sck);
606
607 /* Connect it to the peer address, with a timeout (see below) */
608 ret = connect(sck->m_fd, sck->m_peer->m_addr, sck->m_peer->m_len);
609
610 if (ret == -1)
611 {
612 err = errno;
613
614 /* If connect failed with EINPROGRESS and the GSocket object
615 * is in blocking mode, we select() for the specified timeout
616 * checking for writability to see if the connection request
617 * completes.
618 */
619 if ((err == EINPROGRESS) && (!sck->m_non_blocking))
620 {
621 if (_GSocket_Output_Timeout(sck) == GSOCK_TIMEDOUT)
622 {
623 close(sck->m_fd);
624 sck->m_fd = -1;
625 /* sck->m_error is set in _GSocket_Output_Timeout */
626 return GSOCK_TIMEDOUT;
627 }
628 else
629 {
630 int error;
631 SOCKLEN_T len = sizeof(error);
632
633 getsockopt(sck->m_fd, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
634
635 if (!error)
636 return GSOCK_NOERROR;
637 }
638 }
639
640 /* If connect failed with EINPROGRESS and the GSocket object
641 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
642 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
643 * this way if the connection completes, a GSOCK_CONNECTION
644 * event will be generated, if enabled.
645 */
646 if ((err == EINPROGRESS) && (sck->m_non_blocking))
647 {
648 sck->m_establishing = TRUE;
649 sck->m_error = GSOCK_WOULDBLOCK;
650 return GSOCK_WOULDBLOCK;
651 }
652
653 /* If connect failed with an error other than EINPROGRESS,
654 * then the call to GSocket_Connect has failed.
655 */
656 close(sck->m_fd);
657 sck->m_fd = -1;
658 sck->m_error = GSOCK_IOERR;
659 return GSOCK_IOERR;
660 }
661
662 return GSOCK_NOERROR;
663 }
664
665 /* Generic IO */
666
667 /* Like recv(), send(), ... */
668 int GSocket_Read(GSocket *socket, char *buffer, int size)
669 {
670 int ret;
671
672 assert(socket != NULL);
673
674 /* Reenable INPUT events */
675 _GSocket_Enable(socket, GSOCK_INPUT);
676
677 if (socket->m_fd == -1 || socket->m_server)
678 {
679 socket->m_error = GSOCK_INVSOCK;
680 return -1;
681 }
682
683 /* If the socket is blocking, wait for data (with a timeout) */
684 if (_GSocket_Input_Timeout(socket) == GSOCK_TIMEDOUT)
685 return -1;
686
687 /* Read the data */
688 if (socket->m_stream)
689 ret = _GSocket_Recv_Stream(socket, buffer, size);
690 else
691 ret = _GSocket_Recv_Dgram(socket, buffer, size);
692
693 if (ret == -1)
694 {
695 if (errno == EWOULDBLOCK)
696 socket->m_error = GSOCK_WOULDBLOCK;
697 else
698 socket->m_error = GSOCK_IOERR;
699 }
700
701 return ret;
702 }
703
704 int GSocket_Write(GSocket *socket, const char *buffer, int size)
705 {
706 int ret;
707
708 assert(socket != NULL);
709
710 if (socket->m_fd == -1 || socket->m_server)
711 {
712 socket->m_error = GSOCK_INVSOCK;
713 return -1;
714 }
715
716 /* If the socket is blocking, wait for writability (with a timeout) */
717 if (_GSocket_Output_Timeout(socket) == GSOCK_TIMEDOUT)
718 return -1;
719
720 /* Write the data */
721 if (socket->m_stream)
722 ret = _GSocket_Send_Stream(socket, buffer, size);
723 else
724 ret = _GSocket_Send_Dgram(socket, buffer, size);
725
726 if (ret == -1)
727 {
728 if (errno == EWOULDBLOCK)
729 socket->m_error = GSOCK_WOULDBLOCK;
730 else
731 socket->m_error = GSOCK_IOERR;
732
733 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
734 * in MSW). Once the first OUTPUT event is received, users can assume
735 * that the socket is writable until a read operation fails. Only then
736 * will further OUTPUT events be posted.
737 */
738 _GSocket_Enable(socket, GSOCK_OUTPUT);
739 return -1;
740 }
741
742 return ret;
743 }
744
745 /* GSocket_Select:
746 * Polls the socket to determine its status. This function will
747 * check for the events specified in the 'flags' parameter, and
748 * it will return a mask indicating which operations can be
749 * performed. This function won't block, regardless of the
750 * mode (blocking | nonblocking) of the socket.
751 */
752 GSocketEventFlags GSocket_Select(GSocket *socket, GSocketEventFlags flags)
753 {
754 GSocketEventFlags result = 0;
755 char c;
756
757 assert(socket != NULL);
758
759 result = flags & socket->m_detected;
760
761 if ((flags & GSOCK_INPUT_FLAG) &&
762 (recv(socket->m_fd, &c, 1, MSG_PEEK) > 0))
763 {
764 result |= GSOCK_INPUT_FLAG;
765 }
766
767 return result;
768 }
769
770 /* Flags */
771
772 /* GSocket_SetNonBlocking:
773 * Sets the socket to non-blocking mode. All IO calls will return
774 * immediately.
775 */
776 void GSocket_SetNonBlocking(GSocket *socket, bool non_block)
777 {
778 assert(socket != NULL);
779
780 socket->m_non_blocking = non_block;
781 }
782
783 /* GSocket_SetTimeout:
784 * Sets the timeout for blocking calls. Time is expressed in
785 * milliseconds.
786 */
787 void GSocket_SetTimeout(GSocket *socket, unsigned long millisec)
788 {
789 assert(socket != NULL);
790
791 socket->m_timeout = millisec;
792 }
793
794 /* GSocket_GetError:
795 * Returns the last error occured for this socket. Note that successful
796 * operations do not clear this back to GSOCK_NOERROR, so use it only
797 * after an error.
798 */
799 GSocketError GSocket_GetError(GSocket *socket)
800 {
801 assert(socket != NULL);
802
803 return socket->m_error;
804 }
805
806 /* Callbacks */
807
808 /* GSOCK_INPUT:
809 * There is data to be read in the input buffer. If, after a read
810 * operation, there is still data available, the callback function will
811 * be called again.
812 * GSOCK_OUTPUT:
813 * The socket is available for writing. That is, the next write call
814 * won't block. This event is generated only once, when the connection is
815 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
816 * when the output buffer empties again. This means that the app should
817 * assume that it can write since the first OUTPUT event, and no more
818 * OUTPUT events will be generated unless an error occurs.
819 * GSOCK_CONNECTION:
820 * Connection succesfully established, for client sockets, or incoming
821 * client connection, for server sockets. Wait for this event (also watch
822 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
823 * GSOCK_LOST:
824 * The connection is lost (or a connection request failed); this could
825 * be due to a failure, or due to the peer closing it gracefully.
826 */
827
828 /* GSocket_SetCallback:
829 * Enables the callbacks specified by 'flags'. Note that 'flags'
830 * may be a combination of flags OR'ed toghether, so the same
831 * callback function can be made to accept different events.
832 * The callback function must have the following prototype:
833 *
834 * void function(GSocket *socket, GSocketEvent event, char *cdata)
835 */
836 void GSocket_SetCallback(GSocket *socket, GSocketEventFlags flags,
837 GSocketCallback callback, char *cdata)
838 {
839 int count;
840
841 assert(socket != NULL);
842
843 for (count = 0; count < GSOCK_MAX_EVENT; count++)
844 {
845 if ((flags & (1 << count)) != 0)
846 {
847 socket->m_cbacks[count] = callback;
848 socket->m_data[count] = cdata;
849 }
850 }
851 }
852
853 /* GSocket_UnsetCallback:
854 * Disables all callbacks specified by 'flags', which may be a
855 * combination of flags OR'ed toghether.
856 */
857 void GSocket_UnsetCallback(GSocket *socket, GSocketEventFlags flags)
858 {
859 int count;
860
861 assert(socket != NULL);
862
863 for (count = 0; count < GSOCK_MAX_EVENT; count++)
864 {
865 if ((flags & (1 << count)) != 0)
866 {
867 socket->m_cbacks[count] = NULL;
868 socket->m_data[count] = NULL;
869 }
870 }
871 }
872
873
874 #define CALL_CALLBACK(socket, event) { \
875 _GSocket_Disable(socket, event); \
876 if (socket->m_cbacks[event]) \
877 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
878 }
879
880
881 void _GSocket_Enable(GSocket *socket, GSocketEvent event)
882 {
883 socket->m_detected &= ~(1 << event);
884 _GSocket_Install_Callback(socket, event);
885 }
886
887 void _GSocket_Disable(GSocket *socket, GSocketEvent event)
888 {
889 socket->m_detected |= (1 << event);
890 _GSocket_Uninstall_Callback(socket, event);
891 }
892
893 /* _GSocket_Input_Timeout:
894 * For blocking sockets, wait until data is available or
895 * until timeout ellapses.
896 */
897 GSocketError _GSocket_Input_Timeout(GSocket *socket)
898 {
899 struct timeval tv;
900 fd_set readfds;
901
902 /* Linux select() will overwrite the struct on return */
903 tv.tv_sec = (socket->m_timeout / 1000);
904 tv.tv_usec = (socket->m_timeout % 1000) * 1000;
905
906 if (!socket->m_non_blocking)
907 {
908 FD_ZERO(&readfds);
909 FD_SET(socket->m_fd, &readfds);
910 if (select(socket->m_fd + 1, &readfds, NULL, NULL, &tv) == 0)
911 {
912 socket->m_error = GSOCK_TIMEDOUT;
913 return GSOCK_TIMEDOUT;
914 }
915 }
916 return GSOCK_NOERROR;
917 }
918
919 /* _GSocket_Output_Timeout:
920 * For blocking sockets, wait until data can be sent without
921 * blocking or until timeout ellapses.
922 */
923 GSocketError _GSocket_Output_Timeout(GSocket *socket)
924 {
925 struct timeval tv;
926 fd_set writefds;
927
928 /* Linux select() will overwrite the struct on return */
929 tv.tv_sec = (socket->m_timeout / 1000);
930 tv.tv_usec = (socket->m_timeout % 1000) * 1000;
931
932 if (!socket->m_non_blocking)
933 {
934 FD_ZERO(&writefds);
935 FD_SET(socket->m_fd, &writefds);
936 if (select(socket->m_fd + 1, NULL, &writefds, NULL, &tv) == 0)
937 {
938 socket->m_error = GSOCK_TIMEDOUT;
939 return GSOCK_TIMEDOUT;
940 }
941 }
942 return GSOCK_NOERROR;
943 }
944
945 int _GSocket_Recv_Stream(GSocket *socket, char *buffer, int size)
946 {
947 return recv(socket->m_fd, buffer, size, 0);
948 }
949
950 int _GSocket_Recv_Dgram(GSocket *socket, char *buffer, int size)
951 {
952 struct sockaddr from;
953 SOCKLEN_T fromlen = sizeof(from);
954 int ret;
955 GSocketError err;
956
957 fromlen = sizeof(from);
958
959 ret = recvfrom(socket->m_fd, buffer, size, 0, &from, (SOCKLEN_T *) &fromlen);
960
961 if (ret == -1)
962 return -1;
963
964 /* Translate a system address into a GSocket address */
965 if (!socket->m_peer)
966 {
967 socket->m_peer = GAddress_new();
968 if (!socket->m_peer)
969 {
970 socket->m_error = GSOCK_MEMERR;
971 return -1;
972 }
973 }
974 err = _GAddress_translate_from(socket->m_peer, &from, fromlen);
975 if (err != GSOCK_NOERROR)
976 {
977 GAddress_destroy(socket->m_peer);
978 socket->m_peer = NULL;
979 socket->m_error = err;
980 return -1;
981 }
982
983 return ret;
984 }
985
986 int _GSocket_Send_Stream(GSocket *socket, const char *buffer, int size)
987 {
988 int ret;
989
990 MASK_SIGNAL();
991 ret = send(socket->m_fd, buffer, size, 0);
992 UNMASK_SIGNAL();
993
994 return ret;
995 }
996
997 int _GSocket_Send_Dgram(GSocket *socket, const char *buffer, int size)
998 {
999 struct sockaddr *addr;
1000 int len, ret;
1001 GSocketError err;
1002
1003 if (!socket->m_peer)
1004 {
1005 socket->m_error = GSOCK_INVADDR;
1006 return -1;
1007 }
1008
1009 err = _GAddress_translate_to(socket->m_peer, &addr, &len);
1010 if (err != GSOCK_NOERROR)
1011 {
1012 socket->m_error = err;
1013 return -1;
1014 }
1015
1016 MASK_SIGNAL();
1017 ret = sendto(socket->m_fd, buffer, size, 0, addr, len);
1018 UNMASK_SIGNAL();
1019
1020 /* Frees memory allocated from _GAddress_translate_to */
1021 free(addr);
1022
1023 return ret;
1024 }
1025
1026 void _GSocket_Detected_Read(GSocket *socket)
1027 {
1028 char c;
1029 int ret;
1030
1031 ret = recv(socket->m_fd, &c, 1, MSG_PEEK);
1032
1033 if (socket->m_stream)
1034 {
1035 if (ret < 0 && socket->m_server)
1036 {
1037 CALL_CALLBACK(socket, GSOCK_CONNECTION);
1038 return;
1039 }
1040 }
1041
1042 if (ret > 0)
1043 {
1044 CALL_CALLBACK(socket, GSOCK_INPUT);
1045 }
1046 else
1047 {
1048 CALL_CALLBACK(socket, GSOCK_LOST);
1049 }
1050 }
1051
1052 void _GSocket_Detected_Write(GSocket *socket)
1053 {
1054 if (socket->m_establishing && !socket->m_server)
1055 {
1056 int error;
1057 SOCKLEN_T len = sizeof(error);
1058
1059 socket->m_establishing = FALSE;
1060
1061 getsockopt(socket->m_fd, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
1062
1063 if (error)
1064 {
1065 CALL_CALLBACK(socket, GSOCK_LOST);
1066 }
1067 else
1068 {
1069 CALL_CALLBACK(socket, GSOCK_CONNECTION);
1070 /* We have to fire this event by hand because CONNECTION (for clients)
1071 * and OUTPUT are internally the same and we just disabled CONNECTION
1072 * events with the above macro.
1073 */
1074 CALL_CALLBACK(socket, GSOCK_OUTPUT);
1075 }
1076 }
1077 else
1078 {
1079 CALL_CALLBACK(socket, GSOCK_OUTPUT);
1080 }
1081 }
1082
1083 /*
1084 * -------------------------------------------------------------------------
1085 * GAddress
1086 * -------------------------------------------------------------------------
1087 */
1088
1089 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1090 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1091 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1092 */
1093 #define CHECK_ADDRESS(address, family, retval) \
1094 { \
1095 if (address->m_family == GSOCK_NOFAMILY) \
1096 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1097 return address->m_error; \
1098 if (address->m_family != GSOCK_##family) \
1099 { \
1100 address->m_error = GSOCK_INVADDR; \
1101 return retval; \
1102 } \
1103 }
1104
1105 GAddress *GAddress_new()
1106 {
1107 GAddress *address;
1108
1109 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1110 return NULL;
1111
1112 address->m_family = GSOCK_NOFAMILY;
1113 address->m_addr = NULL;
1114 address->m_len = 0;
1115
1116 return address;
1117 }
1118
1119 GAddress *GAddress_copy(GAddress *address)
1120 {
1121 GAddress *addr2;
1122
1123 assert(address != NULL);
1124
1125 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1126 return NULL;
1127
1128 memcpy(addr2, address, sizeof(GAddress));
1129
1130 if (address->m_addr)
1131 {
1132 addr2->m_addr = (struct sockaddr *)malloc(addr2->m_len);
1133 if (addr2->m_addr == NULL)
1134 {
1135 free(addr2);
1136 return NULL;
1137 }
1138 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1139 }
1140
1141 return addr2;
1142 }
1143
1144 void GAddress_destroy(GAddress *address)
1145 {
1146 assert(address != NULL);
1147
1148 free(address);
1149 }
1150
1151 void GAddress_SetFamily(GAddress *address, GAddressType type)
1152 {
1153 assert(address != NULL);
1154
1155 address->m_family = type;
1156 }
1157
1158 GAddressType GAddress_GetFamily(GAddress *address)
1159 {
1160 assert(address != NULL);
1161
1162 return address->m_family;
1163 }
1164
1165 GSocketError _GAddress_translate_from(GAddress *address,
1166 struct sockaddr *addr, int len)
1167 {
1168 address->m_realfamily = addr->sa_family;
1169 switch (addr->sa_family)
1170 {
1171 case AF_INET:
1172 address->m_family = GSOCK_INET;
1173 break;
1174 case AF_UNIX:
1175 address->m_family = GSOCK_UNIX;
1176 break;
1177 #ifdef AF_INET6
1178 case AF_INET6:
1179 address->m_family = GSOCK_INET6;
1180 break;
1181 #endif
1182 default:
1183 {
1184 address->m_error = GSOCK_INVOP;
1185 return GSOCK_INVOP;
1186 }
1187 }
1188
1189 if (address->m_addr)
1190 free(address->m_addr);
1191
1192 address->m_len = len;
1193 address->m_addr = (struct sockaddr *)malloc(len);
1194
1195 if (address->m_addr == NULL)
1196 {
1197 address->m_error = GSOCK_MEMERR;
1198 return GSOCK_MEMERR;
1199 }
1200 memcpy(address->m_addr, addr, len);
1201
1202 return GSOCK_NOERROR;
1203 }
1204
1205 GSocketError _GAddress_translate_to(GAddress *address,
1206 struct sockaddr **addr, int *len)
1207 {
1208 if (!address->m_addr)
1209 {
1210 address->m_error = GSOCK_INVADDR;
1211 return GSOCK_INVADDR;
1212 }
1213
1214 *len = address->m_len;
1215 *addr = (struct sockaddr *)malloc(address->m_len);
1216 if (*addr == NULL) {
1217 address->m_error = GSOCK_MEMERR;
1218 return GSOCK_MEMERR;
1219 }
1220
1221 memcpy(*addr, address->m_addr, address->m_len);
1222 return GSOCK_NOERROR;
1223 }
1224
1225 /*
1226 * -------------------------------------------------------------------------
1227 * Internet address family
1228 * -------------------------------------------------------------------------
1229 */
1230
1231 GSocketError _GAddress_Init_INET(GAddress *address)
1232 {
1233 address->m_len = sizeof(struct sockaddr_in);
1234 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1235 if (address->m_addr == NULL)
1236 {
1237 address->m_error = GSOCK_MEMERR;
1238 return GSOCK_MEMERR;
1239 }
1240
1241 address->m_family = GSOCK_INET;
1242 address->m_realfamily = PF_INET;
1243 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
1244 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
1245
1246 return GSOCK_NOERROR;
1247 }
1248
1249 GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1250 {
1251 struct hostent *he;
1252 struct in_addr *addr;
1253
1254 assert(address != NULL);
1255
1256 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1257
1258 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1259
1260 /* If it is a numeric host name, convert it now */
1261 #if defined(HAVE_INET_ATON)
1262 if (inet_aton(hostname, addr) == 0)
1263 {
1264 #elif defined(HAVE_INET_ADDR)
1265 if ( (addr->s_addr = inet_addr(hostname)) == -1 )
1266 {
1267 #else
1268 /* Use gethostbyname by default */
1269 if (1)
1270 {
1271 #endif
1272 struct in_addr *array_addr;
1273
1274 /* It is a real name, we solve it */
1275 if ((he = gethostbyname(hostname)) == NULL)
1276 {
1277 /* Reset to invalid address */
1278 addr->s_addr = INADDR_NONE;
1279 address->m_error = GSOCK_NOHOST;
1280 return GSOCK_NOHOST;
1281 }
1282 array_addr = (struct in_addr *) *(he->h_addr_list);
1283 addr->s_addr = array_addr[0].s_addr;
1284 }
1285 return GSOCK_NOERROR;
1286 }
1287
1288 GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1289 {
1290 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1291 }
1292
1293 GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1294 unsigned long hostaddr)
1295 {
1296 struct in_addr *addr;
1297
1298 assert(address != NULL);
1299
1300 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1301
1302 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1303 addr->s_addr = hostaddr;
1304
1305 return GSOCK_NOERROR;
1306 }
1307
1308 GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1309 const char *protocol)
1310 {
1311 struct servent *se;
1312 struct sockaddr_in *addr;
1313
1314 assert(address != NULL);
1315 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1316
1317 if (!port)
1318 {
1319 address->m_error = GSOCK_INVPORT;
1320 return GSOCK_INVPORT;
1321 }
1322
1323 se = getservbyname(port, protocol);
1324 if (!se)
1325 {
1326 if (isdigit(port[0]))
1327 {
1328 int port_int;
1329
1330 port_int = atoi(port);
1331 addr = (struct sockaddr_in *)address->m_addr;
1332 addr->sin_port = htons(port_int);
1333 return GSOCK_NOERROR;
1334 }
1335
1336 address->m_error = GSOCK_INVPORT;
1337 return GSOCK_INVPORT;
1338 }
1339
1340 addr = (struct sockaddr_in *)address->m_addr;
1341 addr->sin_port = se->s_port;
1342
1343 return GSOCK_NOERROR;
1344 }
1345
1346 GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
1347 {
1348 struct sockaddr_in *addr;
1349
1350 assert(address != NULL);
1351 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1352
1353 addr = (struct sockaddr_in *)address->m_addr;
1354 addr->sin_port = htons(port);
1355
1356 return GSOCK_NOERROR;
1357 }
1358
1359 GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
1360 {
1361 struct hostent *he;
1362 char *addr_buf;
1363 struct sockaddr_in *addr;
1364
1365 assert(address != NULL);
1366 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1367
1368 addr = (struct sockaddr_in *)address->m_addr;
1369 addr_buf = (char *)&(addr->sin_addr);
1370
1371 he = gethostbyaddr(addr_buf, sizeof(addr->sin_addr), AF_INET);
1372 if (he == NULL)
1373 {
1374 address->m_error = GSOCK_NOHOST;
1375 return GSOCK_NOHOST;
1376 }
1377
1378 strncpy(hostname, he->h_name, sbuf);
1379
1380 return GSOCK_NOERROR;
1381 }
1382
1383 unsigned long GAddress_INET_GetHostAddress(GAddress *address)
1384 {
1385 struct sockaddr_in *addr;
1386
1387 assert(address != NULL);
1388 CHECK_ADDRESS(address, INET, 0);
1389
1390 addr = (struct sockaddr_in *)address->m_addr;
1391
1392 return addr->sin_addr.s_addr;
1393 }
1394
1395 unsigned short GAddress_INET_GetPort(GAddress *address)
1396 {
1397 struct sockaddr_in *addr;
1398
1399 assert(address != NULL);
1400 CHECK_ADDRESS(address, INET, 0);
1401
1402 addr = (struct sockaddr_in *)address->m_addr;
1403 return ntohs(addr->sin_port);
1404 }
1405
1406 /*
1407 * -------------------------------------------------------------------------
1408 * Unix address family
1409 * -------------------------------------------------------------------------
1410 */
1411
1412 GSocketError _GAddress_Init_UNIX(GAddress *address)
1413 {
1414 address->m_len = sizeof(struct sockaddr_un);
1415 address->m_addr = (struct sockaddr *)malloc(address->m_len);
1416 if (address->m_addr == NULL)
1417 {
1418 address->m_error = GSOCK_MEMERR;
1419 return GSOCK_MEMERR;
1420 }
1421
1422 address->m_family = GSOCK_UNIX;
1423 address->m_realfamily = PF_UNIX;
1424 ((struct sockaddr_un *)address->m_addr)->sun_family = AF_UNIX;
1425 ((struct sockaddr_un *)address->m_addr)->sun_path[0] = 0;
1426
1427 return TRUE;
1428 }
1429
1430 GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *path)
1431 {
1432 struct sockaddr_un *addr;
1433
1434 assert(address != NULL);
1435
1436 CHECK_ADDRESS(address, UNIX, GSOCK_INVADDR);
1437
1438 addr = ((struct sockaddr_un *)address->m_addr);
1439 memcpy(addr->sun_path, path, strlen(path));
1440
1441 return GSOCK_NOERROR;
1442 }
1443
1444 GSocketError GAddress_UNIX_GetPath(GAddress *address, char *path, size_t sbuf)
1445 {
1446 struct sockaddr_un *addr;
1447
1448 assert(address != NULL);
1449 CHECK_ADDRESS(address, UNIX, GSOCK_INVADDR);
1450
1451 addr = (struct sockaddr_un *)address->m_addr;
1452
1453 strncpy(path, addr->sun_path, sbuf);
1454
1455 return GSOCK_NOERROR;
1456 }
1457
1458 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */
1459