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