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