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