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