]> git.sesse.net Git - vlc/blob - src/network/io.c
Reallow file descriptor above FD_SETSIZE since we now use poll()
[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 (waitall && (buflen == 0))
148             return total; // output buffer full
149
150         int delay_ms;
151         if (wait_ms != -1)
152         {
153             delay_ms = (wait_ms > 500) ? 500 : wait_ms;
154             wait_ms -= delay_ms;
155         }
156         else
157             delay_ms = 500;
158
159 #ifdef HAVE_POLL
160         struct pollfd ufd[fdc];
161         memset (ufd, 0, sizeof (ufd));
162
163         for (unsigned i = 0; i < fdc; i++)
164         {
165             ufd[i].fd = fdv[i];
166             ufd[i].events = POLLIN;
167         }
168
169         if (p_this->b_die)
170             return total;
171
172         n = poll (ufd, fdc, (wait_ms == -1) ? -1 : delay_ms);
173         if (n == -1)
174             goto error;
175
176         assert ((unsigned)n <= fdc);
177
178         for (int i = 0; n > 0; i++)
179             if (ufd[i].revents)
180             {
181                 fdc = 1;
182                 fdv += i;
183                 vsv += i;
184                 n--;
185                 goto receive;
186             }
187 #else
188         int maxfd = -1;
189         fd_set set;
190         FD_ZERO (&set);
191
192         for (unsigned i = 0; i < fdc; i++)
193         {
194 #if !defined(WIN32) && !defined(UNDER_CE)
195             if (fdv[i] >= FD_SETSIZE)
196             {
197                 /* We don't want to overflow select() fd_set */
198                 msg_Err( p_this, "select set overflow" );
199                 return -1;
200             }
201 #endif
202             FD_SET (fdv[i], &set);
203             if (fdv[i] > maxfd)
204                 maxfd = fdv[i];
205         }
206
207         n = select (maxfd + 1, &set, NULL, NULL,
208                     (wait_ms == -1) ? NULL
209                         : &(struct timeval){ 0, delay_ms * 1000 });
210         if (n == -1)
211             goto error;
212
213         for (unsigned i = 0; n > 0; i++)
214             if (FD_ISSET (fdv[i], &set))
215             {
216                 fdc = 1;
217                 fdv += i;
218                 vsv += i;
219                 n--;
220                 goto receive;
221             }
222 #endif
223
224         continue;
225
226 receive:
227         if ((*vsv) != NULL)
228             n = (*vsv)->pf_recv ((*vsv)->p_sys, buf, buflen);
229         else
230             n = recv (*fdv, buf, buflen, 0);
231
232         if (n == -1)
233         {
234 #if defined(WIN32) || defined(UNDER_CE)
235             switch (WSAGetLastError())
236             {
237                 case WSAEWOULDBLOCK:
238                 /* only happens with vs != NULL (SSL) - not really an error */
239                     continue;
240
241                 case WSAEMSGSIZE:
242                 /* For UDP only */
243                 /* On Win32, recv() fails if the datagram doesn't fit inside
244                  * the passed buffer, even though the buffer will be filled
245                  * with the first part of the datagram. */
246                     msg_Err( p_this, "recv() failed. "
247                                      "Increase the mtu size (--mtu option)" );
248                     total += buflen;
249                     return total;
250             }
251 #else
252             if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
253                 continue;
254 #endif
255             goto error;
256         }
257
258         total += n;
259         buf += n;
260         buflen -= n;
261     }
262     while (wait_ms);
263
264     return total; // timeout
265
266 error:
267     msg_Err (p_this, "Receive error: %s", net_strerror (net_errno));
268     return (total > 0) ? total : -1;
269 }
270
271
272 /*****************************************************************************
273  * __net_Read:
274  *****************************************************************************
275  * Read from a network socket
276  * If b_retry is true, then we repeat until we have read the right amount of
277  * data
278  *****************************************************************************/
279 int __net_Read( vlc_object_t *restrict p_this, int fd,
280                 v_socket_t *restrict p_vs,
281                 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
282 {
283     struct timeval  timeout;
284     fd_set          fds_r, fds_e;
285     int             i_recv;
286     int             i_total = 0;
287     int             i_ret;
288     vlc_bool_t      b_die = p_this->b_die;
289
290     while( i_data > 0 )
291     {
292         do
293         {
294             if( p_this->b_die != b_die )
295             {
296                 return 0;
297             }
298
299             /* Initialize file descriptor set */
300             FD_ZERO( &fds_r );
301             FD_SET( fd, &fds_r );
302             FD_ZERO( &fds_e );
303             FD_SET( fd, &fds_e );
304
305             /* We'll wait 0.5 second if nothing happens */
306             timeout.tv_sec = 0;
307             timeout.tv_usec = 500000;
308
309         } while( (i_ret = select(fd + 1, &fds_r, NULL, &fds_e, &timeout)) == 0
310                  || ( i_ret < 0 && errno == EINTR ) );
311
312         if( i_ret < 0 )
313         {
314             msg_Err( p_this, "network select error (%s)",
315                      net_strerror(net_errno) );
316             return i_total > 0 ? i_total : -1;
317         }
318
319         if( ( i_recv = (p_vs != NULL)
320               ? p_vs->pf_recv( p_vs->p_sys, p_data, i_data )
321               : recv( fd, p_data, i_data, 0 ) ) < 0 )
322         {
323 #if defined(WIN32) || defined(UNDER_CE)
324             if( WSAGetLastError() == WSAEWOULDBLOCK )
325             {
326                 /* only happens with p_vs (SSL) - not really an error */
327             }
328             else
329             /* For udp only */
330             /* On win32 recv() will fail if the datagram doesn't fit inside
331              * the passed buffer, even though the buffer will be filled with
332              * the first part of the datagram. */
333             if( WSAGetLastError() == WSAEMSGSIZE )
334             {
335                 msg_Err( p_this, "recv() failed. "
336                          "Increase the mtu size (--mtu option)" );
337                 i_total += i_data;
338             }
339             else if( WSAGetLastError() == WSAEINTR ) continue;
340 #else
341             /* EAGAIN only happens with p_vs (TLS) and it's not an error */
342             if( errno != EAGAIN )
343 #endif
344                 msg_Err( p_this, "recv failed: %s", net_strerror(net_errno) );
345             return i_total > 0 ? i_total : -1;
346         }
347         else if( i_recv == 0 )
348         {
349             /* Connection closed */
350             b_retry = VLC_FALSE;
351         }
352
353         p_data += i_recv;
354         i_data -= i_recv;
355         i_total+= i_recv;
356         if( !b_retry )
357         {
358             break;
359         }
360     }
361     return i_total;
362 }
363
364 /*****************************************************************************
365  * __net_ReadNonBlock:
366  *****************************************************************************
367  * Read from a network socket, non blocking mode (with timeout)
368  *****************************************************************************/
369 int __net_ReadNonBlock( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
370                         uint8_t *p_data, int i_data, mtime_t i_wait)
371 {
372     struct timeval  timeout;
373     fd_set          fds_r, fds_e;
374     int             i_recv;
375     int             i_ret;
376
377     /* Initialize file descriptor set */
378     FD_ZERO( &fds_r );
379     FD_SET( fd, &fds_r );
380     FD_ZERO( &fds_e );
381     FD_SET( fd, &fds_e );
382
383     timeout.tv_sec = 0;
384     timeout.tv_usec = i_wait;
385
386     i_ret = select(fd + 1, &fds_r, NULL, &fds_e, &timeout);
387
388     if( i_ret < 0 && errno == EINTR )
389     {
390         return 0;
391     }
392     else if( i_ret < 0 )
393     {
394         msg_Err( p_this, "network error: %s", net_strerror(net_errno) );
395         return -1;
396     }
397     else if( i_ret == 0)
398     {
399         return 0;
400     }
401     else
402     {
403 #if !defined(UNDER_CE)
404         if( fd == 0/*STDIN_FILENO*/ ) i_recv = read( fd, p_data, i_data ); else
405 #endif
406         if( ( i_recv = (p_vs != NULL)
407               ? p_vs->pf_recv( p_vs->p_sys, p_data, i_data )
408               : recv( fd, p_data, i_data, 0 ) ) < 0 )
409         {
410 #if defined(WIN32) || defined(UNDER_CE)
411             /* For udp only */
412             /* On win32 recv() will fail if the datagram doesn't fit inside
413              * the passed buffer, even though the buffer will be filled with
414              * the first part of the datagram. */
415             if( WSAGetLastError() == WSAEMSGSIZE )
416             {
417                 msg_Err( p_this, "recv() failed. "
418                          "Increase the mtu size (--mtu option)" );
419             }
420             else
421 #endif
422             msg_Err( p_this, "recv failed: %s", net_strerror(net_errno) );
423             return -1;
424         }
425
426         return i_recv ? i_recv : -1;  /* !i_recv -> connection closed if tcp */
427     }
428
429     /* We will never be here */
430     return -1;
431 }
432
433 /*****************************************************************************
434  * __net_Select:
435  *****************************************************************************
436  * Read from several sockets (with timeout). Takes data from the first socket
437  * that has some.
438  *****************************************************************************/
439 int __net_Select( vlc_object_t *p_this, int *pi_fd, v_socket_t **pp_vs,
440                   int i_fd, uint8_t *p_data, int i_data, mtime_t i_wait )
441 {
442     struct timeval  timeout;
443     fd_set          fds_r, fds_e;
444     int             i_recv;
445     int             i_ret;
446     int             i;
447     int             i_max_fd = 0;
448
449     /* Initialize file descriptor set */
450     FD_ZERO( &fds_r );
451     FD_ZERO( &fds_e );
452
453     for( i = 0 ; i < i_fd ; i++)
454     {
455         if( pi_fd[i] > i_max_fd ) i_max_fd = pi_fd[i];
456         FD_SET( pi_fd[i], &fds_r );
457         FD_SET( pi_fd[i], &fds_e );
458     }
459
460     timeout.tv_sec = 0;
461     timeout.tv_usec = i_wait;
462
463     i_ret = select( i_max_fd + 1, &fds_r, NULL, &fds_e, &timeout );
464
465     if( i_ret < 0 && errno == EINTR )
466     {
467         return 0;
468     }
469     else if( i_ret < 0 )
470     {
471         msg_Err( p_this, "network selection error: %s", net_strerror(net_errno) );
472         return -1;
473     }
474     else if( i_ret == 0 )
475     {
476         return 0;
477     }
478     else
479     {
480         for( i = 0 ; i < i_fd ; i++)
481         {
482             if( FD_ISSET( pi_fd[i], &fds_r ) )
483             {
484                 i_recv = ((pp_vs != NULL) && (pp_vs[i] != NULL))
485                          ? pp_vs[i]->pf_recv( pp_vs[i]->p_sys, p_data, i_data )
486                          : recv( pi_fd[i], p_data, i_data, 0 );
487                 if( i_recv < 0 )
488                 {
489 #ifdef WIN32
490                     /* For udp only */
491                     /* On win32 recv() will fail if the datagram doesn't
492                      * fit inside the passed buffer, even though the buffer
493                      *  will be filled with the first part of the datagram. */
494                     if( WSAGetLastError() == WSAEMSGSIZE )
495                     {
496                         msg_Err( p_this, "recv() failed. "
497                              "Increase the mtu size (--mtu option)" );
498                     }
499                     else msg_Err( p_this, "recv failed (%i)",
500                                   WSAGetLastError() );
501 #else
502                     msg_Err( p_this, "recv failed (%s)", strerror(errno) );
503 #endif
504                     return VLC_EGENERIC;
505                 }
506
507                 return i_recv;
508             }
509         }
510     }
511
512     /* We will never be here */
513     return -1;
514 }
515
516
517 /* Write exact amount requested */
518 int __net_Write( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
519                  const uint8_t *p_data, int i_data )
520 {
521     struct timeval  timeout;
522     fd_set          fds_w, fds_e;
523     int             i_send;
524     int             i_total = 0;
525     int             i_ret;
526
527     vlc_bool_t      b_die = p_this->b_die;
528
529     while( i_data > 0 )
530     {
531         do
532         {
533             if( p_this->b_die != b_die )
534             {
535                 return 0;
536             }
537
538             /* Initialize file descriptor set */
539             FD_ZERO( &fds_w );
540             FD_SET( fd, &fds_w );
541             FD_ZERO( &fds_e );
542             FD_SET( fd, &fds_e );
543
544             /* We'll wait 0.5 second if nothing happens */
545             timeout.tv_sec = 0;
546             timeout.tv_usec = 500000;
547
548         } while( (i_ret = select(fd + 1, NULL, &fds_w, &fds_e, &timeout)) == 0
549                  || ( i_ret < 0 && errno == EINTR ) );
550
551         if( i_ret < 0 )
552         {
553 #if defined(WIN32) || defined(UNDER_CE)
554             msg_Err( p_this, "network selection error (%d)", WSAGetLastError() );
555 #else
556             msg_Err( p_this, "network selection error (%s)", strerror(errno) );
557 #endif
558             return i_total > 0 ? i_total : -1;
559         }
560
561         if( ( i_send = (p_vs != NULL)
562                        ? p_vs->pf_send( p_vs->p_sys, p_data, i_data )
563                        : send( fd, p_data, i_data, 0 ) ) < 0 )
564         {
565             /* XXX With udp for example, it will issue a message if the host
566              * isn't listening */
567             /* msg_Err( p_this, "send failed (%s)", strerror(errno) ); */
568             return i_total > 0 ? i_total : -1;
569         }
570
571         p_data += i_send;
572         i_data -= i_send;
573         i_total+= i_send;
574     }
575     return i_total;
576 }
577
578 char *__net_Gets( vlc_object_t *p_this, int fd, v_socket_t *p_vs )
579 {
580     char *psz_line = NULL, *ptr = NULL;
581     size_t  i_line = 0, i_max = 0;
582
583
584     for( ;; )
585     {
586         if( i_line == i_max )
587         {
588             i_max += 1024;
589             psz_line = realloc( psz_line, i_max );
590             ptr = psz_line + i_line;
591         }
592
593         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
594         {
595             if( i_line == 0 )
596             {
597                 free( psz_line );
598                 return NULL;
599             }
600             break;
601         }
602
603         if ( *ptr == '\n' )
604             break;
605
606         i_line++;
607         ptr++;
608     }
609
610     *ptr-- = '\0';
611
612     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
613         *ptr = '\0';
614
615     return psz_line;
616 }
617
618 int net_Printf( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
619                 const char *psz_fmt, ... )
620 {
621     int i_ret;
622     va_list args;
623     va_start( args, psz_fmt );
624     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
625     va_end( args );
626
627     return i_ret;
628 }
629
630 int __net_vaPrintf( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
631                     const char *psz_fmt, va_list args )
632 {
633     char    *psz;
634     int     i_size, i_ret;
635
636     i_size = vasprintf( &psz, psz_fmt, args );
637     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
638         ? -1 : i_size;
639     free( psz );
640
641     return i_ret;
642 }
643
644
645 /*****************************************************************************
646  * inet_pton replacement for obsolete and/or crap operating systems
647  *****************************************************************************/
648 #ifndef HAVE_INET_PTON
649 int inet_pton(int af, const char *src, void *dst)
650 {
651 # ifdef WIN32
652     /* As we already know, Microsoft always go its own way, so even if they do
653      * provide IPv6, they don't provide the API. */
654     struct sockaddr_storage addr;
655     int len = sizeof( addr );
656
657     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
658 #ifdef UNICODE
659     wchar_t *workaround_for_ill_designed_api =
660         malloc( MAX_PATH * sizeof(wchar_t) );
661     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
662     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
663 #else
664     char *workaround_for_ill_designed_api = strdup( src );
665 #endif
666
667     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
668                              (LPSOCKADDR)&addr, &len ) )
669     {
670         free( workaround_for_ill_designed_api );
671         return -1;
672     }
673     free( workaround_for_ill_designed_api );
674
675     switch( af )
676     {
677         case AF_INET6:
678             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
679             break;
680
681         case AF_INET:
682             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
683             break;
684
685         default:
686             WSASetLastError( WSAEAFNOSUPPORT );
687             return -1;
688     }
689 # else
690     /* Assume IPv6 is not supported. */
691     /* Would be safer and more simpler to use inet_aton() but it is most
692      * likely not provided either. */
693     uint32_t ipv4;
694
695     if( af != AF_INET )
696     {
697         errno = EAFNOSUPPORT;
698         return -1;
699     }
700
701     ipv4 = inet_addr( src );
702     if( ipv4 == INADDR_NONE )
703         return -1;
704
705     memcpy( dst, &ipv4, 4 );
706 # endif /* WIN32 */
707     return 0;
708 }
709 #endif /* HAVE_INET_PTON */