blob: 87ee5679dace6dd936ea8462422343c08acf06d2 [file] [log] [blame]
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -08001/* Copyright (C) 2007-2008 The Android Open Source Project
2**
3** This software is licensed under the terms of the GNU General Public
4** License version 2, as published by the Free Software Foundation, and
5** may be copied, distributed, and modified under those terms.
6**
7** This program is distributed in the hope that it will be useful,
8** but WITHOUT ANY WARRANTY; without even the implied warranty of
9** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10** GNU General Public License for more details.
11*/
12#include "sockets.h"
13#include "qemu-common.h"
14#include <fcntl.h>
15#include <stddef.h>
16#include "qemu_debug.h"
17#include <stdlib.h>
18#include <string.h>
19#include "android/utils/path.h"
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +020020#include "android/utils/debug.h"
21
22#define D(...) VERBOSE_PRINT(socket,__VA_ARGS__)
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -080023
24#ifdef _WIN32
25# define xxWIN32_LEAN_AND_MEAN
26# include <windows.h>
27# include <winsock2.h>
28# include <ws2tcpip.h>
29#else /* !_WIN32 */
30# include <sys/ioctl.h>
31# include <sys/socket.h>
32# include <netinet/in.h>
33# include <netinet/tcp.h>
34# include <netdb.h>
35# if HAVE_UNIX_SOCKETS
36# include <sys/un.h>
37# ifndef UNIX_PATH_MAX
38# define UNIX_PATH_MAX (sizeof(((struct sockaddr_un*)0)->sun_path)-1)
39# endif
40# endif
41#endif /* !_WIN32 */
42
43
44
45/* QSOCKET_CALL is used to deal with the fact that EINTR happens pretty
46 * easily in QEMU since we use SIGALRM to implement periodic timers
47 */
48#ifdef _WIN32
49# define QSOCKET_CALL(_ret,_cmd) \
50 do { _ret = (_cmd); } while ( _ret < 0 && WSAGetLastError() == WSAEINTR )
51#else
52# define QSOCKET_CALL(_ret,_cmd) \
53 do { _ret = (_cmd); } while ( _ret < 0 && errno == EINTR )
54#endif
55
56#ifdef _WIN32
57
58#include <errno.h>
59
60static int winsock_error;
61
62#define WINSOCK_ERRORS_LIST \
63 EE(WSA_INVALID_HANDLE,EINVAL,"invalid handle") \
64 EE(WSA_NOT_ENOUGH_MEMORY,ENOMEM,"not enough memory") \
65 EE(WSA_INVALID_PARAMETER,EINVAL,"invalid parameter") \
66 EE(WSAEINTR,EINTR,"interrupted function call") \
67 EE(WSAEALREADY,EALREADY,"operation already in progress") \
68 EE(WSAEBADF,EBADF,"bad file descriptor") \
69 EE(WSAEACCES,EACCES,"permission denied") \
70 EE(WSAEFAULT,EFAULT,"bad address") \
71 EE(WSAEINVAL,EINVAL,"invalid argument") \
72 EE(WSAEMFILE,EMFILE,"too many opened files") \
73 EE(WSAEWOULDBLOCK,EAGAIN,"resource temporarily unavailable") \
74 EE(WSAEINPROGRESS,EAGAIN,"operation now in progress") \
75 EE(WSAEALREADY,EAGAIN,"operation already in progress") \
76 EE(WSAENOTSOCK,EBADF,"socket operation not on socket") \
77 EE(WSAEDESTADDRREQ,EDESTADDRREQ,"destination address required") \
78 EE(WSAEMSGSIZE,EMSGSIZE,"message too long") \
79 EE(WSAEPROTOTYPE,EPROTOTYPE,"wrong protocol type for socket") \
80 EE(WSAENOPROTOOPT,ENOPROTOOPT,"bad protocol option") \
81 EE(WSAEADDRINUSE,EADDRINUSE,"address already in use") \
82 EE(WSAEADDRNOTAVAIL,EADDRNOTAVAIL,"cannot assign requested address") \
83 EE(WSAENETDOWN,ENETDOWN,"network is down") \
84 EE(WSAENETUNREACH,ENETUNREACH,"network unreachable") \
85 EE(WSAENETRESET,ENETRESET,"network dropped connection on reset") \
86 EE(WSAECONNABORTED,ECONNABORTED,"software caused connection abort") \
87 EE(WSAECONNRESET,ECONNRESET,"connection reset by peer") \
88 EE(WSAENOBUFS,ENOBUFS,"no buffer space available") \
89 EE(WSAEISCONN,EISCONN,"socket is already connected") \
90 EE(WSAENOTCONN,ENOTCONN,"socket is not connected") \
91 EE(WSAESHUTDOWN,ESHUTDOWN,"cannot send after socket shutdown") \
92 EE(WSAETOOMANYREFS,ETOOMANYREFS,"too many references") \
93 EE(WSAETIMEDOUT,ETIMEDOUT,"connection timed out") \
94 EE(WSAECONNREFUSED,ECONNREFUSED,"connection refused") \
95 EE(WSAELOOP,ELOOP,"cannot translate name") \
96 EE(WSAENAMETOOLONG,ENAMETOOLONG,"name too long") \
97 EE(WSAEHOSTDOWN,EHOSTDOWN,"host is down") \
98 EE(WSAEHOSTUNREACH,EHOSTUNREACH,"no route to host") \
99
100typedef struct {
101 int winsock;
102 int unix;
103 const char* string;
104} WinsockError;
105
106static const WinsockError _winsock_errors[] = {
107#define EE(w,u,s) { w, u, s },
108 WINSOCK_ERRORS_LIST
109#undef EE
110 { -1, -1, NULL }
111};
112
113/* this function reads the latest winsock error code and updates
114 * errno to a matching value. It also returns the new value of
115 * errno.
116 */
117static int
118_fix_errno( void )
119{
120 const WinsockError* werr = _winsock_errors;
121 int unix = EINVAL; /* generic error code */
122
123 for ( ; werr->string != NULL; werr++ ) {
124 if (werr->winsock == winsock_error) {
125 unix = werr->unix;
126 break;
127 }
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +0200128 }
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -0800129 errno = unix;
130 return -1;
131}
132
133static int
134_set_errno( int code )
135{
136 winsock_error = -1;
137 errno = code;
138 return -1;
139}
140
141/* this function returns a string describing the latest Winsock error */
142const char*
143_errno_str(void)
144{
145 const WinsockError* werr = _winsock_errors;
146 const char* result = "<unknown error>";
147
148 for ( ; werr->string; werr++ ) {
149 if (werr->winsock == winsock_error) {
150 result = werr->string;
151 break;
152 }
153 }
154
155 if (result == NULL)
156 result = strerror(errno);
157
158 return result;
159}
160#else
161static int
162_fix_errno( void )
163{
164 return -1;
165}
166
167static int
168_set_errno( int code )
169{
170 errno = code;
171 return -1;
172}
173#endif
174
175/* socket types */
176
177static int
178socket_family_to_bsd( SocketFamily family )
179{
180 switch (family) {
181 case SOCKET_INET: return AF_INET;
182 case SOCKET_IN6: return AF_INET6;
183#if HAVE_UNIX_SOCKETS
184 case SOCKET_UNIX: return AF_LOCAL;
185#endif
186 default: return -1;
187 }
188}
189
190static int
191socket_type_to_bsd( SocketType type )
192{
193 switch (type) {
194 case SOCKET_DGRAM: return SOCK_DGRAM;
195 case SOCKET_STREAM: return SOCK_STREAM;
196 default: return -1;
197 }
198}
199
200static SocketType
201socket_type_from_bsd( int type )
202{
203 switch (type) {
204 case SOCK_DGRAM: return SOCKET_DGRAM;
205 case SOCK_STREAM: return SOCKET_STREAM;
206 default: return (SocketType) -1;
207 }
208}
209
210#if 0
211static int
212socket_type_check( SocketType type )
213{
214 return (type == SOCKET_DGRAM || type == SOCKET_STREAM);
215}
216#endif
217
218/* socket addresses */
219
220void
221sock_address_init_inet( SockAddress* a, uint32_t ip, uint16_t port )
222{
223 a->family = SOCKET_INET;
224 a->u.inet.port = port;
225 a->u.inet.address = ip;
226}
227
228void
229sock_address_init_in6 ( SockAddress* a, const uint8_t* ip6[16], uint16_t port )
230{
231 a->family = SOCKET_IN6;
232 a->u.in6.port = port;
233 memcpy( a->u.in6.address, ip6, sizeof(a->u.in6.address) );
234}
235
236void
237sock_address_init_unix( SockAddress* a, const char* path )
238{
239 a->family = SOCKET_UNIX;
240 a->u._unix.path = strdup(path ? path : "");
241 a->u._unix.owner = 1;
242}
243
244void sock_address_done( SockAddress* a )
245{
246 if (a->family == SOCKET_UNIX && a->u._unix.owner) {
247 a->u._unix.owner = 0;
248 free((char*)a->u._unix.path);
249 }
250}
251
252static char*
253format_char( char* buf, char* end, int c )
254{
255 if (buf >= end)
256 return buf;
257 if (buf+1 == end)
258 c = 0;
259 *buf++ = (char) c;
260 return buf;
261}
262
263static char*
264format_str( char* buf, char* end, const char* str )
265{
266 int len = strlen(str);
267 int avail = end - buf;
268
269 if (len > avail)
270 len = avail;
271
272 memcpy( buf, str, len );
273 buf += len;
274
275 if (buf == end)
276 buf[-1] = 0;
277 else
278 buf[0] = 0;
279
280 return buf;
281}
282
283static char*
284format_unsigned( char* buf, char* end, unsigned val )
285{
286 char temp[16];
287 int nn;
288
289 for ( nn = 0; val != 0; nn++ ) {
290 int rem = val % 10;
291 temp[nn] = '0'+rem;
292 val /= 10;
293 }
294
295 if (nn == 0)
296 temp[nn++] = '0';
297
298 while (nn > 0)
299 buf = format_char(buf, end, temp[--nn]);
300
301 return buf;
302}
303
304static char*
305format_hex( char* buf, char* end, unsigned val, int ndigits )
306{
307 int shift = 4*ndigits;
308 static const char hex[16] = "0123456789abcdef";
309
310 while (shift >= 0) {
311 buf = format_char(buf, end, hex[(val >> shift) & 15]);
312 shift -= 4;
313 }
314 return buf;
315}
316
317static char*
318format_ip4( char* buf, char* end, uint32_t ip )
319{
320 buf = format_unsigned( buf, end, (unsigned)(ip >> 24) );
321 buf = format_char( buf, end, '.');
322 buf = format_unsigned( buf, end, (unsigned)((ip >> 16) & 255));
323 buf = format_char( buf, end, '.');
324 buf = format_unsigned( buf, end, (unsigned)((ip >> 8) & 255));
325 buf = format_char( buf, end, '.');
326 buf = format_unsigned( buf, end, (unsigned)(ip & 255));
327 return buf;
328}
329
330static char*
331format_ip6( char* buf, char* end, const uint8_t* ip6 )
332{
333 int nn;
334 for (nn = 0; nn < 8; nn++) {
335 int val = (ip6[0] << 16) | ip6[1];
336 ip6 += 2;
337 if (nn > 0)
338 buf = format_char(buf, end, ':');
339 if (val == 0)
340 continue;
341 buf = format_hex(buf, end, val, 4);
342 }
343 return buf;
344}
345
346const char*
347sock_address_to_string( const SockAddress* a )
348{
349 static char buf0[MAX_PATH];
350 char *buf = buf0, *end = buf + sizeof(buf0);
351
352 switch (a->family) {
353 case SOCKET_INET:
354 buf = format_ip4( buf, end, a->u.inet.address );
355 buf = format_char( buf, end, ':' );
356 buf = format_unsigned( buf, end, (unsigned) a->u.inet.port );
357 break;
358
359 case SOCKET_IN6:
360 buf = format_ip6( buf, end, a->u.in6.address );
361 buf = format_char( buf, end, ':' );
362 buf = format_unsigned( buf, end, (unsigned) a->u.in6.port );
363 break;
364
365 case SOCKET_UNIX:
366 buf = format_str( buf, end, a->u._unix.path );
367 break;
368
369 default:
370 return NULL;
371 }
372
373 return buf0;
374}
375
376int
377sock_address_equal( const SockAddress* a, const SockAddress* b )
378{
379 if (a->family != b->family)
380 return 0;
381
382 switch (a->family) {
383 case SOCKET_INET:
384 return (a->u.inet.address == b->u.inet.address &&
385 a->u.inet.port == b->u.inet.port);
386
387 case SOCKET_IN6:
388 return (!memcmp(a->u.in6.address, b->u.in6.address, 16) &&
389 a->u.in6.port == b->u.in6.port);
390
391 case SOCKET_UNIX:
392 return (!strcmp(a->u._unix.path, b->u._unix.path));
393
394 default:
395 return 0;
396 }
397}
398
399int
400sock_address_get_port( const SockAddress* a )
401{
402 switch (a->family) {
403 case SOCKET_INET:
404 return a->u.inet.port;
405 case SOCKET_IN6:
406 return a->u.in6.port;
407 default:
408 return -1;
409 }
410}
411
412void
413sock_address_set_port( SockAddress* a, uint16_t port )
414{
415 switch (a->family) {
416 case SOCKET_INET:
417 a->u.inet.port = port;
418 break;
419 case SOCKET_IN6:
420 a->u.in6.port = port;
421 break;
422 default:
423 ;
424 }
425}
426
427const char*
428sock_address_get_path( const SockAddress* a )
429{
430 if (a->family == SOCKET_UNIX)
431 return a->u._unix.path;
432 else
433 return NULL;
434}
435
436int
437sock_address_get_ip( const SockAddress* a )
438{
439 if (a->family == SOCKET_INET)
440 return a->u.inet.address;
441
442 return -1;
443}
444
445#if 0
446char*
447bufprint_sock_address( char* p, char* end, const SockAddress* a )
448{
449 switch (a->family) {
450 case SOCKET_INET:
451 {
452 uint32_t ip = a->u.inet.address;
453
454 return bufprint( p, end, "%d.%d.%d.%d:%d",
455 (ip >> 24) & 255, (ip >> 16) & 255,
456 (ip >> 8) & 255, ip & 255,
457 a->u.inet.port );
458 }
459 case SOCKET_IN6:
460 {
461 int nn = 0;
462 const char* column = "";
463 const uint8_t* tab = a->u.in6.address;
464 for (nn = 0; nn < 16; nn += 2) {
465 p = bufprint(p, end, "%s%04x", column, (tab[n] << 8) | tab[n+1]);
466 column = ":";
467 }
468 return bufprint(p, end, ":%d", a->u.in6.port);
469 }
470 case SOCKET_UNIX:
471 {
472 return bufprint(p, end, "%s", a->u._unix.path);
473 }
474 default:
475 return p;
476 }
477}
478#endif
479
480int
481sock_address_to_bsd( const SockAddress* a, void* paddress, size_t *psize )
482{
483 switch (a->family) {
484 case SOCKET_INET:
485 {
486 struct sockaddr_in* dst = (struct sockaddr_in*) paddress;
487
488 *psize = sizeof(*dst);
489
490 memset( paddress, 0, *psize );
491
492 dst->sin_family = AF_INET;
493 dst->sin_port = htons(a->u.inet.port);
494 dst->sin_addr.s_addr = htonl(a->u.inet.address);
495 }
496 break;
497
498#if HAVE_IN6_SOCKETS
499 case SOCKET_IN6:
500 {
501 struct sockaddr_in6* dst = (struct sockaddr_in6*) paddress;
502
503 *psize = sizeof(*dst);
504
505 memset( paddress, 0, *psize );
506
507 dst->sin6_family = AF_INET6;
508 dst->sin6_port = htons(a->u.in6.port);
509 memcpy( dst->sin6_addr.s6_addr, a->u.in6.address, 16 );
510 }
511 break;
512#endif /* HAVE_IN6_SOCKETS */
513
514#if HAVE_UNIX_SOCKETS
515 case SOCKET_UNIX:
516 {
517 int slen = strlen(a->u._unix.path);
518 struct sockaddr_un* dst = (struct sockaddr_un*) paddress;
519
520 if (slen >= UNIX_PATH_MAX)
521 return -1;
522
523 memset( paddress, 0, sizeof(*dst) );
524
525 dst->sun_family = AF_LOCAL;
526 memcpy( dst->sun_path, a->u._unix.path, slen );
527 dst->sun_path[slen] = 0;
528
529 *psize = (char*)&dst->sun_path[slen+1] - (char*)dst;
530 }
531 break;
532#endif /* HAVE_UNIX_SOCKETS */
533
534 default:
535 return _set_errno(EINVAL);
536 }
537
538 return 0;
539}
540
541int
542sock_address_to_inet( SockAddress* a, int *paddr_ip, int *paddr_port )
543{
544 struct sockaddr addr;
545 socklen_t addrlen;
546
547 if (a->family != SOCKET_INET) {
548 return _set_errno(EINVAL);
549 }
550
551 if (sock_address_to_bsd(a, &addr, &addrlen) < 0)
552 return -1;
553
554 *paddr_ip = ntohl(((struct sockaddr_in*)&addr)->sin_addr.s_addr);
555 *paddr_port = ntohs(((struct sockaddr_in*)&addr)->sin_port);
556
557 return 0;
558}
559
560int
561sock_address_from_bsd( SockAddress* a, const void* from, size_t fromlen )
562{
563 switch (((struct sockaddr*)from)->sa_family) {
564 case AF_INET:
565 {
566 struct sockaddr_in* src = (struct sockaddr_in*) from;
567
568 if (fromlen < sizeof(*src))
569 return _set_errno(EINVAL);
570
571 a->family = SOCKET_INET;
572 a->u.inet.port = ntohs(src->sin_port);
573 a->u.inet.address = ntohl(src->sin_addr.s_addr);
574 }
575 break;
576
577#ifdef HAVE_IN6_SOCKETS
578 case AF_INET6:
579 {
580 struct sockaddr_in6* src = (struct sockaddr_in6*) from;
581
582 if (fromlen < sizeof(*src))
583 return _set_errno(EINVAL);
584
585 a->family = SOCKET_IN6;
586 a->u.in6.port = ntohs(src->sin6_port);
587 memcpy(a->u.in6.address, src->sin6_addr.s6_addr, 16);
588 }
589 break;
590#endif
591
592#ifdef HAVE_UNIX_SOCKETS
593 case AF_LOCAL:
594 {
595 struct sockaddr_un* src = (struct sockaddr_un*) from;
596 char* end;
597
598 if (fromlen < sizeof(*src))
599 return _set_errno(EINVAL);
600
601 /* check that the path is zero-terminated */
602 end = memchr(src->sun_path, 0, UNIX_PATH_MAX);
603 if (end == NULL)
604 return _set_errno(EINVAL);
605
606 a->family = SOCKET_UNIX;
607 a->u._unix.owner = 1;
608 a->u._unix.path = strdup(src->sun_path);
609 }
610 break;
611#endif
612
613 default:
614 return _set_errno(EINVAL);
615 }
616 return 0;
617}
618
619
620int
621sock_address_init_resolve( SockAddress* a, const char* hostname, uint16_t port, int preferIn6 )
622{
623 struct addrinfo hints[1];
624 struct addrinfo* res;
625 int ret;
626
627 memset(hints, 0, sizeof(hints));
628 hints->ai_family = preferIn6 ? AF_INET6 : AF_UNSPEC;
629
David Turner669c4792009-04-13 17:58:45 -0700630 ret = getaddrinfo(hostname, NULL, hints, &res);
631 if (ret != 0) {
632 int err;
633
634 switch (ret) {
635 case EAI_AGAIN: /* server is down */
636 case EAI_FAIL: /* server is sick */
637 err = EHOSTDOWN;
638 break;
639
Nick Pellyf5be61d2009-04-24 15:28:40 -0700640#ifdef EAI_NODATA
David Turner669c4792009-04-13 17:58:45 -0700641 case EAI_NODATA:
Nick Pellyf5be61d2009-04-24 15:28:40 -0700642#endif
David Turner669c4792009-04-13 17:58:45 -0700643 case EAI_NONAME:
644 err = ENOENT;
645 break;
646
647 case EAI_MEMORY:
648 err = ENOMEM;
649 break;
650
651 default:
652 err = EINVAL;
653 }
654 return _set_errno(err);
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -0800655 }
656
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +0200657 /* Parse the returned list of addresses. */
658 {
659 struct addrinfo* res_ipv4 = NULL;
660 struct addrinfo* res_ipv6 = NULL;
661 struct addrinfo* r;
662
663 /* If preferIn6 is false, we stop on the first IPv4 address,
664 * otherwise, we stop on the first IPv6 one
665 */
666 for (r = res; r != NULL; r = r->ai_next) {
667 if (r->ai_family == AF_INET && res_ipv4 == NULL) {
668 res_ipv4 = r;
669 if (!preferIn6)
670 break;
671 }
672 else if (r->ai_family == AF_INET6 && res_ipv6 == NULL) {
673 res_ipv6 = r;
674 if (preferIn6)
675 break;
676 }
677 }
678
679 /* Select the best address in 'r', which will be NULL
680 * if there is no corresponding address.
681 */
682 if (preferIn6) {
683 r = res_ipv6;
684 if (r == NULL)
685 r = res_ipv4;
686 } else {
687 r = res_ipv4;
688 if (r == NULL)
689 r = res_ipv6;
690 }
691
692 if (r == NULL) {
693 ret = _set_errno(ENOENT);
694 goto Exit;
695 }
696
697 /* Convert to a SockAddress */
698 ret = sock_address_from_bsd( a, r->ai_addr, r->ai_addrlen );
699 if (ret < 0)
700 goto Exit;
701 }
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -0800702
703 /* need to set the port */
704 switch (a->family) {
705 case SOCKET_INET: a->u.inet.port = port; break;
706 case SOCKET_IN6: a->u.in6.port = port; break;
707 default: ;
708 }
709
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +0200710Exit:
711 freeaddrinfo(res);
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -0800712 return ret;
713}
714
715
716int
717socket_create( SocketFamily family, SocketType type )
718{
719 int ret;
720 int sfamily = socket_family_to_bsd(family);
721 int stype = socket_type_to_bsd(type);
722
723 if (sfamily < 0 || stype < 0) {
724 return _set_errno(EINVAL);
725 }
726
727 QSOCKET_CALL(ret, socket(sfamily, stype, 0));
728 if (ret < 0)
729 return _fix_errno();
730
731 return ret;
732}
733
734
735int
736socket_create_inet( SocketType type )
737{
738 return socket_create( SOCKET_INET, type );
739}
740
741#if HAVE_IN6_SOCKETS
742int
743socket_create_in6 ( SocketType type )
744{
745 return socket_create( SOCKET_IN6, type );
746}
747#endif
748
749#if HAVE_UNIX_SOCKETS
750int
751socket_create_unix( SocketType type )
752{
753 return socket_create( SOCKET_UNIX, type );
754}
755#endif
756
757int socket_can_read(int fd)
758{
759#ifdef _WIN32
760 unsigned long opt;
761
762 if (ioctlsocket(fd, FIONREAD, &opt) < 0)
763 return 0;
764
765 return opt;
766#else
767 int opt;
768
769 if (ioctl(fd, FIONREAD, &opt) < 0)
770 return 0;
771
772 return opt;
773#endif
774}
775
776#define SOCKET_CALL(cmd) \
777 int ret; \
778 QSOCKET_CALL(ret, (cmd)); \
779 if (ret < 0) \
780 return _fix_errno(); \
781 return ret; \
782
783int
784socket_send(int fd, const void* buf, int buflen)
785{
786 SOCKET_CALL(send(fd, buf, buflen, 0))
787}
788
789int
790socket_send_oob( int fd, const void* buf, int buflen )
791{
792 SOCKET_CALL(send(fd, buf, buflen, MSG_OOB));
793}
794
795int
796socket_sendto(int fd, const void* buf, int buflen, const SockAddress* to)
797{
798 struct sockaddr sa;
799 socklen_t salen;
800
801 if (sock_address_to_bsd(to, &sa, &salen) < 0)
802 return -1;
803
804 SOCKET_CALL(sendto(fd, buf, buflen, 0, &sa, salen));
805}
806
807int
808socket_recv(int fd, void* buf, int len)
809{
810 SOCKET_CALL(recv(fd, buf, len, 0));
811}
812
813int
814socket_recvfrom(int fd, void* buf, int len, SockAddress* from)
815{
816 struct sockaddr sa;
817 socklen_t salen = sizeof(sa);
818 int ret;
819
820 QSOCKET_CALL(ret,recvfrom(fd,buf,len,0,&sa,&salen));
821 if (ret < 0)
822 return _fix_errno();
823
824 if (sock_address_from_bsd(from, &sa, salen) < 0)
825 return -1;
826
827 return ret;
828}
829
830int
831socket_connect( int fd, const SockAddress* address )
832{
833 struct sockaddr addr;
834 socklen_t addrlen;
835
836 if (sock_address_to_bsd(address, &addr, &addrlen) < 0)
837 return -1;
838
839 SOCKET_CALL(connect(fd,&addr,addrlen));
840}
841
842int
843socket_bind( int fd, const SockAddress* address )
844{
845 struct sockaddr addr;
846 socklen_t addrlen;
847
848 if (sock_address_to_bsd(address, &addr, &addrlen) < 0)
849 return -1;
850
851 SOCKET_CALL(bind(fd, &addr, addrlen));
852}
853
854int
855socket_get_address( int fd, SockAddress* address )
856{
857 struct sockaddr addr;
858 socklen_t addrlen = sizeof(addr);
859 int ret;
860
861 QSOCKET_CALL(ret, getsockname(fd, &addr, &addrlen));
862 if (ret < 0)
863 return _fix_errno();
864
865 return sock_address_from_bsd(address, &addr, addrlen);
866}
867
868int
869socket_listen( int fd, int backlog )
870{
871 SOCKET_CALL(listen(fd, backlog));
872}
873
874int
875socket_accept( int fd, SockAddress* address )
876{
877 struct sockaddr addr;
878 socklen_t addrlen = sizeof(addr);
879 int ret;
880
881 QSOCKET_CALL(ret, accept(fd, &addr, &addrlen));
882 if (ret < 0)
883 return _fix_errno();
884
885 if (address) {
886 if (sock_address_from_bsd(address, &addr, addrlen) < 0) {
887 socket_close(ret);
888 return -1;
889 }
890 }
891 return ret;
892}
893
894SocketType socket_get_type(int fd)
895{
896 int opt = -1;
897 int optlen = sizeof(opt);
898 getsockopt(fd, SOL_SOCKET, SO_TYPE, (void*)&opt, (void*)&optlen );
899
900 return socket_type_from_bsd(opt);
901}
902
903int socket_set_nonblock(int fd)
904{
905#ifdef _WIN32
906 unsigned long opt = 1;
907 return ioctlsocket(fd, FIONBIO, &opt);
908#else
909 int flags = fcntl(fd, F_GETFL);
910 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
911#endif
912}
913
914int socket_set_blocking(int fd)
915{
916#ifdef _WIN32
917 unsigned long opt = 0;
918 return ioctlsocket(fd, FIONBIO, &opt);
919#else
920 int flags = fcntl(fd, F_GETFL);
921 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
922#endif
923}
924
925static int
926socket_setoption(int fd, int domain, int option, int _flag)
927{
928#ifdef _WIN32
929 DWORD flag = (DWORD) _flag;
930#else
931 int flag = _flag;
932#endif
933 return setsockopt( fd, domain, option, (const char*)&flag, sizeof(flag) );
934}
935
936
937int socket_set_xreuseaddr(int fd)
938{
939#ifdef _WIN32
940 /* on Windows, SO_REUSEADDR is used to indicate that several programs can
941 * bind to the same port. this is completely different from the Unix
942 * semantics. instead of SO_EXCLUSIVEADDR to ensure that explicitely prevent
943 * this.
944 */
945 return socket_setoption(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1);
946#else
947 return socket_setoption(fd, SOL_SOCKET, SO_REUSEADDR, 1);
948#endif
949}
950
951
952int socket_set_oobinline(int fd)
953{
954 return socket_setoption(fd, SOL_SOCKET, SO_OOBINLINE, 1);
955}
956
957
958int socket_set_nodelay(int fd)
959{
960 return socket_setoption(fd, IPPROTO_TCP, TCP_NODELAY, 1);
961}
962
963
964#ifdef _WIN32
965#include <stdlib.h>
966
967static void socket_cleanup(void)
968{
969 WSACleanup();
970}
971
972int socket_init(void)
973{
974 WSADATA Data;
975 int ret, err;
976
977 ret = WSAStartup(MAKEWORD(2,2), &Data);
978 if (ret != 0) {
979 err = WSAGetLastError();
980 return -1;
981 }
982 atexit(socket_cleanup);
983 return 0;
984}
985
986#else /* !_WIN32 */
987
988int socket_init(void)
989{
990 return 0; /* nothing to do on Unix */
991}
992
993#endif /* !_WIN32 */
994
995#ifdef _WIN32
996
997static void
998socket_close_handler( void* _fd )
999{
1000 int fd = (int)_fd;
1001 int ret;
1002 char buff[64];
1003
1004 /* we want to drain the read side of the socket before closing it */
1005 do {
1006 ret = recv( fd, buff, sizeof(buff), 0 );
1007 } while (ret < 0 && WSAGetLastError() == WSAEINTR);
1008
1009 if (ret < 0 && WSAGetLastError() == EWOULDBLOCK)
1010 return;
1011
1012 qemu_set_fd_handler( fd, NULL, NULL, NULL );
1013 closesocket( fd );
1014}
1015
1016void
1017socket_close( int fd )
1018{
1019 int old_errno = errno;
1020
1021 shutdown( fd, SD_BOTH );
1022 /* we want to drain the socket before closing it */
1023 qemu_set_fd_handler( fd, socket_close_handler, NULL, (void*)fd );
1024
1025 errno = old_errno;
1026}
1027
1028#else /* !_WIN32 */
1029
1030#include <unistd.h>
1031
1032void
1033socket_close( int fd )
1034{
1035 int old_errno = errno;
1036
1037 shutdown( fd, SHUT_RDWR );
1038 close( fd );
1039
1040 errno = old_errno;
1041}
1042
1043#endif /* !_WIN32 */
1044
1045
1046static int
1047socket_bind_server( int s, const SockAddress* to, SocketType type )
1048{
1049 socket_set_xreuseaddr(s);
1050
1051 if (socket_bind(s, to) < 0) {
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +02001052 D("could not bind server socket address %s: %s",
1053 sock_address_to_string(to), errno_str);
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -08001054 goto FAIL;
1055 }
1056
1057 if (type == SOCKET_STREAM) {
1058 if (socket_listen(s, 4) < 0) {
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +02001059 D("could not listen server socket %s: %s",
1060 sock_address_to_string(to), errno_str);
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -08001061 goto FAIL;
1062 }
1063 }
1064 return s;
1065
1066FAIL:
1067 socket_close(s);
1068 return -1;
1069}
1070
1071
1072static int
1073socket_connect_client( int s, const SockAddress* to )
1074{
1075 if (socket_connect(s, to) < 0) {
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +02001076 D( "could not connect client socket to %s: %s\n",
1077 sock_address_to_string(to), errno_str );
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -08001078 socket_close(s);
1079 return -1;
1080 }
1081
1082 socket_set_nonblock( s );
1083 return s;
1084}
1085
1086
1087static int
1088socket_in_server( int address, int port, SocketType type )
1089{
1090 SockAddress addr;
1091 int s;
1092
1093 sock_address_init_inet( &addr, address, port );
1094 s = socket_create_inet( type );
1095 if (s < 0)
1096 return -1;
1097
1098 return socket_bind_server( s, &addr, type );
1099}
1100
1101
1102static int
1103socket_in_client( SockAddress* to, SocketType type )
1104{
1105 int s;
1106
1107 s = socket_create_inet( type );
1108 if (s < 0) return -1;
1109
1110 return socket_connect_client( s, to );
1111}
1112
1113
1114int
1115socket_loopback_server( int port, SocketType type )
1116{
1117 return socket_in_server( SOCK_ADDRESS_INET_LOOPBACK, port, type );
1118}
1119
1120int
1121socket_loopback_client( int port, SocketType type )
1122{
1123 SockAddress addr;
1124
1125 sock_address_init_inet( &addr, SOCK_ADDRESS_INET_LOOPBACK, port );
1126 return socket_in_client( &addr, type );
1127}
1128
1129
1130int
1131socket_network_client( const char* host, int port, SocketType type )
1132{
1133 SockAddress addr;
1134
1135 if (sock_address_init_resolve( &addr, host, port, 0) < 0)
1136 return -1;
1137
1138 return socket_in_client( &addr, type );
1139}
1140
1141
1142int
1143socket_anyaddr_server( int port, SocketType type )
1144{
1145 return socket_in_server( SOCK_ADDRESS_INET_ANY, port, type );
1146}
1147
1148int
1149socket_accept_any( int server_fd )
1150{
1151 int fd;
1152
1153 QSOCKET_CALL(fd, accept( server_fd, NULL, 0 ));
1154 if (fd < 0) {
David 'Digit' Turner3e7a9282009-05-14 11:25:52 +02001155 D( "could not accept client connection from fd %d: %s",
1156 server_fd, errno_str );
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -08001157 return -1;
1158 }
1159
1160 /* set to non-blocking */
1161 socket_set_nonblock( fd );
1162 return fd;
1163}
1164
1165
1166#if HAVE_UNIX_SOCKETS
1167
1168int
1169socket_unix_server( const char* name, SocketType type )
1170{
1171 SockAddress addr;
1172 int s, ret;
1173
1174 s = socket_create_unix( type );
1175 if (s < 0)
1176 return -1;
1177
1178 sock_address_init_unix( &addr, name );
1179
1180 do {
1181 ret = unlink( name );
1182 } while (ret < 0 && errno == EINTR);
1183
1184 ret = socket_bind_server( s, &addr, type );
1185
1186 sock_address_done( &addr );
1187 return ret;
1188}
1189
1190int
1191socket_unix_client( const char* name, SocketType type )
1192{
1193 SockAddress addr;
1194 int s, ret;
1195
1196 s = socket_create_unix(type);
1197 if (s < 0)
1198 return -1;
1199
1200 sock_address_init_unix( &addr, name );
1201
1202 ret = socket_connect_client( s, &addr );
1203
1204 sock_address_done( &addr );
1205 return ret;
1206}
1207
1208#endif /* HAVE_UNIX_SOCKETS */
1209
1210
1211
1212int
1213socket_pair(int *fd1, int *fd2)
1214{
1215#ifndef _WIN32
1216 int fds[2];
1217 int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
1218
1219 if (!ret) {
1220 socket_set_nonblock(fds[0]);
1221 socket_set_nonblock(fds[1]);
1222 *fd1 = fds[0];
1223 *fd2 = fds[1];
1224 }
1225 return ret;
1226#else /* _WIN32 */
1227 /* on Windows, select() only works with network sockets, which
1228 * means we absolutely cannot use Win32 PIPEs to implement
1229 * socket pairs with the current event loop implementation.
1230 * We're going to do like Cygwin: create a random pair
1231 * of localhost TCP sockets and connect them together
1232 */
1233 int s0, s1, s2, port;
1234 struct sockaddr_in sockin;
1235 socklen_t len;
1236
1237 /* first, create the 'server' socket.
1238 * a port number of 0 means 'any port between 1024 and 5000.
1239 * see Winsock bind() documentation for details */
1240 s0 = socket_loopback_server( 0, SOCK_STREAM );
1241 if (s0 < 0)
1242 return -1;
1243
1244 /* now connect a client socket to it, we first need to
1245 * extract the server socket's port number */
1246 len = sizeof sockin;
1247 if (getsockname(s0, (struct sockaddr*) &sockin, &len) < 0) {
1248 closesocket (s0);
1249 return -1;
1250 }
1251
1252 port = ntohs(sockin.sin_port);
1253 s2 = socket_loopback_client( port, SOCK_STREAM );
1254 if (s2 < 0) {
1255 closesocket(s0);
1256 return -1;
1257 }
1258
1259 /* we need to accept the connection on the server socket
1260 * this will create the second socket for the pair
1261 */
1262 len = sizeof sockin;
1263 s1 = accept(s0, (struct sockaddr*) &sockin, &len);
1264 if (s1 == INVALID_SOCKET) {
1265 closesocket (s0);
1266 closesocket (s2);
1267 return -1;
1268 }
1269 socket_set_nonblock(s1);
1270
1271 /* close server socket */
1272 closesocket(s0);
1273 *fd1 = s1;
1274 *fd2 = s2;
1275 return 0;
1276#endif /* _WIN32 */
1277}
1278
1279
1280
1281int
1282socket_mcast_inet_add_membership( int s, uint32_t ip )
1283{
1284 struct ip_mreq imr;
1285
1286 imr.imr_multiaddr.s_addr = htonl(ip);
1287 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1288
1289 if ( setsockopt( s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1290 (const char *)&imr,
1291 sizeof(struct ip_mreq)) < 0 )
1292 {
1293 return _fix_errno();
1294 }
1295 return 0;
1296}
1297
1298int
1299socket_mcast_inet_drop_membership( int s, uint32_t ip )
1300{
1301 struct ip_mreq imr;
1302
1303 imr.imr_multiaddr.s_addr = htonl(ip);
1304 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1305
1306 if ( setsockopt( s, IPPROTO_IP, IP_DROP_MEMBERSHIP,
1307 (const char *)&imr,
1308 sizeof(struct ip_mreq)) < 0 )
1309 {
1310 return _fix_errno();
1311 }
1312 return 0;
1313}
1314
1315int
1316socket_mcast_inet_set_loop( int s, int enabled )
1317{
1318 return socket_setoption( s, IPPROTO_IP, IP_MULTICAST_LOOP, !!enabled );
1319}
1320
1321int
1322socket_mcast_inet_set_ttl( int s, int ttl )
1323{
1324 return socket_setoption( s, IPPROTO_IP, IP_MULTICAST_TTL, ttl );
1325}
1326
1327
1328char*
1329host_name( void )
1330{
1331 static char buf[256]; /* 255 is the max host name length supported by DNS */
1332 int ret;
1333
1334 QSOCKET_CALL(ret, gethostname(buf, sizeof(buf)));
1335
1336 if (ret < 0)
1337 return "localhost";
1338 else
1339 return buf;
1340}