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