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