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