]> git.sesse.net Git - vlc/blob - src/network/io.c
libvlc_MetaRequest: increment item i_preparse_depth
[vlc] / src / network / io.c
1 /*****************************************************************************
2  * io.c: network I/O functions
3  *****************************************************************************
4  * Copyright (C) 2004-2005, 2007 VLC authors and VideoLAN
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 it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * 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_common.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 #include <fcntl.h>
45 #include <unistd.h>
46 #ifdef HAVE_POLL
47 #   include <poll.h>
48 #endif
49
50 #include <vlc_network.h>
51
52 #ifndef INADDR_ANY
53 #   define INADDR_ANY  0x00000000
54 #endif
55 #ifndef INADDR_NONE
56 #   define INADDR_NONE 0xFFFFFFFF
57 #endif
58
59 #if defined(_WIN32)
60 # undef EAFNOSUPPORT
61 # define EAFNOSUPPORT WSAEAFNOSUPPORT
62 # undef EWOULDBLOCK
63 # define EWOULDBLOCK WSAEWOULDBLOCK
64 # undef EAGAIN
65 # define EAGAIN WSAEWOULDBLOCK
66 #endif
67
68 #ifdef HAVE_LINUX_DCCP_H
69 /* TODO: use glibc instead of linux-kernel headers */
70 # include <linux/dccp.h>
71 # define SOL_DCCP 269
72 #endif
73
74 #include "libvlc.h" /* vlc_object_waitpipe */
75
76 extern int rootwrap_bind (int family, int socktype, int protocol,
77                           const struct sockaddr *addr, size_t alen);
78
79 int net_Socket (vlc_object_t *p_this, int family, int socktype,
80                 int protocol)
81 {
82     int fd = vlc_socket (family, socktype, protocol, true);
83     if (fd == -1)
84     {
85         if (net_errno != EAFNOSUPPORT)
86             msg_Err (p_this, "cannot create socket: %s",
87                      vlc_strerror_c(net_errno));
88         return -1;
89     }
90
91     setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof (int));
92
93 #ifdef IPV6_V6ONLY
94     /*
95      * Accepts only IPv6 connections on IPv6 sockets.
96      * If possible, we should open two sockets, but it is not always possible.
97      */
98     if (family == AF_INET6)
99         setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, &(int){ 1 }, sizeof (int));
100 #endif
101
102 #if defined (_WIN32)
103 # ifndef IPV6_PROTECTION_LEVEL
104 #  warning Please update your C library headers.
105 #  define IPV6_PROTECTION_LEVEL 23
106 #  define PROTECTION_LEVEL_UNRESTRICTED 10
107 # endif
108     if (family == AF_INET6)
109         setsockopt (fd, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
110                     &(int){ PROTECTION_LEVEL_UNRESTRICTED }, sizeof (int));
111 #endif
112
113 #ifdef DCCP_SOCKOPT_SERVICE
114     if (socktype == SOL_DCCP)
115     {
116         char *dccps = var_InheritString (p_this, "dccp-service");
117         if (dccps != NULL)
118         {
119             setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_SERVICE, dccps,
120                         (strlen (dccps) + 3) & ~3);
121             free (dccps);
122         }
123     }
124 #endif
125
126     return fd;
127 }
128
129
130 int *net_Listen (vlc_object_t *p_this, const char *psz_host,
131                  int i_port, int type, int protocol)
132 {
133     struct addrinfo hints = {
134         .ai_socktype = type,
135         .ai_protocol = protocol,
136         .ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_IDN,
137     }, *res;
138
139     msg_Dbg (p_this, "net: listening to %s port %d",
140              (psz_host != NULL) ? psz_host : "*", i_port);
141
142     int i_val = vlc_getaddrinfo (psz_host, i_port, &hints, &res);
143     if (i_val)
144     {
145         msg_Err (p_this, "Cannot resolve %s port %d : %s",
146                  (psz_host != NULL) ? psz_host : "", i_port,
147                  gai_strerror (i_val));
148         return NULL;
149     }
150
151     int *sockv = NULL;
152     unsigned sockc = 0;
153
154     for (struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
155     {
156         int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
157                              ptr->ai_protocol);
158         if (fd == -1)
159         {
160             msg_Dbg (p_this, "socket error: %s", vlc_strerror_c(net_errno));
161             continue;
162         }
163
164         /* Bind the socket */
165 #if defined (_WIN32)
166         /*
167          * Under Win32 and for multicasting, we bind to INADDR_ANY.
168          * This is of course a severe bug, since the socket would logically
169          * receive unicast traffic, and multicast traffic of groups subscribed
170          * to via other sockets.
171          */
172         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
173          && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
174         {
175             // This works for IPv4 too - don't worry!
176             struct sockaddr_in6 dumb =
177             {
178                 .sin6_family = ptr->ai_addr->sa_family,
179                 .sin6_port =  ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
180             };
181
182             bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
183         }
184         else
185 #endif
186         if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
187         {
188             net_Close (fd);
189 #if !defined(_WIN32)
190             fd = rootwrap_bind (ptr->ai_family, ptr->ai_socktype,
191                                 ptr->ai_protocol,
192                                 ptr->ai_addr, ptr->ai_addrlen);
193             if (fd != -1)
194             {
195                 msg_Dbg (p_this, "got socket %d from rootwrap", fd);
196             }
197             else
198 #endif
199             {
200                 msg_Err (p_this, "socket bind error: %s",
201                          vlc_strerror_c(net_errno));
202                 continue;
203             }
204         }
205
206         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
207         {
208             if (net_Subscribe (p_this, fd, ptr->ai_addr, ptr->ai_addrlen))
209             {
210                 net_Close (fd);
211                 continue;
212             }
213         }
214
215         /* Listen */
216         switch (ptr->ai_socktype)
217         {
218             case SOCK_STREAM:
219             case SOCK_RDM:
220             case SOCK_SEQPACKET:
221 #ifdef SOCK_DCCP
222             case SOCK_DCCP:
223 #endif
224                 if (listen (fd, INT_MAX))
225                 {
226                     msg_Err (p_this, "socket listen error: %s",
227                              vlc_strerror_c(net_errno));
228                     net_Close (fd);
229                     continue;
230                 }
231         }
232
233         int *nsockv = (int *)realloc (sockv, (sockc + 2) * sizeof (int));
234         if (nsockv != NULL)
235         {
236             nsockv[sockc++] = fd;
237             sockv = nsockv;
238         }
239         else
240             net_Close (fd);
241     }
242
243     freeaddrinfo (res);
244
245     if (sockv != NULL)
246         sockv[sockc] = -1;
247
248     return sockv;
249 }
250
251 #undef net_Read
252 /*****************************************************************************
253  * net_Read:
254  *****************************************************************************
255  * Reads from a network socket. Cancellation point.
256  * If waitall is true, then we repeat until we have read the right amount of
257  * data; in that case, a short count means EOF has been reached or the VLC
258  * object has been signaled.
259  *****************************************************************************/
260 ssize_t
261 net_Read (vlc_object_t *restrict p_this, int fd, const v_socket_t *vs,
262           void *restrict p_buf, size_t i_buflen, bool waitall)
263 {
264     struct pollfd ufd[2];
265
266     ufd[0].fd = fd;
267     ufd[0].events = POLLIN;
268     ufd[1].fd = vlc_object_waitpipe (p_this);
269     ufd[1].events = POLLIN;
270
271     size_t i_total = 0;
272 #if VLC_WINSTORE_APP
273     /* With winrtsock winsocks emulation library, the first call to read()
274      * before poll() starts an asynchronous transfer and returns 0.
275      * Always call poll() first.
276      *
277      * However if we have a virtual socket handler, try to read() first.
278      * See bug #8972 for details.
279      */
280     if (vs == NULL)
281         goto do_poll;
282 #endif
283     do
284     {
285         ssize_t n;
286         if (vs != NULL)
287         {
288             int canc = vlc_savecancel ();
289             n = vs->pf_recv (vs->p_sys, p_buf, i_buflen);
290             vlc_restorecancel (canc);
291         }
292         else
293         {
294 #ifdef _WIN32
295             n = recv (fd, p_buf, i_buflen, 0);
296 #else
297             n = read (fd, p_buf, i_buflen);
298 #endif
299         }
300
301         if (n < 0)
302         {
303             switch (net_errno)
304             {
305                 case EAGAIN: /* no data */
306 #if (EAGAIN != EWOULDBLOCK)
307                 case EWOULDBLOCK:
308 #endif
309                     break;
310 #ifndef _WIN32
311                 case EINTR:  /* asynchronous signal */
312                     continue;
313 #else
314                 case WSAEMSGSIZE: /* datagram too big */
315                     n = i_buflen;
316                     break;
317 #endif
318                 default:
319                     goto error;
320             }
321         }
322         else
323         if (n > 0)
324         {
325             i_total += n;
326             p_buf = (char *)p_buf + n;
327             i_buflen -= n;
328
329             if (!waitall || i_buflen == 0)
330                 break;
331         }
332         else /* n == 0 */
333             break;/* end of stream or empty packet */
334
335         if (ufd[1].fd == -1)
336         {
337             errno = EINTR;
338             return -1;
339         }
340 #if VLC_WINSTORE_APP
341 do_poll:
342 #endif
343         /* Wait for more data */
344         if (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1) < 0)
345         {
346             if (errno == EINTR)
347                 continue;
348             goto error;
349         }
350
351         if (ufd[1].revents)
352         {
353             msg_Dbg (p_this, "socket %d polling interrupted", fd);
354             errno = EINTR;
355             return -1;
356         }
357
358         assert (ufd[0].revents);
359     }
360     while (i_buflen > 0);
361
362     return i_total;
363 error:
364     msg_Err (p_this, "read error: %s", vlc_strerror_c(errno));
365     return -1;
366 }
367
368 #undef net_Write
369 /**
370  * Writes data to a file descriptor.
371  * This blocks until all data is written or an error occurs.
372  *
373  * This function is a cancellation point if p_vs is NULL.
374  * This function is not cancellation-safe if p_vs is not NULL.
375  *
376  * @return the total number of bytes written, or -1 if an error occurs
377  * before any data is written.
378  */
379 ssize_t net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
380                    const void *restrict p_data, size_t i_data )
381 {
382     size_t i_total = 0;
383     struct pollfd ufd[2] = {
384         { .fd = fd,                           .events = POLLOUT },
385         { .fd = vlc_object_waitpipe (p_this), .events = POLLIN  },
386     };
387
388     if (unlikely(ufd[1].fd == -1))
389     {
390         vlc_testcancel ();
391         return -1;
392     }
393
394     while( i_data > 0 )
395     {
396         ssize_t val;
397
398         ufd[0].revents = ufd[1].revents = 0;
399
400         if (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1) == -1)
401         {
402             if (errno == EINTR)
403                 continue;
404             msg_Err (p_this, "Polling error: %s", vlc_strerror_c(errno));
405             return -1;
406         }
407
408         if (i_total > 0)
409         {   /* If POLLHUP resp. POLLERR|POLLNVAL occurs while we have already
410              * read some data, it is important that we first return the number
411              * of bytes read, and then return 0 resp. -1 on the NEXT call. */
412             if (ufd[0].revents & (POLLHUP|POLLERR|POLLNVAL))
413                 break;
414             if (ufd[1].revents) /* VLC object signaled */
415                 break;
416         }
417         else
418         {
419             if (ufd[1].revents)
420             {
421                 errno = EINTR;
422                 goto error;
423             }
424         }
425
426         if (p_vs != NULL)
427             val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
428         else
429 #ifdef _WIN32
430             val = send (fd, p_data, i_data, 0);
431 #else
432             val = write (fd, p_data, i_data);
433 #endif
434
435         if (val == -1)
436         {
437             if (errno == EINTR)
438                 continue;
439             msg_Err (p_this, "Write error: %s", vlc_strerror_c(errno));
440             break;
441         }
442
443         p_data = (const char *)p_data + val;
444         i_data -= val;
445         i_total += val;
446     }
447
448     if (unlikely(i_data == 0))
449         vlc_testcancel (); /* corner case */
450
451     if ((i_total > 0) || (i_data == 0))
452         return i_total;
453
454 error:
455     return -1;
456 }
457
458 #undef net_Gets
459 /**
460  * Reads a line from a file descriptor.
461  * This function is not thread-safe; the same file descriptor I/O cannot be
462  * read by another thread at the same time (although it can be written to).
463  *
464  * @note This only works with stream-oriented file descriptors, not with
465  * datagram or packet-oriented ones.
466  *
467  * @return nul-terminated heap-allocated string, or NULL on I/O error.
468  */
469 char *net_Gets(vlc_object_t *obj, int fd, const v_socket_t *vs)
470 {
471     char *buf = NULL;
472     size_t bufsize = 0, buflen = 0;
473
474     for (;;)
475     {
476         if (buflen == bufsize)
477         {
478             if (unlikely(bufsize >= (1 << 16)))
479                 goto error; /* put sane buffer size limit */
480
481             char *newbuf = realloc(buf, bufsize + 1024);
482             if (unlikely(newbuf == NULL))
483                 goto error;
484             buf = newbuf;
485             bufsize += 1024;
486         }
487
488         ssize_t val = net_Read(obj, fd, vs, buf + buflen, 1, false);
489         if (val < 1)
490             goto error;
491
492         if (buf[buflen] == '\n')
493             break;
494
495         buflen++;
496     }
497
498     buf[buflen] = '\0';
499     if (buflen > 0 && buf[buflen - 1] == '\r')
500         buf[buflen - 1] = '\0';
501     return buf;
502 error:
503     free(buf);
504     return NULL;
505 }
506
507 #undef net_Printf
508 ssize_t net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
509                     const char *psz_fmt, ... )
510 {
511     int i_ret;
512     va_list args;
513     va_start( args, psz_fmt );
514     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
515     va_end( args );
516
517     return i_ret;
518 }
519
520 #undef net_vaPrintf
521 ssize_t net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
522                       const char *psz_fmt, va_list args )
523 {
524     char    *psz;
525     int      i_ret;
526
527     int i_size = vasprintf( &psz, psz_fmt, args );
528     if( i_size == -1 )
529         return -1;
530     i_ret = net_Write( p_this, fd, p_vs, psz, i_size ) < i_size
531         ? -1 : i_size;
532     free( psz );
533
534     return i_ret;
535 }