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