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