blob: 62c1ee377939601b1c155baac99a7645cab6fc9f [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
627 if (getaddrinfo(hostname, NULL, hints, &res) < 0) {
628 return _fix_errno();
629 }
630
631 ret = sock_address_from_bsd( a, res->ai_addr, res->ai_addrlen );
632 freeaddrinfo(res);
633
634 /* need to set the port */
635 switch (a->family) {
636 case SOCKET_INET: a->u.inet.port = port; break;
637 case SOCKET_IN6: a->u.in6.port = port; break;
638 default: ;
639 }
640
641 return ret;
642}
643
644
645int
646socket_create( SocketFamily family, SocketType type )
647{
648 int ret;
649 int sfamily = socket_family_to_bsd(family);
650 int stype = socket_type_to_bsd(type);
651
652 if (sfamily < 0 || stype < 0) {
653 return _set_errno(EINVAL);
654 }
655
656 QSOCKET_CALL(ret, socket(sfamily, stype, 0));
657 if (ret < 0)
658 return _fix_errno();
659
660 return ret;
661}
662
663
664int
665socket_create_inet( SocketType type )
666{
667 return socket_create( SOCKET_INET, type );
668}
669
670#if HAVE_IN6_SOCKETS
671int
672socket_create_in6 ( SocketType type )
673{
674 return socket_create( SOCKET_IN6, type );
675}
676#endif
677
678#if HAVE_UNIX_SOCKETS
679int
680socket_create_unix( SocketType type )
681{
682 return socket_create( SOCKET_UNIX, type );
683}
684#endif
685
686int socket_can_read(int fd)
687{
688#ifdef _WIN32
689 unsigned long opt;
690
691 if (ioctlsocket(fd, FIONREAD, &opt) < 0)
692 return 0;
693
694 return opt;
695#else
696 int opt;
697
698 if (ioctl(fd, FIONREAD, &opt) < 0)
699 return 0;
700
701 return opt;
702#endif
703}
704
705#define SOCKET_CALL(cmd) \
706 int ret; \
707 QSOCKET_CALL(ret, (cmd)); \
708 if (ret < 0) \
709 return _fix_errno(); \
710 return ret; \
711
712int
713socket_send(int fd, const void* buf, int buflen)
714{
715 SOCKET_CALL(send(fd, buf, buflen, 0))
716}
717
718int
719socket_send_oob( int fd, const void* buf, int buflen )
720{
721 SOCKET_CALL(send(fd, buf, buflen, MSG_OOB));
722}
723
724int
725socket_sendto(int fd, const void* buf, int buflen, const SockAddress* to)
726{
727 struct sockaddr sa;
728 socklen_t salen;
729
730 if (sock_address_to_bsd(to, &sa, &salen) < 0)
731 return -1;
732
733 SOCKET_CALL(sendto(fd, buf, buflen, 0, &sa, salen));
734}
735
736int
737socket_recv(int fd, void* buf, int len)
738{
739 SOCKET_CALL(recv(fd, buf, len, 0));
740}
741
742int
743socket_recvfrom(int fd, void* buf, int len, SockAddress* from)
744{
745 struct sockaddr sa;
746 socklen_t salen = sizeof(sa);
747 int ret;
748
749 QSOCKET_CALL(ret,recvfrom(fd,buf,len,0,&sa,&salen));
750 if (ret < 0)
751 return _fix_errno();
752
753 if (sock_address_from_bsd(from, &sa, salen) < 0)
754 return -1;
755
756 return ret;
757}
758
759int
760socket_connect( int fd, const SockAddress* address )
761{
762 struct sockaddr addr;
763 socklen_t addrlen;
764
765 if (sock_address_to_bsd(address, &addr, &addrlen) < 0)
766 return -1;
767
768 SOCKET_CALL(connect(fd,&addr,addrlen));
769}
770
771int
772socket_bind( int fd, const SockAddress* address )
773{
774 struct sockaddr addr;
775 socklen_t addrlen;
776
777 if (sock_address_to_bsd(address, &addr, &addrlen) < 0)
778 return -1;
779
780 SOCKET_CALL(bind(fd, &addr, addrlen));
781}
782
783int
784socket_get_address( int fd, SockAddress* address )
785{
786 struct sockaddr addr;
787 socklen_t addrlen = sizeof(addr);
788 int ret;
789
790 QSOCKET_CALL(ret, getsockname(fd, &addr, &addrlen));
791 if (ret < 0)
792 return _fix_errno();
793
794 return sock_address_from_bsd(address, &addr, addrlen);
795}
796
797int
798socket_listen( int fd, int backlog )
799{
800 SOCKET_CALL(listen(fd, backlog));
801}
802
803int
804socket_accept( int fd, SockAddress* address )
805{
806 struct sockaddr addr;
807 socklen_t addrlen = sizeof(addr);
808 int ret;
809
810 QSOCKET_CALL(ret, accept(fd, &addr, &addrlen));
811 if (ret < 0)
812 return _fix_errno();
813
814 if (address) {
815 if (sock_address_from_bsd(address, &addr, addrlen) < 0) {
816 socket_close(ret);
817 return -1;
818 }
819 }
820 return ret;
821}
822
823SocketType socket_get_type(int fd)
824{
825 int opt = -1;
826 int optlen = sizeof(opt);
827 getsockopt(fd, SOL_SOCKET, SO_TYPE, (void*)&opt, (void*)&optlen );
828
829 return socket_type_from_bsd(opt);
830}
831
832int socket_set_nonblock(int fd)
833{
834#ifdef _WIN32
835 unsigned long opt = 1;
836 return ioctlsocket(fd, FIONBIO, &opt);
837#else
838 int flags = fcntl(fd, F_GETFL);
839 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
840#endif
841}
842
843int socket_set_blocking(int fd)
844{
845#ifdef _WIN32
846 unsigned long opt = 0;
847 return ioctlsocket(fd, FIONBIO, &opt);
848#else
849 int flags = fcntl(fd, F_GETFL);
850 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
851#endif
852}
853
854static int
855socket_setoption(int fd, int domain, int option, int _flag)
856{
857#ifdef _WIN32
858 DWORD flag = (DWORD) _flag;
859#else
860 int flag = _flag;
861#endif
862 return setsockopt( fd, domain, option, (const char*)&flag, sizeof(flag) );
863}
864
865
866int socket_set_xreuseaddr(int fd)
867{
868#ifdef _WIN32
869 /* on Windows, SO_REUSEADDR is used to indicate that several programs can
870 * bind to the same port. this is completely different from the Unix
871 * semantics. instead of SO_EXCLUSIVEADDR to ensure that explicitely prevent
872 * this.
873 */
874 return socket_setoption(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1);
875#else
876 return socket_setoption(fd, SOL_SOCKET, SO_REUSEADDR, 1);
877#endif
878}
879
880
881int socket_set_oobinline(int fd)
882{
883 return socket_setoption(fd, SOL_SOCKET, SO_OOBINLINE, 1);
884}
885
886
887int socket_set_nodelay(int fd)
888{
889 return socket_setoption(fd, IPPROTO_TCP, TCP_NODELAY, 1);
890}
891
892
893#ifdef _WIN32
894#include <stdlib.h>
895
896static void socket_cleanup(void)
897{
898 WSACleanup();
899}
900
901int socket_init(void)
902{
903 WSADATA Data;
904 int ret, err;
905
906 ret = WSAStartup(MAKEWORD(2,2), &Data);
907 if (ret != 0) {
908 err = WSAGetLastError();
909 return -1;
910 }
911 atexit(socket_cleanup);
912 return 0;
913}
914
915#else /* !_WIN32 */
916
917int socket_init(void)
918{
919 return 0; /* nothing to do on Unix */
920}
921
922#endif /* !_WIN32 */
923
924#ifdef _WIN32
925
926static void
927socket_close_handler( void* _fd )
928{
929 int fd = (int)_fd;
930 int ret;
931 char buff[64];
932
933 /* we want to drain the read side of the socket before closing it */
934 do {
935 ret = recv( fd, buff, sizeof(buff), 0 );
936 } while (ret < 0 && WSAGetLastError() == WSAEINTR);
937
938 if (ret < 0 && WSAGetLastError() == EWOULDBLOCK)
939 return;
940
941 qemu_set_fd_handler( fd, NULL, NULL, NULL );
942 closesocket( fd );
943}
944
945void
946socket_close( int fd )
947{
948 int old_errno = errno;
949
950 shutdown( fd, SD_BOTH );
951 /* we want to drain the socket before closing it */
952 qemu_set_fd_handler( fd, socket_close_handler, NULL, (void*)fd );
953
954 errno = old_errno;
955}
956
957#else /* !_WIN32 */
958
959#include <unistd.h>
960
961void
962socket_close( int fd )
963{
964 int old_errno = errno;
965
966 shutdown( fd, SHUT_RDWR );
967 close( fd );
968
969 errno = old_errno;
970}
971
972#endif /* !_WIN32 */
973
974
975static int
976socket_bind_server( int s, const SockAddress* to, SocketType type )
977{
978 socket_set_xreuseaddr(s);
979
980 if (socket_bind(s, to) < 0) {
981 dprint("could not bind server socket address %s: %s",
982 sock_address_to_string(to), errno_str);
983 goto FAIL;
984 }
985
986 if (type == SOCKET_STREAM) {
987 if (socket_listen(s, 4) < 0) {
988 dprint("could not listen server socket %s: %s",
989 sock_address_to_string(to), errno_str);
990 goto FAIL;
991 }
992 }
993 return s;
994
995FAIL:
996 socket_close(s);
997 return -1;
998}
999
1000
1001static int
1002socket_connect_client( int s, const SockAddress* to )
1003{
1004 if (socket_connect(s, to) < 0) {
1005 dprint( "could not connect client socket to %s: %s\n",
1006 sock_address_to_string(to), errno_str );
1007 socket_close(s);
1008 return -1;
1009 }
1010
1011 socket_set_nonblock( s );
1012 return s;
1013}
1014
1015
1016static int
1017socket_in_server( int address, int port, SocketType type )
1018{
1019 SockAddress addr;
1020 int s;
1021
1022 sock_address_init_inet( &addr, address, port );
1023 s = socket_create_inet( type );
1024 if (s < 0)
1025 return -1;
1026
1027 return socket_bind_server( s, &addr, type );
1028}
1029
1030
1031static int
1032socket_in_client( SockAddress* to, SocketType type )
1033{
1034 int s;
1035
1036 s = socket_create_inet( type );
1037 if (s < 0) return -1;
1038
1039 return socket_connect_client( s, to );
1040}
1041
1042
1043int
1044socket_loopback_server( int port, SocketType type )
1045{
1046 return socket_in_server( SOCK_ADDRESS_INET_LOOPBACK, port, type );
1047}
1048
1049int
1050socket_loopback_client( int port, SocketType type )
1051{
1052 SockAddress addr;
1053
1054 sock_address_init_inet( &addr, SOCK_ADDRESS_INET_LOOPBACK, port );
1055 return socket_in_client( &addr, type );
1056}
1057
1058
1059int
1060socket_network_client( const char* host, int port, SocketType type )
1061{
1062 SockAddress addr;
1063
1064 if (sock_address_init_resolve( &addr, host, port, 0) < 0)
1065 return -1;
1066
1067 return socket_in_client( &addr, type );
1068}
1069
1070
1071int
1072socket_anyaddr_server( int port, SocketType type )
1073{
1074 return socket_in_server( SOCK_ADDRESS_INET_ANY, port, type );
1075}
1076
1077int
1078socket_accept_any( int server_fd )
1079{
1080 int fd;
1081
1082 QSOCKET_CALL(fd, accept( server_fd, NULL, 0 ));
1083 if (fd < 0) {
1084 dprint( "could not accept client connection from fd %d: %s",
1085 server_fd, errno_str );
1086 return -1;
1087 }
1088
1089 /* set to non-blocking */
1090 socket_set_nonblock( fd );
1091 return fd;
1092}
1093
1094
1095#if HAVE_UNIX_SOCKETS
1096
1097int
1098socket_unix_server( const char* name, SocketType type )
1099{
1100 SockAddress addr;
1101 int s, ret;
1102
1103 s = socket_create_unix( type );
1104 if (s < 0)
1105 return -1;
1106
1107 sock_address_init_unix( &addr, name );
1108
1109 do {
1110 ret = unlink( name );
1111 } while (ret < 0 && errno == EINTR);
1112
1113 ret = socket_bind_server( s, &addr, type );
1114
1115 sock_address_done( &addr );
1116 return ret;
1117}
1118
1119int
1120socket_unix_client( const char* name, SocketType type )
1121{
1122 SockAddress addr;
1123 int s, ret;
1124
1125 s = socket_create_unix(type);
1126 if (s < 0)
1127 return -1;
1128
1129 sock_address_init_unix( &addr, name );
1130
1131 ret = socket_connect_client( s, &addr );
1132
1133 sock_address_done( &addr );
1134 return ret;
1135}
1136
1137#endif /* HAVE_UNIX_SOCKETS */
1138
1139
1140
1141int
1142socket_pair(int *fd1, int *fd2)
1143{
1144#ifndef _WIN32
1145 int fds[2];
1146 int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
1147
1148 if (!ret) {
1149 socket_set_nonblock(fds[0]);
1150 socket_set_nonblock(fds[1]);
1151 *fd1 = fds[0];
1152 *fd2 = fds[1];
1153 }
1154 return ret;
1155#else /* _WIN32 */
1156 /* on Windows, select() only works with network sockets, which
1157 * means we absolutely cannot use Win32 PIPEs to implement
1158 * socket pairs with the current event loop implementation.
1159 * We're going to do like Cygwin: create a random pair
1160 * of localhost TCP sockets and connect them together
1161 */
1162 int s0, s1, s2, port;
1163 struct sockaddr_in sockin;
1164 socklen_t len;
1165
1166 /* first, create the 'server' socket.
1167 * a port number of 0 means 'any port between 1024 and 5000.
1168 * see Winsock bind() documentation for details */
1169 s0 = socket_loopback_server( 0, SOCK_STREAM );
1170 if (s0 < 0)
1171 return -1;
1172
1173 /* now connect a client socket to it, we first need to
1174 * extract the server socket's port number */
1175 len = sizeof sockin;
1176 if (getsockname(s0, (struct sockaddr*) &sockin, &len) < 0) {
1177 closesocket (s0);
1178 return -1;
1179 }
1180
1181 port = ntohs(sockin.sin_port);
1182 s2 = socket_loopback_client( port, SOCK_STREAM );
1183 if (s2 < 0) {
1184 closesocket(s0);
1185 return -1;
1186 }
1187
1188 /* we need to accept the connection on the server socket
1189 * this will create the second socket for the pair
1190 */
1191 len = sizeof sockin;
1192 s1 = accept(s0, (struct sockaddr*) &sockin, &len);
1193 if (s1 == INVALID_SOCKET) {
1194 closesocket (s0);
1195 closesocket (s2);
1196 return -1;
1197 }
1198 socket_set_nonblock(s1);
1199
1200 /* close server socket */
1201 closesocket(s0);
1202 *fd1 = s1;
1203 *fd2 = s2;
1204 return 0;
1205#endif /* _WIN32 */
1206}
1207
1208
1209
1210int
1211socket_mcast_inet_add_membership( int s, uint32_t ip )
1212{
1213 struct ip_mreq imr;
1214
1215 imr.imr_multiaddr.s_addr = htonl(ip);
1216 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1217
1218 if ( setsockopt( s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1219 (const char *)&imr,
1220 sizeof(struct ip_mreq)) < 0 )
1221 {
1222 return _fix_errno();
1223 }
1224 return 0;
1225}
1226
1227int
1228socket_mcast_inet_drop_membership( int s, uint32_t ip )
1229{
1230 struct ip_mreq imr;
1231
1232 imr.imr_multiaddr.s_addr = htonl(ip);
1233 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1234
1235 if ( setsockopt( s, IPPROTO_IP, IP_DROP_MEMBERSHIP,
1236 (const char *)&imr,
1237 sizeof(struct ip_mreq)) < 0 )
1238 {
1239 return _fix_errno();
1240 }
1241 return 0;
1242}
1243
1244int
1245socket_mcast_inet_set_loop( int s, int enabled )
1246{
1247 return socket_setoption( s, IPPROTO_IP, IP_MULTICAST_LOOP, !!enabled );
1248}
1249
1250int
1251socket_mcast_inet_set_ttl( int s, int ttl )
1252{
1253 return socket_setoption( s, IPPROTO_IP, IP_MULTICAST_TTL, ttl );
1254}
1255
1256
1257char*
1258host_name( void )
1259{
1260 static char buf[256]; /* 255 is the max host name length supported by DNS */
1261 int ret;
1262
1263 QSOCKET_CALL(ret, gethostname(buf, sizeof(buf)));
1264
1265 if (ret < 0)
1266 return "localhost";
1267 else
1268 return buf;
1269}