]> git.sesse.net Git - vlc/blob - src/network/io.c
Windows multicast bind kludge
[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             struct sockaddr_storage dumb =
164             {
165                 .ss_family = ptr->ai_addr->sa_family
166             };
167
168             bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
169         }
170         else
171 #endif
172         if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
173         {
174             int saved_errno = net_errno;
175
176             net_Close (fd);
177 #if !defined(WIN32) && !defined(UNDER_CE)
178             fd = rootwrap_bind (ptr->ai_family, ptr->ai_socktype,
179                                 ptr->ai_protocol, ptr->ai_addr,
180                                 ptr->ai_addrlen);
181             if (fd != -1)
182             {
183                 msg_Dbg (p_this, "got socket %d from rootwrap", fd);
184             }
185             else
186 #endif
187             {
188                 msg_Err (p_this, "socket bind error (%s)",
189                          net_strerror( saved_errno ) );
190                 continue;
191             }
192         }
193
194         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
195         {
196             if (net_Subscribe (p_this, fd, ptr->ai_addr, ptr->ai_addrlen))
197             {
198                 net_Close (fd);
199                 continue;
200             }
201         }
202
203         /* Listen */
204         switch (ptr->ai_socktype)
205         {
206             case SOCK_STREAM:
207             case SOCK_RDM:
208             case SOCK_SEQPACKET:
209                 if (listen (fd, INT_MAX))
210                 {
211                     msg_Err (p_this, "socket listen error (%s)",
212                             net_strerror (net_errno));
213                     net_Close (fd);
214                     continue;
215                 }
216         }
217
218         int *nsockv = (int *)realloc (sockv, (sockc + 2) * sizeof (int));
219         if (nsockv != NULL)
220         {
221             nsockv[sockc++] = fd;
222             sockv = nsockv;
223         }
224         else
225             net_Close (fd);
226     }
227
228     vlc_freeaddrinfo (res);
229
230     if (sockv != NULL)
231         sockv[sockc] = -1;
232
233     return sockv;
234 }
235
236
237 int net_ListenSingle (vlc_object_t *obj, const char *host, int port,
238                       int family, int socktype, int protocol)
239 {
240     int *fdv = net_Listen (obj, host, port, family, socktype, protocol);
241     if (fdv == NULL)
242         return -1;
243
244     for (unsigned i = 1; fdv[i] != -1; i++)
245     {
246         msg_Warn (obj, "A socket has been dropped!");
247         net_Close (fdv[i]);
248     }
249
250     int fd = fdv[0];
251     assert (fd != -1);
252
253     free (fdv);
254     return fd;
255 }
256
257
258
259 /*****************************************************************************
260  * __net_Close:
261  *****************************************************************************
262  * Close a network handle
263  *****************************************************************************/
264 void net_Close (int fd)
265 {
266 #ifdef UNDER_CE
267     CloseHandle ((HANDLE)fd);
268 #elif defined (WIN32)
269     closesocket (fd);
270 #else
271     (void)close (fd);
272 #endif
273 }
274
275
276 static ssize_t
277 net_ReadInner( vlc_object_t *restrict p_this, unsigned fdc, const int *fdv,
278                const v_socket_t *const *restrict vsv,
279                uint8_t *restrict p_buf, size_t i_buflen,
280                int wait_ms, vlc_bool_t waitall )
281 {
282     size_t i_total = 0;
283
284     while (i_buflen > 0)
285     {
286         unsigned i;
287         ssize_t n;
288 #ifdef HAVE_POLL
289         struct pollfd ufd[fdc];
290 #else
291         int maxfd = -1;
292         fd_set set;
293 #endif
294
295         int delay_ms = 500;
296         if ((wait_ms != -1) && (wait_ms < 500))
297             delay_ms = wait_ms;
298
299         if (p_this->b_die)
300         {
301             errno = EINTR;
302             goto error;
303         }
304
305 #ifdef HAVE_POLL
306         memset (ufd, 0, sizeof (ufd));
307
308         for( i = 0; i < fdc; i++ )
309         {
310             ufd[i].fd = fdv[i];
311             ufd[i].events = POLLIN;
312         }
313
314         n = poll( ufd, fdc, delay_ms );
315 #else
316         FD_ZERO (&set);
317
318         for( i = 0; i < fdc; i++ )
319         {
320 #if !defined(WIN32) && !defined(UNDER_CE)
321             if( fdv[i] >= FD_SETSIZE )
322             {
323                 /* We don't want to overflow select() fd_set */
324                 msg_Err( p_this, "select set overflow" );
325                 return -1;
326             }
327 #endif
328             FD_SET( fdv[i], &set );
329             if( fdv[i] > maxfd )
330                 maxfd = fdv[i];
331         }
332
333         n = select( maxfd + 1, &set, NULL, NULL,
334                     (wait_ms == -1) ? NULL
335                                   : &(struct timeval){ 0, delay_ms * 1000 } );
336 #endif
337         if( n == -1 )
338             goto error;
339
340         assert ((unsigned)n <= fdc);
341
342         if (n == 0) // timeout
343             continue;
344
345         for (i = 0;; i++)
346         {
347 #ifdef HAVE_POLL
348             if ((i_total > 0) && (ufd[i].revents & POLLERR))
349                 return i_total; // error will be dequeued on next run
350
351             if ((ufd[i].revents & POLLIN) == 0)
352 #else
353             if (!FD_ISSET (fdv[i], &set))
354                 continue;
355 #endif
356             fdc = 1;
357             fdv += i;
358             vsv += i;
359             break;
360         }
361
362         if( (*vsv) != NULL )
363         {
364             n = (*vsv)->pf_recv( (*vsv)->p_sys, p_buf, i_buflen );
365         }
366         else
367         {
368 #if defined(WIN32) || defined(UNDER_CE)
369             n = recv( *fdv, p_buf, i_buflen, 0 );
370 #else
371             n = read( *fdv, p_buf, i_buflen );
372 #endif
373         }
374
375         if( n == -1 )
376         {
377 #if defined(WIN32) || defined(UNDER_CE)
378             switch( WSAGetLastError() )
379             {
380                 case WSAEWOULDBLOCK:
381                 /* only happens with vs != NULL (SSL) - not really an error */
382                     continue;
383
384                 case WSAEMSGSIZE:
385                 /* For UDP only */
386                 /* On Win32, recv() fails if the datagram doesn't fit inside
387                  * the passed buffer, even though the buffer will be filled
388                  * with the first part of the datagram. */
389                     msg_Err( p_this, "Receive error: "
390                                      "Increase the mtu size (--mtu option)" );
391                     i_total += i_buflen;
392                     return i_total;
393             }
394 #else
395             if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
396                 continue;
397 #endif
398             goto error;
399         }
400
401         if (n == 0) // EOF
402             return i_total;
403
404         i_total += n;
405         p_buf += n;
406         i_buflen -= n;
407
408         if (!waitall)
409             return i_total;
410
411         if (wait_ms != -1)
412         {
413             wait_ms -= delay_ms;
414             if (wait_ms == 0)
415                 return i_total; // time's up!
416         }
417     }
418     return i_total;
419
420 error:
421     if( errno != EINTR )
422         msg_Err( p_this, "Read error: %s", net_strerror (net_errno) );
423     return i_total ? (ssize_t)i_total : -1;
424 }
425
426
427 /*****************************************************************************
428  * __net_Read:
429  *****************************************************************************
430  * Read from a network socket
431  * If b_retry is true, then we repeat until we have read the right amount of
432  * data
433  *****************************************************************************/
434 int __net_Read( vlc_object_t *restrict p_this, int fd,
435                 const v_socket_t *restrict p_vs,
436                 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
437 {
438     return net_ReadInner( p_this, 1, &(int){ fd },
439                           &(const v_socket_t *){ p_vs },
440                           p_data, i_data, -1, b_retry );
441 }
442
443
444 /*****************************************************************************
445  * __net_ReadNonBlock:
446  *****************************************************************************
447  * Read from a network socket, non blocking mode (with timeout)
448  *****************************************************************************/
449 int __net_ReadNonBlock( 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, mtime_t i_wait)
452 {
453     return net_ReadInner (p_this, 1, &(int){ fd },
454                           &(const v_socket_t *){ p_vs },
455                           p_data, i_data, i_wait / 1000, VLC_FALSE);
456 }
457
458
459 /*****************************************************************************
460  * __net_Select:
461  *****************************************************************************
462  * Read from several sockets (with timeout). Takes data from the first socket
463  * that has some.
464  *****************************************************************************/
465 int __net_Select( vlc_object_t *restrict p_this, const int *restrict pi_fd,
466                   const v_socket_t *const *restrict pp_vs,
467                   int i_fd, uint8_t *restrict p_data, int i_data,
468                   mtime_t i_wait )
469 {
470     if( pp_vs == NULL )
471     {
472         const v_socket_t *vsv[i_fd];
473         memset( vsv, 0, sizeof (vsv) );
474
475         return net_ReadInner( p_this, i_fd, pi_fd, vsv, p_data, i_data,
476                               i_wait / 1000, VLC_FALSE );
477     }
478
479     return net_ReadInner( p_this, i_fd, pi_fd, pp_vs, p_data, i_data,
480                           i_wait / 1000, VLC_FALSE );
481 }
482
483
484 /* Write exact amount requested */
485 int __net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
486                  const uint8_t *p_data, int i_data )
487 {
488     size_t i_total = 0;
489
490     while( i_data > 0 )
491     {
492         if( p_this->b_die )
493             return i_total;
494
495 #ifdef HAVE_POLL
496         struct pollfd ufd[1];
497         memset (ufd, 0, sizeof (ufd));
498         ufd[0].fd = fd;
499         ufd[0].events = POLLOUT;
500
501         int val = poll (ufd, 1, 500);
502         if ((val > 0) && (ufd[0].revents & POLLERR) && (i_total > 0))
503             return i_total; // error will be dequeued separately on next call
504 #else
505         fd_set set;
506         FD_ZERO (&set);
507
508 #if !defined(WIN32) && !defined(UNDER_CE)
509         if (fd >= FD_SETSIZE)
510         {
511             /* We don't want to overflow select() fd_set */
512             msg_Err (p_this, "select set overflow");
513             return -1;
514         }
515 #endif
516         FD_SET (fd, &set);
517
518         int val = select (fd + 1, NULL, &set, NULL,
519                           &(struct timeval){ 0, 500000 });
520 #endif
521         switch (val)
522         {
523             case -1:
524                 if (errno != EINTR)
525                 {
526                     msg_Err (p_this, "Write error: %s",
527                              net_strerror (net_errno));
528                     return i_total ? (int)i_total : -1;
529                 }
530
531             case 0:
532                 continue;
533         }
534
535         if (p_vs != NULL)
536             val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
537         else
538 #if defined(WIN32) || defined(UNDER_CE)
539             val = send (fd, p_data, i_data, 0);
540 #else
541             val = write (fd, p_data, i_data);
542 #endif
543
544         if (val == -1)
545             return i_total ? (int)i_total : -1;
546         if (val == 0)
547             return i_total;
548
549         p_data += val;
550         i_data -= val;
551         i_total += val;
552     }
553
554     return i_total;
555 }
556
557 char *__net_Gets( vlc_object_t *p_this, int fd, const v_socket_t *p_vs )
558 {
559     char *psz_line = NULL, *ptr = NULL;
560     size_t  i_line = 0, i_max = 0;
561
562
563     for( ;; )
564     {
565         if( i_line == i_max )
566         {
567             i_max += 1024;
568             psz_line = realloc( psz_line, i_max );
569             ptr = psz_line + i_line;
570         }
571
572         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
573         {
574             if( i_line == 0 )
575             {
576                 free( psz_line );
577                 return NULL;
578             }
579             break;
580         }
581
582         if ( *ptr == '\n' )
583             break;
584
585         i_line++;
586         ptr++;
587     }
588
589     *ptr-- = '\0';
590
591     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
592         *ptr = '\0';
593
594     return psz_line;
595 }
596
597 int net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
598                 const char *psz_fmt, ... )
599 {
600     int i_ret;
601     va_list args;
602     va_start( args, psz_fmt );
603     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
604     va_end( args );
605
606     return i_ret;
607 }
608
609 int __net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
610                     const char *psz_fmt, va_list args )
611 {
612     char    *psz;
613     int     i_size, i_ret;
614
615     i_size = vasprintf( &psz, psz_fmt, args );
616     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
617         ? -1 : i_size;
618     free( psz );
619
620     return i_ret;
621 }
622
623
624 /*****************************************************************************
625  * inet_pton replacement for obsolete and/or crap operating systems
626  *****************************************************************************/
627 #ifndef HAVE_INET_PTON
628 int inet_pton(int af, const char *src, void *dst)
629 {
630 # ifdef WIN32
631     /* As we already know, Microsoft always go its own way, so even if they do
632      * provide IPv6, they don't provide the API. */
633     struct sockaddr_storage addr;
634     int len = sizeof( addr );
635
636     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
637 #ifdef UNICODE
638     wchar_t *workaround_for_ill_designed_api =
639         malloc( MAX_PATH * sizeof(wchar_t) );
640     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
641     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
642 #else
643     char *workaround_for_ill_designed_api = strdup( src );
644 #endif
645
646     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
647                              (LPSOCKADDR)&addr, &len ) )
648     {
649         free( workaround_for_ill_designed_api );
650         return -1;
651     }
652     free( workaround_for_ill_designed_api );
653
654     switch( af )
655     {
656         case AF_INET6:
657             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
658             break;
659
660         case AF_INET:
661             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
662             break;
663
664         default:
665             WSASetLastError( WSAEAFNOSUPPORT );
666             return -1;
667     }
668 # else
669     /* Assume IPv6 is not supported. */
670     /* Would be safer and more simpler to use inet_aton() but it is most
671      * likely not provided either. */
672     uint32_t ipv4;
673
674     if( af != AF_INET )
675     {
676         errno = EAFNOSUPPORT;
677         return -1;
678     }
679
680     ipv4 = inet_addr( src );
681     if( ipv4 == INADDR_NONE )
682         return -1;
683
684     memcpy( dst, &ipv4, 4 );
685 # endif /* WIN32 */
686     return 0;
687 }
688 #endif /* HAVE_INET_PTON */