]> git.saurik.com Git - wxWidgets.git/blob - src/msw/gsocket.c
Fixed compilation for !wxUSE_IMAGE as well as !wxUSE_TOOLBAR.
[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/platform.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 /* allow a socket to re-bind if the socket is in the TIME_WAIT
380 state after being previously closed.
381 */
382 setsockopt(sck->m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(u_long));
383
384 /* Bind to the local address,
385 * retrieve the actual address bound,
386 * and listen up to 5 connections.
387 */
388 if ((bind(sck->m_fd, sck->m_local->m_addr, sck->m_local->m_len) != 0) ||
389 (getsockname(sck->m_fd,
390 sck->m_local->m_addr,
391 (SOCKLEN_T *)&sck->m_local->m_len) != 0) ||
392 (listen(sck->m_fd, 5) != 0))
393 {
394 GSocket_close(sck);
395 sck->m_error = GSOCK_IOERR;
396 return GSOCK_IOERR;
397 }
398
399 return GSOCK_NOERROR;
400 }
401
402 /* GSocket_WaitConnection:
403 * Waits for an incoming client connection. Returns a pointer to
404 * a GSocket object, or NULL if there was an error, in which case
405 * the last error field will be updated for the calling GSocket.
406 *
407 * Error codes (set in the calling GSocket)
408 * GSOCK_INVSOCK - the socket is not valid or not a server.
409 * GSOCK_TIMEDOUT - timeout, no incoming connections.
410 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
411 * GSOCK_MEMERR - couldn't allocate memory.
412 * GSOCK_IOERR - low-level error.
413 */
414 GSocket *GSocket_WaitConnection(GSocket *sck)
415 {
416 GSocket *connection;
417 struct sockaddr from;
418 SOCKLEN_T fromlen = sizeof(from);
419 GSocketError err;
420 u_long arg = 1;
421
422 assert(sck != NULL);
423
424 /* Reenable CONNECTION events */
425 sck->m_detected &= ~GSOCK_CONNECTION_FLAG;
426
427 /* If the socket has already been created, we exit immediately */
428 if (sck->m_fd == INVALID_SOCKET || !sck->m_server)
429 {
430 sck->m_error = GSOCK_INVSOCK;
431 return NULL;
432 }
433
434 /* Create a GSocket object for the new connection */
435 connection = GSocket_new();
436
437 if (!connection)
438 {
439 sck->m_error = GSOCK_MEMERR;
440 return NULL;
441 }
442
443 /* Wait for a connection (with timeout) */
444 if (_GSocket_Input_Timeout(sck) == GSOCK_TIMEDOUT)
445 {
446 GSocket_destroy(connection);
447 /* sck->m_error set by _GSocket_Input_Timeout */
448 return NULL;
449 }
450
451 connection->m_fd = accept(sck->m_fd, &from, &fromlen);
452
453 if (connection->m_fd == INVALID_SOCKET)
454 {
455 if (WSAGetLastError() == WSAEWOULDBLOCK)
456 sck->m_error = GSOCK_WOULDBLOCK;
457 else
458 sck->m_error = GSOCK_IOERR;
459
460 GSocket_destroy(connection);
461 return NULL;
462 }
463
464 /* Initialize all fields */
465 connection->m_server = FALSE;
466 connection->m_stream = TRUE;
467 connection->m_oriented = TRUE;
468
469 /* Setup the peer address field */
470 connection->m_peer = GAddress_new();
471 if (!connection->m_peer)
472 {
473 GSocket_destroy(connection);
474 sck->m_error = GSOCK_MEMERR;
475 return NULL;
476 }
477 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
478 if (err != GSOCK_NOERROR)
479 {
480 GAddress_destroy(connection->m_peer);
481 GSocket_destroy(connection);
482 sck->m_error = err;
483 return NULL;
484 }
485
486 ioctlsocket(connection->m_fd, FIONBIO, (u_long FAR *) &arg);
487 _GSocket_Enable_Events(connection);
488
489 return connection;
490 }
491
492 /* Client specific parts */
493
494 /* GSocket_Connect:
495 * For stream (connection oriented) sockets, GSocket_Connect() tries
496 * to establish a client connection to a server using the peer address
497 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
498 * connection has been succesfully established, or one of the error
499 * codes listed below. Note that for nonblocking sockets, a return
500 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
501 * request can be completed later; you should use GSocket_Select()
502 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
503 * corresponding asynchronous events.
504 *
505 * For datagram (non connection oriented) sockets, GSocket_Connect()
506 * just sets the peer address established with GSocket_SetPeer() as
507 * default destination.
508 *
509 * Error codes:
510 * GSOCK_INVSOCK - the socket is in use or not valid.
511 * GSOCK_INVADDR - the peer address has not been established.
512 * GSOCK_TIMEDOUT - timeout, the connection failed.
513 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
514 * GSOCK_MEMERR - couldn't allocate memory.
515 * GSOCK_IOERR - low-level error.
516 */
517 GSocketError GSocket_Connect(GSocket *sck, GSocketStream stream)
518 {
519 int ret, err;
520 u_long arg = 1;
521
522 assert(sck != NULL);
523
524 /* Enable CONNECTION events (needed for nonblocking connections) */
525 sck->m_detected &= ~GSOCK_CONNECTION_FLAG;
526
527 if (sck->m_fd != INVALID_SOCKET)
528 {
529 sck->m_error = GSOCK_INVSOCK;
530 return GSOCK_INVSOCK;
531 }
532
533 if (!sck->m_peer)
534 {
535 sck->m_error = GSOCK_INVADDR;
536 return GSOCK_INVADDR;
537 }
538
539 /* Streamed or dgram socket? */
540 sck->m_stream = (stream == GSOCK_STREAMED);
541 sck->m_oriented = TRUE;
542 sck->m_server = FALSE;
543 sck->m_establishing = FALSE;
544
545 /* Create the socket */
546 sck->m_fd = socket(sck->m_peer->m_realfamily,
547 sck->m_stream? SOCK_STREAM : SOCK_DGRAM, 0);
548
549 if (sck->m_fd == INVALID_SOCKET)
550 {
551 sck->m_error = GSOCK_IOERR;
552 return GSOCK_IOERR;
553 }
554
555 ioctlsocket(sck->m_fd, FIONBIO, (u_long FAR *) &arg);
556 _GSocket_Enable_Events(sck);
557
558 /* Connect it to the peer address, with a timeout (see below) */
559 ret = connect(sck->m_fd, sck->m_peer->m_addr, sck->m_peer->m_len);
560
561 if (ret == SOCKET_ERROR)
562 {
563 err = WSAGetLastError();
564
565 /* If connect failed with EWOULDBLOCK and the GSocket object
566 * is in blocking mode, we select() for the specified timeout
567 * checking for writability to see if the connection request
568 * completes.
569 */
570 if ((err == WSAEWOULDBLOCK) && (!sck->m_non_blocking))
571 {
572 err = _GSocket_Connect_Timeout(sck);
573
574 if (err != GSOCK_NOERROR)
575 {
576 GSocket_close(sck);
577 /* sck->m_error is set in _GSocket_Connect_Timeout */
578 }
579
580 return (GSocketError) err;
581 }
582
583 /* If connect failed with EWOULDBLOCK and the GSocket object
584 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
585 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
586 * this way if the connection completes, a GSOCK_CONNECTION
587 * event will be generated, if enabled.
588 */
589 if ((err == WSAEWOULDBLOCK) && (sck->m_non_blocking))
590 {
591 sck->m_establishing = TRUE;
592 sck->m_error = GSOCK_WOULDBLOCK;
593 return GSOCK_WOULDBLOCK;
594 }
595
596 /* If connect failed with an error other than EWOULDBLOCK,
597 * then the call to GSocket_Connect() has failed.
598 */
599 GSocket_close(sck);
600 sck->m_error = GSOCK_IOERR;
601 return GSOCK_IOERR;
602 }
603
604 return GSOCK_NOERROR;
605 }
606
607 /* Datagram sockets */
608
609 /* GSocket_SetNonOriented:
610 * Sets up this socket as a non-connection oriented (datagram) socket.
611 * Before using this function, the local address must have been set
612 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
613 * on success, or one of the following otherwise.
614 *
615 * Error codes:
616 * GSOCK_INVSOCK - the socket is in use.
617 * GSOCK_INVADDR - the local address has not been set.
618 * GSOCK_IOERR - low-level error.
619 */
620 GSocketError GSocket_SetNonOriented(GSocket *sck)
621 {
622 u_long arg = 1;
623
624 assert(sck != NULL);
625
626 if (sck->m_fd != INVALID_SOCKET)
627 {
628 sck->m_error = GSOCK_INVSOCK;
629 return GSOCK_INVSOCK;
630 }
631
632 if (!sck->m_local)
633 {
634 sck->m_error = GSOCK_INVADDR;
635 return GSOCK_INVADDR;
636 }
637
638 /* Initialize all fields */
639 sck->m_stream = FALSE;
640 sck->m_server = FALSE;
641 sck->m_oriented = FALSE;
642
643 /* Create the socket */
644 sck->m_fd = socket(sck->m_local->m_realfamily, SOCK_DGRAM, 0);
645
646 if (sck->m_fd == INVALID_SOCKET)
647 {
648 sck->m_error = GSOCK_IOERR;
649 return GSOCK_IOERR;
650 }
651
652 ioctlsocket(sck->m_fd, FIONBIO, (u_long FAR *) &arg);
653 _GSocket_Enable_Events(sck);
654
655 /* Bind to the local address,
656 * and retrieve the actual address bound.
657 */
658 if ((bind(sck->m_fd, sck->m_local->m_addr, sck->m_local->m_len) != 0) ||
659 (getsockname(sck->m_fd,
660 sck->m_local->m_addr,
661 (SOCKLEN_T *)&sck->m_local->m_len) != 0))
662 {
663 GSocket_close(sck);
664 sck->m_error = GSOCK_IOERR;
665 return GSOCK_IOERR;
666 }
667
668 return GSOCK_NOERROR;
669 }
670
671 /* Generic IO */
672
673 /* Like recv(), send(), ... */
674 int GSocket_Read(GSocket *socket, char *buffer, int size)
675 {
676 int ret;
677
678 assert(socket != NULL);
679
680 /* Reenable INPUT events */
681 socket->m_detected &= ~GSOCK_INPUT_FLAG;
682
683 if (socket->m_fd == INVALID_SOCKET || socket->m_server)
684 {
685 socket->m_error = GSOCK_INVSOCK;
686 return -1;
687 }
688
689 /* If the socket is blocking, wait for data (with a timeout) */
690 if (_GSocket_Input_Timeout(socket) == GSOCK_TIMEDOUT)
691 return -1;
692
693 /* Read the data */
694 if (socket->m_stream)
695 ret = _GSocket_Recv_Stream(socket, buffer, size);
696 else
697 ret = _GSocket_Recv_Dgram(socket, buffer, size);
698
699 if (ret == SOCKET_ERROR)
700 {
701 if (WSAGetLastError() != WSAEWOULDBLOCK)
702 socket->m_error = GSOCK_IOERR;
703 else
704 socket->m_error = GSOCK_WOULDBLOCK;
705 return -1;
706 }
707
708 return ret;
709 }
710
711 int GSocket_Write(GSocket *socket, const char *buffer, int size)
712 {
713 int ret;
714
715 assert(socket != NULL);
716
717 if (socket->m_fd == INVALID_SOCKET || socket->m_server)
718 {
719 socket->m_error = GSOCK_INVSOCK;
720 return -1;
721 }
722
723 /* If the socket is blocking, wait for writability (with a timeout) */
724 if (_GSocket_Output_Timeout(socket) == GSOCK_TIMEDOUT)
725 return -1;
726
727 /* Write the data */
728 if (socket->m_stream)
729 ret = _GSocket_Send_Stream(socket, buffer, size);
730 else
731 ret = _GSocket_Send_Dgram(socket, buffer, size);
732
733 if (ret == SOCKET_ERROR)
734 {
735 if (WSAGetLastError() != WSAEWOULDBLOCK)
736 socket->m_error = GSOCK_IOERR;
737 else
738 socket->m_error = GSOCK_WOULDBLOCK;
739
740 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
741 * does). Once the first OUTPUT event is received, users can assume
742 * that the socket is writable until a read operation fails. Only then
743 * will further OUTPUT events be posted.
744 */
745 socket->m_detected &= ~GSOCK_OUTPUT_FLAG;
746 return -1;
747 }
748
749 return ret;
750 }
751
752 /* GSocket_Select:
753 * Polls the socket to determine its status. This function will
754 * check for the events specified in the 'flags' parameter, and
755 * it will return a mask indicating which operations can be
756 * performed. This function won't block, regardless of the
757 * mode (blocking | nonblocking) of the socket.
758 */
759 GSocketEventFlags GSocket_Select(GSocket *socket, GSocketEventFlags flags)
760 {
761 if (!USE_GUI())
762 {
763 GSocketEventFlags result = 0;
764 fd_set readfds;
765 fd_set writefds;
766 fd_set exceptfds;
767
768 assert(socket != NULL);
769
770 FD_ZERO(&readfds);
771 FD_ZERO(&writefds);
772 FD_ZERO(&exceptfds);
773 FD_SET(socket->m_fd, &readfds);
774 if (flags & GSOCK_OUTPUT_FLAG)
775 FD_SET(socket->m_fd, &writefds);
776 FD_SET(socket->m_fd, &exceptfds);
777
778 /* Check 'sticky' CONNECTION flag first */
779 result |= (GSOCK_CONNECTION_FLAG & socket->m_detected);
780
781 /* If we have already detected a LOST event, then don't try
782 * to do any further processing.
783 */
784 if ((socket->m_detected & GSOCK_LOST_FLAG) != 0)
785 {
786 socket->m_establishing = FALSE;
787
788 return (GSOCK_LOST_FLAG & flags);
789 }
790
791 /* Try select now */
792 if (select(socket->m_fd + 1, &readfds, &writefds, &exceptfds,
793 &socket->m_timeout) <= 0)
794 {
795 /* What to do here? */
796 return (result & flags);
797 }
798
799 /* Check for readability */
800 if (FD_ISSET(socket->m_fd, &readfds))
801 {
802 char c;
803
804 if (!socket->m_stream || recv(socket->m_fd, &c, 1, MSG_PEEK) > 0)
805 {
806 result |= GSOCK_INPUT_FLAG;
807 }
808 else
809 {
810 if (socket->m_server && socket->m_stream)
811 {
812 result |= GSOCK_CONNECTION_FLAG;
813 socket->m_detected |= GSOCK_CONNECTION_FLAG;
814 }
815 else
816 {
817 socket->m_detected = GSOCK_LOST_FLAG;
818 socket->m_establishing = FALSE;
819
820 /* LOST event: Abort any further processing */
821 return (GSOCK_LOST_FLAG & flags);
822 }
823 }
824 }
825
826 /* Check for writability */
827 if (FD_ISSET(socket->m_fd, &writefds))
828 {
829 if (socket->m_establishing && !socket->m_server)
830 {
831 int error;
832 SOCKLEN_T len = sizeof(error);
833
834 socket->m_establishing = FALSE;
835
836 getsockopt(socket->m_fd, SOL_SOCKET, SO_ERROR, (void*)&error, &len);
837
838 if (error)
839 {
840 socket->m_detected = GSOCK_LOST_FLAG;
841
842 /* LOST event: Abort any further processing */
843 return (GSOCK_LOST_FLAG & flags);
844 }
845 else
846 {
847 result |= GSOCK_CONNECTION_FLAG;
848 socket->m_detected |= GSOCK_CONNECTION_FLAG;
849 }
850 }
851 else
852 {
853 result |= GSOCK_OUTPUT_FLAG;
854 }
855 }
856
857 /* Check for exceptions and errors (is this useful in Unices?) */
858 if (FD_ISSET(socket->m_fd, &exceptfds))
859 {
860 socket->m_establishing = FALSE;
861 socket->m_detected = GSOCK_LOST_FLAG;
862
863 /* LOST event: Abort any further processing */
864 return (GSOCK_LOST_FLAG & flags);
865 }
866
867 return (result & flags);
868 }
869 else /* USE_GUI() */
870 {
871 assert(socket != NULL);
872 return flags & socket->m_detected;
873 }
874 }
875
876 /* Attributes */
877
878 /* GSocket_SetNonBlocking:
879 * Sets the socket to non-blocking mode. All IO calls will return
880 * immediately.
881 */
882 void GSocket_SetNonBlocking(GSocket *socket, int non_block)
883 {
884 assert(socket != NULL);
885
886 socket->m_non_blocking = non_block;
887 }
888
889 /* GSocket_SetTimeout:
890 * Sets the timeout for blocking calls. Time is expressed in
891 * milliseconds.
892 */
893 void GSocket_SetTimeout(GSocket *socket, unsigned long millis)
894 {
895 assert(socket != NULL);
896
897 socket->m_timeout.tv_sec = (millis / 1000);
898 socket->m_timeout.tv_usec = (millis % 1000) * 1000;
899 }
900
901 /* GSocket_GetError:
902 * Returns the last error occured for this socket. Note that successful
903 * operations do not clear this back to GSOCK_NOERROR, so use it only
904 * after an error.
905 */
906 GSocketError GSocket_GetError(GSocket *socket)
907 {
908 assert(socket != NULL);
909
910 return socket->m_error;
911 }
912
913 /* Callbacks */
914
915 /* GSOCK_INPUT:
916 * There is data to be read in the input buffer. If, after a read
917 * operation, there is still data available, the callback function will
918 * be called again.
919 * GSOCK_OUTPUT:
920 * The socket is available for writing. That is, the next write call
921 * won't block. This event is generated only once, when the connection is
922 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
923 * when the output buffer empties again. This means that the app should
924 * assume that it can write since the first OUTPUT event, and no more
925 * OUTPUT events will be generated unless an error occurs.
926 * GSOCK_CONNECTION:
927 * Connection succesfully established, for client sockets, or incoming
928 * client connection, for server sockets. Wait for this event (also watch
929 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
930 * GSOCK_LOST:
931 * The connection is lost (or a connection request failed); this could
932 * be due to a failure, or due to the peer closing it gracefully.
933 */
934
935 /* GSocket_SetCallback:
936 * Enables the callbacks specified by 'flags'. Note that 'flags'
937 * may be a combination of flags OR'ed toghether, so the same
938 * callback function can be made to accept different events.
939 * The callback function must have the following prototype:
940 *
941 * void function(GSocket *socket, GSocketEvent event, char *cdata)
942 */
943 void GSocket_SetCallback(GSocket *socket, GSocketEventFlags flags,
944 GSocketCallback callback, char *cdata)
945 {
946 int count;
947
948 assert(socket != NULL);
949
950 for (count = 0; count < GSOCK_MAX_EVENT; count++)
951 {
952 if ((flags & (1 << count)) != 0)
953 {
954 socket->m_cbacks[count] = callback;
955 socket->m_data[count] = cdata;
956 }
957 }
958 }
959
960 /* GSocket_UnsetCallback:
961 * Disables all callbacks specified by 'flags', which may be a
962 * combination of flags OR'ed toghether.
963 */
964 void GSocket_UnsetCallback(GSocket *socket, GSocketEventFlags flags)
965 {
966 int count;
967
968 assert(socket != NULL);
969
970 for (count = 0; count < GSOCK_MAX_EVENT; count++)
971 {
972 if ((flags & (1 << count)) != 0)
973 {
974 socket->m_cbacks[count] = NULL;
975 socket->m_data[count] = NULL;
976 }
977 }
978 }
979
980 /* Internals (IO) */
981
982 /* _GSocket_Input_Timeout:
983 * For blocking sockets, wait until data is available or
984 * until timeout ellapses.
985 */
986 GSocketError _GSocket_Input_Timeout(GSocket *socket)
987 {
988 fd_set readfds;
989
990 if (!socket->m_non_blocking)
991 {
992 FD_ZERO(&readfds);
993 FD_SET(socket->m_fd, &readfds);
994 if (select(0, &readfds, NULL, NULL, &socket->m_timeout) == 0)
995 {
996 socket->m_error = GSOCK_TIMEDOUT;
997 return GSOCK_TIMEDOUT;
998 }
999 }
1000 return GSOCK_NOERROR;
1001 }
1002
1003 /* _GSocket_Output_Timeout:
1004 * For blocking sockets, wait until data can be sent without
1005 * blocking or until timeout ellapses.
1006 */
1007 GSocketError _GSocket_Output_Timeout(GSocket *socket)
1008 {
1009 fd_set writefds;
1010
1011 if (!socket->m_non_blocking)
1012 {
1013 FD_ZERO(&writefds);
1014 FD_SET(socket->m_fd, &writefds);
1015 if (select(0, NULL, &writefds, NULL, &socket->m_timeout) == 0)
1016 {
1017 socket->m_error = GSOCK_TIMEDOUT;
1018 return GSOCK_TIMEDOUT;
1019 }
1020 }
1021 return GSOCK_NOERROR;
1022 }
1023
1024 /* _GSocket_Connect_Timeout:
1025 * For blocking sockets, wait until the connection is
1026 * established or fails, or until timeout ellapses.
1027 */
1028 GSocketError _GSocket_Connect_Timeout(GSocket *socket)
1029 {
1030 fd_set writefds;
1031 fd_set exceptfds;
1032
1033 FD_ZERO(&writefds);
1034 FD_ZERO(&exceptfds);
1035 FD_SET(socket->m_fd, &writefds);
1036 FD_SET(socket->m_fd, &exceptfds);
1037 if (select(0, NULL, &writefds, &exceptfds, &socket->m_timeout) == 0)
1038 {
1039 socket->m_error = GSOCK_TIMEDOUT;
1040 return GSOCK_TIMEDOUT;
1041 }
1042 if (!FD_ISSET(socket->m_fd, &writefds))
1043 {
1044 socket->m_error = GSOCK_IOERR;
1045 return GSOCK_IOERR;
1046 }
1047
1048 return GSOCK_NOERROR;
1049 }
1050
1051 int _GSocket_Recv_Stream(GSocket *socket, char *buffer, int size)
1052 {
1053 return recv(socket->m_fd, buffer, size, 0);
1054 }
1055
1056 int _GSocket_Recv_Dgram(GSocket *socket, char *buffer, int size)
1057 {
1058 struct sockaddr from;
1059 SOCKLEN_T fromlen = sizeof(from);
1060 int ret;
1061 GSocketError err;
1062
1063 ret = recvfrom(socket->m_fd, buffer, size, 0, &from, &fromlen);
1064
1065 if (ret == SOCKET_ERROR)
1066 return SOCKET_ERROR;
1067
1068 /* Translate a system address into a GSocket address */
1069 if (!socket->m_peer)
1070 {
1071 socket->m_peer = GAddress_new();
1072 if (!socket->m_peer)
1073 {
1074 socket->m_error = GSOCK_MEMERR;
1075 return -1;
1076 }
1077 }
1078 err = _GAddress_translate_from(socket->m_peer, &from, fromlen);
1079 if (err != GSOCK_NOERROR)
1080 {
1081 GAddress_destroy(socket->m_peer);
1082 socket->m_peer = NULL;
1083 socket->m_error = err;
1084 return -1;
1085 }
1086
1087 return ret;
1088 }
1089
1090 int _GSocket_Send_Stream(GSocket *socket, const char *buffer, int size)
1091 {
1092 return send(socket->m_fd, buffer, size, 0);
1093 }
1094
1095 int _GSocket_Send_Dgram(GSocket *socket, const char *buffer, int size)
1096 {
1097 struct sockaddr *addr;
1098 int len, ret;
1099 GSocketError err;
1100
1101 if (!socket->m_peer)
1102 {
1103 socket->m_error = GSOCK_INVADDR;
1104 return -1;
1105 }
1106
1107 err = _GAddress_translate_to(socket->m_peer, &addr, &len);
1108 if (err != GSOCK_NOERROR)
1109 {
1110 socket->m_error = err;
1111 return -1;
1112 }
1113
1114 ret = sendto(socket->m_fd, buffer, size, 0, addr, len);
1115
1116 /* Frees memory allocated by _GAddress_translate_to */
1117 free(addr);
1118
1119 return ret;
1120 }
1121
1122
1123 /*
1124 * -------------------------------------------------------------------------
1125 * GAddress
1126 * -------------------------------------------------------------------------
1127 */
1128
1129 /* CHECK_ADDRESS verifies that the current address family is either
1130 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1131 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1132 * an appropiate error code.
1133 *
1134 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1135 */
1136 #define CHECK_ADDRESS(address, family) \
1137 { \
1138 if (address->m_family == GSOCK_NOFAMILY) \
1139 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1140 return address->m_error; \
1141 if (address->m_family != GSOCK_##family) \
1142 { \
1143 address->m_error = GSOCK_INVADDR; \
1144 return GSOCK_INVADDR; \
1145 } \
1146 }
1147
1148 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1149 { \
1150 if (address->m_family == GSOCK_NOFAMILY) \
1151 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1152 return retval; \
1153 if (address->m_family != GSOCK_##family) \
1154 { \
1155 address->m_error = GSOCK_INVADDR; \
1156 return retval; \
1157 } \
1158 }
1159
1160
1161 GAddress *GAddress_new(void)
1162 {
1163 GAddress *address;
1164
1165 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1166 return NULL;
1167
1168 address->m_family = GSOCK_NOFAMILY;
1169 address->m_addr = NULL;
1170 address->m_len = 0;
1171
1172 return address;
1173 }
1174
1175 GAddress *GAddress_copy(GAddress *address)
1176 {
1177 GAddress *addr2;
1178
1179 assert(address != NULL);
1180
1181 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1182 return NULL;
1183
1184 memcpy(addr2, address, sizeof(GAddress));
1185
1186 if (address->m_addr)
1187 {
1188 addr2->m_addr = (struct sockaddr *) malloc(addr2->m_len);
1189 if (addr2->m_addr == NULL)
1190 {
1191 free(addr2);
1192 return NULL;
1193 }
1194 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1195 }
1196
1197 return addr2;
1198 }
1199
1200 void GAddress_destroy(GAddress *address)
1201 {
1202 assert(address != NULL);
1203
1204 if (address->m_addr)
1205 free(address->m_addr);
1206
1207 free(address);
1208 }
1209
1210 void GAddress_SetFamily(GAddress *address, GAddressType type)
1211 {
1212 assert(address != NULL);
1213
1214 address->m_family = type;
1215 }
1216
1217 GAddressType GAddress_GetFamily(GAddress *address)
1218 {
1219 assert(address != NULL);
1220
1221 return address->m_family;
1222 }
1223
1224 GSocketError _GAddress_translate_from(GAddress *address,
1225 struct sockaddr *addr, int len)
1226 {
1227 address->m_realfamily = addr->sa_family;
1228 switch (addr->sa_family)
1229 {
1230 case AF_INET:
1231 address->m_family = GSOCK_INET;
1232 break;
1233 case AF_UNIX:
1234 address->m_family = GSOCK_UNIX;
1235 break;
1236 #ifdef AF_INET6
1237 case AF_INET6:
1238 address->m_family = GSOCK_INET6;
1239 break;
1240 #endif
1241 default:
1242 {
1243 address->m_error = GSOCK_INVOP;
1244 return GSOCK_INVOP;
1245 }
1246 }
1247
1248 if (address->m_addr)
1249 free(address->m_addr);
1250
1251 address->m_len = len;
1252 address->m_addr = (struct sockaddr *) malloc(len);
1253
1254 if (address->m_addr == NULL)
1255 {
1256 address->m_error = GSOCK_MEMERR;
1257 return GSOCK_MEMERR;
1258 }
1259 memcpy(address->m_addr, addr, len);
1260
1261 return GSOCK_NOERROR;
1262 }
1263
1264 GSocketError _GAddress_translate_to(GAddress *address,
1265 struct sockaddr **addr, int *len)
1266 {
1267 if (!address->m_addr)
1268 {
1269 address->m_error = GSOCK_INVADDR;
1270 return GSOCK_INVADDR;
1271 }
1272
1273 *len = address->m_len;
1274 *addr = (struct sockaddr *) malloc(address->m_len);
1275 if (*addr == NULL)
1276 {
1277 address->m_error = GSOCK_MEMERR;
1278 return GSOCK_MEMERR;
1279 }
1280
1281 memcpy(*addr, address->m_addr, address->m_len);
1282 return GSOCK_NOERROR;
1283 }
1284
1285 /*
1286 * -------------------------------------------------------------------------
1287 * Internet address family
1288 * -------------------------------------------------------------------------
1289 */
1290
1291 GSocketError _GAddress_Init_INET(GAddress *address)
1292 {
1293 address->m_len = sizeof(struct sockaddr_in);
1294 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1295 if (address->m_addr == NULL)
1296 {
1297 address->m_error = GSOCK_MEMERR;
1298 return GSOCK_MEMERR;
1299 }
1300
1301 address->m_family = GSOCK_INET;
1302 address->m_realfamily = PF_INET;
1303 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
1304 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
1305
1306 return GSOCK_NOERROR;
1307 }
1308
1309 GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1310 {
1311 struct hostent *he;
1312 struct in_addr *addr;
1313
1314 assert(address != NULL);
1315
1316 CHECK_ADDRESS(address, INET);
1317
1318 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1319
1320 addr->s_addr = inet_addr(hostname);
1321
1322 /* If it is a numeric host name, convert it now */
1323 if (addr->s_addr == INADDR_NONE)
1324 {
1325 struct in_addr *array_addr;
1326
1327 /* It is a real name, we solve it */
1328 if ((he = gethostbyname(hostname)) == NULL)
1329 {
1330 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1331 address->m_error = GSOCK_NOHOST;
1332 return GSOCK_NOHOST;
1333 }
1334 array_addr = (struct in_addr *) *(he->h_addr_list);
1335 addr->s_addr = array_addr[0].s_addr;
1336 }
1337 return GSOCK_NOERROR;
1338 }
1339
1340 GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1341 {
1342 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1343 }
1344
1345 GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1346 unsigned long hostaddr)
1347 {
1348 struct in_addr *addr;
1349
1350 assert(address != NULL);
1351
1352 CHECK_ADDRESS(address, INET);
1353
1354 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1355 addr->s_addr = hostaddr;
1356
1357 return GSOCK_NOERROR;
1358 }
1359
1360 GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1361 const char *protocol)
1362 {
1363 struct servent *se;
1364 struct sockaddr_in *addr;
1365
1366 assert(address != NULL);
1367 CHECK_ADDRESS(address, INET);
1368
1369 if (!port)
1370 {
1371 address->m_error = GSOCK_INVPORT;
1372 return GSOCK_INVPORT;
1373 }
1374
1375 se = getservbyname(port, protocol);
1376 if (!se)
1377 {
1378 if (isdigit(port[0]))
1379 {
1380 int port_int;
1381
1382 port_int = atoi(port);
1383 addr = (struct sockaddr_in *)address->m_addr;
1384 addr->sin_port = htons((u_short) port_int);
1385 return GSOCK_NOERROR;
1386 }
1387
1388 address->m_error = GSOCK_INVPORT;
1389 return GSOCK_INVPORT;
1390 }
1391
1392 addr = (struct sockaddr_in *)address->m_addr;
1393 addr->sin_port = se->s_port;
1394
1395 return GSOCK_NOERROR;
1396 }
1397
1398 GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
1399 {
1400 struct sockaddr_in *addr;
1401
1402 assert(address != NULL);
1403 CHECK_ADDRESS(address, INET);
1404
1405 addr = (struct sockaddr_in *)address->m_addr;
1406 addr->sin_port = htons(port);
1407
1408 return GSOCK_NOERROR;
1409 }
1410
1411 GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
1412 {
1413 struct hostent *he;
1414 char *addr_buf;
1415 struct sockaddr_in *addr;
1416
1417 assert(address != NULL);
1418 CHECK_ADDRESS(address, INET);
1419
1420 addr = (struct sockaddr_in *)address->m_addr;
1421 addr_buf = (char *)&(addr->sin_addr);
1422
1423 he = gethostbyaddr(addr_buf, sizeof(addr->sin_addr), AF_INET);
1424 if (he == NULL)
1425 {
1426 address->m_error = GSOCK_NOHOST;
1427 return GSOCK_NOHOST;
1428 }
1429
1430 strncpy(hostname, he->h_name, sbuf);
1431
1432 return GSOCK_NOERROR;
1433 }
1434
1435 unsigned long GAddress_INET_GetHostAddress(GAddress *address)
1436 {
1437 struct sockaddr_in *addr;
1438
1439 assert(address != NULL);
1440 CHECK_ADDRESS_RETVAL(address, INET, 0);
1441
1442 addr = (struct sockaddr_in *)address->m_addr;
1443
1444 return addr->sin_addr.s_addr;
1445 }
1446
1447 unsigned short GAddress_INET_GetPort(GAddress *address)
1448 {
1449 struct sockaddr_in *addr;
1450
1451 assert(address != NULL);
1452 CHECK_ADDRESS_RETVAL(address, INET, 0);
1453
1454 addr = (struct sockaddr_in *)address->m_addr;
1455 return ntohs(addr->sin_port);
1456 }
1457
1458 /*
1459 * -------------------------------------------------------------------------
1460 * Unix address family
1461 * -------------------------------------------------------------------------
1462 */
1463
1464 GSocketError _GAddress_Init_UNIX(GAddress *address)
1465 {
1466 assert (address != NULL);
1467 address->m_error = GSOCK_INVADDR;
1468 return GSOCK_INVADDR;
1469 }
1470
1471 GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *path)
1472 {
1473 #if defined(__BORLANDC__)
1474 /* prevents unused variable message in Borland */
1475 (void)path;
1476 #endif
1477 assert (address != NULL);
1478 address->m_error = GSOCK_INVADDR;
1479 return GSOCK_INVADDR;
1480 }
1481
1482 GSocketError GAddress_UNIX_GetPath(GAddress *address, char *path, size_t sbuf)
1483 {
1484 #if defined(__BORLANDC__)
1485 /* prevents unused variable message in Borland */
1486 (void)path;
1487 (void)sbuf;
1488 #endif
1489 assert (address != NULL);
1490 address->m_error = GSOCK_INVADDR;
1491 return GSOCK_INVADDR;
1492 }
1493
1494 #else /* !wxUSE_SOCKETS */
1495
1496 /*
1497 * Translation unit shouldn't be empty, so include this typedef to make the
1498 * compiler (VC++ 6.0, for example) happy
1499 */
1500 typedef void (*wxDummy)();
1501
1502 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */
1503