]> git.sesse.net Git - vlc/blob - src/network/io.c
Do not assert memory allocations
[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_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 #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 #include "libvlc.h" /* vlc_object_waitpipe */
78
79 extern int rootwrap_bind (int family, int socktype, int protocol,
80                           const struct sockaddr *addr, size_t alen);
81
82 int net_SetupSocket (int fd)
83 {
84 #if defined (WIN32) || defined (UNDER_CE)
85     ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
86 #else
87     fcntl (fd, F_SETFD, FD_CLOEXEC);
88     fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
89 #endif
90
91     setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof (int));
92     return 0;
93 }
94
95
96 int net_Socket (vlc_object_t *p_this, int family, int socktype,
97                 int protocol)
98 {
99     int fd;
100
101 #ifdef SOCK_CLOEXEC
102     fd = socket (family, socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
103     if (fd == -1 && errno == EINVAL)
104 #endif
105     {
106         fd = socket (family, socktype, protocol);
107         if (fd == -1)
108         {
109             if (net_errno != EAFNOSUPPORT)
110                 msg_Err (p_this, "cannot create socket: %m");
111             return -1;
112         }
113 #ifndef WIN32
114         fcntl (fd, F_SETFD, FD_CLOEXEC);
115         fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
116 #else
117         ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
118 #endif
119     }
120
121     setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof (int));
122
123 #ifdef IPV6_V6ONLY
124     /*
125      * Accepts only IPv6 connections on IPv6 sockets.
126      * If possible, we should open two sockets, but it is not always possible.
127      */
128     if (family == AF_INET6)
129         setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, &(int){ 1 }, sizeof (int));
130 #endif
131
132 #if defined (WIN32) || defined (UNDER_CE)
133 # ifndef IPV6_PROTECTION_LEVEL
134 #  warning Please update your C library headers.
135 #  define IPV6_PROTECTION_LEVEL 23
136 #  define PROTECTION_LEVEL_UNRESTRICTED 10
137 # endif
138     if (family == AF_INET6)
139         setsockopt (fd, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
140                     &(int){ PROTECTION_LEVEL_UNRESTRICTED }, sizeof (int));
141 #endif
142
143 #ifdef DCCP_SOCKOPT_SERVICE
144     if (socktype == SOL_DCCP)
145     {
146         char *dccps = var_CreateGetNonEmptyString (p_this, "dccp-service");
147         if (dccps != NULL)
148         {
149             setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_SERVICE, dccps,
150                         (strlen (dccps) + 3) & ~3);
151             free (dccps);
152         }
153     }
154 #endif
155
156     return fd;
157 }
158
159
160 int *net_Listen (vlc_object_t *p_this, const char *psz_host,
161                  int i_port, int protocol)
162 {
163     struct addrinfo hints, *res;
164     int socktype = SOCK_DGRAM;
165
166     switch( protocol )
167     {
168         case IPPROTO_TCP:
169             socktype = SOCK_STREAM;
170             break;
171         case 33: /* DCCP */
172 #ifdef __linux__
173 # ifndef SOCK_DCCP
174 #  define SOCK_DCCP 6
175 # endif
176             socktype = SOCK_DCCP;
177 #endif
178             break;
179     }
180
181     memset (&hints, 0, sizeof( hints ));
182     /* Since we use port numbers rather than service names, the socket type
183      * does not really matter. */
184     hints.ai_socktype = SOCK_DGRAM;
185     hints.ai_flags = AI_PASSIVE;
186
187     msg_Dbg (p_this, "net: listening to %s port %d", psz_host, i_port);
188
189     int i_val = vlc_getaddrinfo (p_this, psz_host, i_port, &hints, &res);
190     if (i_val)
191     {
192         msg_Err (p_this, "Cannot resolve %s port %d : %s", psz_host, i_port,
193                  vlc_gai_strerror (i_val));
194         return NULL;
195     }
196
197     int *sockv = NULL;
198     unsigned sockc = 0;
199
200     for (struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
201     {
202         int fd = net_Socket (p_this, ptr->ai_family, socktype, protocol);
203         if (fd == -1)
204         {
205             msg_Dbg (p_this, "socket error: %m");
206             continue;
207         }
208
209         /* Bind the socket */
210 #if defined (WIN32) || defined (UNDER_CE)
211         /*
212          * Under Win32 and for multicasting, we bind to INADDR_ANY.
213          * This is of course a severe bug, since the socket would logically
214          * receive unicast traffic, and multicast traffic of groups subscribed
215          * to via other sockets.
216          */
217         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
218          && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
219         {
220             // This works for IPv4 too - don't worry!
221             struct sockaddr_in6 dumb =
222             {
223                 .sin6_family = ptr->ai_addr->sa_family,
224                 .sin6_port =  ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
225             };
226
227             bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
228         }
229         else
230 #endif
231         if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
232         {
233             net_Close (fd);
234 #if !defined(WIN32) && !defined(UNDER_CE)
235             fd = rootwrap_bind (ptr->ai_family, socktype,
236                                 protocol ? protocol : ptr->ai_protocol,
237                                 ptr->ai_addr, ptr->ai_addrlen);
238             if (fd != -1)
239             {
240                 msg_Dbg (p_this, "got socket %d from rootwrap", fd);
241             }
242             else
243 #endif
244             {
245                 msg_Err (p_this, "socket bind error (%m)");
246                 continue;
247             }
248         }
249
250         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
251         {
252             if (net_Subscribe (p_this, fd, ptr->ai_addr, ptr->ai_addrlen))
253             {
254                 net_Close (fd);
255                 continue;
256             }
257         }
258
259         /* Listen */
260         switch (socktype)
261         {
262             case SOCK_STREAM:
263             case SOCK_RDM:
264             case SOCK_SEQPACKET:
265 #ifdef SOCK_DCCP
266             case SOCK_DCCP:
267 #endif
268                 if (listen (fd, INT_MAX))
269                 {
270                     msg_Err (p_this, "socket listen error (%m)");
271                     net_Close (fd);
272                     continue;
273                 }
274         }
275
276         int *nsockv = (int *)realloc (sockv, (sockc + 2) * sizeof (int));
277         if (nsockv != NULL)
278         {
279             nsockv[sockc++] = fd;
280             sockv = nsockv;
281         }
282         else
283             net_Close (fd);
284     }
285
286     vlc_freeaddrinfo (res);
287
288     if (sockv != NULL)
289         sockv[sockc] = -1;
290
291     return sockv;
292 }
293
294
295 /*****************************************************************************
296  * __net_Read:
297  *****************************************************************************
298  * Reads from a network socket. Cancellation point.
299  * If waitall is true, then we repeat until we have read the right amount of
300  * data; in that case, a short count means EOF has been reached or the VLC
301  * object has been signaled.
302  *****************************************************************************/
303 ssize_t
304 __net_Read (vlc_object_t *restrict p_this, int fd, const v_socket_t *vs,
305             void *restrict p_buf, size_t i_buflen, bool waitall)
306 {
307     size_t i_total = 0;
308     struct pollfd ufd[2] = {
309         { .fd = fd,                           .events = POLLIN },
310         { .fd = vlc_object_waitpipe (p_this), .events = POLLIN },
311     };
312
313     if (ufd[1].fd == -1)
314         return -1; /* vlc_object_waitpipe() sets errno */
315
316     while (i_buflen > 0)
317     {
318         ufd[0].revents = ufd[1].revents = 0;
319
320         if (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1) < 0)
321         {
322             if (errno != EINTR)
323                 goto error;
324             continue;
325         }
326
327 #ifndef POLLRDHUP /* This is nice but non-portable */
328 # define POLLRDHUP 0
329 #endif
330         if (i_total > 0)
331         {
332             /* Errors (-1) and EOF (0) will be returned on next call,
333              * otherwise we'd "hide" the error from the caller, which is a
334              * bad idea™. */
335             if (ufd[0].revents & (POLLERR|POLLNVAL|POLLRDHUP))
336                 break;
337             if (ufd[1].revents)
338                 break;
339         }
340         else
341         {
342             if (ufd[1].revents)
343             {
344                 assert (p_this->b_die);
345                 msg_Dbg (p_this, "socket %d polling interrupted", fd);
346 #if defined(WIN32) || defined(UNDER_CE)
347                 WSASetLastError (WSAEINTR);
348 #else
349                 errno = EINTR;
350 #endif
351                 goto silent;
352             }
353         }
354
355         assert (ufd[0].revents);
356
357         ssize_t n;
358         if (vs != NULL)
359         {
360             int canc = vlc_savecancel ();
361             n = vs->pf_recv (vs->p_sys, p_buf, i_buflen);
362             vlc_restorecancel (canc);
363         }
364         else
365         {
366 #ifdef WIN32
367             n = recv (fd, p_buf, i_buflen, 0);
368 #else
369             n = read (fd, p_buf, i_buflen);
370 #endif
371         }
372
373         if (n == -1)
374         {
375 #if defined(WIN32) || defined(UNDER_CE)
376             switch (WSAGetLastError ())
377             {
378                 case WSAEWOULDBLOCK:
379                 /* only happens with vs != NULL (TLS) - not really an error */
380                     continue;
381
382                 case WSAEMSGSIZE:
383                 /* For UDP only */
384                 /* On Win32, recv() fails if the datagram doesn't fit inside
385                  * the passed buffer, even though the buffer will be filled
386                  * with the first part of the datagram. */
387                     msg_Err (p_this, "Receive error: "
388                                      "Increase the mtu size (--mtu option)");
389                     n = i_buflen;
390                     break;
391             }
392 #else
393             switch (errno)
394             {
395                 case EAGAIN: /* spurious wakeup or no TLS data */
396 #if (EAGAIN != EWOULDBLOCK)
397                 case EWOULDBLOCK:
398 #endif
399                 case EINTR:  /* asynchronous signal */
400                     continue;
401             }
402 #endif
403             goto error;
404         }
405
406         if (n == 0)
407             /* For streams, this means end of file, and there will not be any
408              * further data ever on the stream. For datagram sockets, this
409              * means empty datagram, and there could be more data coming.
410              * However, it makes no sense to set <waitall> with datagrams in the
411              * first place.
412              */
413             break; // EOF
414
415         i_total += n;
416         p_buf = (char *)p_buf + n;
417         i_buflen -= n;
418
419         if (!waitall)
420             break;
421     }
422
423     return i_total;
424
425 error:
426     msg_Err (p_this, "Read error: %m");
427 silent:
428     return -1;
429 }
430
431
432 /* Write exact amount requested */
433 ssize_t __net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
434                      const void *restrict p_data, size_t i_data )
435 {
436     size_t i_total = 0;
437     struct pollfd ufd[2] = {
438         { .fd = fd,                           .events = POLLOUT },
439         { .fd = vlc_object_waitpipe (p_this), .events = POLLIN  },
440     };
441
442     if (ufd[1].fd == -1)
443         return -1;
444
445     while( i_data > 0 )
446     {
447         ssize_t val;
448
449         ufd[0].revents = ufd[1].revents = 0;
450
451         if (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1) == -1)
452         {
453             if (errno == EINTR)
454                 continue;
455             msg_Err (p_this, "Polling error: %m");
456             return -1;
457         }
458
459         if (i_total > 0)
460         {   /* If POLLHUP resp. POLLERR|POLLNVAL occurs while we have already
461              * read some data, it is important that we first return the number
462              * of bytes read, and then return 0 resp. -1 on the NEXT call. */
463             if (ufd[0].revents & (POLLHUP|POLLERR|POLLNVAL))
464                 break;
465             if (ufd[1].revents) /* VLC object signaled */
466                 break;
467         }
468         else
469         {
470             if (ufd[1].revents)
471             {
472                 assert (p_this->b_die);
473                 errno = EINTR;
474                 goto error;
475             }
476         }
477
478         if (p_vs != NULL)
479             val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
480         else
481 #ifdef WIN32
482             val = send (fd, p_data, i_data, 0);
483 #else
484             val = write (fd, p_data, i_data);
485 #endif
486
487         if (val == -1)
488         {
489             if (errno == EINTR)
490                 continue;
491             msg_Err (p_this, "Write error: %m");
492             break;
493         }
494
495         p_data = (const char *)p_data + val;
496         i_data -= val;
497         i_total += val;
498     }
499
500     if ((i_total > 0) || (i_data == 0))
501         return i_total;
502
503 error:
504     return -1;
505 }
506
507 /**
508  * Reads a line from a file descriptor.
509  * This function is not thread-safe; the same file descriptor cI/O annot be read
510  * by another thread at the same time (although it can be written to).
511  *
512  * @return nul-terminated heap-allocated string, or NULL on I/O error.
513  */
514 char *__net_Gets( vlc_object_t *p_this, int fd, const v_socket_t *p_vs )
515 {
516     char *psz_line = NULL, *ptr = NULL;
517     size_t  i_line = 0, i_max = 0;
518
519
520     for( ;; )
521     {
522         if( i_line == i_max )
523         {
524             i_max += 1024;
525             psz_line = xrealloc( psz_line, i_max );
526             ptr = psz_line + i_line;
527         }
528
529         if( net_Read( p_this, fd, p_vs, ptr, 1, true ) != 1 )
530         {
531             if( i_line == 0 )
532             {
533                 free( psz_line );
534                 return NULL;
535             }
536             break;
537         }
538
539         if ( *ptr == '\n' )
540             break;
541
542         i_line++;
543         ptr++;
544     }
545
546     *ptr-- = '\0';
547
548     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
549         *ptr = '\0';
550
551     return psz_line;
552 }
553
554 ssize_t net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
555                     const char *psz_fmt, ... )
556 {
557     int i_ret;
558     va_list args;
559     va_start( args, psz_fmt );
560     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
561     va_end( args );
562
563     return i_ret;
564 }
565
566 ssize_t __net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
567                         const char *psz_fmt, va_list args )
568 {
569     char    *psz;
570     int      i_ret;
571
572     int i_size = vasprintf( &psz, psz_fmt, args );
573     if( i_size == -1 )
574         return -1;
575     i_ret = __net_Write( p_this, fd, p_vs, psz, i_size ) < i_size
576         ? -1 : i_size;
577     free( psz );
578
579     return i_ret;
580 }