2 * Copyright (c) 2007 The FFmpeg Project
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "libavcodec/internal.h"
26 #include "libavutil/avutil.h"
27 #include "libavutil/avassert.h"
28 #include "libavutil/mem.h"
29 #include "libavutil/time.h"
33 #if CONFIG_TLS_PROTOCOL
36 if ((ret = ff_openssl_init()) < 0)
46 void ff_tls_deinit(void)
48 #if CONFIG_TLS_PROTOCOL
58 int ff_network_init(void)
63 if (WSAStartup(MAKEWORD(1,1), &wsaData))
69 int ff_network_wait_fd(int fd, int write)
71 int ev = write ? POLLOUT : POLLIN;
72 struct pollfd p = { .fd = fd, .events = ev, .revents = 0 };
74 ret = poll(&p, 1, POLLING_TIME);
75 return ret < 0 ? ff_neterrno() : p.revents & (ev | POLLERR | POLLHUP) ? 0 : AVERROR(EAGAIN);
78 int ff_network_wait_fd_timeout(int fd, int write, int64_t timeout, AVIOInterruptCB *int_cb)
81 int64_t wait_start = 0;
84 if (ff_check_interrupt(int_cb))
86 ret = ff_network_wait_fd(fd, write);
87 if (ret != AVERROR(EAGAIN))
91 wait_start = av_gettime_relative();
92 else if (av_gettime_relative() - wait_start > timeout)
93 return AVERROR(ETIMEDOUT);
98 int ff_network_sleep_interruptible(int64_t timeout, AVIOInterruptCB *int_cb)
100 int64_t wait_start = av_gettime_relative();
105 if (ff_check_interrupt(int_cb))
108 time_left = timeout - (av_gettime_relative() - wait_start);
110 return AVERROR(ETIMEDOUT);
112 av_usleep(FFMIN(time_left, POLLING_TIME * 1000));
116 void ff_network_close(void)
124 int ff_neterrno(void)
126 int err = WSAGetLastError();
129 return AVERROR(EAGAIN);
131 return AVERROR(EINTR);
132 case WSAEPROTONOSUPPORT:
133 return AVERROR(EPROTONOSUPPORT);
135 return AVERROR(ETIMEDOUT);
136 case WSAECONNREFUSED:
137 return AVERROR(ECONNREFUSED);
139 return AVERROR(EINPROGRESS);
145 int ff_is_multicast_address(struct sockaddr *addr)
147 if (addr->sa_family == AF_INET) {
148 return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr));
150 #if HAVE_STRUCT_SOCKADDR_IN6
151 if (addr->sa_family == AF_INET6) {
152 return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr);
159 static int ff_poll_interrupt(struct pollfd *p, nfds_t nfds, int timeout,
162 int runs = timeout / POLLING_TIME;
166 if (ff_check_interrupt(cb))
168 ret = poll(p, nfds, POLLING_TIME);
172 if (ret == AVERROR(EINTR))
176 } while (timeout <= 0 || runs-- > 0);
179 return AVERROR(ETIMEDOUT);
183 int ff_socket(int af, int type, int proto)
188 fd = socket(af, type | SOCK_CLOEXEC, proto);
189 if (fd == -1 && errno == EINVAL)
192 fd = socket(af, type, proto);
195 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
196 av_log(NULL, AV_LOG_DEBUG, "Failed to set close on exec\n");
202 if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &(int){1}, sizeof(int))) {
203 av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_NOSIGPIPE) failed\n");
210 int ff_listen(int fd, const struct sockaddr *addr,
215 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) {
216 av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_REUSEADDR) failed\n");
218 ret = bind(fd, addr, addrlen);
220 return ff_neterrno();
224 return ff_neterrno();
228 int ff_accept(int fd, int timeout, URLContext *h)
231 struct pollfd lp = { fd, POLLIN, 0 };
233 ret = ff_poll_interrupt(&lp, 1, timeout, &h->interrupt_callback);
237 ret = accept(fd, NULL, NULL);
239 return ff_neterrno();
240 if (ff_socket_nonblock(ret, 1) < 0)
241 av_log(h, AV_LOG_DEBUG, "ff_socket_nonblock failed\n");
246 int ff_listen_bind(int fd, const struct sockaddr *addr,
247 socklen_t addrlen, int timeout, URLContext *h)
250 if ((ret = ff_listen(fd, addr, addrlen)) < 0)
252 if ((ret = ff_accept(fd, timeout, h)) < 0)
258 int ff_listen_connect(int fd, const struct sockaddr *addr,
259 socklen_t addrlen, int timeout, URLContext *h,
262 struct pollfd p = {fd, POLLOUT, 0};
266 if (ff_socket_nonblock(fd, 1) < 0)
267 av_log(h, AV_LOG_DEBUG, "ff_socket_nonblock failed\n");
269 while ((ret = connect(fd, addr, addrlen))) {
273 if (ff_check_interrupt(&h->interrupt_callback))
276 case AVERROR(EINPROGRESS):
277 case AVERROR(EAGAIN):
278 ret = ff_poll_interrupt(&p, 1, timeout, &h->interrupt_callback);
281 optlen = sizeof(ret);
282 if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen))
283 ret = AVUNERROR(ff_neterrno());
287 av_strerror(ret, errbuf, sizeof(errbuf));
289 av_log(h, AV_LOG_WARNING,
290 "Connection to %s failed (%s), trying next address\n",
291 h->filename, errbuf);
293 av_log(h, AV_LOG_ERROR, "Connection to %s failed: %s\n",
294 h->filename, errbuf);
303 static void interleave_addrinfo(struct addrinfo *base)
305 struct addrinfo **next = &base->ai_next;
307 struct addrinfo *cur = *next;
308 // Iterate forward until we find an entry of a different family.
309 if (cur->ai_family == base->ai_family) {
310 next = &cur->ai_next;
313 if (cur == base->ai_next) {
314 // If the first one following base is of a different family, just
315 // move base forward one step and continue.
317 next = &base->ai_next;
320 // Unchain cur from the rest of the list from its current spot.
321 *next = cur->ai_next;
322 // Hook in cur directly after base.
323 cur->ai_next = base->ai_next;
325 // Restart with a new base. We know that before moving the cur element,
326 // everything between the previous base and cur had the same family,
327 // different from cur->ai_family. Therefore, we can keep next pointing
328 // where it was, and continue from there with base at the one after
334 static void print_address_list(void *ctx, const struct addrinfo *addr,
337 char hostbuf[100], portbuf[20];
338 av_log(ctx, AV_LOG_DEBUG, "%s:\n", title);
340 getnameinfo(addr->ai_addr, addr->ai_addrlen,
341 hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
342 NI_NUMERICHOST | NI_NUMERICSERV);
343 av_log(ctx, AV_LOG_DEBUG, "Address %s port %s\n", hostbuf, portbuf);
344 addr = addr->ai_next;
348 struct ConnectionAttempt {
351 struct addrinfo *addr;
354 // Returns < 0 on error, 0 on successfully started connection attempt,
355 // > 0 for a connection that succeeded already.
356 static int start_connect_attempt(struct ConnectionAttempt *attempt,
357 struct addrinfo **ptr, int timeout_ms,
359 void (*customize_fd)(void *, int), void *customize_ctx)
361 struct addrinfo *ai = *ptr;
366 attempt->fd = ff_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
368 return ff_neterrno();
369 attempt->deadline_us = av_gettime_relative() + timeout_ms * 1000;
372 ff_socket_nonblock(attempt->fd, 1);
375 customize_fd(customize_ctx, attempt->fd);
377 while ((ret = connect(attempt->fd, ai->ai_addr, ai->ai_addrlen))) {
381 if (ff_check_interrupt(&h->interrupt_callback)) {
382 closesocket(attempt->fd);
387 case AVERROR(EINPROGRESS):
388 case AVERROR(EAGAIN):
391 closesocket(attempt->fd);
399 // Try a new connection to another address after 200 ms, as suggested in
400 // RFC 8305 (or sooner if an earlier attempt fails).
401 #define NEXT_ATTEMPT_DELAY_MS 200
403 int ff_connect_parallel(struct addrinfo *addrs, int timeout_ms_per_address,
404 int parallel, URLContext *h, int *fd,
405 void (*customize_fd)(void *, int), void *customize_ctx)
407 struct ConnectionAttempt attempts[3];
408 struct pollfd pfd[3];
409 int nb_attempts = 0, i, j;
410 int64_t next_attempt_us = av_gettime_relative(), next_deadline_us;
411 int last_err = AVERROR(EIO);
413 char errbuf[100], hostbuf[100], portbuf[20];
415 if (parallel > FF_ARRAY_ELEMS(attempts))
416 parallel = FF_ARRAY_ELEMS(attempts);
418 print_address_list(h, addrs, "Original list of addresses");
419 // This mutates the list, but the head of the list is still the same
420 // element, so the caller, who owns the list, doesn't need to get
421 // an updated pointer.
422 interleave_addrinfo(addrs);
423 print_address_list(h, addrs, "Interleaved list of addresses");
425 while (nb_attempts > 0 || addrs) {
426 // Start a new connection attempt, if possible.
427 if (nb_attempts < parallel && addrs) {
428 getnameinfo(addrs->ai_addr, addrs->ai_addrlen,
429 hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
430 NI_NUMERICHOST | NI_NUMERICSERV);
431 av_log(h, AV_LOG_VERBOSE, "Starting connection attempt to %s port %s\n",
433 last_err = start_connect_attempt(&attempts[nb_attempts], &addrs,
434 timeout_ms_per_address, h,
435 customize_fd, customize_ctx);
437 av_strerror(last_err, errbuf, sizeof(errbuf));
438 av_log(h, AV_LOG_VERBOSE, "Connected attempt failed: %s\n",
443 for (i = 0; i < nb_attempts; i++)
444 closesocket(attempts[i].fd);
445 *fd = attempts[nb_attempts].fd;
448 pfd[nb_attempts].fd = attempts[nb_attempts].fd;
449 pfd[nb_attempts].events = POLLOUT;
450 next_attempt_us = av_gettime_relative() + NEXT_ATTEMPT_DELAY_MS * 1000;
454 av_assert0(nb_attempts > 0);
455 // The connection attempts are sorted from oldest to newest, so the
456 // first one will have the earliest deadline.
457 next_deadline_us = attempts[0].deadline_us;
458 // If we can start another attempt in parallel, wait until that time.
459 if (nb_attempts < parallel && addrs)
460 next_deadline_us = FFMIN(next_deadline_us, next_attempt_us);
461 last_err = ff_poll_interrupt(pfd, nb_attempts,
462 (next_deadline_us - av_gettime_relative())/1000,
463 &h->interrupt_callback);
464 if (last_err < 0 && last_err != AVERROR(ETIMEDOUT))
467 // Check the status from the poll output.
468 for (i = 0; i < nb_attempts; i++) {
470 if (pfd[i].revents) {
471 // Some sort of action for this socket, check its status (either
472 // a successful connection or an error).
473 optlen = sizeof(last_err);
474 if (getsockopt(attempts[i].fd, SOL_SOCKET, SO_ERROR, &last_err, &optlen))
475 last_err = ff_neterrno();
476 else if (last_err != 0)
477 last_err = AVERROR(last_err);
479 // Everything is ok, we seem to have a successful
480 // connection. Close other sockets and return this one.
481 for (j = 0; j < nb_attempts; j++)
483 closesocket(attempts[j].fd);
484 *fd = attempts[i].fd;
485 getnameinfo(attempts[i].addr->ai_addr, attempts[i].addr->ai_addrlen,
486 hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
487 NI_NUMERICHOST | NI_NUMERICSERV);
488 av_log(h, AV_LOG_VERBOSE, "Successfully connected to %s port %s\n",
493 if (attempts[i].deadline_us < av_gettime_relative() && !last_err)
494 last_err = AVERROR(ETIMEDOUT);
497 // Error (or timeout) for this socket; close the socket and remove
498 // it from the attempts/pfd arrays, to let a new attempt start
500 getnameinfo(attempts[i].addr->ai_addr, attempts[i].addr->ai_addrlen,
501 hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
502 NI_NUMERICHOST | NI_NUMERICSERV);
503 av_strerror(last_err, errbuf, sizeof(errbuf));
504 av_log(h, AV_LOG_VERBOSE, "Connection attempt to %s port %s "
505 "failed: %s\n", hostbuf, portbuf, errbuf);
506 closesocket(attempts[i].fd);
507 memmove(&attempts[i], &attempts[i + 1],
508 (nb_attempts - i - 1) * sizeof(*attempts));
509 memmove(&pfd[i], &pfd[i + 1],
510 (nb_attempts - i - 1) * sizeof(*pfd));
515 for (i = 0; i < nb_attempts; i++)
516 closesocket(attempts[i].fd);
518 last_err = AVERROR(ECONNREFUSED);
519 if (last_err != AVERROR_EXIT) {
520 av_strerror(last_err, errbuf, sizeof(errbuf));
521 av_log(h, AV_LOG_ERROR, "Connection to %s failed: %s\n",
522 h->filename, errbuf);
527 static int match_host_pattern(const char *pattern, const char *hostname)
530 if (!strcmp(pattern, "*"))
532 // Skip a possible *. at the start of the pattern
533 if (pattern[0] == '*')
535 if (pattern[0] == '.')
537 len_p = strlen(pattern);
538 len_h = strlen(hostname);
541 // Simply check if the end of hostname is equal to 'pattern'
542 if (!strcmp(pattern, &hostname[len_h - len_p])) {
544 return 1; // Exact match
545 if (hostname[len_h - len_p - 1] == '.')
546 return 1; // The matched substring is a domain and not just a substring of a domain
551 int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
559 buf = av_strdup(no_proxy);
564 char *sep, *next = NULL;
565 start += strspn(start, " ,");
566 sep = start + strcspn(start, " ,");
571 if (match_host_pattern(start, hostname)) {
581 void ff_log_net_error(void *ctx, int level, const char* prefix)
584 av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
585 av_log(ctx, level, "%s: %s\n", prefix, errbuf);