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