udp.c 14.9 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1 2
/*
 * UDP prototype streaming system
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * Libav is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
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
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
21 22

/**
23
 * @file
24 25 26
 * UDP protocol
 */

27
#define _BSD_SOURCE     /* Needed for using struct ip_mreq with recent glibc */
28

Fabrice Bellard's avatar
Fabrice Bellard committed
29
#include "avformat.h"
30
#include "avio_internal.h"
31
#include "libavutil/parseutils.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
32
#include <unistd.h>
33
#include "internal.h"
34
#include "network.h"
35
#include "os_support.h"
36
#include "url.h"
37
#include <sys/time.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
38

39 40 41 42 43
#ifndef IPV6_ADD_MEMBERSHIP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif

Fabrice Bellard's avatar
Fabrice Bellard committed
44
typedef struct {
45 46
    int udp_fd;
    int ttl;
47
    int buffer_size;
48 49
    int is_multicast;
    int local_port;
50
    int reuse_socket;
51
    struct sockaddr_storage dest_addr;
52
    int dest_addr_len;
53
    int is_connected;
Fabrice Bellard's avatar
Fabrice Bellard committed
54 55 56
} UDPContext;

#define UDP_TX_BUF_SIZE 32768
57
#define UDP_MAX_PKT_SIZE 65536
Fabrice Bellard's avatar
Fabrice Bellard committed
58

59 60 61
static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
                                 struct sockaddr *addr)
{
62
#ifdef IP_MULTICAST_TTL
63 64
    if (addr->sa_family == AF_INET) {
        if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
65
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
66 67 68
            return -1;
        }
    }
69
#endif
70
#if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
71 72
    if (addr->sa_family == AF_INET6) {
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
73
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
74 75 76
            return -1;
        }
    }
77
#endif
78 79 80
    return 0;
}

81 82
static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
{
83
#ifdef IP_ADD_MEMBERSHIP
84
    if (addr->sa_family == AF_INET) {
85 86
        struct ip_mreq mreq;

87 88 89
        mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
        mreq.imr_interface.s_addr= INADDR_ANY;
        if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
90
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
91 92 93
            return -1;
        }
    }
94
#endif
95
#if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
96
    if (addr->sa_family == AF_INET6) {
97 98
        struct ipv6_mreq mreq6;

99 100 101
        memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
        mreq6.ipv6mr_interface= 0;
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
102
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
103 104 105
            return -1;
        }
    }
106
#endif
107 108 109
    return 0;
}

110 111
static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
{
112
#ifdef IP_DROP_MEMBERSHIP
113
    if (addr->sa_family == AF_INET) {
114 115
        struct ip_mreq mreq;

116 117 118
        mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
        mreq.imr_interface.s_addr= INADDR_ANY;
        if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
119
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
120 121 122
            return -1;
        }
    }
123
#endif
124
#if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
125
    if (addr->sa_family == AF_INET6) {
126 127
        struct ipv6_mreq mreq6;

128 129 130
        memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
        mreq6.ipv6mr_interface= 0;
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
131
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
132 133 134
            return -1;
        }
    }
135
#endif
136 137 138
    return 0;
}

139 140 141
static struct addrinfo* udp_resolve_host(const char *hostname, int port,
                                         int type, int family, int flags)
{
142 143 144
    struct addrinfo hints, *res = 0;
    int error;
    char sport[16];
145
    const char *node = 0, *service = "0";
146 147

    if (port > 0) {
Michael Niedermayer's avatar
Michael Niedermayer committed
148
        snprintf(sport, sizeof(sport), "%d", port);
149 150 151 152 153
        service = sport;
    }
    if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
        node = hostname;
    }
Luca Abeni's avatar
Luca Abeni committed
154 155 156 157 158
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = type;
    hints.ai_family   = family;
    hints.ai_flags = flags;
    if ((error = getaddrinfo(node, service, &hints, &res))) {
159
        res = NULL;
160
        av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
Luca Abeni's avatar
Luca Abeni committed
161 162
    }

163 164 165
    return res;
}

166 167 168
static int udp_set_url(struct sockaddr_storage *addr,
                       const char *hostname, int port)
{
169
    struct addrinfo *res0;
170 171
    int addr_len;

172
    res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
173
    if (res0 == 0) return AVERROR(EIO);
174 175
    memcpy(addr, res0->ai_addr, res0->ai_addrlen);
    addr_len = res0->ai_addrlen;
176
    freeaddrinfo(res0);
177 178

    return addr_len;
179 180
}

181 182
static int udp_socket_create(UDPContext *s,
                             struct sockaddr_storage *addr, int *addr_len)
183
{
184
    int udp_fd = -1;
185
    struct addrinfo *res0 = NULL, *res = NULL;
186
    int family = AF_UNSPEC;
187

188 189
    if (((struct sockaddr *) &s->dest_addr)->sa_family)
        family = ((struct sockaddr *) &s->dest_addr)->sa_family;
190
    res0 = udp_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE);
