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