]> git.sesse.net Git - vlc/blob - src/network/io.c
Fixes
[vlc] / src / network / io.c
1 /*****************************************************************************
2  * io.c: network I/O functions
3  *****************************************************************************
4  * Copyright (C) 2004-2005 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  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <stdlib.h>
30 #include <vlc/vlc.h>
31
32 #include <errno.h>
33 #include <assert.h>
34
35 #ifdef HAVE_FCNTL_H
36 #   include <fcntl.h>
37 #endif
38 #ifdef HAVE_SYS_TIME_H
39 #    include <sys/time.h>
40 #endif
41 #ifdef HAVE_UNISTD_H
42 #   include <unistd.h>
43 #endif
44 #ifdef HAVE_POLL
45 #   include <sys/poll.h>
46 #endif
47
48 #include "network.h"
49
50 #ifndef INADDR_ANY
51 #   define INADDR_ANY  0x00000000
52 #endif
53 #ifndef INADDR_NONE
54 #   define INADDR_NONE 0xFFFFFFFF
55 #endif
56
57 int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
58                 int i_protocol )
59 {
60     int fd, i_val;
61
62     fd = socket( i_family, i_socktype, i_protocol );
63     if( fd == -1 )
64     {
65 #if defined(WIN32) || defined(UNDER_CE)
66         if( WSAGetLastError ( ) != WSAEAFNOSUPPORT )
67 #else
68         if( errno != EAFNOSUPPORT )
69 #endif
70             msg_Warn( p_this, "cannot create socket: %s",
71                       net_strerror(net_errno) );
72         return -1;
73     }
74
75 #if defined( WIN32 ) || defined( UNDER_CE )
76     {
77         unsigned long i_dummy = 1;
78         if( ioctlsocket( fd, FIONBIO, &i_dummy ) != 0 )
79             msg_Err( p_this, "cannot set socket to non-blocking mode" );
80     }
81 #else
82     fcntl( fd, F_SETFD, FD_CLOEXEC );
83     i_val = fcntl( fd, F_GETFL, 0 );
84     fcntl( fd, F_SETFL, ((i_val != -1) ? i_val : 0) | O_NONBLOCK );
85 #endif
86
87     i_val = 1;
88     setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (void *)&i_val,
89                 sizeof( i_val ) );
90
91 #ifdef IPV6_V6ONLY
92     /*
93      * Accepts only IPv6 connections on IPv6 sockets
94      * (and open an IPv4 socket later as well if needed).
95      * Only Linux and FreeBSD can map IPv4 connections on IPv6 sockets,
96      * so this allows for more uniform handling across platforms. Besides,
97      * it makes sure that IPv4 addresses will be printed as w.x.y.z rather
98      * than ::ffff:w.x.y.z
99      */
100     if( i_family == AF_INET6 )
101         setsockopt( fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&i_val,
102                     sizeof( i_val ) );
103 #endif
104
105 #if defined( WIN32 ) || defined( UNDER_CE )
106 # ifndef IPV6_PROTECTION_LEVEL
107 #  define IPV6_PROTECTION_LEVEL 23
108 # endif
109     if( i_family == AF_INET6 )
110     {
111         i_val = 30 /*PROTECTION_LEVEL_UNRESTRICTED*/;
112         setsockopt( fd, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
113                    (const char*)&i_val, sizeof( i_val ) );
114     }
115 #endif
116     return fd;
117 }
118
119
120 /*****************************************************************************
121  * __net_Close:
122  *****************************************************************************
123  * Close a network handle
124  *****************************************************************************/
125 void net_Close( int fd )
126 {
127 #ifdef UNDER_CE
128     CloseHandle( (HANDLE)fd );
129 #elif defined( WIN32 )
130     closesocket( fd );
131 #else
132     close( fd );
133 #endif
134 }
135
136
137 static int
138 net_ReadInner( vlc_object_t *restrict p_this, unsigned fdc, const int *fdv,
139                v_socket_t *const *restrict vsv,
140                uint8_t *restrict buf, size_t buflen,
141                int wait_ms, vlc_bool_t waitall )
142 {
143     int total = 0, n;
144
145     do
146     {
147         if (buflen == 0)
148             return total; // output buffer full
149
150         int delay_ms = 500;
151         if ((wait_ms != -1) && (wait_ms < 500))
152             delay_ms = wait_ms;
153
154 #ifdef HAVE_POLL
155         struct pollfd ufd[fdc];
156         memset (ufd, 0, sizeof (ufd));
157
158         for (unsigned i = 0; i < fdc; i++)
159         {
160             ufd[i].fd = fdv[i];
161             ufd[i].events = POLLIN;
162         }
163
164         if (p_this->b_die)
165             return total;
166
167         n = poll (ufd, fdc, (wait_ms == -1) ? -1 : delay_ms);
168         if (n == -1)
169             goto error;
170
171         assert ((unsigned)n <= fdc);
172
173         for (int i = 0; n > 0; i++)
174             if (ufd[i].revents)
175             {
176                 fdc = 1;
177                 fdv += i;
178                 vsv += i;
179                 n--;
180                 goto receive;
181             }
182 #else
183         int maxfd = -1;
184         fd_set set;
185         FD_ZERO (&set);
186
187         for (unsigned i = 0; i < fdc; i++)
188         {
189 #if !defined(WIN32) && !defined(UNDER_CE)
190             if (fdv[i] >= FD_SETSIZE)
191             {
192                 /* We don't want to overflow select() fd_set */
193                 msg_Err( p_this, "select set overflow" );
194                 return -1;
195             }
196 #endif
197             FD_SET (fdv[i], &set);
198             if (fdv[i] > maxfd)
199                 maxfd = fdv[i];
200         }
201
202         n = select (maxfd + 1, &set, NULL, NULL,
203                     (wait_ms == -1) ? NULL
204                         : &(struct timeval){ 0, delay_ms * 1000 });
205         if (n == -1)
206             goto error;
207
208         for (unsigned i = 0; n > 0; i++)
209             if (FD_ISSET (fdv[i], &set))
210             {
211                 fdc = 1;
212                 fdv += i;
213                 vsv += i;
214                 n--;
215                 goto receive;
216             }
217 #endif
218
219         continue;
220
221 receive:
222         if ((*vsv) != NULL)
223             n = (*vsv)->pf_recv ((*vsv)->p_sys, buf, buflen);
224         else
225             n = recv (*fdv, buf, buflen, 0);
226
227         if (n == -1)
228         {
229 #if defined(WIN32) || defined(UNDER_CE)
230             switch (WSAGetLastError())
231             {
232                 case WSAEWOULDBLOCK:
233                 /* only happens with vs != NULL (SSL) - not really an error */
234                     continue;
235
236                 case WSAEMSGSIZE:
237                 /* For UDP only */
238                 /* On Win32, recv() fails if the datagram doesn't fit inside
239                  * the passed buffer, even though the buffer will be filled
240                  * with the first part of the datagram. */
241                     msg_Err( p_this, "recv() failed. "
242                                      "Increase the mtu size (--mtu option)" );
243                     total += buflen;
244                     return total;
245             }
246 #else
247             if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
248                 continue;
249 #endif
250             goto error;
251         }
252
253         total += n;
254         buf += n;
255         buflen -= n;
256
257         if (wait_ms == -1)
258         {
259             if (!waitall)
260                 return total;
261         }
262         else
263             wait_ms -= delay_ms;
264     }
265     while (wait_ms);
266
267     return total; // timeout
268
269 error:
270     msg_Err (p_this, "Receive error: %s", net_strerror (net_errno));
271     return (total > 0) ? total : -1;
272 }
273
274
275 /*****************************************************************************
276  * __net_Read:
277  *****************************************************************************
278  * Read from a network socket
279  * If b_retry is true, then we repeat until we have read the right amount of
280  * data
281  *****************************************************************************/
282 int __net_Read( vlc_object_t *restrict p_this, int fd,
283                 v_socket_t *restrict p_vs,
284                 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
285 {
286     struct timeval  timeout;
287     fd_set          fds_r, fds_e;
288     int             i_recv;
289     int             i_total = 0;
290     int             i_ret;
291     vlc_bool_t      b_die = p_this->b_die;
292
293     while( i_data > 0 )
294     {
295         do
296         {
297             if( p_this->b_die != b_die )
298             {
299                 return 0;
300             }
301
302             /* Initialize file descriptor set */
303             FD_ZERO( &fds_r );
304             FD_SET( fd, &fds_r );
305             FD_ZERO( &fds_e );
306             FD_SET( fd, &fds_e );
307
308             /* We'll wait 0.5 second if nothing happens */
309             timeout.tv_sec = 0;
310             timeout.tv_usec = 500000;
311
312         } while( (i_ret = select(fd + 1, &fds_r, NULL, &fds_e, &timeout)) == 0
313                  || ( i_ret < 0 && errno == EINTR ) );
314
315         if( i_ret < 0 )
316         {
317             msg_Err( p_this, "network select error (%s)",
318                      net_strerror(net_errno) );
319             return i_total > 0 ? i_total : -1;
320         }
321
322         if( ( i_recv = (p_vs != NULL)
323               ? p_vs->pf_recv( p_vs->p_sys, p_data, i_data )
324               : recv( fd, p_data, i_data, 0 ) ) < 0 )
325         {
326 #if defined(WIN32) || defined(UNDER_CE)
327             if( WSAGetLastError() == WSAEWOULDBLOCK )
328             {
329                 /* only happens with p_vs (SSL) - not really an error */
330             }
331             else
332             /* For udp only */
333             /* On win32 recv() will fail if the datagram doesn't fit inside
334              * the passed buffer, even though the buffer will be filled with
335              * the first part of the datagram. */
336             if( WSAGetLastError() == WSAEMSGSIZE )
337             {
338                 msg_Err( p_this, "recv() failed. "
339                          "Increase the mtu size (--mtu option)" );
340                 i_total += i_data;
341             }
342             else if( WSAGetLastError() == WSAEINTR ) continue;
343 #else
344             /* EAGAIN only happens with p_vs (TLS) and it's not an error */
345             if( errno != EAGAIN )
346 #endif
347                 msg_Err( p_this, "recv failed: %s", net_strerror(net_errno) );
348             return i_total > 0 ? i_total : -1;
349         }
350         else if( i_recv == 0 )
351         {
352             /* Connection closed */
353             b_retry = VLC_FALSE;
354         }
355
356         p_data += i_recv;
357         i_data -= i_recv;
358         i_total+= i_recv;
359         if( !b_retry )
360         {
361             break;
362         }
363     }
364     return i_total;
365 }
366
367 /*****************************************************************************
368  * __net_ReadNonBlock:
369  *****************************************************************************
370  * Read from a network socket, non blocking mode (with timeout)
371  *****************************************************************************/
372 int __net_ReadNonBlock( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
373                         uint8_t *p_data, int i_data, mtime_t i_wait)
374 {
375     struct timeval  timeout;
376     fd_set          fds_r, fds_e;
377     int             i_recv;
378     int             i_ret;
379
380     /* Initialize file descriptor set */
381     FD_ZERO( &fds_r );
382     FD_SET( fd, &fds_r );
383     FD_ZERO( &fds_e );
384     FD_SET( fd, &fds_e );
385
386     timeout.tv_sec = 0;
387     timeout.tv_usec = i_wait;
388
389     i_ret = select(fd + 1, &fds_r, NULL, &fds_e, &timeout);
390
391     if( i_ret < 0 && errno == EINTR )
392     {
393         return 0;
394     }
395     else if( i_ret < 0 )
396     {
397         msg_Err( p_this, "network error: %s", net_strerror(net_errno) );
398         return -1;
399     }
400     else if( i_ret == 0)
401     {
402         return 0;
403     }
404     else
405     {
406 #if !defined(UNDER_CE)
407         if( fd == 0/*STDIN_FILENO*/ ) i_recv = read( fd, p_data, i_data ); else
408 #endif
409         if( ( i_recv = (p_vs != NULL)
410               ? p_vs->pf_recv( p_vs->p_sys, p_data, i_data )
411               : recv( fd, p_data, i_data, 0 ) ) < 0 )
412         {
413 #if defined(WIN32) || defined(UNDER_CE)
414             /* For udp only */
415             /* On win32 recv() will fail if the datagram doesn't fit inside
416              * the passed buffer, even though the buffer will be filled with
417              * the first part of the datagram. */
418             if( WSAGetLastError() == WSAEMSGSIZE )
419             {
420                 msg_Err( p_this, "recv() failed. "
421                          "Increase the mtu size (--mtu option)" );
422             }
423             else
424 #endif
425             msg_Err( p_this, "recv failed: %s", net_strerror(net_errno) );
426             return -1;
427         }
428
429         return i_recv ? i_recv : -1;  /* !i_recv -> connection closed if tcp */
430     }
431
432     /* We will never be here */
433     return -1;
434 }
435
436 /*****************************************************************************
437  * __net_Select:
438  *****************************************************************************
439  * Read from several sockets (with timeout). Takes data from the first socket
440  * that has some.
441  *****************************************************************************/
442 int __net_Select( vlc_object_t *p_this, int *pi_fd, v_socket_t **pp_vs,
443                   int i_fd, uint8_t *p_data, int i_data, mtime_t i_wait )
444 {
445     struct timeval  timeout;
446     fd_set          fds_r, fds_e;
447     int             i_recv;
448     int             i_ret;
449     int             i;
450     int             i_max_fd = 0;
451
452     /* Initialize file descriptor set */
453     FD_ZERO( &fds_r );
454     FD_ZERO( &fds_e );
455
456     for( i = 0 ; i < i_fd ; i++)
457     {
458         if( pi_fd[i] > i_max_fd ) i_max_fd = pi_fd[i];
459         FD_SET( pi_fd[i], &fds_r );
460         FD_SET( pi_fd[i], &fds_e );
461     }
462
463     timeout.tv_sec = 0;
464     timeout.tv_usec = i_wait;
465
466     i_ret = select( i_max_fd + 1, &fds_r, NULL, &fds_e, &timeout );
467
468     if( i_ret < 0 && errno == EINTR )
469     {
470         return 0;
471     }
472     else if( i_ret < 0 )
473     {
474         msg_Err( p_this, "network selection error: %s", net_strerror(net_errno) );
475         return -1;
476     }
477     else if( i_ret == 0 )
478     {
479         return 0;
480     }
481     else
482     {
483         for( i = 0 ; i < i_fd ; i++)
484         {
485             if( FD_ISSET( pi_fd[i], &fds_r ) )
486             {
487                 i_recv = ((pp_vs != NULL) && (pp_vs[i] != NULL))
488                          ? pp_vs[i]->pf_recv( pp_vs[i]->p_sys, p_data, i_data )
489                          : recv( pi_fd[i], p_data, i_data, 0 );
490                 if( i_recv < 0 )
491                 {
492 #ifdef WIN32
493                     /* For udp only */
494                     /* On win32 recv() will fail if the datagram doesn't
495                      * fit inside the passed buffer, even though the buffer
496                      *  will be filled with the first part of the datagram. */
497                     if( WSAGetLastError() == WSAEMSGSIZE )
498                     {
499                         msg_Err( p_this, "recv() failed. "
500                              "Increase the mtu size (--mtu option)" );
501                     }
502                     else msg_Err( p_this, "recv failed (%i)",
503                                   WSAGetLastError() );
504 #else
505                     msg_Err( p_this, "recv failed (%s)", strerror(errno) );
506 #endif
507                     return VLC_EGENERIC;
508                 }
509
510                 return i_recv;
511             }
512         }
513     }
514
515     /* We will never be here */
516     return -1;
517 }
518
519
520 /* Write exact amount requested */
521 int __net_Write( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
522                  const uint8_t *p_data, int i_data )
523 {
524     struct timeval  timeout;
525     fd_set          fds_w, fds_e;
526     int             i_send;
527     int             i_total = 0;
528     int             i_ret;
529
530     vlc_bool_t      b_die = p_this->b_die;
531
532     while( i_data > 0 )
533     {
534         do
535         {
536             if( p_this->b_die != b_die )
537             {
538                 return 0;
539             }
540
541             /* Initialize file descriptor set */
542             FD_ZERO( &fds_w );
543             FD_SET( fd, &fds_w );
544             FD_ZERO( &fds_e );
545             FD_SET( fd, &fds_e );
546
547             /* We'll wait 0.5 second if nothing happens */
548             timeout.tv_sec = 0;
549             timeout.tv_usec = 500000;
550
551         } while( (i_ret = select(fd + 1, NULL, &fds_w, &fds_e, &timeout)) == 0
552                  || ( i_ret < 0 && errno == EINTR ) );
553
554         if( i_ret < 0 )
555         {
556 #if defined(WIN32) || defined(UNDER_CE)
557             msg_Err( p_this, "network selection error (%d)", WSAGetLastError() );
558 #else
559             msg_Err( p_this, "network selection error (%s)", strerror(errno) );
560 #endif
561             return i_total > 0 ? i_total : -1;
562         }
563
564         if( ( i_send = (p_vs != NULL)
565                        ? p_vs->pf_send( p_vs->p_sys, p_data, i_data )
566                        : send( fd, p_data, i_data, 0 ) ) < 0 )
567         {
568             /* XXX With udp for example, it will issue a message if the host
569              * isn't listening */
570             /* msg_Err( p_this, "send failed (%s)", strerror(errno) ); */
571             return i_total > 0 ? i_total : -1;
572         }
573
574         p_data += i_send;
575         i_data -= i_send;
576         i_total+= i_send;
577     }
578     return i_total;
579 }
580
581 char *__net_Gets( vlc_object_t *p_this, int fd, v_socket_t *p_vs )
582 {
583     char *psz_line = NULL, *ptr = NULL;
584     size_t  i_line = 0, i_max = 0;
585
586
587     for( ;; )
588     {
589         if( i_line == i_max )
590         {
591             i_max += 1024;
592             psz_line = realloc( psz_line, i_max );
593             ptr = psz_line + i_line;
594         }
595
596         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
597         {
598             if( i_line == 0 )
599             {
600                 free( psz_line );
601                 return NULL;
602             }
603             break;
604         }
605
606         if ( *ptr == '\n' )
607             break;
608
609         i_line++;
610         ptr++;
611     }
612
613     *ptr-- = '\0';
614
615     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
616         *ptr = '\0';
617
618     return psz_line;
619 }
620
621 int net_Printf( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
622                 const char *psz_fmt, ... )
623 {
624     int i_ret;
625     va_list args;
626     va_start( args, psz_fmt );
627     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
628     va_end( args );
629
630     return i_ret;
631 }
632
633 int __net_vaPrintf( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
634                     const char *psz_fmt, va_list args )
635 {
636     char    *psz;
637     int     i_size, i_ret;
638
639     i_size = vasprintf( &psz, psz_fmt, args );
640     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
641         ? -1 : i_size;
642     free( psz );
643
644     return i_ret;
645 }
646
647
648 /*****************************************************************************
649  * inet_pton replacement for obsolete and/or crap operating systems
650  *****************************************************************************/
651 #ifndef HAVE_INET_PTON
652 int inet_pton(int af, const char *src, void *dst)
653 {
654 # ifdef WIN32
655     /* As we already know, Microsoft always go its own way, so even if they do
656      * provide IPv6, they don't provide the API. */
657     struct sockaddr_storage addr;
658     int len = sizeof( addr );
659
660     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
661 #ifdef UNICODE
662     wchar_t *workaround_for_ill_designed_api =
663         malloc( MAX_PATH * sizeof(wchar_t) );
664     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
665     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
666 #else
667     char *workaround_for_ill_designed_api = strdup( src );
668 #endif
669
670     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
671                              (LPSOCKADDR)&addr, &len ) )
672     {
673         free( workaround_for_ill_designed_api );
674         return -1;
675     }
676     free( workaround_for_ill_designed_api );
677
678     switch( af )
679     {
680         case AF_INET6:
681             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
682             break;
683
684         case AF_INET:
685             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
686             break;
687
688         default:
689             WSASetLastError( WSAEAFNOSUPPORT );
690             return -1;
691     }
692 # else
693     /* Assume IPv6 is not supported. */
694     /* Would be safer and more simpler to use inet_aton() but it is most
695      * likely not provided either. */
696     uint32_t ipv4;
697
698     if( af != AF_INET )
699     {
700         errno = EAFNOSUPPORT;
701         return -1;
702     }
703
704     ipv4 = inet_addr( src );
705     if( ipv4 == INADDR_NONE )
706         return -1;
707
708     memcpy( dst, &ipv4, 4 );
709 # endif /* WIN32 */
710     return 0;
711 }
712 #endif /* HAVE_INET_PTON */