Luca Abeni's avatar
Luca Abeni committed
191 192 193 194 195
    if (res0 == 0)
        goto fail;
    for (res = res0; res; res=res->ai_next) {
        udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
        if (udp_fd > 0) break;
196
        av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
Luca Abeni's avatar
Luca Abeni committed
197
    }
198 199

    if (udp_fd < 0)
200
        goto fail;
201

202 203
    memcpy(addr, res->ai_addr, res->ai_addrlen);
    *addr_len = res->ai_addrlen;
204

205
    freeaddrinfo(res0);
206

207
    return udp_fd;
208

209 210 211
 fail:
    if (udp_fd >= 0)
        closesocket(udp_fd);
212 213
    if(res0)
        freeaddrinfo(res0);
214 215 216
    return -1;
}

217 218
static int udp_port(struct sockaddr_storage *addr, int addr_len)
{
219
    char sbuf[sizeof(int)*3+1];
220

221
    if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
222
        av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
223 224 225 226 227 228
        return -1;
    }

    return strtol(sbuf, NULL, 10);
}

229

230 231 232 233 234 235
/**
 * If no filename is given to av_open_input_file because you want to
 * get the local port first, then you must call this function to set
 * the remote server address.
 *
 * url syntax: udp://host:port[?option=val...]
236
 * option: 'ttl=n'       : set the ttl value (for multicast only)
237
 *         'localport=n' : set the local port
238
 *         'pkt_size=n'  : set max packet size
239
 *         'reuse=1'     : enable reusing the socket
240
 *
241
 * @param h media file context
242 243 244
 * @param uri of the remote server
 * @return zero if no error.
 */
245
int ff_udp_set_remote_url(URLContext *h, const char *uri)
246 247
{
    UDPContext *s = h->priv_data;
248
    char hostname[256], buf[10];
249
    int port;
250
    const char *p;
251

252
    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
Fabrice Bellard's avatar
Fabrice Bellard committed
253

254
    /* set the destination address */
255 256
    s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
    if (s->dest_addr_len < 0) {
257
        return AVERROR(EIO);
258
    }
259
    s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
260 261
    p = strchr(uri, '?');
    if (p) {
262
        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
263 264 265 266 267 268
            int was_connected = s->is_connected;
            s->is_connected = strtol(buf, NULL, 10);
            if (s->is_connected && !was_connected) {
                if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
                            s->dest_addr_len)) {
                    s->is_connected = 0;
269
                    av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
270 271 272 273 274
                    return AVERROR(EIO);
                }
            }
        }
    }
275

276 277 278 279
    return 0;
}

/**
280
 * Return the local port used by the UDP connection
281
 * @param h media file context
282 283
 * @return the local port number
 */
284
int ff_udp_get_local_port(URLContext *h)
285 286 287 288 289 290 291 292 293 294
{
    UDPContext *s = h->priv_data;
    return s->local_port;
}

/**
 * Return the udp file handle for select() usage to wait for several RTP
 * streams at the same time.
 * @param h media file context
 */
295
static int udp_get_file_handle(URLContext *h)
296 297 298 299 300 301
{
    UDPContext *s = h->priv_data;
    return s->udp_fd;
}

/* put it in UDP context */
Fabrice Bellard's avatar
Fabrice Bellard committed
302 303 304 305
/* return non zero if error */
static int udp_open(URLContext *h, const char *uri, int flags)
{
    char hostname[1024];
306
    int port, udp_fd = -1, tmp, bind_ret = -1;
307
    UDPContext *s = NULL;
308
    int is_output;
309 310
    const char *p;
    char buf[256];
311 312
    struct sockaddr_storage my_addr;
    int len;
313
    int reuse_specified = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
314 315

    h->is_streamed = 1;
316
    h->max_packet_size = 1472;
Fabrice Bellard's avatar
Fabrice Bellard committed
317

318
    is_output = !(flags & AVIO_FLAG_READ);
319

320
    s = av_mallocz(sizeof(UDPContext));
321
    if (!s)
322
        return AVERROR(ENOMEM);
323 324 325

    h->priv_data = s;
    s->ttl = 16;
326 327
    s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;

328 329
    p = strchr(uri, '?');
    if (p) {
330
        if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
331
            char *endptr = NULL;
332 333 334 335 336 337
            s->reuse_socket = strtol(buf, &endptr, 10);
            /* assume if no digits were found it is a request to enable it */
            if (buf == endptr)
                s->reuse_socket = 1;
            reuse_specified = 1;
        }
338
        if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
339 340
            s->ttl = strtol(buf, NULL, 10);
        }
341
        if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
342 343
            s->local_port = strtol(buf, NULL, 10);
        }
344
        if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
