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