]> git.sesse.net Git - vlc/blob - src/network/io.c
Switch net_Write to poll() to avoid fd set overflow.
[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 <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                const 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;
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         int 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         int 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 #if defined(WIN32) || defined(UNDER_CE)
226             n = recv (*fdv, buf, buflen, 0);
227 #else
228             n = read (*fdv, buf, buflen);
229 #endif
230
231         if (n == -1)
232         {
233 #if defined(WIN32) || defined(UNDER_CE)
234             switch (WSAGetLastError())
235             {
236                 case WSAEWOULDBLOCK:
237                 /* only happens with vs != NULL (SSL) - not really an error */
238                     continue;
239
240                 case WSAEMSGSIZE:
241                 /* For UDP only */
242                 /* On Win32, recv() fails if the datagram doesn't fit inside
243                  * the passed buffer, even though the buffer will be filled
244                  * with the first part of the datagram. */
245                     msg_Err( p_this, "Receive error: "
246                                      "Increase the mtu size (--mtu option)" );
247                     total += buflen;
248                     return total;
249             }
250 #else
251             if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
252                 continue;
253 #endif
254             goto error;
255         }
256
257         total += n;
258         buf += n;
259         buflen -= n;
260
261         if (wait_ms == -1)
262         {
263             if (!waitall)
264                 return total;
265         }
266         else
267             wait_ms -= delay_ms;
268     }
269     while (wait_ms);
270
271     return total; // timeout
272
273 error:
274     msg_Err (p_this, "Read error: %s", net_strerror (net_errno));
275     return total ?: -1;
276 }
277
278
279 /*****************************************************************************
280  * __net_Read:
281  *****************************************************************************
282  * Read from a network socket
283  * If b_retry is true, then we repeat until we have read the right amount of
284  * data
285  *****************************************************************************/
286 int __net_Read( vlc_object_t *restrict p_this, int fd,
287                 const v_socket_t *restrict p_vs,
288                 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
289 {
290     return net_ReadInner (p_this, 1, &(int){ fd },
291                           &(const v_socket_t *){ p_vs },
292                           p_data, i_data, -1, b_retry);
293 }
294
295
296 /*****************************************************************************
297  * __net_ReadNonBlock:
298  *****************************************************************************
299  * Read from a network socket, non blocking mode (with timeout)
300  *****************************************************************************/
301 int __net_ReadNonBlock( vlc_object_t *restrict p_this, int fd,
302                         const v_socket_t *restrict p_vs,
303                         uint8_t *restrict p_data, int i_data, mtime_t i_wait)
304 {
305     return net_ReadInner (p_this, 1, &(int){ fd },
306                           &(const v_socket_t *){ p_vs },
307                           p_data, i_data, i_wait / 1000, VLC_FALSE);
308 }
309
310
311 /*****************************************************************************
312  * __net_Select:
313  *****************************************************************************
314  * Read from several sockets (with timeout). Takes data from the first socket
315  * that has some.
316  *****************************************************************************/
317 int __net_Select( vlc_object_t *restrict p_this, const int *restrict pi_fd,
318                   const v_socket_t *const *restrict pp_vs,
319                   int i_fd, uint8_t *restrict p_data, int i_data,
320                   mtime_t i_wait )
321 {
322     if (pp_vs == NULL)
323     {
324         const v_socket_t *vsv[i_fd];
325         memset (vsv, 0, sizeof (vsv));
326
327         return net_ReadInner (p_this, i_fd, pi_fd, vsv, p_data, i_data,
328                               i_wait / 1000, VLC_FALSE);
329     }
330
331     return net_ReadInner (p_this, i_fd, pi_fd, pp_vs, p_data, i_data,
332                           i_wait / 1000, VLC_FALSE);
333 }
334
335
336 /* Write exact amount requested */
337 int __net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
338                  const uint8_t *p_data, int i_data )
339 {
340     int i_total = 0;
341
342     while (i_data > 0)
343     {
344         if (p_this->b_die)
345             return i_total;
346
347 #ifdef HAVE_POLL
348         struct pollfd ufd[1];
349         memset (ufd, 0, sizeof (ufd));
350         ufd[0].fd = fd;
351         ufd[0].events = POLLOUT;
352
353         int val = poll (ufd, 1, 500);
354 #else
355         fd_set set;
356         FD_ZERO (&set);
357
358 #if !defined(WIN32) && !defined(UNDER_CE)
359         if (fd >= FD_SETSIZE)
360         {
361             /* We don't want to overflow select() fd_set */
362             msg_Err (p_this, "select set overflow");
363             return -1;
364         }
365 #endif
366         FD_SET (fd, &set);
367
368         int val = select (fd + 1, NULL, &set, NULL,
369                           &(struct timeval){ 0, 500000 });
370 #endif
371         switch (val)
372         {
373             case -1:
374                 if (errno != EINTR)
375                 {
376                     msg_Err (p_this, "Write error: %s",
377                              net_strerror (net_errno));
378                     return i_total ?: -1;
379                 }
380
381             case 0:
382                 continue;
383         }
384
385         if (p_vs != NULL)
386             val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
387         else
388 #if defined(WIN32) || defined(UNDER_CE)
389             val = recv (fd, p_data, i_data, 0);
390 #else
391             val = write (fd, p_data, i_data);
392 #endif
393
394         if (val == -1)
395             return i_total ?: -1;
396         if (val == 0)
397             return i_total;
398
399         p_data += val;
400         i_data -= val;
401         i_total += val;
402     }
403
404     return i_total;
405 }
406
407 char *__net_Gets( vlc_object_t *p_this, int fd, const v_socket_t *p_vs )
408 {
409     char *psz_line = NULL, *ptr = NULL;
410     size_t  i_line = 0, i_max = 0;
411
412
413     for( ;; )
414     {
415         if( i_line == i_max )
416         {
417             i_max += 1024;
418             psz_line = realloc( psz_line, i_max );
419             ptr = psz_line + i_line;
420         }
421
422         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
423         {
424             if( i_line == 0 )
425             {
426                 free( psz_line );
427                 return NULL;
428             }
429             break;
430         }
431
432         if ( *ptr == '\n' )
433             break;
434
435         i_line++;
436         ptr++;
437     }
438
439     *ptr-- = '\0';
440
441     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
442         *ptr = '\0';
443
444     return psz_line;
445 }
446
447 int net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
448                 const char *psz_fmt, ... )
449 {
450     int i_ret;
451     va_list args;
452     va_start( args, psz_fmt );
453     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
454     va_end( args );
455
456     return i_ret;
457 }
458
459 int __net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
460                     const char *psz_fmt, va_list args )
461 {
462     char    *psz;
463     int     i_size, i_ret;
464
465     i_size = vasprintf( &psz, psz_fmt, args );
466     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
467         ? -1 : i_size;
468     free( psz );
469
470     return i_ret;
471 }
472
473
474 /*****************************************************************************
475  * inet_pton replacement for obsolete and/or crap operating systems
476  *****************************************************************************/
477 #ifndef HAVE_INET_PTON
478 int inet_pton(int af, const char *src, void *dst)
479 {
480 # ifdef WIN32
481     /* As we already know, Microsoft always go its own way, so even if they do
482      * provide IPv6, they don't provide the API. */
483     struct sockaddr_storage addr;
484     int len = sizeof( addr );
485
486     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
487 #ifdef UNICODE
488     wchar_t *workaround_for_ill_designed_api =
489         malloc( MAX_PATH * sizeof(wchar_t) );
490     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
491     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
492 #else
493     char *workaround_for_ill_designed_api = strdup( src );
494 #endif
495
496     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
497                              (LPSOCKADDR)&addr, &len ) )
498     {
499         free( workaround_for_ill_designed_api );
500         return -1;
501     }
502     free( workaround_for_ill_designed_api );
503
504     switch( af )
505     {
506         case AF_INET6:
507             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
508             break;
509
510         case AF_INET:
511             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
512             break;
513
514         default:
515             WSASetLastError( WSAEAFNOSUPPORT );
516             return -1;
517     }
518 # else
519     /* Assume IPv6 is not supported. */
520     /* Would be safer and more simpler to use inet_aton() but it is most
521      * likely not provided either. */
522     uint32_t ipv4;
523
524     if( af != AF_INET )
525     {
526         errno = EAFNOSUPPORT;
527         return -1;
528     }
529
530     ipv4 = inet_addr( src );
531     if( ipv4 == INADDR_NONE )
532         return -1;
533
534     memcpy( dst, &ipv4, 4 );
535 # endif /* WIN32 */
536     return 0;
537 }
538 #endif /* HAVE_INET_PTON */