You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

522 lines
17KB

  1. /*
  2. * Copyright (c) 2007 The Libav Project
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav 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.
  10. *
  11. * Libav 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.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with Libav; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <fcntl.h>
  21. #include "network.h"
  22. #include "tls.h"
  23. #include "url.h"
  24. #include "libavcodec/internal.h"
  25. #include "libavutil/avassert.h"
  26. #include "libavutil/mem.h"
  27. #include "libavutil/time.h"
  28. void ff_tls_init(void)
  29. {
  30. #if CONFIG_TLS_PROTOCOL
  31. #if CONFIG_OPENSSL
  32. ff_openssl_init();
  33. #endif
  34. #if CONFIG_GNUTLS
  35. ff_gnutls_init();
  36. #endif
  37. #endif
  38. }
  39. void ff_tls_deinit(void)
  40. {
  41. #if CONFIG_TLS_PROTOCOL
  42. #if CONFIG_OPENSSL
  43. ff_openssl_deinit();
  44. #endif
  45. #if CONFIG_GNUTLS
  46. ff_gnutls_deinit();
  47. #endif
  48. #endif
  49. }
  50. int ff_network_inited_globally;
  51. int ff_network_init(void)
  52. {
  53. #if HAVE_WINSOCK2_H
  54. WSADATA wsaData;
  55. #endif
  56. if (!ff_network_inited_globally)
  57. av_log(NULL, AV_LOG_WARNING, "Using network protocols without global "
  58. "network initialization. Please use "
  59. "avformat_network_init(), this will "
  60. "become mandatory later.\n");
  61. #if HAVE_WINSOCK2_H
  62. if (WSAStartup(MAKEWORD(1,1), &wsaData))
  63. return 0;
  64. #endif
  65. return 1;
  66. }
  67. int ff_network_wait_fd(int fd, int write)
  68. {
  69. int ev = write ? POLLOUT : POLLIN;
  70. struct pollfd p = { .fd = fd, .events = ev, .revents = 0 };
  71. int ret;
  72. ret = poll(&p, 1, 100);
  73. return ret < 0 ? ff_neterrno() : p.revents & (ev | POLLERR | POLLHUP) ? 0 : AVERROR(EAGAIN);
  74. }
  75. void ff_network_close(void)
  76. {
  77. #if HAVE_WINSOCK2_H
  78. WSACleanup();
  79. #endif
  80. }
  81. #if HAVE_WINSOCK2_H
  82. int ff_neterrno(void)
  83. {
  84. int err = WSAGetLastError();
  85. switch (err) {
  86. case WSAEWOULDBLOCK:
  87. return AVERROR(EAGAIN);
  88. case WSAEINTR:
  89. return AVERROR(EINTR);
  90. case WSAEPROTONOSUPPORT:
  91. return AVERROR(EPROTONOSUPPORT);
  92. case WSAETIMEDOUT:
  93. return AVERROR(ETIMEDOUT);
  94. case WSAECONNREFUSED:
  95. return AVERROR(ECONNREFUSED);
  96. case WSAEINPROGRESS:
  97. return AVERROR(EINPROGRESS);
  98. }
  99. return -err;
  100. }
  101. #endif
  102. int ff_is_multicast_address(struct sockaddr *addr)
  103. {
  104. if (addr->sa_family == AF_INET) {
  105. return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr));
  106. }
  107. #if HAVE_STRUCT_SOCKADDR_IN6
  108. if (addr->sa_family == AF_INET6) {
  109. return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr);
  110. }
  111. #endif
  112. return 0;
  113. }
  114. static int ff_poll_interrupt(struct pollfd *p, nfds_t nfds, int timeout,
  115. AVIOInterruptCB *cb)
  116. {
  117. int runs = timeout / POLLING_TIME;
  118. int ret = 0;
  119. do {
  120. if (ff_check_interrupt(cb))
  121. return AVERROR_EXIT;
  122. ret = poll(p, nfds, POLLING_TIME);
  123. if (ret != 0) {
  124. if (ret < 0)
  125. ret = ff_neterrno();
  126. if (ret == AVERROR(EINTR))
  127. continue;
  128. break;
  129. }
  130. } while (timeout < 0 || runs-- > 0);
  131. if (!ret)
  132. return AVERROR(ETIMEDOUT);
  133. return ret;
  134. }
  135. int ff_socket(int af, int type, int proto)
  136. {
  137. int fd;
  138. #ifdef SOCK_CLOEXEC
  139. fd = socket(af, type | SOCK_CLOEXEC, proto);
  140. if (fd == -1 && errno == EINVAL)
  141. #endif
  142. {
  143. fd = socket(af, type, proto);
  144. #if HAVE_FCNTL
  145. if (fd != -1)
  146. fcntl(fd, F_SETFD, FD_CLOEXEC);
  147. #endif
  148. }
  149. #ifdef SO_NOSIGPIPE
  150. if (fd != -1)
  151. setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &(int){1}, sizeof(int));
  152. #endif
  153. return fd;
  154. }
  155. int ff_listen_bind(int fd, const struct sockaddr *addr,
  156. socklen_t addrlen, int timeout, URLContext *h)
  157. {
  158. int ret;
  159. int reuse = 1;
  160. struct pollfd lp = { fd, POLLIN, 0 };
  161. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  162. ret = bind(fd, addr, addrlen);
  163. if (ret)
  164. return ff_neterrno();
  165. ret = listen(fd, 1);
  166. if (ret)
  167. return ff_neterrno();
  168. ret = ff_poll_interrupt(&lp, 1, timeout, &h->interrupt_callback);
  169. if (ret < 0)
  170. return ret;
  171. ret = accept(fd, NULL, NULL);
  172. if (ret < 0)
  173. return ff_neterrno();
  174. closesocket(fd);
  175. ff_socket_nonblock(ret, 1);
  176. return ret;
  177. }
  178. int ff_listen_connect(int fd, const struct sockaddr *addr,
  179. socklen_t addrlen, int timeout, URLContext *h,
  180. int will_try_next)
  181. {
  182. struct pollfd p = {fd, POLLOUT, 0};
  183. int ret;
  184. socklen_t optlen;
  185. ff_socket_nonblock(fd, 1);
  186. while ((ret = connect(fd, addr, addrlen))) {
  187. ret = ff_neterrno();
  188. switch (ret) {
  189. case AVERROR(EINTR):
  190. if (ff_check_interrupt(&h->interrupt_callback))
  191. return AVERROR_EXIT;
  192. continue;
  193. case AVERROR(EINPROGRESS):
  194. case AVERROR(EAGAIN):
  195. ret = ff_poll_interrupt(&p, 1, timeout, &h->interrupt_callback);
  196. if (ret < 0)
  197. return ret;
  198. optlen = sizeof(ret);
  199. if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen))
  200. ret = AVUNERROR(ff_neterrno());
  201. if (ret != 0) {
  202. char errbuf[100];
  203. ret = AVERROR(ret);
  204. av_strerror(ret, errbuf, sizeof(errbuf));
  205. if (will_try_next)
  206. av_log(h, AV_LOG_WARNING,
  207. "Connection to %s failed (%s), trying next address\n",
  208. h->filename, errbuf);
  209. else
  210. av_log(h, AV_LOG_ERROR, "Connection to %s failed: %s\n",
  211. h->filename, errbuf);
  212. }
  213. default:
  214. return ret;
  215. }
  216. }
  217. return ret;
  218. }
  219. static void interleave_addrinfo(struct addrinfo *base)
  220. {
  221. struct addrinfo **next = &base->ai_next;
  222. while (*next) {
  223. struct addrinfo *cur = *next;
  224. // Iterate forward until we find an entry of a different family.
  225. if (cur->ai_family == base->ai_family) {
  226. next = &cur->ai_next;
  227. continue;
  228. }
  229. if (cur == base->ai_next) {
  230. // If the first one following base is of a different family, just
  231. // move base forward one step and continue.
  232. base = cur;
  233. next = &base->ai_next;
  234. continue;
  235. }
  236. // Unchain cur from the rest of the list from its current spot.
  237. *next = cur->ai_next;
  238. // Hook in cur directly after base.
  239. cur->ai_next = base->ai_next;
  240. base->ai_next = cur;
  241. // Restart with a new base. We know that before moving the cur element,
  242. // everything between the previous base and cur had the same family,
  243. // different from cur->ai_family. Therefore, we can keep next pointing
  244. // where it was, and continue from there with base at the one after
  245. // cur.
  246. base = cur->ai_next;
  247. }
  248. }
  249. static void print_address_list(void *ctx, const struct addrinfo *addr,
  250. const char *title)
  251. {
  252. char hostbuf[100], portbuf[20];
  253. av_log(ctx, AV_LOG_DEBUG, "%s:\n", title);
  254. while (addr) {
  255. getnameinfo(addr->ai_addr, addr->ai_addrlen,
  256. hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
  257. NI_NUMERICHOST | NI_NUMERICSERV);
  258. av_log(ctx, AV_LOG_DEBUG, "Address %s port %s\n", hostbuf, portbuf);
  259. addr = addr->ai_next;
  260. }
  261. }
  262. struct ConnectionAttempt {
  263. int fd;
  264. int64_t deadline_us;
  265. struct addrinfo *addr;
  266. };
  267. // Returns < 0 on error, 0 on successfully started connection attempt,
  268. // > 0 for a connection that succeeded already.
  269. static int start_connect_attempt(struct ConnectionAttempt *attempt,
  270. struct addrinfo **ptr, int timeout_ms,
  271. URLContext *h,
  272. void (*customize_fd)(void *, int), void *customize_ctx)
  273. {
  274. struct addrinfo *ai = *ptr;
  275. int ret;
  276. *ptr = ai->ai_next;
  277. attempt->fd = ff_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  278. if (attempt->fd < 0)
  279. return ff_neterrno();
  280. attempt->deadline_us = av_gettime_relative() + timeout_ms * 1000;
  281. attempt->addr = ai;
  282. ff_socket_nonblock(attempt->fd, 1);
  283. if (customize_fd)
  284. customize_fd(customize_ctx, attempt->fd);
  285. while ((ret = connect(attempt->fd, ai->ai_addr, ai->ai_addrlen))) {
  286. ret = ff_neterrno();
  287. switch (ret) {
  288. case AVERROR(EINTR):
  289. if (ff_check_interrupt(&h->interrupt_callback)) {
  290. closesocket(attempt->fd);
  291. attempt->fd = -1;
  292. return AVERROR_EXIT;
  293. }
  294. continue;
  295. case AVERROR(EINPROGRESS):
  296. case AVERROR(EAGAIN):
  297. return 0;
  298. default:
  299. closesocket(attempt->fd);
  300. attempt->fd = -1;
  301. return ret;
  302. }
  303. }
  304. return 1;
  305. }
  306. // Try a new connection to another address after 200 ms, as suggested in
  307. // RFC 8305 (or sooner if an earlier attempt fails).
  308. #define NEXT_ATTEMPT_DELAY_MS 200
  309. int ff_connect_parallel(struct addrinfo *addrs, int timeout_ms_per_address,
  310. int parallel, URLContext *h, int *fd,
  311. void (*customize_fd)(void *, int), void *customize_ctx)
  312. {
  313. struct ConnectionAttempt attempts[3];
  314. struct pollfd pfd[3];
  315. int nb_attempts = 0, i, j;
  316. int64_t next_attempt_us = av_gettime_relative(), next_deadline_us;
  317. int last_err = AVERROR(EIO);
  318. socklen_t optlen;
  319. char errbuf[100], hostbuf[100], portbuf[20];
  320. if (parallel > FF_ARRAY_ELEMS(attempts))
  321. parallel = FF_ARRAY_ELEMS(attempts);
  322. print_address_list(h, addrs, "Original list of addresses");
  323. // This mutates the list, but the head of the list is still the same
  324. // element, so the caller, who owns the list, doesn't need to get
  325. // an updated pointer.
  326. interleave_addrinfo(addrs);
  327. print_address_list(h, addrs, "Interleaved list of addresses");
  328. while (nb_attempts > 0 || addrs) {
  329. // Start a new connection attempt, if possible.
  330. if (nb_attempts < parallel && addrs) {
  331. getnameinfo(addrs->ai_addr, addrs->ai_addrlen,
  332. hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
  333. NI_NUMERICHOST | NI_NUMERICSERV);
  334. av_log(h, AV_LOG_VERBOSE, "Starting connection attempt to %s port %s\n",
  335. hostbuf, portbuf);
  336. last_err = start_connect_attempt(&attempts[nb_attempts], &addrs,
  337. timeout_ms_per_address, h,
  338. customize_fd, customize_ctx);
  339. if (last_err < 0) {
  340. av_strerror(last_err, errbuf, sizeof(errbuf));
  341. av_log(h, AV_LOG_VERBOSE, "Connected attempt failed: %s\n",
  342. errbuf);
  343. continue;
  344. }
  345. if (last_err > 0) {
  346. for (i = 0; i < nb_attempts; i++)
  347. closesocket(attempts[i].fd);
  348. *fd = attempts[nb_attempts].fd;
  349. return 0;
  350. }
  351. pfd[nb_attempts].fd = attempts[nb_attempts].fd;
  352. pfd[nb_attempts].events = POLLOUT;
  353. next_attempt_us = av_gettime_relative() + NEXT_ATTEMPT_DELAY_MS * 1000;
  354. nb_attempts++;
  355. }
  356. av_assert0(nb_attempts > 0);
  357. // The connection attempts are sorted from oldest to newest, so the
  358. // first one will have the earliest deadline.
  359. next_deadline_us = attempts[0].deadline_us;
  360. // If we can start another attempt in parallel, wait until that time.
  361. if (nb_attempts < parallel && addrs)
  362. next_deadline_us = FFMIN(next_deadline_us, next_attempt_us);
  363. last_err = ff_poll_interrupt(pfd, nb_attempts,
  364. (next_deadline_us - av_gettime_relative())/1000,
  365. &h->interrupt_callback);
  366. if (last_err < 0 && last_err != AVERROR(ETIMEDOUT))
  367. break;
  368. // Check the status from the poll output.
  369. for (i = 0; i < nb_attempts; i++) {
  370. last_err = 0;
  371. if (pfd[i].revents) {
  372. // Some sort of action for this socket, check its status (either
  373. // a successful connection or an error).
  374. optlen = sizeof(last_err);
  375. if (getsockopt(attempts[i].fd, SOL_SOCKET, SO_ERROR, &last_err, &optlen))
  376. last_err = ff_neterrno();
  377. else if (last_err != 0)
  378. last_err = AVERROR(last_err);
  379. if (last_err == 0) {
  380. // Everything is ok, we seem to have a successful
  381. // connection. Close other sockets and return this one.
  382. for (j = 0; j < nb_attempts; j++)
  383. if (j != i)
  384. closesocket(attempts[j].fd);
  385. *fd = attempts[i].fd;
  386. getnameinfo(attempts[i].addr->ai_addr, attempts[i].addr->ai_addrlen,
  387. hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
  388. NI_NUMERICHOST | NI_NUMERICSERV);
  389. av_log(h, AV_LOG_VERBOSE, "Successfully connected to %s port %s\n",
  390. hostbuf, portbuf);
  391. return 0;
  392. }
  393. }
  394. if (attempts[i].deadline_us < av_gettime_relative() && !last_err)
  395. last_err = AVERROR(ETIMEDOUT);
  396. if (!last_err)
  397. continue;
  398. // Error (or timeout) for this socket; close the socket and remove
  399. // it from the attempts/pfd arrays, to let a new attempt start
  400. // directly.
  401. getnameinfo(attempts[i].addr->ai_addr, attempts[i].addr->ai_addrlen,
  402. hostbuf, sizeof(hostbuf), portbuf, sizeof(portbuf),
  403. NI_NUMERICHOST | NI_NUMERICSERV);
  404. av_strerror(last_err, errbuf, sizeof(errbuf));
  405. av_log(h, AV_LOG_VERBOSE, "Connection attempt to %s port %s "
  406. "failed: %s\n", hostbuf, portbuf, errbuf);
  407. closesocket(attempts[i].fd);
  408. memmove(&attempts[i], &attempts[i + 1],
  409. (nb_attempts - i - 1) * sizeof(*attempts));
  410. memmove(&pfd[i], &pfd[i + 1],
  411. (nb_attempts - i - 1) * sizeof(*pfd));
  412. i--;
  413. nb_attempts--;
  414. }
  415. }
  416. for (i = 0; i < nb_attempts; i++)
  417. closesocket(attempts[i].fd);
  418. if (last_err >= 0)
  419. last_err = AVERROR(ECONNREFUSED);
  420. if (last_err != AVERROR_EXIT) {
  421. av_strerror(last_err, errbuf, sizeof(errbuf));
  422. av_log(h, AV_LOG_ERROR, "Connection to %s failed: %s\n",
  423. h->filename, errbuf);
  424. }
  425. return last_err;
  426. }
  427. static int match_host_pattern(const char *pattern, const char *hostname)
  428. {
  429. int len_p, len_h;
  430. if (!strcmp(pattern, "*"))
  431. return 1;
  432. // Skip a possible *. at the start of the pattern
  433. if (pattern[0] == '*')
  434. pattern++;
  435. if (pattern[0] == '.')
  436. pattern++;
  437. len_p = strlen(pattern);
  438. len_h = strlen(hostname);
  439. if (len_p > len_h)
  440. return 0;
  441. // Simply check if the end of hostname is equal to 'pattern'
  442. if (!strcmp(pattern, &hostname[len_h - len_p])) {
  443. if (len_h == len_p)
  444. return 1; // Exact match
  445. if (hostname[len_h - len_p - 1] == '.')
  446. return 1; // The matched substring is a domain and not just a substring of a domain
  447. }
  448. return 0;
  449. }
  450. int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
  451. {
  452. char *buf, *start;
  453. int ret = 0;
  454. if (!no_proxy)
  455. return 0;
  456. if (!hostname)
  457. return 0;
  458. buf = av_strdup(no_proxy);
  459. if (!buf)
  460. return 0;
  461. start = buf;
  462. while (start) {
  463. char *sep, *next = NULL;
  464. start += strspn(start, " ,");
  465. sep = start + strcspn(start, " ,");
  466. if (*sep) {
  467. next = sep + 1;
  468. *sep = '\0';
  469. }
  470. if (match_host_pattern(start, hostname)) {
  471. ret = 1;
  472. break;
  473. }
  474. start = next;
  475. }
  476. av_free(buf);
  477. return ret;
  478. }