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