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