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