1 /*****************************************************************************
2 * io.c: network I/O functions
3 *****************************************************************************
4 * Copyright (C) 2004-2005, 2007 VLC authors and VideoLAN
5 * Copyright © 2005-2006 Rémi Denis-Courmont
8 * Authors: Laurent Aimar <fenrir@videolan.org>
9 * Rémi Denis-Courmont <rem # videolan.org>
10 * Christophe Mutricy <xtophe at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU Lesser General Public License as published by
14 * the Free Software Foundation; either version 2.1 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public License
23 * along with this program; if not, write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
35 #include <vlc_common.h>
50 #include <vlc_network.h>
53 # define INADDR_ANY 0x00000000
56 # define INADDR_NONE 0xFFFFFFFF
61 # define EAFNOSUPPORT WSAEAFNOSUPPORT
63 # define EWOULDBLOCK WSAEWOULDBLOCK
65 # define EAGAIN WSAEWOULDBLOCK
68 #ifdef HAVE_LINUX_DCCP_H
69 /* TODO: use glibc instead of linux-kernel headers */
70 # include <linux/dccp.h>
74 #include "libvlc.h" /* vlc_object_waitpipe */
76 extern int rootwrap_bind (int family, int socktype, int protocol,
77 const struct sockaddr *addr, size_t alen);
79 int net_Socket (vlc_object_t *p_this, int family, int socktype,
82 int fd = vlc_socket (family, socktype, protocol, true);
85 if (net_errno != EAFNOSUPPORT)
86 msg_Err (p_this, "cannot create socket: %s",
87 vlc_strerror_c(net_errno));
91 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof (int));
95 * Accepts only IPv6 connections on IPv6 sockets.
96 * If possible, we should open two sockets, but it is not always possible.
98 if (family == AF_INET6)
99 setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, &(int){ 1 }, sizeof (int));
103 # ifndef IPV6_PROTECTION_LEVEL
104 # warning Please update your C library headers.
105 # define IPV6_PROTECTION_LEVEL 23
106 # define PROTECTION_LEVEL_UNRESTRICTED 10
108 if (family == AF_INET6)
109 setsockopt (fd, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
110 &(int){ PROTECTION_LEVEL_UNRESTRICTED }, sizeof (int));
113 #ifdef DCCP_SOCKOPT_SERVICE
114 if (socktype == SOL_DCCP)
116 char *dccps = var_InheritString (p_this, "dccp-service");
119 setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_SERVICE, dccps,
120 (strlen (dccps) + 3) & ~3);
130 int *net_Listen (vlc_object_t *p_this, const char *psz_host,
131 int i_port, int type, int protocol)
133 struct addrinfo hints = {
135 .ai_protocol = protocol,
136 .ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_IDN,
139 msg_Dbg (p_this, "net: listening to %s port %d",
140 (psz_host != NULL) ? psz_host : "*", i_port);
142 int i_val = vlc_getaddrinfo (psz_host, i_port, &hints, &res);
145 msg_Err (p_this, "Cannot resolve %s port %d : %s",
146 (psz_host != NULL) ? psz_host : "", i_port,
147 gai_strerror (i_val));
154 for (struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
156 int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
160 msg_Dbg (p_this, "socket error: %s", vlc_strerror_c(net_errno));
164 /* Bind the socket */
167 * Under Win32 and for multicasting, we bind to INADDR_ANY.
168 * This is of course a severe bug, since the socket would logically
169 * receive unicast traffic, and multicast traffic of groups subscribed
170 * to via other sockets.
172 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
173 && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
175 // This works for IPv4 too - don't worry!
176 struct sockaddr_in6 dumb =
178 .sin6_family = ptr->ai_addr->sa_family,
179 .sin6_port = ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
182 bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
186 if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
190 fd = rootwrap_bind (ptr->ai_family, ptr->ai_socktype,
192 ptr->ai_addr, ptr->ai_addrlen);
195 msg_Dbg (p_this, "got socket %d from rootwrap", fd);
200 msg_Err (p_this, "socket bind error: %s",
201 vlc_strerror_c(net_errno));
206 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
208 if (net_Subscribe (p_this, fd, ptr->ai_addr, ptr->ai_addrlen))
216 switch (ptr->ai_socktype)
224 if (listen (fd, INT_MAX))
226 msg_Err (p_this, "socket listen error: %s",
227 vlc_strerror_c(net_errno));
233 int *nsockv = (int *)realloc (sockv, (sockc + 2) * sizeof (int));
236 nsockv[sockc++] = fd;
252 /*****************************************************************************
254 *****************************************************************************
255 * Reads from a network socket. Cancellation point.
256 * If waitall is true, then we repeat until we have read the right amount of
257 * data; in that case, a short count means EOF has been reached or the VLC
258 * object has been signaled.
259 *****************************************************************************/
261 net_Read (vlc_object_t *restrict p_this, int fd, const v_socket_t *vs,
262 void *restrict p_buf, size_t i_buflen, bool waitall)
264 struct pollfd ufd[2];
267 ufd[0].events = POLLIN;
268 ufd[1].fd = vlc_object_waitpipe (p_this);
269 ufd[1].events = POLLIN;
273 /* With winrtsock winsocks emulation library, the first call to read()
274 * before poll() starts an asynchronous transfer and returns 0.
275 * Always call poll() first.
277 * However if we have a virtual socket handler, try to read() first.
278 * See bug #8972 for details.
288 int canc = vlc_savecancel ();
289 n = vs->pf_recv (vs->p_sys, p_buf, i_buflen);
290 vlc_restorecancel (canc);
295 n = recv (fd, p_buf, i_buflen, 0);
297 n = read (fd, p_buf, i_buflen);
305 case EAGAIN: /* no data */
306 #if (EAGAIN != EWOULDBLOCK)
311 case EINTR: /* asynchronous signal */
314 case WSAEMSGSIZE: /* datagram too big */
326 p_buf = (char *)p_buf + n;
329 if (!waitall || i_buflen == 0)
333 break;/* end of stream or empty packet */
343 /* Wait for more data */
344 if (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1) < 0)
353 msg_Dbg (p_this, "socket %d polling interrupted", fd);
358 assert (ufd[0].revents);
360 while (i_buflen > 0);
364 msg_Err (p_this, "read error: %s", vlc_strerror_c(errno));
370 * Writes data to a file descriptor.
371 * This blocks until all data is written or an error occurs.
373 * This function is a cancellation point if p_vs is NULL.
374 * This function is not cancellation-safe if p_vs is not NULL.
376 * @return the total number of bytes written, or -1 if an error occurs
377 * before any data is written.
379 ssize_t net_Write( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
380 const void *restrict p_data, size_t i_data )
383 struct pollfd ufd[2] = {
384 { .fd = fd, .events = POLLOUT },
385 { .fd = vlc_object_waitpipe (p_this), .events = POLLIN },
388 if (unlikely(ufd[1].fd == -1))
398 ufd[0].revents = ufd[1].revents = 0;
400 if (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1) == -1)
404 msg_Err (p_this, "Polling error: %s", vlc_strerror_c(errno));
409 { /* If POLLHUP resp. POLLERR|POLLNVAL occurs while we have already
410 * read some data, it is important that we first return the number
411 * of bytes read, and then return 0 resp. -1 on the NEXT call. */
412 if (ufd[0].revents & (POLLHUP|POLLERR|POLLNVAL))
414 if (ufd[1].revents) /* VLC object signaled */
427 val = p_vs->pf_send (p_vs->p_sys, p_data, i_data);
430 val = send (fd, p_data, i_data, 0);
432 val = write (fd, p_data, i_data);
439 msg_Err (p_this, "Write error: %s", vlc_strerror_c(errno));
443 p_data = (const char *)p_data + val;
448 if (unlikely(i_data == 0))
449 vlc_testcancel (); /* corner case */
451 if ((i_total > 0) || (i_data == 0))
460 * Reads a line from a file descriptor.
461 * This function is not thread-safe; the same file descriptor I/O cannot be
462 * read by another thread at the same time (although it can be written to).
464 * @note This only works with stream-oriented file descriptors, not with
465 * datagram or packet-oriented ones.
467 * @return nul-terminated heap-allocated string, or NULL on I/O error.
469 char *net_Gets(vlc_object_t *obj, int fd, const v_socket_t *vs)
472 size_t bufsize = 0, buflen = 0;
476 if (buflen == bufsize)
478 if (unlikely(bufsize >= (1 << 16)))
479 goto error; /* put sane buffer size limit */
481 char *newbuf = realloc(buf, bufsize + 1024);
482 if (unlikely(newbuf == NULL))
488 ssize_t val = net_Read(obj, fd, vs, buf + buflen, 1, false);
492 if (buf[buflen] == '\n')
499 if (buflen > 0 && buf[buflen - 1] == '\r')
500 buf[buflen - 1] = '\0';
508 ssize_t net_Printf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
509 const char *psz_fmt, ... )
513 va_start( args, psz_fmt );
514 i_ret = net_vaPrintf( p_this, fd, p_vs, psz_fmt, args );
521 ssize_t net_vaPrintf( vlc_object_t *p_this, int fd, const v_socket_t *p_vs,
522 const char *psz_fmt, va_list args )
527 int i_size = vasprintf( &psz, psz_fmt, args );
530 i_ret = net_Write( p_this, fd, p_vs, psz, i_size ) < i_size