]> git.sesse.net Git - vlc/blob - src/network/io.c
Add missing const qualifier and fix warnings
[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             n = recv (*fdv, buf, buflen, 0);
226
227         if (n == -1)
228         {
229 #if defined(WIN32) || defined(UNDER_CE)
230             switch (WSAGetLastError())
231             {
232                 case WSAEWOULDBLOCK:
233                 /* only happens with vs != NULL (SSL) - not really an error */
234                     continue;
235
236                 case WSAEMSGSIZE:
237                 /* For UDP only */
238                 /* On Win32, recv() fails if the datagram doesn't fit inside
239                  * the passed buffer, even though the buffer will be filled
240                  * with the first part of the datagram. */
241                     msg_Err( p_this, "recv() failed. "
242                                      "Increase the mtu size (--mtu option)" );
243                     total += buflen;
244                     return total;
245             }
246 #else
247             if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
248                 continue;
249 #endif
250             goto error;
251         }
252
253         total += n;
254         buf += n;
255         buflen -= n;
256
257         if (wait_ms == -1)
258         {
259             if (!waitall)
260                 return total;
261         }
262         else
263             wait_ms -= delay_ms;
264     }
265     while (wait_ms);
266
267     return total; // timeout
268
269 error:
270     msg_Err (p_this, "Receive error: %s", net_strerror (net_errno));
271     return (total > 0) ? total : -1;
272 }
273
274
275 /*****************************************************************************
276  * __net_Read:
277  *****************************************************************************
278  * Read from a network socket
279  * If b_retry is true, then we repeat until we have read the right amount of
280  * data
281  *****************************************************************************/
282 int __net_Read( vlc_object_t *restrict p_this, int fd,
283                 const v_socket_t *restrict p_vs,
284                 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
285 {
286     return net_ReadInner (p_this, 1, &(int){ fd },
287                           &(const v_socket_t *){ p_vs },
288                           p_data, i_data, -1, b_retry);
289 }
290
291
292 /*****************************************************************************
293  * __net_ReadNonBlock:
294  *****************************************************************************
295  * Read from a network socket, non blocking mode (with timeout)
296  *****************************************************************************/
297 int __net_ReadNonBlock( vlc_object_t *restrict p_this, int fd,
298                         const v_socket_t *restrict p_vs,
299                         uint8_t *restrict p_data, int i_data, mtime_t i_wait)
300 {
301     return net_ReadInner (p_this, 1, &(int){ fd },
302                           &(const v_socket_t *){ p_vs },
303                           p_data, i_data, i_wait / 1000, VLC_FALSE);
304 }
305
306
307 /*****************************************************************************
308  * __net_Select:
309  *****************************************************************************
310  * Read from several sockets (with timeout). Takes data from the first socket
311  * that has some.
312  *****************************************************************************/
313 int __net_Select( vlc_object_t *restrict p_this, const int *restrict pi_fd,
314                   const v_socket_t *const *restrict pp_vs,
315                   int i_fd, uint8_t *restrict p_data, int i_data,
316                   mtime_t i_wait )
317 {
318     if (pp_vs == NULL)
319     {
320         const v_socket_t *vsv[i_fd];
321         memset (vsv, 0, sizeof (vsv));
322
323         return net_ReadInner (p_this, i_fd, pi_fd, vsv, p_data, i_data,
324                               i_wait / 1000, VLC_FALSE);
325     }
326
327     return net_ReadInner (p_this, i_fd, pi_fd, pp_vs, p_data, i_data,
328                           i_wait / 1000, VLC_FALSE);
329 }
330
331
332 /* Write exact amount requested */
333 int __net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
334                  const uint8_t *p_data, int i_data )
335 {
336     struct timeval  timeout;
337     fd_set          fds_w, fds_e;
338     int             i_send;
339     int             i_total = 0;
340     int             i_ret;
341
342     vlc_bool_t      b_die = p_this->b_die;
343
344     while( i_data > 0 )
345     {
346         do
347         {
348             if( p_this->b_die != b_die )
349             {
350                 return 0;
351             }
352
353             /* Initialize file descriptor set */
354             FD_ZERO( &fds_w );
355             FD_SET( fd, &fds_w );
356             FD_ZERO( &fds_e );
357             FD_SET( fd, &fds_e );
358
359             /* We'll wait 0.5 second if nothing happens */
360             timeout.tv_sec = 0;
361             timeout.tv_usec = 500000;
362
363         } while( (i_ret = select(fd + 1, NULL, &fds_w, &fds_e, &timeout)) == 0
364                  || ( i_ret < 0 && errno == EINTR ) );
365
366         if( i_ret < 0 )
367         {
368 #if defined(WIN32) || defined(UNDER_CE)
369             msg_Err( p_this, "network selection error (%d)", WSAGetLastError() );
370 #else
371             msg_Err( p_this, "network selection error (%s)", strerror(errno) );
372 #endif
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 */