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