]> git.sesse.net Git - vlc/blob - src/network/io.c
Interrupt blocking socket reads
[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
30 #include <vlc/vlc.h>
31
32 #include <stdlib.h>
33 #include <stdio.h>
34
35 #include <errno.h>
36 #include <assert.h>
37
38 #ifdef HAVE_FCNTL_H
39 #   include <fcntl.h>
40 #endif
41 #ifdef HAVE_SYS_TIME_H
42 #    include <sys/time.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 #   include <unistd.h>
46 #endif
47 #ifdef HAVE_POLL
48 #   include <poll.h>
49 #endif
50
51 #include "network.h"
52
53 #ifndef INADDR_ANY
54 #   define INADDR_ANY  0x00000000
55 #endif
56 #ifndef INADDR_NONE
57 #   define INADDR_NONE 0xFFFFFFFF
58 #endif
59
60 int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
61                 int i_protocol )
62 {
63     int fd, i_val;
64
65     fd = socket( i_family, i_socktype, i_protocol );
66     if( fd == -1 )
67     {
68 #if defined(WIN32) || defined(UNDER_CE)
69         if( WSAGetLastError ( ) != WSAEAFNOSUPPORT )
70 #else
71         if( errno != EAFNOSUPPORT )
72 #endif
73             msg_Warn( p_this, "cannot create socket: %s",
74                       net_strerror(net_errno) );
75         return -1;
76     }
77
78 #if defined( WIN32 ) || defined( UNDER_CE )
79     {
80         unsigned long i_dummy = 1;
81         if( ioctlsocket( fd, FIONBIO, &i_dummy ) != 0 )
82             msg_Err( p_this, "cannot set socket to non-blocking mode" );
83     }
84 #else
85     fcntl( fd, F_SETFD, FD_CLOEXEC );
86     i_val = fcntl( fd, F_GETFL, 0 );
87     fcntl( fd, F_SETFL, ((i_val != -1) ? i_val : 0) | O_NONBLOCK );
88 #endif
89
90     i_val = 1;
91     setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (void *)&i_val,
92                 sizeof( i_val ) );
93
94 #ifdef IPV6_V6ONLY
95     /*
96      * Accepts only IPv6 connections on IPv6 sockets
97      * (and open an IPv4 socket later as well if needed).
98      * Only Linux and FreeBSD can map IPv4 connections on IPv6 sockets,
99      * so this allows for more uniform handling across platforms. Besides,
100      * it makes sure that IPv4 addresses will be printed as w.x.y.z rather
101      * than ::ffff:w.x.y.z
102      */
103     if( i_family == AF_INET6 )
104         setsockopt( fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&i_val,
105                     sizeof( i_val ) );
106 #endif
107
108 #if defined( WIN32 ) || defined( UNDER_CE )
109 # ifndef IPV6_PROTECTION_LEVEL
110 #  define IPV6_PROTECTION_LEVEL 23
111 # endif
112     if( i_family == AF_INET6 )
113     {
114         i_val = 30 /*PROTECTION_LEVEL_UNRESTRICTED*/;
115         setsockopt( fd, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
116                    (const char*)&i_val, sizeof( i_val ) );
117     }
118 #endif
119     return fd;
120 }
121
122
123 /*****************************************************************************
124  * __net_Close:
125  *****************************************************************************
126  * Close a network handle
127  *****************************************************************************/
128 void net_Close( int fd )
129 {
130 #ifdef UNDER_CE
131     CloseHandle( (HANDLE)fd );
132 #elif defined( WIN32 )
133     closesocket( fd );
134 #else
135     close( fd );
136 #endif
137 }
138
139
140 static int
141 net_ReadInner( vlc_object_t *restrict p_this, unsigned fdc, const int *fdv,
142                const v_socket_t *const *restrict vsv,
143                uint8_t *restrict p_buf, size_t i_buflen,
144                int wait_ms, vlc_bool_t waitall )
145 {
146     size_t i_total = 0;
147     int eof[fdc];
148     unsigned int i_eof = 0;
149     memset( eof, 0, sizeof( eof ) );
150
151     do
152     {
153         unsigned int i;
154         int n, delay_ms;
155 #ifdef HAVE_POLL
156         struct pollfd ufd[fdc];
157 #else
158         int maxfd = -1;
159         fd_set set;
160 #endif
161
162         if( i_buflen == 0 )
163             return i_total; // output buffer full
164
165         if( i_eof == fdc )
166             return i_total; // all sockets are at EOF
167
168         delay_ms = 500;
169         if( (wait_ms != -1) && (wait_ms < 500) )
170             delay_ms = wait_ms;
171
172         if( p_this->b_die )
173         {
174             errno = EINTR;
175             goto error;
176         }
177
178 #ifdef HAVE_POLL
179         memset(ufd, 0, sizeof (ufd) );
180
181         for( i = 0; i < fdc; i++ )
182         {
183             ufd[i].fd = fdv[i];
184             ufd[i].events = POLLIN;
185         }
186
187         n = poll( ufd, fdc, delay_ms );
188         if( n == -1 )
189             goto error;
190
191         assert( (unsigned int)n <= fdc );
192
193         for( i = 0; n > 0; i++ )
194         {
195             if( (i_total > 0) && (ufd[i].revents & POLLERR) )
196                 return i_total; // error will be dequeued on next run
197
198             if( ufd[i].revents )
199             {
200                 fdc = 1;
201                 fdv += i;
202                 vsv += i;
203                 n--;
204                 goto receive;
205             }
206         }
207 #else
208         FD_ZERO (&set);
209
210         for( i = 0; i < fdc; i++ )
211         {
212 #if !defined(WIN32) && !defined(UNDER_CE)
213             if( fdv[i] >= FD_SETSIZE )
214             {
215                 /* We don't want to overflow select() fd_set */
216                 msg_Err( p_this, "select set overflow" );
217                 return -1;
218             }
219 #endif
220             FD_SET( fdv[i], &set );
221             if( fdv[i] > maxfd )
222                 maxfd = fdv[i];
223         }
224
225         n = select( maxfd + 1, &set, NULL, NULL,
226                     (wait_ms == -1) ? NULL
227                                   : &(struct timeval){ 0, delay_ms * 1000 } );
228         if( n == -1 )
229             goto error;
230
231         for( i = 0; n > 0; i++ )
232             if( FD_ISSET (fdv[i], &set) )
233             {
234                 fdc = 1;
235                 fdv += i;
236                 vsv += i;
237                 n--;
238                 goto receive;
239             }
240 #endif
241
242         continue;
243
244 receive:
245         if( (*vsv) != NULL )
246         {
247             n = (*vsv)->pf_recv( (*vsv)->p_sys, p_buf, i_buflen );
248         }
249         else
250         {
251 #if defined(WIN32) || defined(UNDER_CE)
252             n = recv( *fdv, p_buf, i_buflen, 0 );
253 #else
254             n = read( *fdv, p_buf, i_buflen );
255 #endif
256         }
257
258         if( n == -1 )
259         {
260 #if defined(WIN32) || defined(UNDER_CE)
261             switch( WSAGetLastError() )
262             {
263                 case WSAEWOULDBLOCK:
264                 /* only happens with vs != NULL (SSL) - not really an error */
265                     continue;
266
267                 case WSAEMSGSIZE:
268                 /* For UDP only */
269                 /* On Win32, recv() fails if the datagram doesn't fit inside
270                  * the passed buffer, even though the buffer will be filled
271                  * with the first part of the datagram. */
272                     msg_Err( p_this, "Receive error: "
273                                      "Increase the mtu size (--mtu option)" );
274                     i_total += i_buflen;
275                     return i_total;
276             }
277 #else
278             if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
279                 continue;
280 #endif
281             goto error;
282         }
283
284         i_total += n;
285         p_buf += n;
286         i_buflen -= n;
287
288         if( n ==  0 ) // EOF on socket
289         {
290             unsigned int j;
291             for( j = 0 ; j < i_eof ; j++ )
292                 if( eof[j] == *fdv ) goto end;
293             eof[i_eof++] = *fdv;
294         }
295 end:
296         if( wait_ms == -1 )
297         {
298             if( !waitall )
299                 return i_total;
300         }
301         else
302         {
303             wait_ms -= delay_ms;
304         }
305     }
306     while( wait_ms );
307
308     return i_total; // timeout
309
310 error:
311     msg_Err( p_this, "Read error: %s", net_strerror (net_errno) );
312     return i_total ? (int)i_total : -1;
313 }
314
315
316 /*****************************************************************************
317  * __net_Read:
318  *****************************************************************************
319  * Read from a network socket
320  * If b_retry is true, then we repeat until we have read the right amount of
321  * data
322  *****************************************************************************/
323 int __net_Read( vlc_object_t *restrict p_this, int fd,
324                 const v_socket_t *restrict p_vs,
325                 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
326 {
327     return net_ReadInner( p_this, 1, &(int){ fd },
328                           &(const v_socket_t *){ p_vs },
329                           p_data, i_data, -1, b_retry );
330 }
331
332
333 /*****************************************************************************
334  * __net_ReadNonBlock:
335  *****************************************************************************
336  * Read from a network socket, non blocking mode (with timeout)
337  *****************************************************************************/
338 int __net_ReadNonBlock( vlc_object_t *restrict p_this, int fd,
339                         const v_socket_t *restrict p_vs,
340                         uint8_t *restrict p_data, int i_data, mtime_t i_wait)
341 {
342     return net_ReadInner (p_this, 1, &(int){ fd },
343                           &(const v_socket_t *){ p_vs },
344                           p_data, i_data, i_wait / 1000, VLC_FALSE);
345 }
346
347
348 /*****************************************************************************
349  * __net_Select:
350  *****************************************************************************
351  * Read from several sockets (with timeout). Takes data from the first socket
352  * that has some.
353  *****************************************************************************/
354 int __net_Select( vlc_object_t *restrict p_this, const int *restrict pi_fd,
355                   const v_socket_t *const *restrict pp_vs,
356                   int i_fd, uint8_t *restrict p_data, int i_data,
357                   mtime_t i_wait )
358 {
359     if( pp_vs == NULL )
360     {
361         const v_socket_t *vsv[i_fd];
362         memset( vsv, 0, sizeof (vsv) );
363
364         return net_ReadInner( p_this, i_fd, pi_fd, vsv, p_data, i_data,
365                               i_wait / 1000, VLC_FALSE );
366     }
367
368     return net_ReadInner( p_this, i_fd, pi_fd, pp_vs, p_data, i_data,
369                           i_wait / 1000, VLC_FALSE );
370 }
371
372
373 /* Write exact amount requested */
374 int __net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
375                  const uint8_t *p_data, int i_data )
376 {
377     size_t i_total = 0;
378
379     while( i_data > 0 )
380     {
381         if( p_this->b_die )
382             return i_total;
383
384 #ifdef HAVE_POLL
385         struct pollfd ufd[1];
386         memset (ufd, 0, sizeof (ufd));
387         ufd[0].fd = fd;
388         ufd[0].events = POLLOUT;
389
390         int val = poll (ufd, 1, 500);
391         if ((val > 0) && (ufd[0].revents & POLLERR) && (i_total > 0))
392             return i_total; // error will be dequeued separately on next call
393 #else
394         fd_set set;
395         FD_ZERO (&set);
396
397 #if !defined(WIN32) && !defined(UNDER_CE)
398         if (fd >= FD_SETSIZE)
399         {
400             /* We don't want to overflow select() fd_set */
401             msg_Err (p_this, "select set overflow");
402             return -1;
403         }
404 #endif
405         FD_SET (fd, &set);
406
407         int val = select (fd + 1, NULL, &set, NULL,
408                           &(struct timeval){ 0, 500000 });
409 #endif
410         switch (val)
411         {
412             case -1:
413                 if (errno != EINTR)
414                 {
415                     msg_Err (p_this, "Write error: %s",
416                              net_strerror (net_errno));
417                     return i_total ? (int)i_total : -1;
418                 }
419
420             case 0:
421                 continue;
422         }
423
424         if (p_vs != NULL)
425             val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
426         else
427 #if defined(WIN32) || defined(UNDER_CE)
428             val = send (fd, p_data, i_data, 0);
429 #else
430             val = write (fd, p_data, i_data);
431 #endif
432
433         if (val == -1)
434             return i_total ? (int)i_total : -1;
435         if (val == 0)
436             return i_total;
437
438         p_data += val;
439         i_data -= val;
440         i_total += val;
441     }
442
443     return i_total;
444 }
445
446 char *__net_Gets( vlc_object_t *p_this, int fd, const v_socket_t *p_vs )
447 {
448     char *psz_line = NULL, *ptr = NULL;
449     size_t  i_line = 0, i_max = 0;
450
451
452     for( ;; )
453     {
454         if( i_line == i_max )
455         {
456             i_max += 1024;
457             psz_line = realloc( psz_line, i_max );
458             ptr = psz_line + i_line;
459         }
460
461         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
462         {
463             if( i_line == 0 )
464             {
465                 free( psz_line );
466                 return NULL;
467             }
468             break;
469         }
470
471         if ( *ptr == '\n' )
472             break;
473
474         i_line++;
475         ptr++;
476     }
477
478     *ptr-- = '\0';
479
480     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
481         *ptr = '\0';
482
483     return psz_line;
484 }
485
486 int net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
487                 const char *psz_fmt, ... )
488 {
489     int i_ret;
490     va_list args;
491     va_start( args, psz_fmt );
492     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
493     va_end( args );
494
495     return i_ret;
496 }
497
498 int __net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
499                     const char *psz_fmt, va_list args )
500 {
501     char    *psz;
502     int     i_size, i_ret;
503
504     i_size = vasprintf( &psz, psz_fmt, args );
505     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
506         ? -1 : i_size;
507     free( psz );
508
509     return i_ret;
510 }
511
512
513 /*****************************************************************************
514  * inet_pton replacement for obsolete and/or crap operating systems
515  *****************************************************************************/
516 #ifndef HAVE_INET_PTON
517 int inet_pton(int af, const char *src, void *dst)
518 {
519 # ifdef WIN32
520     /* As we already know, Microsoft always go its own way, so even if they do
521      * provide IPv6, they don't provide the API. */
522     struct sockaddr_storage addr;
523     int len = sizeof( addr );
524
525     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
526 #ifdef UNICODE
527     wchar_t *workaround_for_ill_designed_api =
528         malloc( MAX_PATH * sizeof(wchar_t) );
529     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
530     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
531 #else
532     char *workaround_for_ill_designed_api = strdup( src );
533 #endif
534
535     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
536                              (LPSOCKADDR)&addr, &len ) )
537     {
538         free( workaround_for_ill_designed_api );
539         return -1;
540     }
541     free( workaround_for_ill_designed_api );
542
543     switch( af )
544     {
545         case AF_INET6:
546             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
547             break;
548
549         case AF_INET:
550             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
551             break;
552
553         default:
554             WSASetLastError( WSAEAFNOSUPPORT );
555             return -1;
556     }
557 # else
558     /* Assume IPv6 is not supported. */
559     /* Would be safer and more simpler to use inet_aton() but it is most
560      * likely not provided either. */
561     uint32_t ipv4;
562
563     if( af != AF_INET )
564     {
565         errno = EAFNOSUPPORT;
566         return -1;
567     }
568
569     ipv4 = inet_addr( src );
570     if( ipv4 == INADDR_NONE )
571         return -1;
572
573     memcpy( dst, &ipv4, 4 );
574 # endif /* WIN32 */
575     return 0;
576 }
577 #endif /* HAVE_INET_PTON */