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