FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
network.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2007 The FFmpeg Project
3  *
4  * This file is part of FFmpeg.
5  *
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.
10  *
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.
15  *
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
19  */
20 
21 #include <fcntl.h>
22 #include "network.h"
23 #include "url.h"
24 #include "libavcodec/internal.h"
25 #include "libavutil/avutil.h"
26 #include "libavutil/mem.h"
27 #include "libavutil/time.h"
28 
29 #if HAVE_THREADS
30 #if HAVE_PTHREADS
31 #include <pthread.h>
32 #elif HAVE_OS2THREADS
33 #include "compat/os2threads.h"
34 #else
35 #include "compat/w32pthreads.h"
36 #endif
37 #endif
38 
39 #if CONFIG_OPENSSL
40 #include <openssl/ssl.h>
41 static int openssl_init;
42 #if HAVE_THREADS
43 #include <openssl/crypto.h>
44 pthread_mutex_t *openssl_mutexes;
45 static void openssl_lock(int mode, int type, const char *file, int line)
46 {
47  if (mode & CRYPTO_LOCK)
48  pthread_mutex_lock(&openssl_mutexes[type]);
49  else
50  pthread_mutex_unlock(&openssl_mutexes[type]);
51 }
52 #if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
53 static unsigned long openssl_thread_id(void)
54 {
55  return (intptr_t) pthread_self();
56 }
57 #endif
58 #endif
59 #endif
60 #if CONFIG_GNUTLS
61 #include <gnutls/gnutls.h>
62 #if HAVE_THREADS && GNUTLS_VERSION_NUMBER <= 0x020b00
63 #include <gcrypt.h>
64 #include <errno.h>
65 GCRY_THREAD_OPTION_PTHREAD_IMPL;
66 #endif
67 #endif
68 
69 int ff_tls_init(void)
70 {
72 #if CONFIG_OPENSSL
73  if (!openssl_init) {
74  SSL_library_init();
75  SSL_load_error_strings();
76 #if HAVE_THREADS
77  if (!CRYPTO_get_locking_callback()) {
78  int i;
79  openssl_mutexes = av_malloc_array(sizeof(pthread_mutex_t), CRYPTO_num_locks());
80  if (!openssl_mutexes)
81  return AVERROR(ENOMEM);
82  for (i = 0; i < CRYPTO_num_locks(); i++)
83  pthread_mutex_init(&openssl_mutexes[i], NULL);
84  CRYPTO_set_locking_callback(openssl_lock);
85 #if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
86  CRYPTO_set_id_callback(openssl_thread_id);
87 #endif
88  }
89 #endif
90  }
91  openssl_init++;
92 #endif
93 #if CONFIG_GNUTLS
94 #if HAVE_THREADS && GNUTLS_VERSION_NUMBER < 0x020b00
95  if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P) == 0)
96  gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
97 #endif
98  gnutls_global_init();
99 #endif
101 
102  return 0;
103 }
104 
105 void ff_tls_deinit(void)
106 {
108 #if CONFIG_OPENSSL
109  openssl_init--;
110  if (!openssl_init) {
111 #if HAVE_THREADS
112  if (CRYPTO_get_locking_callback() == openssl_lock) {
113  int i;
114  CRYPTO_set_locking_callback(NULL);
115  for (i = 0; i < CRYPTO_num_locks(); i++)
116  pthread_mutex_destroy(&openssl_mutexes[i]);
117  av_free(openssl_mutexes);
118  }
119 #endif
120  }
121 #endif
122 #if CONFIG_GNUTLS
123  gnutls_global_deinit();
124 #endif
126 }
127 
129 
131 {
132 #if HAVE_WINSOCK2_H
133  WSADATA wsaData;
134 #endif
135 
136  if (!ff_network_inited_globally)
137  av_log(NULL, AV_LOG_WARNING, "Using network protocols without global "
138  "network initialization. Please use "
139  "avformat_network_init(), this will "
140  "become mandatory later.\n");
141 #if HAVE_WINSOCK2_H
142  if (WSAStartup(MAKEWORD(1,1), &wsaData))
143  return 0;
144 #endif
145  return 1;
146 }
147 
148 int ff_network_wait_fd(int fd, int write)
149 {
150  int ev = write ? POLLOUT : POLLIN;
151  struct pollfd p = { .fd = fd, .events = ev, .revents = 0 };
152  int ret;
153  ret = poll(&p, 1, 100);
154  return ret < 0 ? ff_neterrno() : p.revents & (ev | POLLERR | POLLHUP) ? 0 : AVERROR(EAGAIN);
155 }
156 
157 int ff_network_wait_fd_timeout(int fd, int write, int64_t timeout, AVIOInterruptCB *int_cb)
158 {
159  int ret;
160  int64_t wait_start = 0;
161 
162  while (1) {
163  if (ff_check_interrupt(int_cb))
164  return AVERROR_EXIT;
165  ret = ff_network_wait_fd(fd, write);
166  if (ret != AVERROR(EAGAIN))
167  return ret;
168  if (timeout > 0) {
169  if (!wait_start)
170  wait_start = av_gettime_relative();
171  else if (av_gettime_relative() - wait_start > timeout)
172  return AVERROR(ETIMEDOUT);
173  }
174  }
175 }
176 
178 {
179 #if HAVE_WINSOCK2_H
180  WSACleanup();
181 #endif
182 }
183 
184 #if HAVE_WINSOCK2_H
185 int ff_neterrno(void)
186 {
187  int err = WSAGetLastError();
188  switch (err) {
189  case WSAEWOULDBLOCK:
190  return AVERROR(EAGAIN);
191  case WSAEINTR:
192  return AVERROR(EINTR);
193  case WSAEPROTONOSUPPORT:
194  return AVERROR(EPROTONOSUPPORT);
195  case WSAETIMEDOUT:
196  return AVERROR(ETIMEDOUT);
197  case WSAECONNREFUSED:
198  return AVERROR(ECONNREFUSED);
199  case WSAEINPROGRESS:
200  return AVERROR(EINPROGRESS);
201  }
202  return -err;
203 }
204 #endif
205 
206 int ff_is_multicast_address(struct sockaddr *addr)
207 {
208  if (addr->sa_family == AF_INET) {
209  return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr));
210  }
211 #if HAVE_STRUCT_SOCKADDR_IN6
212  if (addr->sa_family == AF_INET6) {
213  return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr);
214  }
215 #endif
216 
217  return 0;
218 }
219 
220 static int ff_poll_interrupt(struct pollfd *p, nfds_t nfds, int timeout,
222 {
223  int runs = timeout / POLLING_TIME;
224  int ret = 0;
225 
226  do {
227  if (ff_check_interrupt(cb))
228  return AVERROR_EXIT;
229  ret = poll(p, nfds, POLLING_TIME);
230  if (ret != 0)
231  break;
232  } while (timeout <= 0 || runs-- > 0);
233 
234  if (!ret)
235  return AVERROR(ETIMEDOUT);
236  if (ret < 0)
237  return AVERROR(errno);
238  return ret;
239 }
240 
241 int ff_socket(int af, int type, int proto)
242 {
243  int fd;
244 
245 #ifdef SOCK_CLOEXEC
246  fd = socket(af, type | SOCK_CLOEXEC, proto);
247  if (fd == -1 && errno == EINVAL)
248 #endif
249  {
250  fd = socket(af, type, proto);
251 #if HAVE_FCNTL
252  if (fd != -1) {
253  if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
254  av_log(NULL, AV_LOG_DEBUG, "Failed to set close on exec\n");
255  }
256 #endif
257  }
258  return fd;
259 }
260 
261 int ff_listen_bind(int fd, const struct sockaddr *addr,
262  socklen_t addrlen, int timeout, URLContext *h)
263 {
264  int ret;
265  int reuse = 1;
266  struct pollfd lp = { fd, POLLIN, 0 };
267  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) {
268  av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_REUSEADDR) failed\n");
269  }
270  ret = bind(fd, addr, addrlen);
271  if (ret)
272  return ff_neterrno();
273 
274  ret = listen(fd, 1);
275  if (ret)
276  return ff_neterrno();
277 
278  ret = ff_poll_interrupt(&lp, 1, timeout, &h->interrupt_callback);
279  if (ret < 0)
280  return ret;
281 
282  ret = accept(fd, NULL, NULL);
283  if (ret < 0)
284  return ff_neterrno();
285 
286  closesocket(fd);
287 
288  if (ff_socket_nonblock(ret, 1) < 0)
289  av_log(NULL, AV_LOG_DEBUG, "ff_socket_nonblock failed\n");
290 
291  return ret;
292 }
293 
294 int ff_listen_connect(int fd, const struct sockaddr *addr,
295  socklen_t addrlen, int timeout, URLContext *h,
296  int will_try_next)
297 {
298  struct pollfd p = {fd, POLLOUT, 0};
299  int ret;
300  socklen_t optlen;
301 
302  if (ff_socket_nonblock(fd, 1) < 0)
303  av_log(NULL, AV_LOG_DEBUG, "ff_socket_nonblock failed\n");
304 
305  while ((ret = connect(fd, addr, addrlen))) {
306  ret = ff_neterrno();
307  switch (ret) {
308  case AVERROR(EINTR):
310  return AVERROR_EXIT;
311  continue;
312  case AVERROR(EINPROGRESS):
313  case AVERROR(EAGAIN):
314  ret = ff_poll_interrupt(&p, 1, timeout, &h->interrupt_callback);
315  if (ret < 0)
316  return ret;
317  optlen = sizeof(ret);
318  if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen))
319  ret = AVUNERROR(ff_neterrno());
320  if (ret != 0) {
321  char errbuf[100];
322  ret = AVERROR(ret);
323  av_strerror(ret, errbuf, sizeof(errbuf));
324  if (will_try_next)
326  "Connection to %s failed (%s), trying next address\n",
327  h->filename, errbuf);
328  else
329  av_log(h, AV_LOG_ERROR, "Connection to %s failed: %s\n",
330  h->filename, errbuf);
331  }
332  default:
333  return ret;
334  }
335  }
336  return ret;
337 }
338 
339 static int match_host_pattern(const char *pattern, const char *hostname)
340 {
341  int len_p, len_h;
342  if (!strcmp(pattern, "*"))
343  return 1;
344  // Skip a possible *. at the start of the pattern
345  if (pattern[0] == '*')
346  pattern++;
347  if (pattern[0] == '.')
348  pattern++;
349  len_p = strlen(pattern);
350  len_h = strlen(hostname);
351  if (len_p > len_h)
352  return 0;
353  // Simply check if the end of hostname is equal to 'pattern'
354  if (!strcmp(pattern, &hostname[len_h - len_p])) {
355  if (len_h == len_p)
356  return 1; // Exact match
357  if (hostname[len_h - len_p - 1] == '.')
358  return 1; // The matched substring is a domain and not just a substring of a domain
359  }
360  return 0;
361 }
362 
363 int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
364 {
365  char *buf, *start;
366  int ret = 0;
367  if (!no_proxy)
368  return 0;
369  if (!hostname)
370  return 0;
371  buf = av_strdup(no_proxy);
372  if (!buf)
373  return 0;
374  start = buf;
375  while (start) {
376  char *sep, *next = NULL;
377  start += strspn(start, " ,");
378  sep = start + strcspn(start, " ,");
379  if (*sep) {
380  next = sep + 1;
381  *sep = '\0';
382  }
383  if (match_host_pattern(start, hostname)) {
384  ret = 1;
385  break;
386  }
387  start = next;
388  }
389  av_free(buf);
390  return ret;
391 }