]> git.sesse.net Git - vlc/blob - src/network/io.c
Revert "Include vlc_common.h to get VLC_UNUSED()"
[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     char *dccps = var_CreateGetNonEmptyString (p_this, "dccp-service");
129     if (dccps != NULL)
130     {
131         setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_SERVICE, dccps,
132                     (strlen (dccps) + 3) & ~3);
133         free (dccps);
134     }
135 #endif
136
137     return fd;
138 }
139
140
141 int *net_Listen (vlc_object_t *p_this, const char *psz_host,
142                  int i_port, int protocol)
143 {
144     struct addrinfo hints, *res;
145     int socktype = SOCK_DGRAM;
146
147     switch( protocol )
148     {
149         case IPPROTO_TCP:
150             socktype = SOCK_STREAM;
151             break;
152         case 33: /* DCCP */
153 #ifdef __linux__
154 # ifndef SOCK_DCCP
155 #  define SOCK_DCCP 6
156 # endif
157             socktype = SOCK_DCCP;
158 #endif
159             break;
160     }
161
162     memset (&hints, 0, sizeof( hints ));
163     /* Since we use port numbers rather than service names, the socket type
164      * does not really matter. */
165     hints.ai_socktype = SOCK_DGRAM;
166     hints.ai_flags = AI_PASSIVE;
167
168     msg_Dbg (p_this, "net: listening to %s port %d", psz_host, i_port);
169
170     int i_val = vlc_getaddrinfo (p_this, psz_host, i_port, &hints, &res);
171     if (i_val)
172     {
173         msg_Err (p_this, "Cannot resolve %s port %d : %s", psz_host, i_port,
174                  vlc_gai_strerror (i_val));
175         return NULL;
176     }
177
178     int *sockv = NULL;
179     unsigned sockc = 0;
180
181     for (struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
182     {
183         int fd = net_Socket (p_this, ptr->ai_family, socktype, protocol);
184         if (fd == -1)
185         {
186             msg_Dbg (p_this, "socket error: %m");
187             continue;
188         }
189
190         /* Bind the socket */
191 #if defined (WIN32) || defined (UNDER_CE)
192         /*
193          * Under Win32 and for multicasting, we bind to INADDR_ANY.
194          * This is of course a severe bug, since the socket would logically
195          * receive unicast traffic, and multicast traffic of groups subscribed
196          * to via other sockets.
197          */
198         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
199          && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
200         {
201             // This works for IPv4 too - don't worry!
202             struct sockaddr_in6 dumb =
203             {
204                 .sin6_family = ptr->ai_addr->sa_family,
205                 .sin6_port =  ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
206             };
207
208             bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
209         }
210         else
211 #endif
212         if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
213         {
214             net_Close (fd);
215 #if !defined(WIN32) && !defined(UNDER_CE)
216             fd = rootwrap_bind (ptr->ai_family, ptr->ai_socktype,
217                                 protocol ?: ptr->ai_protocol, ptr->ai_addr,
218                                 ptr->ai_addrlen);
219             if (fd != -1)
220             {
221                 msg_Dbg (p_this, "got socket %d from rootwrap", fd);
222             }
223             else
224 #endif
225             {
226                 msg_Err (p_this, "socket bind error (%m)");
227                 continue;
228             }
229         }
230
231         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
232         {
233             if (net_Subscribe (p_this, fd, ptr->ai_addr, ptr->ai_addrlen))
234             {
235                 net_Close (fd);
236                 continue;
237             }
238         }
239
240         /* Listen */
241         switch (socktype)
242         {
243             case SOCK_STREAM:
244             case SOCK_RDM:
245             case SOCK_SEQPACKET:
246 #ifdef SOCK_DCCP
247             case SOCK_DCCP:
248 #endif
249                 if (listen (fd, INT_MAX))
250                 {
251                     msg_Err (p_this, "socket listen error (%m)");
252                     net_Close (fd);
253                     continue;
254                 }
255         }
256
257         int *nsockv = (int *)realloc (sockv, (sockc + 2) * sizeof (int));
258         if (nsockv != NULL)
259         {
260             nsockv[sockc++] = fd;
261             sockv = nsockv;
262         }
263         else
264             net_Close (fd);
265     }
266
267     vlc_freeaddrinfo (res);
268
269     if (sockv != NULL)
270         sockv[sockc] = -1;
271
272     return sockv;
273 }
274
275
276 /*****************************************************************************
277  * __net_Read:
278  *****************************************************************************
279  * Reads from a network socket.
280  * If waitall is true, then we repeat until we have read the right amount of
281  * data; in that case, a short count means EOF has been reached or the VLC
282  * object has been signaled.
283  *****************************************************************************/
284 ssize_t
285 __net_Read (vlc_object_t *restrict p_this, int fd, const v_socket_t *vs,
286             uint8_t *restrict p_buf, size_t i_buflen, vlc_bool_t waitall)
287 {
288     size_t i_total = 0;
289     struct pollfd ufd[2] = {
290         { .fd = fd,                           .events = POLLIN },
291         { .fd = vlc_object_waitpipe (p_this), .events = POLLIN },
292     };
293
294     if (ufd[1].fd == -1)
295         return -1; /* vlc_object_waitpipe() sets errno */
296
297     while (i_buflen > 0)
298     {
299         ufd[0].revents = ufd[1].revents = 0;
300
301         if (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1) < 0)
302         {
303             if (errno != EINTR)
304                 goto error;
305             continue;
306         }
307
308 #ifndef POLLRDHUP /* This is nice but non-portable */
309 # define POLLRDHUP 0
310 #endif
311         if (i_total > 0)
312         {
313             /* Errors (-1) and EOF (0) will be returned on next call,
314              * otherwise we'd "hide" the error from the caller, which is a
315              * bad idea™. */
316             if (ufd[0].revents & (POLLERR|POLLNVAL|POLLRDHUP))
317                 break;
318             if (ufd[1].revents)
319                 break;
320         }
321         else
322         {
323             if (ufd[1].revents)
324             {
325                 assert (p_this->b_die);
326                 msg_Dbg (p_this, "socket %d polling interrupted", fd);
327 #if defined(WIN32) || defined(UNDER_CE)
328                 WSASetLastError (WSAEINTR);
329 #else
330                 errno = EINTR;
331 #endif
332                 goto error;
333             }
334         }
335
336         assert (ufd[0].revents);
337
338         ssize_t n;
339         if (vs != NULL)
340         {
341             n = vs->pf_recv (vs->p_sys, p_buf, i_buflen);
342         }
343         else
344         {
345 #ifdef WIN32
346             n = recv (fd, p_buf, i_buflen, 0);
347 #else
348             n = read (fd, p_buf, i_buflen);
349 #endif
350         }
351
352         if (n == -1)
353         {
354 #if defined(WIN32) || defined(UNDER_CE)
355             switch (WSAGetLastError ())
356             {
357                 case WSAEWOULDBLOCK:
358                 /* only happens with vs != NULL (TLS) - not really an error */
359                     continue;
360
361                 case WSAEMSGSIZE:
362                 /* For UDP only */
363                 /* On Win32, recv() fails if the datagram doesn't fit inside
364                  * the passed buffer, even though the buffer will be filled
365                  * with the first part of the datagram. */
366                     msg_Err (p_this, "Receive error: "
367                                      "Increase the mtu size (--mtu option)");
368                     n = i_buflen;
369                     break;
370
371                 default:
372                     goto error;
373             }
374 #else
375             /* spurious wake-up or TLS did not yield any actual data */
376             if (errno == EAGAIN)
377                 continue;
378             goto error;
379 #endif
380         }
381
382         if (n == 0)
383             /* For streams, this means end of file, and there will not be any
384              * further data ever on the stream. For datagram sockets, this
385              * means empty datagram, and there could be more data coming.
386              * However, it makes no sense to set <waitall> with datagrams in the
387              * first place.
388              */
389             break; // EOF
390
391         i_total += n;
392         p_buf += n;
393         i_buflen -= n;
394
395         if (!waitall)
396             break;
397     }
398
399     return i_total;
400
401 error:
402     msg_Err (p_this, "Read error: %m");
403     return -1;
404 }
405
406
407 /* Write exact amount requested */
408 ssize_t __net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
409                      const uint8_t *p_data, size_t i_data )
410 {
411     size_t i_total = 0;
412     struct pollfd ufd[2] = {
413         { .fd = fd,                           .events = POLLOUT },
414         { .fd = vlc_object_waitpipe (p_this), .events = POLLIN  },
415     };
416
417     if (ufd[1].fd == -1)
418         return -1;
419
420     while( i_data > 0 )
421     {
422         ssize_t val;
423
424         ufd[0].revents = ufd[1].revents = 0;
425
426         if (poll (ufd, 1, -1) == -1)
427         {
428             if (errno != EINTR)
429             {
430                 msg_Err (p_this, "Write error: %m");
431                 goto error;
432             }
433             continue;
434         }
435
436         if (i_total > 0)
437         {
438             /* Errors will be dequeued separately, upon next call. */
439             if (ufd[0].revents & (POLLERR|POLLNVAL|POLLHUP))
440                 break;
441             if (ufd[1].revents)
442                 break;
443         }
444         else
445         {
446             if (ufd[1].revents)
447             {
448                 assert (p_this->b_die);
449                 errno = EINTR;
450                 goto error;
451             }
452         }
453
454         if (p_vs != NULL)
455             val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
456         else
457 #ifdef WIN32
458             val = send (fd, p_data, i_data, 0);
459 #else
460             val = write (fd, p_data, i_data);
461 #endif
462
463         if (val == -1)
464         {
465             msg_Err (p_this, "Write error: %m");
466             break;
467         }
468
469         p_data += val;
470         i_data -= val;
471         i_total += val;
472     }
473
474     if ((i_total > 0) || (i_data == 0))
475         return i_total;
476
477 error:
478     return -1;
479 }
480
481 char *__net_Gets( vlc_object_t *p_this, int fd, const v_socket_t *p_vs )
482 {
483     char *psz_line = NULL, *ptr = NULL;
484     size_t  i_line = 0, i_max = 0;
485
486
487     for( ;; )
488     {
489         if( i_line == i_max )
490         {
491             i_max += 1024;
492             psz_line = realloc( psz_line, i_max );
493             ptr = psz_line + i_line;
494         }
495
496         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
497         {
498             if( i_line == 0 )
499             {
500                 free( psz_line );
501                 return NULL;
502             }
503             break;
504         }
505
506         if ( *ptr == '\n' )
507             break;
508
509         i_line++;
510         ptr++;
511     }
512
513     *ptr-- = '\0';
514
515     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
516         *ptr = '\0';
517
518     return psz_line;
519 }
520
521 ssize_t net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
522                     const char *psz_fmt, ... )
523 {
524     int i_ret;
525     va_list args;
526     va_start( args, psz_fmt );
527     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
528     va_end( args );
529
530     return i_ret;
531 }
532
533 ssize_t __net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
534                         const char *psz_fmt, va_list args )
535 {
536     char    *psz;
537     int     i_size, i_ret;
538
539     i_size = vasprintf( &psz, psz_fmt, args );
540     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
541         ? -1 : i_size;
542     free( psz );
543
544     return i_ret;
545 }
546
547
548 /*****************************************************************************
549  * inet_pton replacement for obsolete and/or crap operating systems
550  *****************************************************************************/
551 #ifndef HAVE_INET_PTON
552 int inet_pton(int af, const char *src, void *dst)
553 {
554 # ifdef WIN32
555     /* As we already know, Microsoft always go its own way, so even if they do
556      * provide IPv6, they don't provide the API. */
557     struct sockaddr_storage addr;
558     int len = sizeof( addr );
559
560     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
561 #ifdef UNICODE
562     wchar_t *workaround_for_ill_designed_api =
563         malloc( MAX_PATH * sizeof(wchar_t) );
564     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
565     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
566 #else
567     char *workaround_for_ill_designed_api = strdup( src );
568 #endif
569
570     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
571                              (LPSOCKADDR)&addr, &len ) )
572     {
573         free( workaround_for_ill_designed_api );
574         return -1;
575     }
576     free( workaround_for_ill_designed_api );
577
578     switch( af )
579     {
580         case AF_INET6:
581             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
582             break;
583
584         case AF_INET:
585             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
586             break;
587
588         default:
589             WSASetLastError( WSAEAFNOSUPPORT );
590             return -1;
591     }
592 # else
593     /* Assume IPv6 is not supported. */
594     /* Would be safer and more simpler to use inet_aton() but it is most
595      * likely not provided either. */
596     uint32_t ipv4;
597
598     if( af != AF_INET )
599     {
600         errno = EAFNOSUPPORT;
601         return -1;
602     }
603
604     ipv4 = inet_addr( src );
605     if( ipv4 == INADDR_NONE )
606         return -1;
607
608     memcpy( dst, &ipv4, 4 );
609 # endif /* WIN32 */
610     return 0;
611 }
612 #endif /* HAVE_INET_PTON */
613
614 #ifndef HAVE_INET_NTOP
615 #ifdef WIN32
616 const char *inet_ntop(int af, const void * src,
617                                char * dst, socklen_t cnt)
618 {
619     switch( af )
620     {
621 #ifdef AF_INET6
622         case AF_INET6:
623             {
624                 struct sockaddr_in6 addr;
625                 memset(&addr, 0, sizeof(addr));
626                 addr.sin6_family = AF_INET6;
627                 addr.sin6_addr = *((struct in6_addr*)src);
628                 if( 0 == WSAAddressToStringA((LPSOCKADDR)&addr,
629                                              sizeof(struct sockaddr_in6),
630                                              NULL, dst, &cnt) )
631                 {
632                     dst[cnt] = '\0';
633                     return dst;
634                 }
635                 errno = WSAGetLastError();
636                 return NULL;
637
638             }
639
640 #endif
641         case AF_INET:
642             {
643                 struct sockaddr_in addr;
644                 memset(&addr, 0, sizeof(addr));
645                 addr.sin_family = AF_INET;
646                 addr.sin_addr = *((struct in_addr*)src);
647                 if( 0 == WSAAddressToStringA((LPSOCKADDR)&addr,
648                                              sizeof(struct sockaddr_in),
649                                              NULL, dst, &cnt) )
650                 {
651                     dst[cnt] = '\0';
652                     return dst;
653                 }
654                 errno = WSAGetLastError();
655                 return NULL;
656
657             }
658     }
659     errno = EAFNOSUPPORT;
660     return NULL;
661 }
662 #endif
663 #endif