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