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
8 * Authors: Laurent Aimar <fenrir@videolan.org>
9 * Rémi Denis-Courmont <rem # videolan.org>
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.
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.
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 *****************************************************************************/
26 /*****************************************************************************
28 *****************************************************************************/
38 #ifdef HAVE_SYS_TIME_H
39 # include <sys/time.h>
45 # include <sys/poll.h>
51 # define INADDR_ANY 0x00000000
54 # define INADDR_NONE 0xFFFFFFFF
57 int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
62 fd = socket( i_family, i_socktype, i_protocol );
65 #if defined(WIN32) || defined(UNDER_CE)
66 if( WSAGetLastError ( ) != WSAEAFNOSUPPORT )
68 if( errno != EAFNOSUPPORT )
70 msg_Warn( p_this, "cannot create socket: %s",
71 net_strerror(net_errno) );
75 #if defined( WIN32 ) || defined( UNDER_CE )
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" );
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 );
88 setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (void *)&i_val,
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
100 if( i_family == AF_INET6 )
101 setsockopt( fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&i_val,
105 #if defined( WIN32 ) || defined( UNDER_CE )
106 # ifndef IPV6_PROTECTION_LEVEL
107 # define IPV6_PROTECTION_LEVEL 23
109 if( i_family == AF_INET6 )
111 i_val = 30 /*PROTECTION_LEVEL_UNRESTRICTED*/;
112 setsockopt( fd, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
113 (const char*)&i_val, sizeof( i_val ) );
120 /*****************************************************************************
122 *****************************************************************************
123 * Close a network handle
124 *****************************************************************************/
125 void net_Close( int fd )
128 CloseHandle( (HANDLE)fd );
129 #elif defined( WIN32 )
138 net_ReadInner( vlc_object_t *restrict p_this, unsigned fdc, const int *fdv,
139 v_socket_t *const *restrict vsv,
140 uint8_t *restrict buf, size_t buflen,
141 int wait_ms, vlc_bool_t waitall )
147 if (waitall && (buflen == 0))
148 return total; // output buffer full
153 delay_ms = (wait_ms > 500) ? 500 : wait_ms;
160 struct pollfd ufd[fdc];
161 memset (ufd, 0, sizeof (ufd));
163 for (unsigned i = 0; i < fdc; i++)
166 ufd[i].events = POLLIN;
172 n = poll (ufd, fdc, (wait_ms == -1) ? -1 : delay_ms);
176 assert ((unsigned)n <= fdc);
178 for (int i = 0; n > 0; i++)
192 for (unsigned i = 0; i < fdc; i++)
194 #if !defined(WIN32) && !defined(UNDER_CE)
195 if (fdv[i] >= FD_SETSIZE)
197 /* We don't want to overflow select() fd_set */
198 msg_Err( p_this, "select set overflow" );
202 FD_SET (fdv[i], &set);
207 n = select (maxfd + 1, &set, NULL, NULL,
208 (wait_ms == -1) ? NULL
209 : &(struct timeval){ 0, delay_ms * 1000 });
213 for (unsigned i = 0; n > 0; i++)
214 if (FD_ISSET (fdv[i], &set))
228 n = (*vsv)->pf_recv ((*vsv)->p_sys, buf, buflen);
230 n = recv (*fdv, buf, buflen, 0);
234 #if defined(WIN32) || defined(UNDER_CE)
235 switch (WSAGetLastError())
238 /* only happens with vs != NULL (SSL) - not really an error */
243 /* On Win32, recv() fails if the datagram doesn't fit inside
244 * the passed buffer, even though the buffer will be filled
245 * with the first part of the datagram. */
246 msg_Err( p_this, "recv() failed. "
247 "Increase the mtu size (--mtu option)" );
252 if( errno == EAGAIN ) /* spurious wake-up (sucks if fdc > 1) */
264 return total; // timeout
267 msg_Err (p_this, "Receive error: %s", net_strerror (net_errno));
268 return (total > 0) ? total : -1;
272 /*****************************************************************************
274 *****************************************************************************
275 * Read from a network socket
276 * If b_retry is true, then we repeat until we have read the right amount of
278 *****************************************************************************/
279 int __net_Read( vlc_object_t *restrict p_this, int fd,
280 v_socket_t *restrict p_vs,
281 uint8_t *restrict p_data, int i_data, vlc_bool_t b_retry )
283 struct timeval timeout;
288 vlc_bool_t b_die = p_this->b_die;
294 if( p_this->b_die != b_die )
299 /* Initialize file descriptor set */
301 FD_SET( fd, &fds_r );
303 FD_SET( fd, &fds_e );
305 /* We'll wait 0.5 second if nothing happens */
307 timeout.tv_usec = 500000;
309 } while( (i_ret = select(fd + 1, &fds_r, NULL, &fds_e, &timeout)) == 0
310 || ( i_ret < 0 && errno == EINTR ) );
314 msg_Err( p_this, "network select error (%s)",
315 net_strerror(net_errno) );
316 return i_total > 0 ? i_total : -1;
319 if( ( i_recv = (p_vs != NULL)
320 ? p_vs->pf_recv( p_vs->p_sys, p_data, i_data )
321 : recv( fd, p_data, i_data, 0 ) ) < 0 )
323 #if defined(WIN32) || defined(UNDER_CE)
324 if( WSAGetLastError() == WSAEWOULDBLOCK )
326 /* only happens with p_vs (SSL) - not really an error */
330 /* On win32 recv() will fail if the datagram doesn't fit inside
331 * the passed buffer, even though the buffer will be filled with
332 * the first part of the datagram. */
333 if( WSAGetLastError() == WSAEMSGSIZE )
335 msg_Err( p_this, "recv() failed. "
336 "Increase the mtu size (--mtu option)" );
339 else if( WSAGetLastError() == WSAEINTR ) continue;
341 /* EAGAIN only happens with p_vs (TLS) and it's not an error */
342 if( errno != EAGAIN )
344 msg_Err( p_this, "recv failed: %s", net_strerror(net_errno) );
345 return i_total > 0 ? i_total : -1;
347 else if( i_recv == 0 )
349 /* Connection closed */
364 /*****************************************************************************
365 * __net_ReadNonBlock:
366 *****************************************************************************
367 * Read from a network socket, non blocking mode (with timeout)
368 *****************************************************************************/
369 int __net_ReadNonBlock( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
370 uint8_t *p_data, int i_data, mtime_t i_wait)
372 struct timeval timeout;
377 /* Initialize file descriptor set */
379 FD_SET( fd, &fds_r );
381 FD_SET( fd, &fds_e );
384 timeout.tv_usec = i_wait;
386 i_ret = select(fd + 1, &fds_r, NULL, &fds_e, &timeout);
388 if( i_ret < 0 && errno == EINTR )
394 msg_Err( p_this, "network error: %s", net_strerror(net_errno) );
403 #if !defined(UNDER_CE)
404 if( fd == 0/*STDIN_FILENO*/ ) i_recv = read( fd, p_data, i_data ); else
406 if( ( i_recv = (p_vs != NULL)
407 ? p_vs->pf_recv( p_vs->p_sys, p_data, i_data )
408 : recv( fd, p_data, i_data, 0 ) ) < 0 )
410 #if defined(WIN32) || defined(UNDER_CE)
412 /* On win32 recv() will fail if the datagram doesn't fit inside
413 * the passed buffer, even though the buffer will be filled with
414 * the first part of the datagram. */
415 if( WSAGetLastError() == WSAEMSGSIZE )
417 msg_Err( p_this, "recv() failed. "
418 "Increase the mtu size (--mtu option)" );
422 msg_Err( p_this, "recv failed: %s", net_strerror(net_errno) );
426 return i_recv ? i_recv : -1; /* !i_recv -> connection closed if tcp */
429 /* We will never be here */
433 /*****************************************************************************
435 *****************************************************************************
436 * Read from several sockets (with timeout). Takes data from the first socket
438 *****************************************************************************/
439 int __net_Select( vlc_object_t *p_this, int *pi_fd, v_socket_t **pp_vs,
440 int i_fd, uint8_t *p_data, int i_data, mtime_t i_wait )
442 struct timeval timeout;
449 /* Initialize file descriptor set */
453 for( i = 0 ; i < i_fd ; i++)
455 if( pi_fd[i] > i_max_fd ) i_max_fd = pi_fd[i];
456 FD_SET( pi_fd[i], &fds_r );
457 FD_SET( pi_fd[i], &fds_e );
461 timeout.tv_usec = i_wait;
463 i_ret = select( i_max_fd + 1, &fds_r, NULL, &fds_e, &timeout );
465 if( i_ret < 0 && errno == EINTR )
471 msg_Err( p_this, "network selection error: %s", net_strerror(net_errno) );
474 else if( i_ret == 0 )
480 for( i = 0 ; i < i_fd ; i++)
482 if( FD_ISSET( pi_fd[i], &fds_r ) )
484 i_recv = ((pp_vs != NULL) && (pp_vs[i] != NULL))
485 ? pp_vs[i]->pf_recv( pp_vs[i]->p_sys, p_data, i_data )
486 : recv( pi_fd[i], p_data, i_data, 0 );
491 /* On win32 recv() will fail if the datagram doesn't
492 * fit inside the passed buffer, even though the buffer
493 * will be filled with the first part of the datagram. */
494 if( WSAGetLastError() == WSAEMSGSIZE )
496 msg_Err( p_this, "recv() failed. "
497 "Increase the mtu size (--mtu option)" );
499 else msg_Err( p_this, "recv failed (%i)",
502 msg_Err( p_this, "recv failed (%s)", strerror(errno) );
512 /* We will never be here */
517 /* Write exact amount requested */
518 int __net_Write( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
519 const uint8_t *p_data, int i_data )
521 struct timeval timeout;
527 vlc_bool_t b_die = p_this->b_die;
533 if( p_this->b_die != b_die )
538 /* Initialize file descriptor set */
540 FD_SET( fd, &fds_w );
542 FD_SET( fd, &fds_e );
544 /* We'll wait 0.5 second if nothing happens */
546 timeout.tv_usec = 500000;
548 } while( (i_ret = select(fd + 1, NULL, &fds_w, &fds_e, &timeout)) == 0
549 || ( i_ret < 0 && errno == EINTR ) );
553 #if defined(WIN32) || defined(UNDER_CE)
554 msg_Err( p_this, "network selection error (%d)", WSAGetLastError() );
556 msg_Err( p_this, "network selection error (%s)", strerror(errno) );
558 return i_total > 0 ? i_total : -1;
561 if( ( i_send = (p_vs != NULL)
562 ? p_vs->pf_send( p_vs->p_sys, p_data, i_data )
563 : send( fd, p_data, i_data, 0 ) ) < 0 )
565 /* XXX With udp for example, it will issue a message if the host
567 /* msg_Err( p_this, "send failed (%s)", strerror(errno) ); */
568 return i_total > 0 ? i_total : -1;
578 char *__net_Gets( vlc_object_t *p_this, int fd, v_socket_t *p_vs )
580 char *psz_line = NULL, *ptr = NULL;
581 size_t i_line = 0, i_max = 0;
586 if( i_line == i_max )
589 psz_line = realloc( psz_line, i_max );
590 ptr = psz_line + i_line;
593 if( net_Read( p_this, fd, p_vs, (uint8_t *)ptr, 1, VLC_TRUE ) != 1 )
612 if( ( ptr >= psz_line ) && ( *ptr == '\r' ) )
618 int net_Printf( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
619 const char *psz_fmt, ... )
623 va_start( args, psz_fmt );
624 i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
630 int __net_vaPrintf( vlc_object_t *p_this, int fd, v_socket_t *p_vs,
631 const char *psz_fmt, va_list args )
636 i_size = vasprintf( &psz, psz_fmt, args );
637 i_ret = __net_Write( p_this, fd, p_vs, (uint8_t *)psz, i_size ) < i_size
645 /*****************************************************************************
646 * inet_pton replacement for obsolete and/or crap operating systems
647 *****************************************************************************/
648 #ifndef HAVE_INET_PTON
649 int inet_pton(int af, const char *src, void *dst)
652 /* As we already know, Microsoft always go its own way, so even if they do
653 * provide IPv6, they don't provide the API. */
654 struct sockaddr_storage addr;
655 int len = sizeof( addr );
657 /* Damn it, they didn't even put LPCSTR for the firs parameter!!! */
659 wchar_t *workaround_for_ill_designed_api =
660 malloc( MAX_PATH * sizeof(wchar_t) );
661 mbstowcs( workaround_for_ill_designed_api, src, MAX_PATH );
662 workaround_for_ill_designed_api[MAX_PATH-1] = 0;
664 char *workaround_for_ill_designed_api = strdup( src );
667 if( !WSAStringToAddress( workaround_for_ill_designed_api, af, NULL,
668 (LPSOCKADDR)&addr, &len ) )
670 free( workaround_for_ill_designed_api );
673 free( workaround_for_ill_designed_api );
678 memcpy( dst, &((struct sockaddr_in6 *)&addr)->sin6_addr, 16 );
682 memcpy( dst, &((struct sockaddr_in *)&addr)->sin_addr, 4 );
686 WSASetLastError( WSAEAFNOSUPPORT );
690 /* Assume IPv6 is not supported. */
691 /* Would be safer and more simpler to use inet_aton() but it is most
692 * likely not provided either. */
697 errno = EAFNOSUPPORT;
701 ipv4 = inet_addr( src );
702 if( ipv4 == INADDR_NONE )
705 memcpy( dst, &ipv4, 4 );
709 #endif /* HAVE_INET_PTON */