]> git.saurik.com Git - wxWidgets.git/blob - src/msw/gsocket.c
Applied patch [ 850483 ] Toolbar bugfix (Mac)
[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 /* 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
763 assert(socket != NULL);
764
765 FD_ZERO(&readfds);
766 FD_ZERO(&writefds);
767 FD_ZERO(&exceptfds);
768 FD_SET(socket->m_fd, &readfds);
769 if (flags & GSOCK_OUTPUT_FLAG)
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,
788 &socket->m_timeout) <= 0)
789 {
790 /* What to do here? */
791 return (result & flags);
792 }
793
794 /* Check for readability */
795 if (FD_ISSET(socket->m_fd, &readfds))
796 {
797 char c;
798
799 if (!socket->m_stream || recv(socket->m_fd, &c, 1, MSG_PEEK) > 0)
800 {
801 result |= GSOCK_INPUT_FLAG;
802 }
803 else
804 {
805 if (socket->m_server && socket->m_stream)
806 {
807 result |= GSOCK_CONNECTION_FLAG;
808 socket->m_detected |= GSOCK_CONNECTION_FLAG;
809 }
810 else
811 {
812 socket->m_detected = GSOCK_LOST_FLAG;
813 socket->m_establishing = FALSE;
814
815 /* LOST event: Abort any further processing */
816 return (GSOCK_LOST_FLAG & flags);
817 }
818 }
819 }
820
821 /* Check for writability */
822 if (FD_ISSET(socket->m_fd, &writefds))
823 {
824 if (socket->m_establishing && !socket->m_server)
825 {
826 int error;
827 SOCKLEN_T len = sizeof(error);
828
829 socket->m_establishing = FALSE;
830
831 getsockopt(socket->m_fd, SOL_SOCKET, SO_ERROR, (void*)&error, &len);
832
833 if (error)
834 {
835 socket->m_detected = GSOCK_LOST_FLAG;
836
837 /* LOST event: Abort any further processing */
838 return (GSOCK_LOST_FLAG & flags);
839 }
840 else
841 {
842 result |= GSOCK_CONNECTION_FLAG;
843 socket->m_detected |= GSOCK_CONNECTION_FLAG;
844 }
845 }
846 else
847 {
848 result |= GSOCK_OUTPUT_FLAG;
849 }
850 }
851
852 /* Check for exceptions and errors (is this useful in Unices?) */
853 if (FD_ISSET(socket->m_fd, &exceptfds))
854 {
855 socket->m_establishing = FALSE;
856 socket->m_detected = GSOCK_LOST_FLAG;
857
858 /* LOST event: Abort any further processing */
859 return (GSOCK_LOST_FLAG & flags);
860 }
861
862 return (result & flags);
863 }
864 else /* USE_GUI() */
865 {
866 assert(socket != NULL);
867 return flags & socket->m_detected;
868 }
869 }
870
871 /* Attributes */
872
873 /* GSocket_SetNonBlocking:
874 * Sets the socket to non-blocking mode. All IO calls will return
875 * immediately.
876 */
877 void GSocket_SetNonBlocking(GSocket *socket, int non_block)
878 {
879 assert(socket != NULL);
880
881 socket->m_non_blocking = non_block;
882 }
883
884 /* GSocket_SetTimeout:
885 * Sets the timeout for blocking calls. Time is expressed in
886 * milliseconds.
887 */
888 void GSocket_SetTimeout(GSocket *socket, unsigned long millis)
889 {
890 assert(socket != NULL);
891
892 socket->m_timeout.tv_sec = (millis / 1000);
893 socket->m_timeout.tv_usec = (millis % 1000) * 1000;
894 }
895
896 /* GSocket_GetError:
897 * Returns the last error occured for this socket. Note that successful
898 * operations do not clear this back to GSOCK_NOERROR, so use it only
899 * after an error.
900 */
901 GSocketError GSocket_GetError(GSocket *socket)
902 {
903 assert(socket != NULL);
904
905 return socket->m_error;
906 }
907
908 /* Callbacks */
909
910 /* GSOCK_INPUT:
911 * There is data to be read in the input buffer. If, after a read
912 * operation, there is still data available, the callback function will
913 * be called again.
914 * GSOCK_OUTPUT:
915 * The socket is available for writing. That is, the next write call
916 * won't block. This event is generated only once, when the connection is
917 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
918 * when the output buffer empties again. This means that the app should
919 * assume that it can write since the first OUTPUT event, and no more
920 * OUTPUT events will be generated unless an error occurs.
921 * GSOCK_CONNECTION:
922 * Connection succesfully established, for client sockets, or incoming
923 * client connection, for server sockets. Wait for this event (also watch
924 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
925 * GSOCK_LOST:
926 * The connection is lost (or a connection request failed); this could
927 * be due to a failure, or due to the peer closing it gracefully.
928 */
929
930 /* GSocket_SetCallback:
931 * Enables the callbacks specified by 'flags'. Note that 'flags'
932 * may be a combination of flags OR'ed toghether, so the same
933 * callback function can be made to accept different events.
934 * The callback function must have the following prototype:
935 *
936 * void function(GSocket *socket, GSocketEvent event, char *cdata)
937 */
938 void GSocket_SetCallback(GSocket *socket, GSocketEventFlags flags,
939 GSocketCallback callback, char *cdata)
940 {
941 int count;
942
943 assert(socket != NULL);
944
945 for (count = 0; count < GSOCK_MAX_EVENT; count++)
946 {
947 if ((flags & (1 << count)) != 0)
948 {
949 socket->m_cbacks[count] = callback;
950 socket->m_data[count] = cdata;
951 }
952 }
953 }
954
955 /* GSocket_UnsetCallback:
956 * Disables all callbacks specified by 'flags', which may be a
957 * combination of flags OR'ed toghether.
958 */
959 void GSocket_UnsetCallback(GSocket *socket, GSocketEventFlags flags)
960 {
961 int count;
962
963 assert(socket != NULL);
964
965 for (count = 0; count < GSOCK_MAX_EVENT; count++)
966 {
967 if ((flags & (1 << count)) != 0)
968 {
969 socket->m_cbacks[count] = NULL;
970 socket->m_data[count] = NULL;
971 }
972 }
973 }
974
975 /* Internals (IO) */
976
977 /* _GSocket_Input_Timeout:
978 * For blocking sockets, wait until data is available or
979 * until timeout ellapses.
980 */
981 GSocketError _GSocket_Input_Timeout(GSocket *socket)
982 {
983 fd_set readfds;
984
985 if (!socket->m_non_blocking)
986 {
987 FD_ZERO(&readfds);
988 FD_SET(socket->m_fd, &readfds);
989 if (select(0, &readfds, NULL, NULL, &socket->m_timeout) == 0)
990 {
991 socket->m_error = GSOCK_TIMEDOUT;
992 return GSOCK_TIMEDOUT;
993 }
994 }
995 return GSOCK_NOERROR;
996 }
997
998 /* _GSocket_Output_Timeout:
999 * For blocking sockets, wait until data can be sent without
1000 * blocking or until timeout ellapses.
1001 */
1002 GSocketError _GSocket_Output_Timeout(GSocket *socket)
1003 {
1004 fd_set writefds;
1005
1006 if (!socket->m_non_blocking)
1007 {
1008 FD_ZERO(&writefds);
1009 FD_SET(socket->m_fd, &writefds);
1010 if (select(0, NULL, &writefds, NULL, &socket->m_timeout) == 0)
1011 {
1012 socket->m_error = GSOCK_TIMEDOUT;
1013 return GSOCK_TIMEDOUT;
1014 }
1015 }
1016 return GSOCK_NOERROR;
1017 }
1018
1019 /* _GSocket_Connect_Timeout:
1020 * For blocking sockets, wait until the connection is
1021 * established or fails, or until timeout ellapses.
1022 */
1023 GSocketError _GSocket_Connect_Timeout(GSocket *socket)
1024 {
1025 fd_set writefds;
1026 fd_set exceptfds;
1027
1028 FD_ZERO(&writefds);
1029 FD_ZERO(&exceptfds);
1030 FD_SET(socket->m_fd, &writefds);
1031 FD_SET(socket->m_fd, &exceptfds);
1032 if (select(0, NULL, &writefds, &exceptfds, &socket->m_timeout) == 0)
1033 {
1034 socket->m_error = GSOCK_TIMEDOUT;
1035 return GSOCK_TIMEDOUT;
1036 }
1037 if (!FD_ISSET(socket->m_fd, &writefds))
1038 {
1039 socket->m_error = GSOCK_IOERR;
1040 return GSOCK_IOERR;
1041 }
1042
1043 return GSOCK_NOERROR;
1044 }
1045
1046 int _GSocket_Recv_Stream(GSocket *socket, char *buffer, int size)
1047 {
1048 return recv(socket->m_fd, buffer, size, 0);
1049 }
1050
1051 int _GSocket_Recv_Dgram(GSocket *socket, char *buffer, int size)
1052 {
1053 struct sockaddr from;
1054 SOCKLEN_T fromlen = sizeof(from);
1055 int ret;
1056 GSocketError err;
1057
1058 ret = recvfrom(socket->m_fd, buffer, size, 0, &from, &fromlen);
1059
1060 if (ret == SOCKET_ERROR)
1061 return SOCKET_ERROR;
1062
1063 /* Translate a system address into a GSocket address */
1064 if (!socket->m_peer)
1065 {
1066 socket->m_peer = GAddress_new();
1067 if (!socket->m_peer)
1068 {
1069 socket->m_error = GSOCK_MEMERR;
1070 return -1;
1071 }
1072 }
1073 err = _GAddress_translate_from(socket->m_peer, &from, fromlen);
1074 if (err != GSOCK_NOERROR)
1075 {
1076 GAddress_destroy(socket->m_peer);
1077 socket->m_peer = NULL;
1078 socket->m_error = err;
1079 return -1;
1080 }
1081
1082 return ret;
1083 }
1084
1085 int _GSocket_Send_Stream(GSocket *socket, const char *buffer, int size)
1086 {
1087 return send(socket->m_fd, buffer, size, 0);
1088 }
1089
1090 int _GSocket_Send_Dgram(GSocket *socket, const char *buffer, int size)
1091 {
1092 struct sockaddr *addr;
1093 int len, ret;
1094 GSocketError err;
1095
1096 if (!socket->m_peer)
1097 {
1098 socket->m_error = GSOCK_INVADDR;
1099 return -1;
1100 }
1101
1102 err = _GAddress_translate_to(socket->m_peer, &addr, &len);
1103 if (err != GSOCK_NOERROR)
1104 {
1105 socket->m_error = err;
1106 return -1;
1107 }
1108
1109 ret = sendto(socket->m_fd, buffer, size, 0, addr, len);
1110
1111 /* Frees memory allocated by _GAddress_translate_to */
1112 free(addr);
1113
1114 return ret;
1115 }
1116
1117
1118 /*
1119 * -------------------------------------------------------------------------
1120 * GAddress
1121 * -------------------------------------------------------------------------
1122 */
1123
1124 /* CHECK_ADDRESS verifies that the current address family is either
1125 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1126 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1127 * an appropiate error code.
1128 *
1129 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1130 */
1131 #define CHECK_ADDRESS(address, family) \
1132 { \
1133 if (address->m_family == GSOCK_NOFAMILY) \
1134 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1135 return address->m_error; \
1136 if (address->m_family != GSOCK_##family) \
1137 { \
1138 address->m_error = GSOCK_INVADDR; \
1139 return GSOCK_INVADDR; \
1140 } \
1141 }
1142
1143 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1144 { \
1145 if (address->m_family == GSOCK_NOFAMILY) \
1146 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1147 return retval; \
1148 if (address->m_family != GSOCK_##family) \
1149 { \
1150 address->m_error = GSOCK_INVADDR; \
1151 return retval; \
1152 } \
1153 }
1154
1155
1156 GAddress *GAddress_new(void)
1157 {
1158 GAddress *address;
1159
1160 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1161 return NULL;
1162
1163 address->m_family = GSOCK_NOFAMILY;
1164 address->m_addr = NULL;
1165 address->m_len = 0;
1166
1167 return address;
1168 }
1169
1170 GAddress *GAddress_copy(GAddress *address)
1171 {
1172 GAddress *addr2;
1173
1174 assert(address != NULL);
1175
1176 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1177 return NULL;
1178
1179 memcpy(addr2, address, sizeof(GAddress));
1180
1181 if (address->m_addr)
1182 {
1183 addr2->m_addr = (struct sockaddr *) malloc(addr2->m_len);
1184 if (addr2->m_addr == NULL)
1185 {
1186 free(addr2);
1187 return NULL;
1188 }
1189 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1190 }
1191
1192 return addr2;
1193 }
1194
1195 void GAddress_destroy(GAddress *address)
1196 {
1197 assert(address != NULL);
1198
1199 if (address->m_addr)
1200 free(address->m_addr);
1201
1202 free(address);
1203 }
1204
1205 void GAddress_SetFamily(GAddress *address, GAddressType type)
1206 {
1207 assert(address != NULL);
1208
1209 address->m_family = type;
1210 }
1211
1212 GAddressType GAddress_GetFamily(GAddress *address)
1213 {
1214 assert(address != NULL);
1215
1216 return address->m_family;
1217 }
1218
1219 GSocketError _GAddress_translate_from(GAddress *address,
1220 struct sockaddr *addr, int len)
1221 {
1222 address->m_realfamily = addr->sa_family;
1223 switch (addr->sa_family)
1224 {
1225 case AF_INET:
1226 address->m_family = GSOCK_INET;
1227 break;
1228 case AF_UNIX:
1229 address->m_family = GSOCK_UNIX;
1230 break;
1231 #ifdef AF_INET6
1232 case AF_INET6:
1233 address->m_family = GSOCK_INET6;
1234 break;
1235 #endif
1236 default:
1237 {
1238 address->m_error = GSOCK_INVOP;
1239 return GSOCK_INVOP;
1240 }
1241 }
1242
1243 if (address->m_addr)
1244 free(address->m_addr);
1245
1246 address->m_len = len;
1247 address->m_addr = (struct sockaddr *) malloc(len);
1248
1249 if (address->m_addr == NULL)
1250 {
1251 address->m_error = GSOCK_MEMERR;
1252 return GSOCK_MEMERR;
1253 }
1254 memcpy(address->m_addr, addr, len);
1255
1256 return GSOCK_NOERROR;
1257 }
1258
1259 GSocketError _GAddress_translate_to(GAddress *address,
1260 struct sockaddr **addr, int *len)
1261 {
1262 if (!address->m_addr)
1263 {
1264 address->m_error = GSOCK_INVADDR;
1265 return GSOCK_INVADDR;
1266 }
1267
1268 *len = address->m_len;
1269 *addr = (struct sockaddr *) malloc(address->m_len);
1270 if (*addr == NULL)
1271 {
1272 address->m_error = GSOCK_MEMERR;
1273 return GSOCK_MEMERR;
1274 }
1275
1276 memcpy(*addr, address->m_addr, address->m_len);
1277 return GSOCK_NOERROR;
1278 }
1279
1280 /*
1281 * -------------------------------------------------------------------------
1282 * Internet address family
1283 * -------------------------------------------------------------------------
1284 */
1285
1286 GSocketError _GAddress_Init_INET(GAddress *address)
1287 {
1288 address->m_len = sizeof(struct sockaddr_in);
1289 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1290 if (address->m_addr == NULL)
1291 {
1292 address->m_error = GSOCK_MEMERR;
1293 return GSOCK_MEMERR;
1294 }
1295
1296 address->m_family = GSOCK_INET;
1297 address->m_realfamily = PF_INET;
1298 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
1299 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
1300
1301 return GSOCK_NOERROR;
1302 }
1303
1304 GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1305 {
1306 struct hostent *he;
1307 struct in_addr *addr;
1308
1309 assert(address != NULL);
1310
1311 CHECK_ADDRESS(address, INET);
1312
1313 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1314
1315 addr->s_addr = inet_addr(hostname);
1316
1317 /* If it is a numeric host name, convert it now */
1318 if (addr->s_addr == INADDR_NONE)
1319 {
1320 struct in_addr *array_addr;
1321
1322 /* It is a real name, we solve it */
1323 if ((he = gethostbyname(hostname)) == NULL)
1324 {
1325 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1326 address->m_error = GSOCK_NOHOST;
1327 return GSOCK_NOHOST;
1328 }
1329 array_addr = (struct in_addr *) *(he->h_addr_list);
1330 addr->s_addr = array_addr[0].s_addr;
1331 }
1332 return GSOCK_NOERROR;
1333 }
1334
1335 GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1336 {
1337 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1338 }
1339
1340 GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1341 unsigned long hostaddr)
1342 {
1343 struct in_addr *addr;
1344
1345 assert(address != NULL);
1346
1347 CHECK_ADDRESS(address, INET);
1348
1349 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1350 addr->s_addr = hostaddr;
1351
1352 return GSOCK_NOERROR;
1353 }
1354
1355 GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1356 const char *protocol)
1357 {
1358 struct servent *se;
1359 struct sockaddr_in *addr;
1360
1361 assert(address != NULL);
1362 CHECK_ADDRESS(address, INET);
1363
1364 if (!port)
1365 {
1366 address->m_error = GSOCK_INVPORT;
1367 return GSOCK_INVPORT;
1368 }
1369
1370 se = getservbyname(port, protocol);
1371 if (!se)
1372 {
1373 if (isdigit(port[0]))
1374 {
1375 int port_int;
1376
1377 port_int = atoi(port);
1378 addr = (struct sockaddr_in *)address->m_addr;
1379 addr->sin_port = htons((u_short) port_int);
1380 return GSOCK_NOERROR;
1381 }
1382
1383 address->m_error = GSOCK_INVPORT;
1384 return GSOCK_INVPORT;
1385 }
1386
1387 addr = (struct sockaddr_in *)address->m_addr;
1388 addr->sin_port = se->s_port;
1389
1390 return GSOCK_NOERROR;
1391 }
1392
1393 GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
1394 {
1395 struct sockaddr_in *addr;
1396
1397 assert(address != NULL);
1398 CHECK_ADDRESS(address, INET);
1399
1400 addr = (struct sockaddr_in *)address->m_addr;
1401 addr->sin_port = htons(port);
1402
1403 return GSOCK_NOERROR;
1404 }
1405
1406 GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
1407 {
1408 struct hostent *he;
1409 char *addr_buf;
1410 struct sockaddr_in *addr;
1411
1412 assert(address != NULL);
1413 CHECK_ADDRESS(address, INET);
1414
1415 addr = (struct sockaddr_in *)address->m_addr;
1416 addr_buf = (char *)&(addr->sin_addr);
1417
1418 he = gethostbyaddr(addr_buf, sizeof(addr->sin_addr), AF_INET);
1419 if (he == NULL)
1420 {
1421 address->m_error = GSOCK_NOHOST;
1422 return GSOCK_NOHOST;
1423 }
1424
1425 strncpy(hostname, he->h_name, sbuf);
1426
1427 return GSOCK_NOERROR;
1428 }
1429
1430 unsigned long GAddress_INET_GetHostAddress(GAddress *address)
1431 {
1432 struct sockaddr_in *addr;
1433
1434 assert(address != NULL);
1435 CHECK_ADDRESS_RETVAL(address, INET, 0);
1436
1437 addr = (struct sockaddr_in *)address->m_addr;
1438
1439 return addr->sin_addr.s_addr;
1440 }
1441
1442 unsigned short GAddress_INET_GetPort(GAddress *address)
1443 {
1444 struct sockaddr_in *addr;
1445
1446 assert(address != NULL);
1447 CHECK_ADDRESS_RETVAL(address, INET, 0);
1448
1449 addr = (struct sockaddr_in *)address->m_addr;
1450 return ntohs(addr->sin_port);
1451 }
1452
1453 /*
1454 * -------------------------------------------------------------------------
1455 * Unix address family
1456 * -------------------------------------------------------------------------
1457 */
1458
1459 GSocketError _GAddress_Init_UNIX(GAddress *address)
1460 {
1461 assert (address != NULL);
1462 address->m_error = GSOCK_INVADDR;
1463 return GSOCK_INVADDR;
1464 }
1465
1466 GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *path)
1467 {
1468 #if defined(__BORLANDC__)
1469 /* prevents unused variable message in Borland */
1470 (void)path;
1471 #endif
1472 assert (address != NULL);
1473 address->m_error = GSOCK_INVADDR;
1474 return GSOCK_INVADDR;
1475 }
1476
1477 GSocketError GAddress_UNIX_GetPath(GAddress *address, char *path, size_t sbuf)
1478 {
1479 #if defined(__BORLANDC__)
1480 /* prevents unused variable message in Borland */
1481 (void)path;
1482 (void)sbuf;
1483 #endif
1484 assert (address != NULL);
1485 address->m_error = GSOCK_INVADDR;
1486 return GSOCK_INVADDR;
1487 }
1488
1489 #else /* !wxUSE_SOCKETS */
1490
1491 /*
1492 * Translation unit shouldn't be empty, so include this typedef to make the
1493 * compiler (VC++ 6.0, for example) happy
1494 */
1495 typedef void (*wxDummy)();
1496
1497 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */
1498