]> git.sesse.net Git - vlc/blob - src/network/io.c
Accept non-socket handles through net_Read* (closes #731)
[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                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, 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 #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, "recv() failed. "
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, "Receive error: %s", net_strerror (net_errno));
275     return (total > 0) ? 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     struct timeval  timeout;
341     fd_set          fds_w, fds_e;
342     int             i_send;
343     int             i_total = 0;
344     int             i_ret;
345
346     vlc_bool_t      b_die = p_this->b_die;
347
348     while( i_data > 0 )
349     {
350         do
351         {
352             if( p_this->b_die != b_die )
353             {
354                 return 0;
355             }
356
357             /* Initialize file descriptor set */
358             FD_ZERO( &fds_w );
359             FD_SET( fd, &fds_w );
360             FD_ZERO( &fds_e );
361             FD_SET( fd, &fds_e );
362
363             /* We'll wait 0.5 second if nothing happens */
364             timeout.tv_sec = 0;
365             timeout.tv_usec = 500000;
366
367         } while( (i_ret = select(fd + 1, NULL, &fds_w, &fds_e, &timeout)) == 0
368                  || ( i_ret < 0 && errno == EINTR ) );
369
370         if( i_ret < 0 )
371         {
372             msg_Err( p_this, "network error: %s", net_strerror(net_errno) );
373             return i_total > 0 ? i_total : -1;
374         }
375
376         if( ( i_send = (p_vs != NULL)
377                        ? p_vs->pf_send( p_vs->p_sys, p_data, i_data )
378                        : send( fd, p_data, i_data, 0 ) ) < 0 )
379         {
380             /* XXX With udp for example, it will issue a message if the host
381              * isn't listening */
382             /* msg_Err( p_this, "send failed (%s)", strerror(errno) ); */
383             return i_total > 0 ? i_total : -1;
384         }
385
386         p_data += i_send;
387         i_data -= i_send;
388         i_total+= i_send;
389     }
390     return i_total;
391 }
392
393 char *__net_Gets( vlc_object_t *p_this, int fd, const v_socket_t *p_vs )
394 {
395     char *psz_line = NULL, *ptr = NULL;
396     size_t  i_line = 0, i_max = 0;
397
398
399     for( ;; )
400     {
401         if( i_line == i_max )
402         {
403             i_max += 1024;
404             psz_line = realloc( psz_line, i_max );
405             ptr = psz_line + i_line;
406         }
407
408         if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
409         {
410             if( i_line == 0 )
411             {
412                 free( psz_line );
413                 return NULL;
414             }
415             break;
416         }
417
418         if ( *ptr == '\n' )
419             break;
420
421         i_line++;
422         ptr++;
423     }
424
425     *ptr-- = '\0';
426
427     if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
428         *ptr = '\0';
429
430     return psz_line;
431 }
432
433 int net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
434                 const char *psz_fmt, ... )
435 {
436     int i_ret;
437     va_list args;
438     va_start( args, psz_fmt );
439     i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
440     va_end( args );
441
442     return i_ret;
443 }
444
445 int __net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
446                     const char *psz_fmt, va_list args )
447 {
448     char    *psz;
449     int     i_size, i_ret;
450
451     i_size = vasprintf( &psz, psz_fmt, args );
452     i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
453         ? -1 : i_size;
454     free( psz );
455
456     return i_ret;
457 }
458
459
460 /*****************************************************************************
461  * inet_pton replacement for obsolete and/or crap operating systems
462  *****************************************************************************/
463 #ifndef HAVE_INET_PTON
464 int inet_pton(int af, const char *src, void *dst)
465 {
466 # ifdef WIN32
467     /* As we already know, Microsoft always go its own way, so even if they do
468      * provide IPv6, they don't provide the API. */
469     struct sockaddr_storage addr;
470     int len = sizeof( addr );
471
472     /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
473 #ifdef UNICODE
474     wchar_t *workaround_for_ill_designed_api =
475         malloc( MAX_PATH * sizeof(wchar_t) );
476     mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
477     workaround_for_ill_designed_api[MAX_PATH-1] = 0;
478 #else
479     char *workaround_for_ill_designed_api = strdup( src );
480 #endif
481
482     if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
483                              (LPSOCKADDR)&addr, &len ) )
484     {
485         free( workaround_for_ill_designed_api );
486         return -1;
487     }
488     free( workaround_for_ill_designed_api );
489
490     switch( af )
491     {
492         case AF_INET6:
493             memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
494             break;
495
496         case AF_INET:
497             memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
498             break;
499
500         default:
501             WSASetLastError( WSAEAFNOSUPPORT );
502             return -1;
503     }
504 # else
505     /* Assume IPv6 is not supported. */
506     /* Would be safer and more simpler to use inet_aton() but it is most
507      * likely not provided either. */
508     uint32_t ipv4;
509
510     if( af != AF_INET )
511     {
512         errno = EAFNOSUPPORT;
513         return -1;
514     }
515
516     ipv4 = inet_addr( src );
517     if( ipv4 == INADDR_NONE )
518         return -1;
519
520     memcpy( dst, &ipv4, 4 );
521 # endif /* WIN32 */
522     return 0;
523 }
524 #endif /* HAVE_INET_PTON */