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