]> git.sesse.net Git - vlc/blob - src/network/io.c
Try to use dual-stack when needed, and warn user if it failed.
[vlc] / src / network / io.c
1 /*****************************************************************************
2  * io.c: network I/O functions
3  *****************************************************************************
4  * Copyright (C) 2004-2005 the VideoLAN team
5  * Copyright © 2005-2006 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Laurent Aimar <fenrir@videolan.org>
9  *          Rémi Denis-Courmont <rem # videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29
30 #include <vlc/vlc.h>
31
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <limits.h>
35
36 #include <errno.h>
37 #include <assert.h>
38
39 #ifdef HAVE_FCNTL_H
40 #   include <fcntl.h>
41 #endif
42 #ifdef HAVE_SYS_TIME_H
43 #    include <sys/time.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #   include <unistd.h>
47 #endif
48 #ifdef HAVE_POLL
49 #   include <poll.h>
50 #endif
51
52 #include "network.h"
53
54 #ifndef INADDR_ANY
55 #   define INADDR_ANY  0x00000000
56 #endif
57 #ifndef INADDR_NONE
58 #   define INADDR_NONE 0xFFFFFFFF
59 #endif
60
61 #if defined(WIN32) || defined(UNDER_CE)
62 # undef EAFNOSUPPORT
63 # define EAFNOSUPPORT WSAEAFNOSUPPORT
64 #endif
65
66 extern int rootwrap_bind (int family, int socktype, int protocol,
67                           const struct sockaddr *addr, size_t alen);
68
69 int net_Socket (vlc_object_t *p_this, int family, int socktype,
70                 int protocol)
71 {
72     int fd = socket (family, socktype, protocol);
73     if (fd == -1)
74     {
75         if (net_errno != EAFNOSUPPORT)
76             msg_Err (p_this, "cannot create socket: %s",
77                      net_strerror (net_errno));
78         return -1;
79     }
80
81 #if defined (WIN32) || defined (UNDER_CE)
82     ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
83 #else
84     fcntl (fd, F_SETFD, FD_CLOEXEC);
85     fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
86 #endif
87
88     setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof (int));
89
90 #ifdef IPV6_V6ONLY
91     /*
92      * Accepts only IPv6 connections on IPv6 sockets
93      * (and open an IPv4 socket later as well if needed).
94      * Only Linux and FreeBSD can map IPv4 connections on IPv6 sockets,
95      * so this allows for more uniform handling across platforms. Besides,
96      * it makes sure that IPv4 addresses will be printed as w.x.y.z rather
97      * than ::ffff:w.x.y.z
98      */
99     if (family == AF_INET6)
100         setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, &(int){ 1 }, sizeof (int));
101 #endif
102
103 #if defined (WIN32) || defined (UNDER_CE)
104 # ifndef IPV6_PROTECTION_LEVEL
105 #  warning Please update your C library headers.
106 #  define IPV6_PROTECTION_LEVEL 23
107 #  define PROTECTION_LEVEL_UNRESTRICTED 10
108 # endif
109     if (family == AF_INET6)
110         setsockopt (fd, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
111                     &(int){ PROTECTION_LEVEL_UNRESTRICTED }, sizeof (int));
112 #endif
113
114     return fd;
115 }
116
117
118 int *net_Listen (vlc_object_t *p_this, const char *psz_host,
119                  int i_port, int family, int socktype, int protocol)
120 {
121     struct addrinfo hints, *res;
122
123     memset (&hints, 0, sizeof( hints ));
124     hints.ai_family = family;
125     hints.ai_socktype = socktype;
126     hints.ai_protocol = protocol;
127     hints.ai_flags = AI_PASSIVE;
128
129     msg_Dbg (p_this, "net: listening to %s port %d", psz_host, i_port);
130
131     int i_val = vlc_getaddrinfo (p_this, psz_host, i_port, &hints, &res);
132     if (i_val)
133     {
134         msg_Err (p_this, "Cannot resolve %s port %d : %s", psz_host, i_port,
135                  vlc_gai_strerror (i_val));
136         return NULL;
137     }
138
139     int *sockv = NULL;
140     unsigned sockc = 0;
141
142     for (struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
143     {
144         int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
145                              ptr->ai_protocol);
146         if (fd == -1)
147         {
148             msg_Dbg (p_this, "socket error: %s", net_strerror (net_errno));
149             continue;
150         }
151
152         /* Bind the socket */
153 #if defined (WIN32) || defined (UNDER_CE)
154         /*
155          * Under Win32 and for multicasting, we bind to INADDR_ANY.
156          * This is of course a severe bug, since the socket would logically
157          * receive unicast traffic, and multicast traffic of groups subscribed
158          * to via other sockets.
159          */
160         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
161          && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
162         {
163             // This works for IPv4 too - don't worry!
164             struct sockaddr_in6 dumb =
165             {
166                 .sin6_family = ptr->ai_addr->sa_family,
167                 .sin6_port =  ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
168             };
169
170             bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
171         }
172         else
173 #endif
174         if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
175         {
176             int saved_errno = net_errno;
177
178             net_Close (fd);
179 #if !defined(WIN32) && !defined(UNDER_CE)
180             fd = rootwrap_bind (ptr->ai_family, ptr->ai_socktype,
181                                 ptr->ai_protocol, ptr->ai_addr,
182                                 ptr->ai_addrlen);
183             if (fd != -1)
184             {
185                 msg_Dbg (p_this, "got socket %d from rootwrap", fd);
186             }
187             else
188 #endif
189             {
190                 msg_Err (p_this, "socket bind error (%s)",
191                          net_strerror( saved_errno ) );
192                 continue;
193             }
194         }
195
196         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
197         {
198             if (net_Subscribe (p_this, fd, ptr->ai_addr, ptr->ai_addrlen))
199             {
200                 net_Close (fd);
201                 continue;
202             }
203         }
204
205         /* Listen */
206         switch (ptr->ai_socktype)
207         {
208             case SOCK_STREAM:
209             case SOCK_RDM:
210             case SOCK_SEQPACKET:
211                 if (listen (fd, INT_MAX))
212                 {
213                     msg_Err (p_this, "socket listen error (%s)",
214                             net_strerror (net_errno));
215                     net_Close (fd);
216                     continue;
217                 }
218         }
219
220         int *nsockv = (int *)realloc (sockv, (sockc + 2) * sizeof (int));
221         if (nsockv != NULL)
222         {
223             nsockv[sockc++] = fd;
224             sockv = nsockv;
225         }
226         else
227             net_Close (fd);
228     }
229
230     vlc_freeaddrinfo (res);
231
232     if (sockv != NULL)
233         sockv[sockc] = -1;
234
235     return sockv;
236 }
237
238
239 int net_ListenSingle (vlc_object_t *obj, const char *host, int port,
240                       int family, int socktype, int protocol)
241 {
242     int *fdv = net_Listen (obj, host, port, family, socktype, protocol);
243     if (fdv == NULL)
244         return -1;
245
246     for (unsigned i = 1; fdv[i] != -1; i++)
247     {
248         msg_Warn (obj, "A socket has been dropped!");
249         net_Close (fdv[i]);
250     }
251
252     int fd = fdv[0];
253     assert (fd != -1);
254
255     if (fdv[1] != -1)
256     {
257 #ifdef IPV6_V6ONLY
258         struct sockaddr_storage addr;
259         getsockname (fd, (struct sockaddr *)&addr,
260                      &(socklen_t){ sizeof (addr) });
261         if ((addr.ss_family == AF_INET6)
262          && setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, &(int){ 0 },
263                         sizeof (int)))
264 #endif
265             msg_Err (obj, "Lame IP dual-stack: IPv4 connections might fail.");
266     }
267
268     free (fdv);
269     return fd;
270 }
271
272
273
274 /*****************************************************************************
275  * __net_Close:
276  *****************************************************************************
277  * Close a network handle
278  *****************************************************************************/
279 void net_Close (int fd)
280 {
281 #ifdef UNDER_CE
282     CloseHandle ((HANDLE)fd);
283 #elif defined (WIN32)
284     closesocket (fd);
285 #else
286     (void)close (fd);
287 #endif
288 }
289
290
291 static ssize_t
292 net_ReadInner( vlc_object_t *restrict p_this, unsigned fdc, const int *fdv,
293                const v_socket_t *const *restrict vsv,
294                uint8_t *restrict p_buf, size_t i_buflen,
295                int wait_ms, vlc_bool_t waitall )
296 {
297     size_t i_total = 0;
298
299     while (i_buflen > 0)
300     {
301         unsigned i;
302         ssize_t n;
303 #ifdef HAVE_POLL
304         struct pollfd ufd[fdc];
305 #else
306         int maxfd = -1;
307         fd_set set;
308 #endif
309
310         int delay_ms = 500;
311         if ((wait_ms != -1) && (wait_ms < 500))
312             delay_ms = wait_ms;
313
314         if (p_this->b_die)
315         {
316             errno = EINTR;
317             goto error;
318         }
319
320 #ifdef HAVE_POLL
321         memset (ufd, 0, sizeof (ufd));
322
323         for( i = 0; i < fdc; i++ )
324         {
325             ufd[i].fd = fdv[i];
326             ufd[i].events = POLLIN;
327         }
328
329         n = poll( ufd, fdc, delay_ms );
330 #else
331         FD_ZERO (&set);
332
333         for( i = 0; i < fdc; i++ )
334         {
335 #if !defined(WIN32) && !defined(UNDER_CE)
336             if( fdv[i] >= FD_SETSIZE )
337             {
338                 /* We don't want to overflow select() fd_set */
339                 msg_Err( p_this, "select set overflow" );
340                 return -1;
341             }
342 #endif
343             FD_SET( fdv[i], &set );
344             if( fdv[i] > maxfd )
345                 maxfd = fdv[i];
346         }
347
348         n = select( maxfd + 1, &set, NULL, NULL,
349                     (wait_ms == -1) ? NULL
350                                   : &(struct timeval){ 0, delay_ms * 1000 } );
351 #endif
352         if( n == -1 )
353             goto error;
354
355         assert ((unsigned)n <= fdc);
356
357         if (n == 0) // timeout
358             continue;
359
360         for (i = 0;; i++)
361         {
362 #ifdef HAVE_POLL
363             if ((i_total > 0) && (ufd[i].revents & POLLERR))
364                 return i_total; // error will be dequeued on next run
365
366             if ((ufd[i].revents & POLLIN) == 0)
367 #else
368             if (!FD_ISSET (fdv[i], &set))
369                 continue;
370 #endif
371             fdc = 1;
372             fdv += i;
373             vsv += i;
374             break;
375         }
376
377         if( (*vsv) != NULL )
378         {
379             n = (*vsv)->pf_recv( (*vsv)->p_sys, p_buf, i_buflen );
380         }
381         else
382         {
383 #if defined(WIN32) || defined(UNDER_CE)
384             n = recv( *fdv, p_buf, i_buflen, 0 );
385 #else
386             n = read( *fdv, p_buf, i_buflen );
387 #endif
388         }
389
390         if( n == -1 )
391         {
392 #if defined(WIN32) || defined(UNDER_CE)
393             switch( WSAGetLastError() )
394             {
395                 case WSAEWOULDBLOCK:
396                 /* only happens with vs != NULL (SSL) - not really an error */
397                     continue;
398
399                 case WSAEMSGSIZE:
400                 /* For UDP only */
401                 /* On Win32, recv() fails if the datagram doesn't fit inside
402                  * the passed buffer, even though the buffer will be filled
403                  * with the first part of the datagram. */
404                     msg_Err( p_this, "Receive error: "
405                                      "Increase the mtu size (--mtu option)" );
406                     i_total += i_buflen;
407                     return i_total;
408             }
409 #else
410             if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
411                 continue;
412 #endif
413             goto error;
414         }
415
416         if (n == 0) // EOF
417             return i_total;
418
419         i_total += n;
420         p_buf += n;
421         i_buflen -= n;
422
423         if (!waitall)
424             return i_total;
425
426         if (wait_ms != -1)
427         {
428             wait_ms -= delay_ms;
429             if (wait_ms == 0)
430                 return i_total; // time's up!
431         }
432     }
433     return i_total;
434
435 error:
436     if( errno != EINTR )
437         msg_Err( p_this, "Read error: %s", net_strerror (net_errno) );
438     return i_total ? (ssize_t)i_total : -1;
439 }
440
441
442 /*****************************************************************************
443  * __net_Read:
444  *****************************************************************************
445  * Read from a network socket
446  * If b_retry is true, then we repeat until we have read the right amount of
447  * data
448  *****************************************************************************/
449 int __net_Read( vlc_object_t *restrict p_this, int fd,
450                 const v_socket_t *restrict p_vs,
451                 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
452 {
453     return net_ReadInner( p_this, 1, &(int){ fd },
454                           &(const v_socket_t *){ p_vs },
455                           p_data, i_data, -1, b_retry );
456 }
457
458
459 /*****************************************************************************
460  * __net_ReadNonBlock:
461  *****************************************************************************
462  * Read from a network socket, non blocking mode (with timeout)
463  *****************************************************************************/
464 int __net_ReadNonBlock( vlc_object_t *restrict p_this, int fd,
465                         const v_socket_t *restrict p_vs,
466                         uint8_t *restrict p_data, int i_data, mtime_t i_wait)
467 {
468     return net_ReadInner (p_this, 1, &(int){ fd },
469                           &(const v_socket_t *){ p_vs },
470                           p_data, i_data, i_wait / 1000, VLC_FALSE);
471 }
472
473
474 /*****************************************************************************
475  * __net_Select:
476  *****************************************************************************
477  * Read from several sockets (with timeout). Takes data from the first socket
478  * that has some.
479  *****************************************************************************/
480 int __net_Select( vlc_object_t *restrict p_this, const int *restrict pi_fd,
481                   const v_socket_t *const *restrict pp_vs,
482                   int i_fd, uint8_t *restrict p_data, int i_data,
483                   mtime_t i_wait )
484 {
485     if( pp_vs == NULL )
486     {
487         const v_socket_t *vsv[i_fd];
488         memset( vsv, 0, sizeof (vsv) );
489
490         return net_ReadInner( p_this, i_fd, pi_fd, vsv, p_data, i_data,
491                               i_wait / 1000, VLC_FALSE );
492     }
493
494     return net_ReadInner( p_this, i_fd, pi_fd, pp_vs, p_data, i_data,
495                           i_wait / 1000, VLC_FALSE );
496 }
497
498
499 /* Write exact amount requested */
500 int __net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
501                  const uint8_t *p_data, int i_data )
502 {
503     size_t i_total = 0;
504
505     while( i_data > 0 )
506     {
507         if( p_this->b_die )
508             return i_total;
509
510 #ifdef HAVE_POLL
511         struct pollfd ufd[1];
512         memset (ufd, 0, sizeof (ufd));
513         ufd[0].fd = fd;
514         ufd[0].events = POLLOUT;
515
516         int val = poll (ufd, 1, 500);
517         if ((val > 0) && (ufd[0].revents & POLLERR) && (i_total > 0))
518             return i_total; // error will be dequeued separately on next call
519 #else
520         fd_set set;
521         FD_ZERO (&set);
522
523 #if !defined(WIN32) && !defined(UNDER_CE)
524         if (fd >= FD_SETSIZE)
525         {
526             /* We don't want to overflow select() fd_set */
527             msg_Err (p_this, "select set overflow");
528             return -1;
529         }
530 #endif
531         FD_SET (fd, &set);
532
533         int val = select (fd + 1, NULL, &set, NULL,
534                           &(struct timeval){ 0, 500000 });
535 #endif
536         switch (val)
537         {
538             case -1:
539                 if (errno != EINTR)
540                 {
541                     msg_Err (p_this, "Write error: %s",
542                              net_strerror (net_errno));
543                     return i_total ? (int)i_total : -1;
544                 }
545
546             case 0:
547                 continue;
548         }
549
550         if (p_vs != NULL)
551             val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
552         else
553 #if defined(WIN32) || defined(UNDER_CE)
554             val = send (fd, p_data, i_data, 0);
555 #else
556             val = write (fd, p_data, i_data);
557 #endif
558
559         if (val == -1)
560             return i_total ? (int)i_total : -1;
561         if (val == 0)
562             return i_total;
563
564         p_data += val;
565         i_data -= val;
566         i_total += val;
567     }
568
569     return i_total;
570 }
571
572 char *__net_Gets( vlc_object_t *p_this, int fd, const v_socket_t *p_vs )
573 {
574     char *psz_line = NULL, *ptr = NULL;
575     size_t  i_line = 0, i_max = 0;
576
577
578     for( ;; )
579     {
580         if( i_line == i_max )
581         {
582             i_max += 1024;
583             psz_line = realloc( psz_line, i_max );
584             ptr = psz_line + i_line;
585         }
586
587         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
588         {
589             if( i_line == 0 )
590             {
591                 free( psz_line );
592                 return NULL;
593             }
594             break;
595         }
596
597         if ( *ptr == '\n' )
598             break;
599
600         i_line++;
601         ptr++;
602     }
603
604     *ptr-- = '\0';
605
606     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
607         *ptr = '\0';
608
609     return psz_line;
610 }
611
612 int net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
613                 const char *psz_fmt, ... )
614 {
615     int i_ret;
616     va_list args;
617     va_start( args, psz_fmt );
618     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
619     va_end( args );
620
621     return i_ret;
622 }
623
624 int __net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
625                     const char *psz_fmt, va_list args )
626 {
627     char    *psz;
628     int     i_size, i_ret;
629
630     i_size = vasprintf( &psz, psz_fmt, args );
631     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
632         ? -1 : i_size;
633     free( psz );
634
635     return i_ret;
636 }
637
638
639 /*****************************************************************************
640  * inet_pton replacement for obsolete and/or crap operating systems
641  *****************************************************************************/
642 #ifndef HAVE_INET_PTON
643 int inet_pton(int af, const char *src, void *dst)
644 {
645 # ifdef WIN32
646     /* As we already know, Microsoft always go its own way, so even if they do
647      * provide IPv6, they don't provide the API. */
648     struct sockaddr_storage addr;
649     int len = sizeof( addr );
650
651     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
652 #ifdef UNICODE
653     wchar_t *workaround_for_ill_designed_api =
654         malloc( MAX_PATH * sizeof(wchar_t) );
655     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
656     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
657 #else
658     char *workaround_for_ill_designed_api = strdup( src );
659 #endif
660
661     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
662                              (LPSOCKADDR)&addr, &len ) )
663     {
664         free( workaround_for_ill_designed_api );
665         return -1;
666     }
667     free( workaround_for_ill_designed_api );
668
669     switch( af )
670     {
671         case AF_INET6:
672             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
673             break;
674
675         case AF_INET:
676             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
677             break;
678
679         default:
680             WSASetLastError( WSAEAFNOSUPPORT );
681             return -1;
682     }
683 # else
684     /* Assume IPv6 is not supported. */
685     /* Would be safer and more simpler to use inet_aton() but it is most
686      * likely not provided either. */
687     uint32_t ipv4;
688
689     if( af != AF_INET )
690     {
691         errno = EAFNOSUPPORT;
692         return -1;
693     }
694
695     ipv4 = inet_addr( src );
696     if( ipv4 == INADDR_NONE )
697         return -1;
698
699     memcpy( dst, &ipv4, 4 );
700 # endif /* WIN32 */
701     return 0;
702 }
703 #endif /* HAVE_INET_PTON */