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