]> git.sesse.net Git - ffmpeg/blob - libavformat/avio.c
Merge commit '3b08d9d932eef09403074d5af31e10d8011e840b'
[ffmpeg] / libavformat / avio.c
1 /*
2  * unbuffered I/O
3  * Copyright (c) 2001 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/avstring.h"
23 #include "libavutil/dict.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/time.h"
26 #include "libavutil/avassert.h"
27 #include "os_support.h"
28 #include "avformat.h"
29 #if CONFIG_NETWORK
30 #include "network.h"
31 #endif
32 #include "url.h"
33
34 /** @name Logging context. */
35 /*@{*/
36 static const char *urlcontext_to_name(void *ptr)
37 {
38     URLContext *h = (URLContext *)ptr;
39     if (h->prot)
40         return h->prot->name;
41     else
42         return "NULL";
43 }
44
45 static void *urlcontext_child_next(void *obj, void *prev)
46 {
47     URLContext *h = obj;
48     if (!prev && h->priv_data && h->prot->priv_data_class)
49         return h->priv_data;
50     return NULL;
51 }
52
53 #define OFFSET(x) offsetof(URLContext,x)
54 #define E AV_OPT_FLAG_ENCODING_PARAM
55 #define D AV_OPT_FLAG_DECODING_PARAM
56 static const AVOption options[] = {
57     {"protocol_whitelist", "List of protocols that are allowed to be used", OFFSET(protocol_whitelist), AV_OPT_TYPE_STRING, { .str = NULL },  CHAR_MIN, CHAR_MAX, D },
58     {"protocol_blacklist", "List of protocols that are not allowed to be used", OFFSET(protocol_blacklist), AV_OPT_TYPE_STRING, { .str = NULL },  CHAR_MIN, CHAR_MAX, D },
59     {"rw_timeout", "Timeout for IO operations (in microseconds)", offsetof(URLContext, rw_timeout), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_DECODING_PARAM },
60     { NULL }
61 };
62
63 const AVClass ffurl_context_class = {
64     .class_name       = "URLContext",
65     .item_name        = urlcontext_to_name,
66     .option           = options,
67     .version          = LIBAVUTIL_VERSION_INT,
68     .child_next       = urlcontext_child_next,
69     .child_class_next = ff_urlcontext_child_class_next,
70 };
71 /*@}*/
72
73 static int url_alloc_for_protocol(URLContext **puc, const URLProtocol *up,
74                                   const char *filename, int flags,
75                                   const AVIOInterruptCB *int_cb)
76 {
77     URLContext *uc;
78     int err;
79
80 #if CONFIG_NETWORK
81     if (up->flags & URL_PROTOCOL_FLAG_NETWORK && !ff_network_init())
82         return AVERROR(EIO);
83 #endif
84     if ((flags & AVIO_FLAG_READ) && !up->url_read) {
85         av_log(NULL, AV_LOG_ERROR,
86                "Impossible to open the '%s' protocol for reading\n", up->name);
87         return AVERROR(EIO);
88     }
89     if ((flags & AVIO_FLAG_WRITE) && !up->url_write) {
90         av_log(NULL, AV_LOG_ERROR,
91                "Impossible to open the '%s' protocol for writing\n", up->name);
92         return AVERROR(EIO);
93     }
94     uc = av_mallocz(sizeof(URLContext) + strlen(filename) + 1);
95     if (!uc) {
96         err = AVERROR(ENOMEM);
97         goto fail;
98     }
99     uc->av_class = &ffurl_context_class;
100     uc->filename = (char *)&uc[1];
101     strcpy(uc->filename, filename);
102     uc->prot            = up;
103     uc->flags           = flags;
104     uc->is_streamed     = 0; /* default = not streamed */
105     uc->max_packet_size = 0; /* default: stream file */
106     if (up->priv_data_size) {
107         uc->priv_data = av_mallocz(up->priv_data_size);
108         if (!uc->priv_data) {
109             err = AVERROR(ENOMEM);
110             goto fail;
111         }
112         if (up->priv_data_class) {
113             int proto_len= strlen(up->name);
114             char *start = strchr(uc->filename, ',');
115             *(const AVClass **)uc->priv_data = up->priv_data_class;
116             av_opt_set_defaults(uc->priv_data);
117             if(!strncmp(up->name, uc->filename, proto_len) && uc->filename + proto_len == start){
118                 int ret= 0;
119                 char *p= start;
120                 char sep= *++p;
121                 char *key, *val;
122                 p++;
123
124                 if (strcmp(up->name, "subfile"))
125                     ret = AVERROR(EINVAL);
126
127                 while(ret >= 0 && (key= strchr(p, sep)) && p<key && (val = strchr(key+1, sep))){
128                     *val= *key= 0;
129                     if (strcmp(p, "start") && strcmp(p, "end")) {
130                         ret = AVERROR_OPTION_NOT_FOUND;
131                     } else
132                         ret= av_opt_set(uc->priv_data, p, key+1, 0);
133                     if (ret == AVERROR_OPTION_NOT_FOUND)
134                         av_log(uc, AV_LOG_ERROR, "Key '%s' not found.\n", p);
135                     *val= *key= sep;
136                     p= val+1;
137                 }
138                 if(ret<0 || p!=key){
139                     av_log(uc, AV_LOG_ERROR, "Error parsing options string %s\n", start);
140                     av_freep(&uc->priv_data);
141                     av_freep(&uc);
142                     err = AVERROR(EINVAL);
143                     goto fail;
144                 }
145                 memmove(start, key+1, strlen(key));
146             }
147         }
148     }
149     if (int_cb)
150         uc->interrupt_callback = *int_cb;
151
152     *puc = uc;
153     return 0;
154 fail:
155     *puc = NULL;
156     if (uc)
157         av_freep(&uc->priv_data);
158     av_freep(&uc);
159 #if CONFIG_NETWORK
160     if (up->flags & URL_PROTOCOL_FLAG_NETWORK)
161         ff_network_close();
162 #endif
163     return err;
164 }
165
166 int ffurl_connect(URLContext *uc, AVDictionary **options)
167 {
168     int err;
169     AVDictionary *tmp_opts = NULL;
170     AVDictionaryEntry *e;
171
172     if (!options)
173         options = &tmp_opts;
174
175     // Check that URLContext was initialized correctly and lists are matching if set
176     av_assert0(!(e=av_dict_get(*options, "protocol_whitelist", NULL, 0)) ||
177                (uc->protocol_whitelist && !strcmp(uc->protocol_whitelist, e->value)));
178     av_assert0(!(e=av_dict_get(*options, "protocol_blacklist", NULL, 0)) ||
179                (uc->protocol_blacklist && !strcmp(uc->protocol_blacklist, e->value)));
180
181     if (uc->protocol_whitelist && av_match_list(uc->prot->name, uc->protocol_whitelist, ',') <= 0) {
182         av_log(uc, AV_LOG_ERROR, "Protocol not on whitelist \'%s\'!\n", uc->protocol_whitelist);
183         return AVERROR(EINVAL);
184     }
185
186     if (uc->protocol_blacklist && av_match_list(uc->prot->name, uc->protocol_blacklist, ',') > 0) {
187         av_log(uc, AV_LOG_ERROR, "Protocol blacklisted \'%s\'!\n", uc->protocol_blacklist);
188         return AVERROR(EINVAL);
189     }
190
191     if (!uc->protocol_whitelist && uc->prot->default_whitelist) {
192         av_log(uc, AV_LOG_DEBUG, "Setting default whitelist '%s'\n", uc->prot->default_whitelist);
193         uc->protocol_whitelist = av_strdup(uc->prot->default_whitelist);
194         if (!uc->protocol_whitelist) {
195             return AVERROR(ENOMEM);
196         }
197     } else if (!uc->protocol_whitelist)
198         av_log(uc, AV_LOG_DEBUG, "No default whitelist set\n"); // This should be an error once all declare a default whitelist
199
200     if ((err = av_dict_set(options, "protocol_whitelist", uc->protocol_whitelist, 0)) < 0)
201         return err;
202     if ((err = av_dict_set(options, "protocol_blacklist", uc->protocol_blacklist, 0)) < 0)
203         return err;
204
205     err =
206         uc->prot->url_open2 ? uc->prot->url_open2(uc,
207                                                   uc->filename,
208                                                   uc->flags,
209                                                   options) :
210         uc->prot->url_open(uc, uc->filename, uc->flags);
211
212     av_dict_set(options, "protocol_whitelist", NULL, 0);
213     av_dict_set(options, "protocol_blacklist", NULL, 0);
214
215     if (err)
216         return err;
217     uc->is_connected = 1;
218     /* We must be careful here as ffurl_seek() could be slow,
219      * for example for http */
220     if ((uc->flags & AVIO_FLAG_WRITE) || !strcmp(uc->prot->name, "file"))
221         if (!uc->is_streamed && ffurl_seek(uc, 0, SEEK_SET) < 0)
222             uc->is_streamed = 1;
223     return 0;
224 }
225
226 int ffurl_accept(URLContext *s, URLContext **c)
227 {
228     av_assert0(!*c);
229     if (s->prot->url_accept)
230         return s->prot->url_accept(s, c);
231     return AVERROR(EBADF);
232 }
233
234 int ffurl_handshake(URLContext *c)
235 {
236     int ret;
237     if (c->prot->url_handshake) {
238         ret = c->prot->url_handshake(c);
239         if (ret)
240             return ret;
241     }
242     c->is_connected = 1;
243     return 0;
244 }
245
246 #define URL_SCHEME_CHARS                        \
247     "abcdefghijklmnopqrstuvwxyz"                \
248     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"                \
249     "0123456789+-."
250
251 static const struct URLProtocol *url_find_protocol(const char *filename)
252 {
253     const URLProtocol **protocols;
254     char proto_str[128], proto_nested[128], *ptr;
255     size_t proto_len = strspn(filename, URL_SCHEME_CHARS);
256     int i;
257
258     if (filename[proto_len] != ':' &&
259         (strncmp(filename, "subfile,", 8) || !strchr(filename + proto_len + 1, ':')) ||
260         is_dos_path(filename))
261         strcpy(proto_str, "file");
262     else
263         av_strlcpy(proto_str, filename,
264                    FFMIN(proto_len + 1, sizeof(proto_str)));
265
266     if ((ptr = strchr(proto_str, ',')))
267         *ptr = '\0';
268     av_strlcpy(proto_nested, proto_str, sizeof(proto_nested));
269     if ((ptr = strchr(proto_nested, '+')))
270         *ptr = '\0';
271
272     protocols = ffurl_get_protocols(NULL, NULL);
273     for (i = 0; protocols[i]; i++) {
274             const URLProtocol *up = protocols[i];
275         if (!strcmp(proto_str, up->name)) {
276             av_freep(&protocols);
277             return up;
278         }
279         if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME &&
280             !strcmp(proto_nested, up->name)) {
281             av_freep(&protocols);
282             return up;
283         }
284     }
285
286     return NULL;
287 }
288
289 int ffurl_alloc(URLContext **puc, const char *filename, int flags,
290                 const AVIOInterruptCB *int_cb)
291 {
292     const URLProtocol *p = NULL;
293
294     p = url_find_protocol(filename);
295     if (p)
296        return url_alloc_for_protocol(puc, p, filename, flags, int_cb);
297
298     *puc = NULL;
299     if (av_strstart(filename, "https:", NULL))
300         av_log(NULL, AV_LOG_WARNING, "https protocol not found, recompile FFmpeg with "
301                                      "openssl, gnutls "
302                                      "or securetransport enabled.\n");
303     return AVERROR_PROTOCOL_NOT_FOUND;
304 }
305
306 int ffurl_open_whitelist(URLContext **puc, const char *filename, int flags,
307                          const AVIOInterruptCB *int_cb, AVDictionary **options,
308                          const char *whitelist, const char* blacklist,
309                          URLContext *parent)
310 {
311     AVDictionary *tmp_opts = NULL;
312     AVDictionaryEntry *e;
313     int ret = ffurl_alloc(puc, filename, flags, int_cb);
314     if (ret < 0)
315         return ret;
316     if (parent)
317         av_opt_copy(*puc, parent);
318     if (options &&
319         (ret = av_opt_set_dict(*puc, options)) < 0)
320         goto fail;
321     if (options && (*puc)->prot->priv_data_class &&
322         (ret = av_opt_set_dict((*puc)->priv_data, options)) < 0)
323         goto fail;
324
325     if (!options)
326         options = &tmp_opts;
327
328     av_assert0(!whitelist ||
329                !(e=av_dict_get(*options, "protocol_whitelist", NULL, 0)) ||
330                !strcmp(whitelist, e->value));
331     av_assert0(!blacklist ||
332                !(e=av_dict_get(*options, "protocol_blacklist", NULL, 0)) ||
333                !strcmp(blacklist, e->value));
334
335     if ((ret = av_dict_set(options, "protocol_whitelist", whitelist, 0)) < 0)
336         goto fail;
337
338     if ((ret = av_dict_set(options, "protocol_blacklist", blacklist, 0)) < 0)
339         goto fail;
340
341     if ((ret = av_opt_set_dict(*puc, options)) < 0)
342         goto fail;
343
344     ret = ffurl_connect(*puc, options);
345
346     if (!ret)
347         return 0;
348 fail:
349     ffurl_close(*puc);
350     *puc = NULL;
351     return ret;
352 }
353
354 int ffurl_open(URLContext **puc, const char *filename, int flags,
355                const AVIOInterruptCB *int_cb, AVDictionary **options)
356 {
357     return ffurl_open_whitelist(puc, filename, flags,
358                                 int_cb, options, NULL, NULL, NULL);
359 }
360
361 static inline int retry_transfer_wrapper(URLContext *h, uint8_t *buf,
362                                          int size, int size_min,
363                                          int (*transfer_func)(URLContext *h,
364                                                               uint8_t *buf,
365                                                               int size))
366 {
367     int ret, len;
368     int fast_retries = 5;
369     int64_t wait_since = 0;
370
371     len = 0;
372     while (len < size_min) {
373         if (ff_check_interrupt(&h->interrupt_callback))
374             return AVERROR_EXIT;
375         ret = transfer_func(h, buf + len, size - len);
376         if (ret == AVERROR(EINTR))
377             continue;
378         if (h->flags & AVIO_FLAG_NONBLOCK)
379             return ret;
380         if (ret == AVERROR(EAGAIN)) {
381             ret = 0;
382             if (fast_retries) {
383                 fast_retries--;
384             } else {
385                 if (h->rw_timeout) {
386                     if (!wait_since)
387                         wait_since = av_gettime_relative();
388                     else if (av_gettime_relative() > wait_since + h->rw_timeout)
389                         return AVERROR(EIO);
390                 }
391                 av_usleep(1000);
392             }
393         } else if (ret < 1)
394             return (ret < 0 && ret != AVERROR_EOF) ? ret : len;
395         if (ret) {
396             fast_retries = FFMAX(fast_retries, 2);
397             wait_since = 0;
398         }
399         len += ret;
400     }
401     return len;
402 }
403
404 int ffurl_read(URLContext *h, unsigned char *buf, int size)
405 {
406     if (!(h->flags & AVIO_FLAG_READ))
407         return AVERROR(EIO);
408     return retry_transfer_wrapper(h, buf, size, 1, h->prot->url_read);
409 }
410
411 int ffurl_read_complete(URLContext *h, unsigned char *buf, int size)
412 {
413     if (!(h->flags & AVIO_FLAG_READ))
414         return AVERROR(EIO);
415     return retry_transfer_wrapper(h, buf, size, size, h->prot->url_read);
416 }
417
418 int ffurl_write(URLContext *h, const unsigned char *buf, int size)
419 {
420     if (!(h->flags & AVIO_FLAG_WRITE))
421         return AVERROR(EIO);
422     /* avoid sending too big packets */
423     if (h->max_packet_size && size > h->max_packet_size)
424         return AVERROR(EIO);
425
426     return retry_transfer_wrapper(h, (unsigned char *)buf, size, size,
427                                   (int (*)(struct URLContext *, uint8_t *, int))
428                                   h->prot->url_write);
429 }
430
431 int64_t ffurl_seek(URLContext *h, int64_t pos, int whence)
432 {
433     int64_t ret;
434
435     if (!h->prot->url_seek)
436         return AVERROR(ENOSYS);
437     ret = h->prot->url_seek(h, pos, whence & ~AVSEEK_FORCE);
438     return ret;
439 }
440
441 int ffurl_closep(URLContext **hh)
442 {
443     URLContext *h= *hh;
444     int ret = 0;
445     if (!h)
446         return 0;     /* can happen when ffurl_open fails */
447
448     if (h->is_connected && h->prot->url_close)
449         ret = h->prot->url_close(h);
450 #if CONFIG_NETWORK
451     if (h->prot->flags & URL_PROTOCOL_FLAG_NETWORK)
452         ff_network_close();
453 #endif
454     if (h->prot->priv_data_size) {
455         if (h->prot->priv_data_class)
456             av_opt_free(h->priv_data);
457         av_freep(&h->priv_data);
458     }
459     av_opt_free(h);
460     av_freep(hh);
461     return ret;
462 }
463
464 int ffurl_close(URLContext *h)
465 {
466     return ffurl_closep(&h);
467 }
468
469
470 const char *avio_find_protocol_name(const char *url)
471 {
472     const URLProtocol *p = url_find_protocol(url);
473
474     return p ? p->name : NULL;
475 }
476
477 int avio_check(const char *url, int flags)
478 {
479     URLContext *h;
480     int ret = ffurl_alloc(&h, url, flags, NULL);
481     if (ret < 0)
482         return ret;
483
484     if (h->prot->url_check) {
485         ret = h->prot->url_check(h, flags);
486     } else {
487         ret = ffurl_connect(h, NULL);
488         if (ret >= 0)
489             ret = flags;
490     }
491
492     ffurl_close(h);
493     return ret;
494 }
495
496 int avpriv_io_move(const char *url_src, const char *url_dst)
497 {
498     URLContext *h_src, *h_dst;
499     int ret = ffurl_alloc(&h_src, url_src, AVIO_FLAG_READ_WRITE, NULL);
500     if (ret < 0)
501         return ret;
502     ret = ffurl_alloc(&h_dst, url_dst, AVIO_FLAG_WRITE, NULL);
503     if (ret < 0) {
504         ffurl_close(h_src);
505         return ret;
506     }
507
508     if (h_src->prot == h_dst->prot && h_src->prot->url_move)
509         ret = h_src->prot->url_move(h_src, h_dst);
510     else
511         ret = AVERROR(ENOSYS);
512
513     ffurl_close(h_src);
514     ffurl_close(h_dst);
515     return ret;
516 }
517
518 int avpriv_io_delete(const char *url)
519 {
520     URLContext *h;
521     int ret = ffurl_alloc(&h, url, AVIO_FLAG_WRITE, NULL);
522     if (ret < 0)
523         return ret;
524
525     if (h->prot->url_delete)
526         ret = h->prot->url_delete(h);
527     else
528         ret = AVERROR(ENOSYS);
529
530     ffurl_close(h);
531     return ret;
532 }
533
534 int avio_open_dir(AVIODirContext **s, const char *url, AVDictionary **options)
535 {
536     URLContext *h = NULL;
537     AVIODirContext *ctx = NULL;
538     int ret;
539     av_assert0(s);
540
541     ctx = av_mallocz(sizeof(*ctx));
542     if (!ctx) {
543         ret = AVERROR(ENOMEM);
544         goto fail;
545     }
546
547     if ((ret = ffurl_alloc(&h, url, AVIO_FLAG_READ, NULL)) < 0)
548         goto fail;
549
550     if (h->prot->url_open_dir && h->prot->url_read_dir && h->prot->url_close_dir) {
551         if (options && h->prot->priv_data_class &&
552             (ret = av_opt_set_dict(h->priv_data, options)) < 0)
553             goto fail;
554         ret = h->prot->url_open_dir(h);
555     } else
556         ret = AVERROR(ENOSYS);
557     if (ret < 0)
558         goto fail;
559
560     h->is_connected = 1;
561     ctx->url_context = h;
562     *s = ctx;
563     return 0;
564
565   fail:
566     av_free(ctx);
567     *s = NULL;
568     ffurl_close(h);
569     return ret;
570 }
571
572 int avio_read_dir(AVIODirContext *s, AVIODirEntry **next)
573 {
574     URLContext *h;
575     int ret;
576
577     if (!s || !s->url_context)
578         return AVERROR(EINVAL);
579     h = s->url_context;
580     if ((ret = h->prot->url_read_dir(h, next)) < 0)
581         avio_free_directory_entry(next);
582     return ret;
583 }
584
585 int avio_close_dir(AVIODirContext **s)
586 {
587     URLContext *h;
588
589     av_assert0(s);
590     if (!(*s) || !(*s)->url_context)
591         return AVERROR(EINVAL);
592     h = (*s)->url_context;
593     h->prot->url_close_dir(h);
594     ffurl_close(h);
595     av_freep(s);
596     *s = NULL;
597     return 0;
598 }
599
600 void avio_free_directory_entry(AVIODirEntry **entry)
601 {
602     if (!entry || !*entry)
603         return;
604     av_free((*entry)->name);
605     av_freep(entry);
606 }
607
608 int64_t ffurl_size(URLContext *h)
609 {
610     int64_t pos, size;
611
612     size = ffurl_seek(h, 0, AVSEEK_SIZE);
613     if (size < 0) {
614         pos = ffurl_seek(h, 0, SEEK_CUR);
615         if ((size = ffurl_seek(h, -1, SEEK_END)) < 0)
616             return size;
617         size++;
618         ffurl_seek(h, pos, SEEK_SET);
619     }
620     return size;
621 }
622
623 int ffurl_get_file_handle(URLContext *h)
624 {
625     if (!h->prot->url_get_file_handle)
626         return -1;
627     return h->prot->url_get_file_handle(h);
628 }
629
630 int ffurl_get_multi_file_handle(URLContext *h, int **handles, int *numhandles)
631 {
632     if (!h->prot->url_get_multi_file_handle) {
633         if (!h->prot->url_get_file_handle)
634             return AVERROR(ENOSYS);
635         *handles = av_malloc(sizeof(**handles));
636         if (!*handles)
637             return AVERROR(ENOMEM);
638         *numhandles = 1;
639         *handles[0] = h->prot->url_get_file_handle(h);
640         return 0;
641     }
642     return h->prot->url_get_multi_file_handle(h, handles, numhandles);
643 }
644
645 int ffurl_shutdown(URLContext *h, int flags)
646 {
647     if (!h->prot->url_shutdown)
648         return AVERROR(EINVAL);
649     return h->prot->url_shutdown(h, flags);
650 }
651
652 int ff_check_interrupt(AVIOInterruptCB *cb)
653 {
654     int ret;
655     if (cb && cb->callback && (ret = cb->callback(cb->opaque)))
656         return ret;
657     return 0;
658 }