345 346
            h->max_packet_size = strtol(buf, NULL, 10);
        }
347
        if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
348 349
            s->buffer_size = strtol(buf, NULL, 10);
        }
350
        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
351 352
            s->is_connected = strtol(buf, NULL, 10);
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
353
    }
354 355

    /* fill the dest addr */
356
    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
357

358
    /* XXX: fix av_url_split */
359 360
    if (hostname[0] == '\0' || hostname[0] == '?') {
        /* only accepts null hostname if input */
361
        if (!(flags & AVIO_FLAG_READ))
362 363
            goto fail;
    } else {
364
        if (ff_udp_set_remote_url(h, uri) < 0)
365
            goto fail;
366
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
367

368
    if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
369
        s->local_port = port;
370
    udp_fd = udp_socket_create(s, &my_addr, &len);
371 372 373
    if (udp_fd < 0)
        goto fail;

374 375 376 377 378
    /* Follow the requested reuse option, unless it's multicast in which
     * case enable reuse unless explicitely disabled.
     */
    if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
        s->reuse_socket = 1;
379 380
        if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
            goto fail;
381
    }
382

Fabrice Bellard's avatar
Fabrice Bellard committed
383
    /* the bind is needed to give a port to the socket now */
384
    /* if multicast, try the multicast address bind first */
385
    if (s->is_multicast && (h->flags & AVIO_FLAG_READ)) {
386 387 388 389 390
        bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
    }
    /* bind to the local address if not multicast or if the multicast
     * bind failed */
    if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0)
Fabrice Bellard's avatar
Fabrice Bellard committed
391 392
        goto fail;

393 394
    len = sizeof(my_addr);
    getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
395 396
    s->local_port = udp_port(&my_addr, len);

397
    if (s->is_multicast) {
398
        if (!(h->flags & AVIO_FLAG_READ)) {
399
            /* output */
400
            if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
401 402
                goto fail;
        } else {
403
            /* input */
404
            if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
405 406 407
                goto fail;
        }
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
408

409 410
    if (is_output) {
        /* limit the tx buf size to limit latency */
411
        tmp = s->buffer_size;
412
        if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
413
            av_log(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
414 415
            goto fail;
        }
416 417 418
    } else {
        /* set udp recv buffer size to the largest possible udp packet size to
         * avoid losing data on OSes that set this too low by default. */
419 420
        tmp = s->buffer_size;
        if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
421
            av_log(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
422
        }
423 424
        /* make the socket non-blocking */
        ff_socket_nonblock(udp_fd, 1);
425
    }
426 427
    if (s->is_connected) {
        if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
428
            av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
429 430 431
            goto fail;
        }
    }
432 433

    s->udp_fd = udp_fd;
Fabrice Bellard's avatar
Fabrice Bellard committed
434 435
    return 0;
 fail:
436
    if (udp_fd >= 0)
437
        closesocket(udp_fd);
438
    av_free(s);
439
    return AVERROR(EIO);
Fabrice Bellard's avatar
Fabrice Bellard committed
440 441
}

442
static int udp_read(URLContext *h, uint8_t *buf, int size)
Fabrice Bellard's avatar
Fabrice Bellard committed
443 444
{
    UDPContext *s = h->priv_data;
445
    int ret;
446

447
    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
448 449 450
        ret = ff_network_wait_fd(s->udp_fd, 0);
        if (ret < 0)
            return ret;
451
    }
452 453
    ret = recv(s->udp_fd, buf, size, 0);
    return ret < 0 ? ff_neterrno() : ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
454 455
}

456
static int udp_write(URLContext *h, const uint8_t *buf, int size)
Fabrice Bellard's avatar
Fabrice Bellard committed
457 458
{
    UDPContext *s = h->priv_data;
459 460
    int ret;

461
    if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
462 463 464
        ret = ff_network_wait_fd(s->udp_fd, 1);
        if (ret < 0)
            return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
465
    }
466 467 468 469 470 471 472 473 474

    if (!s->is_connected) {
        ret = sendto (s->udp_fd, buf, size, 0,
                      (struct sockaddr *) &s->dest_addr,
                      s->dest_addr_len);
    } else
        ret = send(s->udp_fd, buf, size, 0);

    return ret < 0 ? ff_neterrno() : ret;
475 476 477 478 479 480
}

static int udp_close(URLContext *h)
{
    UDPContext *s = h->priv_data;

481
    if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
482
        udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
483
    closesocket(s->udp_fd);
484 485
    av_free(s);
    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
486 487
}

488
URLProtocol ff_udp_protocol = {
489 490 491 492 493
    .name                = "udp",
    .url_open            = udp_open,
    .url_read            = udp_read,
    .url_write           = udp_write,
    .url_close           = udp_close,
494
    .url_get_file_handle = udp_get_file_handle,
Fabrice Bellard's avatar
Fabrice Bellard committed
495
};