]> git.sesse.net Git - ffmpeg/blob - libavformat/udp.c
network: Include unistd.h from network.h
[ffmpeg] / libavformat / udp.c
1 /*
2  * UDP prototype streaming system
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * UDP protocol
25  */
26
27 #define _BSD_SOURCE     /* Needed for using struct ip_mreq with recent glibc */
28
29 #include "avformat.h"
30 #include "avio_internal.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/avstring.h"
33 #include "internal.h"
34 #include "network.h"
35 #include "os_support.h"
36 #include "url.h"
37
38 #ifndef IPV6_ADD_MEMBERSHIP
39 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
40 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
41 #endif
42
43 typedef struct {
44     int udp_fd;
45     int ttl;
46     int buffer_size;
47     int is_multicast;
48     int local_port;
49     int reuse_socket;
50     struct sockaddr_storage dest_addr;
51     int dest_addr_len;
52     int is_connected;
53 } UDPContext;
54
55 #define UDP_TX_BUF_SIZE 32768
56 #define UDP_MAX_PKT_SIZE 65536
57
58 static void log_net_error(void *ctx, int level, const char* prefix)
59 {
60     char errbuf[100];
61     av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
62     av_log(ctx, level, "%s: %s\n", prefix, errbuf);
63 }
64
65 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
66                                  struct sockaddr *addr)
67 {
68 #ifdef IP_MULTICAST_TTL
69     if (addr->sa_family == AF_INET) {
70         if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
71             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
72             return -1;
73         }
74     }
75 #endif
76 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
77     if (addr->sa_family == AF_INET6) {
78         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
79             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
80             return -1;
81         }
82     }
83 #endif
84     return 0;
85 }
86
87 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
88 {
89 #ifdef IP_ADD_MEMBERSHIP
90     if (addr->sa_family == AF_INET) {
91         struct ip_mreq mreq;
92
93         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
94         mreq.imr_interface.s_addr= INADDR_ANY;
95         if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
96             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
97             return -1;
98         }
99     }
100 #endif
101 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
102     if (addr->sa_family == AF_INET6) {
103         struct ipv6_mreq mreq6;
104
105         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
106         mreq6.ipv6mr_interface= 0;
107         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
108             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
109             return -1;
110         }
111     }
112 #endif
113     return 0;
114 }
115
116 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
117 {
118 #ifdef IP_DROP_MEMBERSHIP
119     if (addr->sa_family == AF_INET) {
120         struct ip_mreq mreq;
121
122         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
123         mreq.imr_interface.s_addr= INADDR_ANY;
124         if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
125             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
126             return -1;
127         }
128     }
129 #endif
130 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
131     if (addr->sa_family == AF_INET6) {
132         struct ipv6_mreq mreq6;
133
134         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
135         mreq6.ipv6mr_interface= 0;
136         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
137             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
138             return -1;
139         }
140     }
141 #endif
142     return 0;
143 }
144
145 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
146                                          int type, int family, int flags)
147 {
148     struct addrinfo hints = { 0 }, *res = 0;
149     int error;
150     char sport[16];
151     const char *node = 0, *service = "0";
152
153     if (port > 0) {
154         snprintf(sport, sizeof(sport), "%d", port);
155         service = sport;
156     }
157     if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
158         node = hostname;
159     }
160     hints.ai_socktype = type;
161     hints.ai_family   = family;
162     hints.ai_flags = flags;
163     if ((error = getaddrinfo(node, service, &hints, &res))) {
164         res = NULL;
165         av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
166     }
167
168     return res;
169 }
170
171 static int udp_set_url(struct sockaddr_storage *addr,
172                        const char *hostname, int port)
173 {
174     struct addrinfo *res0;
175     int addr_len;
176
177     res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
178     if (res0 == 0) return AVERROR(EIO);
179     memcpy(addr, res0->ai_addr, res0->ai_addrlen);
180     addr_len = res0->ai_addrlen;
181     freeaddrinfo(res0);
182
183     return addr_len;
184 }
185
186 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
187                              int *addr_len, const char *localaddr)
188 {
189     int udp_fd = -1;
190     struct addrinfo *res0 = NULL, *res = NULL;
191     int family = AF_UNSPEC;
192
193     if (((struct sockaddr *) &s->dest_addr)->sa_family)
194         family = ((struct sockaddr *) &s->dest_addr)->sa_family;
195     res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
196                             SOCK_DGRAM, family, AI_PASSIVE);
197     if (res0 == 0)
198         goto fail;
199     for (res = res0; res; res=res->ai_next) {
200         udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
201         if (udp_fd != -1) break;
202         log_net_error(NULL, AV_LOG_ERROR, "socket");
203     }
204
205     if (udp_fd < 0)
206         goto fail;
207
208     memcpy(addr, res->ai_addr, res->ai_addrlen);
209     *addr_len = res->ai_addrlen;
210
211     freeaddrinfo(res0);
212
213     return udp_fd;
214
215  fail:
216     if (udp_fd >= 0)
217         closesocket(udp_fd);
218     if(res0)
219         freeaddrinfo(res0);
220     return -1;
221 }
222
223 static int udp_port(struct sockaddr_storage *addr, int addr_len)
224 {
225     char sbuf[sizeof(int)*3+1];
226     int error;
227
228     if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
229         av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
230         return -1;
231     }
232
233     return strtol(sbuf, NULL, 10);
234 }
235
236
237 /**
238  * If no filename is given to av_open_input_file because you want to
239  * get the local port first, then you must call this function to set
240  * the remote server address.
241  *
242  * url syntax: udp://host:port[?option=val...]
243  * option: 'ttl=n'       : set the ttl value (for multicast only)
244  *         'localport=n' : set the local port
245  *         'pkt_size=n'  : set max packet size
246  *         'reuse=1'     : enable reusing the socket
247  *
248  * @param h media file context
249  * @param uri of the remote server
250  * @return zero if no error.
251  */
252 int ff_udp_set_remote_url(URLContext *h, const char *uri)
253 {
254     UDPContext *s = h->priv_data;
255     char hostname[256], buf[10];
256     int port;
257     const char *p;
258
259     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
260
261     /* set the destination address */
262     s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
263     if (s->dest_addr_len < 0) {
264         return AVERROR(EIO);
265     }
266     s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
267     p = strchr(uri, '?');
268     if (p) {
269         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
270             int was_connected = s->is_connected;
271             s->is_connected = strtol(buf, NULL, 10);
272             if (s->is_connected && !was_connected) {
273                 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
274                             s->dest_addr_len)) {
275                     s->is_connected = 0;
276                     log_net_error(h, AV_LOG_ERROR, "connect");
277                     return AVERROR(EIO);
278                 }
279             }
280         }
281     }
282
283     return 0;
284 }
285
286 /**
287  * Return the local port used by the UDP connection
288  * @param h media file context
289  * @return the local port number
290  */
291 int ff_udp_get_local_port(URLContext *h)
292 {
293     UDPContext *s = h->priv_data;
294     return s->local_port;
295 }
296
297 /**
298  * Return the udp file handle for select() usage to wait for several RTP
299  * streams at the same time.
300  * @param h media file context
301  */
302 static int udp_get_file_handle(URLContext *h)
303 {
304     UDPContext *s = h->priv_data;
305     return s->udp_fd;
306 }
307
308 /* put it in UDP context */
309 /* return non zero if error */
310 static int udp_open(URLContext *h, const char *uri, int flags)
311 {
312     char hostname[1024], localaddr[1024] = "";
313     int port, udp_fd = -1, tmp, bind_ret = -1;
314     UDPContext *s = h->priv_data;
315     int is_output;
316     const char *p;
317     char buf[256];
318     struct sockaddr_storage my_addr;
319     int len;
320     int reuse_specified = 0;
321
322     h->is_streamed = 1;
323     h->max_packet_size = 1472;
324
325     is_output = !(flags & AVIO_FLAG_READ);
326
327     s->ttl = 16;
328     s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
329
330     p = strchr(uri, '?');
331     if (p) {
332         if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
333             char *endptr = NULL;
334             s->reuse_socket = strtol(buf, &endptr, 10);
335             /* assume if no digits were found it is a request to enable it */
336             if (buf == endptr)
337                 s->reuse_socket = 1;
338             reuse_specified = 1;
339         }
340         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
341             s->ttl = strtol(buf, NULL, 10);
342         }
343         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
344             s->local_port = strtol(buf, NULL, 10);
345         }
346         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
347             h->max_packet_size = strtol(buf, NULL, 10);
348         }
349         if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
350             s->buffer_size = strtol(buf, NULL, 10);
351         }
352         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
353             s->is_connected = strtol(buf, NULL, 10);
354         }
355         if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
356             av_strlcpy(localaddr, buf, sizeof(localaddr));
357         }
358     }
359
360     /* fill the dest addr */
361     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
362
363     /* XXX: fix av_url_split */
364     if (hostname[0] == '\0' || hostname[0] == '?') {
365         /* only accepts null hostname if input */
366         if (!(flags & AVIO_FLAG_READ))
367             goto fail;
368     } else {
369         if (ff_udp_set_remote_url(h, uri) < 0)
370             goto fail;
371     }
372
373     if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
374         s->local_port = port;
375     udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
376     if (udp_fd < 0)
377         goto fail;
378
379     /* Follow the requested reuse option, unless it's multicast in which
380      * case enable reuse unless explicitly disabled.
381      */
382     if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
383         s->reuse_socket = 1;
384         if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
385             goto fail;
386     }
387
388     /* If multicast, try binding the multicast address first, to avoid
389      * receiving UDP packets from other sources aimed at the same UDP
390      * port. This fails on windows. This makes sending to the same address
391      * using sendto() fail, so only do it if we're opened in read-only mode. */
392     if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
393         bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
394     }
395     /* bind to the local address if not multicast or if the multicast
396      * bind failed */
397     /* the bind is needed to give a port to the socket now */
398     if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
399         log_net_error(h, AV_LOG_ERROR, "bind failed");
400         goto fail;
401     }
402
403     len = sizeof(my_addr);
404     getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
405     s->local_port = udp_port(&my_addr, len);
406
407     if (s->is_multicast) {
408         if (h->flags & AVIO_FLAG_WRITE) {
409             /* output */
410             if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
411                 goto fail;
412         }
413         if (h->flags & AVIO_FLAG_READ) {
414             /* input */
415             if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
416                 goto fail;
417         }
418     }
419
420     if (is_output) {
421         /* limit the tx buf size to limit latency */
422         tmp = s->buffer_size;
423         if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
424             log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
425             goto fail;
426         }
427     } else {
428         /* set udp recv buffer size to the largest possible udp packet size to
429          * avoid losing data on OSes that set this too low by default. */
430         tmp = s->buffer_size;
431         if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
432             log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
433         }
434         /* make the socket non-blocking */
435         ff_socket_nonblock(udp_fd, 1);
436     }
437     if (s->is_connected) {
438         if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
439             log_net_error(h, AV_LOG_ERROR, "connect");
440             goto fail;
441         }
442     }
443
444     s->udp_fd = udp_fd;
445     return 0;
446  fail:
447     if (udp_fd >= 0)
448         closesocket(udp_fd);
449     return AVERROR(EIO);
450 }
451
452 static int udp_read(URLContext *h, uint8_t *buf, int size)
453 {
454     UDPContext *s = h->priv_data;
455     int ret;
456
457     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
458         ret = ff_network_wait_fd(s->udp_fd, 0);
459         if (ret < 0)
460             return ret;
461     }
462     ret = recv(s->udp_fd, buf, size, 0);
463     return ret < 0 ? ff_neterrno() : ret;
464 }
465
466 static int udp_write(URLContext *h, const uint8_t *buf, int size)
467 {
468     UDPContext *s = h->priv_data;
469     int ret;
470
471     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
472         ret = ff_network_wait_fd(s->udp_fd, 1);
473         if (ret < 0)
474             return ret;
475     }
476
477     if (!s->is_connected) {
478         ret = sendto (s->udp_fd, buf, size, 0,
479                       (struct sockaddr *) &s->dest_addr,
480                       s->dest_addr_len);
481     } else
482         ret = send(s->udp_fd, buf, size, 0);
483
484     return ret < 0 ? ff_neterrno() : ret;
485 }
486
487 static int udp_close(URLContext *h)
488 {
489     UDPContext *s = h->priv_data;
490
491     if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
492         udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
493     closesocket(s->udp_fd);
494     return 0;
495 }
496
497 URLProtocol ff_udp_protocol = {
498     .name                = "udp",
499     .url_open            = udp_open,
500     .url_read            = udp_read,
501     .url_write           = udp_write,
502     .url_close           = udp_close,
503     .url_get_file_handle = udp_get_file_handle,
504     .priv_data_size      = sizeof(UDPContext),
505     .flags               = URL_PROTOCOL_FLAG_NETWORK,
506 };