FFmpeg
Loading...
Searching...
No Matches
libcurl.c
Go to the documentation of this file.
1/*
2 * libcurl based HTTP(S) protocol
3 * Copyright (C) 2026 Kacper Michajłow
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 "config_components.h"
23
24#include <curl/curl.h>
25#include <errno.h>
26#include <inttypes.h>
27#include <limits.h>
28#include <stdlib.h>
29#include <string.h>
30
31#include "libavutil/avstring.h"
32#include "libavutil/bprint.h"
33#include "libavutil/dict.h"
34#include "libavutil/error.h"
35#include "libavutil/fifo.h"
36#include "libavutil/log.h"
37#include "libavutil/macros.h"
38#include "libavutil/mem.h"
39#include "libavutil/opt.h"
40#include "libavutil/thread.h"
41#include "libavutil/time.h"
42
43#include "avformat.h"
44#include "http.h"
45#include "internal.h"
46#include "network.h"
47#include "url.h"
48#include "version.h"
49
50#define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
51#define CURL_DEFAULT_BUFFER_SIZE (4 << 20)
52
53/* Blocking waits wake up this often so url_read()/open can poll the interrupt
54 * callback. */
55#define CURL_WAIT_US 100000
56
57/* Cap on the accumulated "Icy-*" reply headers exported to the caller. */
58#define ICY_MAX_HEADERS 65536
59
60/* Largest in-band metadata block: the length byte counts 16 byte units. */
61#define ICY_MAX_BLOCK (255 * 16)
62
63/* How many microseconds to wait before retrying a failed request; grows
64 * exponentially (2^) with each consecutive failure up to MAX_US. Note that the
65 * first retry is always immediate. */
66#define CURL_RETRY_BASE_US 1000000
67#define CURL_RETRY_MAX_US 60000000
68
69typedef struct CurlContext CurlContext;
70
72 CMD_ADD, /* add the easy handle to the multi and start the transfer */
73 CMD_REMOVE, /* remove the easy handle from the multi */
74 CMD_UNPAUSE, /* resume a transfer paused because the FIFO was full */
75 CMD_SEEK, /* restart the transfer at a new byte offset */
76};
77
78typedef struct CurlCmd {
81 int64_t pos; /* CMD_SEEK target offset */
82 int sync; /* caller waits for completion */
83 int done;
84 struct CurlCmd *next;
85} CurlCmd;
86
87typedef struct CurlLoop {
88 AVFormatContext *avfc; /* owning context (if any) */
89
91 CURLM *multi;
92 CURLSH *share; /* shared cookies/HSTS */
93 int has_cookies; /* libcurl was built with cookie support */
94
95 pthread_mutex_t mutex; /* guards the command queue, exit, share and cmd->done */
96 pthread_cond_t cond; /* signaled when a sync command completes */
98 int exit;
99
100 /* Connection statistics (updated by loop thread) */
107} CurlLoop;
108
110 const AVClass *class;
112
114 int private_loop; /* loop is owned by this context (not shared) */
115 CURL *easy;
116 struct curl_slist *header_list;
117 struct curl_slist *alias_list;
118
119 /* AVOptions. */
121 char *method; /* client HTTP method (GET/HEAD/...), or NULL */
122 char *referer;
123 char *headers;
125 char *cookies;
126 char *ca_file;
128 char *key_file;
129 char *location; /* effective URL after redirects (output) */
130 int64_t off; /* initial byte offset */
131 int64_t end_off; /* exclusive upper byte bound (0 = none) */
143 int icy;
145 char *icy_metadata_headers; /* "Icy-*" reply headers (output) */
146 char *icy_metadata_packet; /* last in-band block (output) */
147 AVDictionary *metadata; /* ICY metadata (output) */
148
149 /* URL thread bookkeeping, not touched by loop thread */
150 int64_t logical_pos; /* next byte url_read() will return, caller side */
151 int retry_count; /* consecutive recoverable failures */
152 int64_t retry_time; /* timestamp of next retry */
153 int64_t icy_data_read; /* payload bytes since the last block, caller side */
154 int icy_block_len; /* -1 while the length byte is pending */
157
158 /* Producer bookkeeping, touched only by the loop thread. no_body is
159 * set once by setup_curl() before the handle is added, then read-only. */
160 int active; /* currently added to the multi */
161 int64_t request_start; /* absolute offset the current request began at */
162 int64_t request_received;/* bytes delivered in the current request */
163 int64_t request_end; /* expected end of request, or -1 if unknown */
164 int is_initial; /* using reduced request size */
165 int no_body; /* HEAD request: CURLOPT_NOBODY is set */
166 int seek_queued; /* soft seeking; drain remaining bytes until done */
167
168 /* Per-response-block header scratch, loop thread only. */
171 int64_t hdr_content_start; /* inclusive start, or -1 */
172 int64_t hdr_content_end; /* inclusive end, or -1 */
173 int64_t hdr_content_total; /* if known, or -1 */
174 int64_t hdr_content_length; /* if known, or -1 */
175 AVDictionary *hdr_icy; /* "Icy-*" headers of this block */
176 int64_t hdr_icy_metaint; /* in-band metadata interval, or -1 */
177
178 /* Probe result. Set by the loop thread, read by url_open() once probed. */
180 int probe_ok; /* the first reply can be read */
184
185 /* Shared transfer state, guarded by mutex. */
189 int paused; /* write callback paused, FIFO was full */
190 int aborted; /* transfer should stop (open was interrupted) */
191 int status; /* current stream status (AVERROR code) */
192 CURLcode curl_status; /* corresponding libcurl status code */
193 int64_t icy_metaint; /* in-band metadata interval, 0 if none */
194};
195
196/* Guards lazy creation of a format context's shared loop. */
198
199static int curlcode_to_averror(CURLcode code)
200{
201 switch (code) {
202 case CURLE_OK: return 0;
203 case CURLE_URL_MALFORMAT:
204 case CURLE_UNSUPPORTED_PROTOCOL:
205 case CURLE_BAD_FUNCTION_ARGUMENT: return AVERROR(EINVAL);
206 case CURLE_UNKNOWN_OPTION:
207 case CURLE_NOT_BUILT_IN: return AVERROR(ENOSYS);
208 case CURLE_COULDNT_RESOLVE_PROXY:
209 case CURLE_COULDNT_RESOLVE_HOST: return AVERROR(EHOSTUNREACH);
210 case CURLE_COULDNT_CONNECT: return AVERROR(ECONNREFUSED);
211 case CURLE_OPERATION_TIMEDOUT: return AVERROR(ETIMEDOUT);
212 case CURLE_LOGIN_DENIED:
213 case CURLE_REMOTE_ACCESS_DENIED: return AVERROR(EACCES);
214 case CURLE_OUT_OF_MEMORY: return AVERROR(ENOMEM);
215 case CURLE_PEER_FAILED_VERIFICATION:
216 case CURLE_SSL_CACERT_BADFILE: return AVERROR_INVALIDDATA;
217 default: return AVERROR(EIO);
218 }
219}
220
221static int curl_setopt_checked(CurlContext *c, const char *name, CURLcode code)
222{
223 if (code == CURLE_OK)
224 return 0;
225
226 av_log(c->h, AV_LOG_ERROR, "Could not set %s: %s\n",
227 name, curl_easy_strerror(code));
229}
230
231static int curlmcode_to_averror(CURLMcode code)
232{
233 switch (code) {
234 case CURLM_OK: return 0;
235 case CURLM_UNKNOWN_OPTION: return AVERROR(EINVAL);
236 case CURLM_OUT_OF_MEMORY: return AVERROR(ENOMEM);
237 default: return AVERROR(EIO);
238 }
239}
240
241static int curlmcode_to_curlcode(CURLMcode code)
242{
243 switch (code) {
244 case CURLM_OK: return CURLE_OK;
245 case CURLM_UNKNOWN_OPTION: return CURLE_UNKNOWN_OPTION;
246 case CURLM_OUT_OF_MEMORY: return CURLE_OUT_OF_MEMORY;
247 case CURLM_ABORTED_BY_CALLBACK: return CURLE_ABORTED_BY_CALLBACK;
248 case CURLM_UNRECOVERABLE_POLL: return CURLE_UNRECOVERABLE_POLL;
249 default: return CURLE_FAILED_INIT;
250 }
251}
252
253static int is_recoverable(CURLcode code)
254{
255 switch (code) {
256 case CURLE_RECV_ERROR:
257 case CURLE_SEND_ERROR:
258 case CURLE_PARTIAL_FILE:
259 case CURLE_OPERATION_TIMEDOUT:
260 case CURLE_GOT_NOTHING:
261 case CURLE_COULDNT_CONNECT:
262 case CURLE_COULDNT_RESOLVE_HOST:
263 case CURLE_HTTP2:
264 case CURLE_HTTP2_STREAM:
265 return 1;
266 default:
267 return 0;
268 }
269}
270
271/* ------------------------------------------------------------------------- */
272/* curl callbacks (run on the loop thread) */
273/* ------------------------------------------------------------------------- */
274
275static void update_status_locked(CurlContext *c, int status, CURLcode code)
276{
277 if (c->status)
278 return;
279
280 c->status = status;
281 c->curl_status = code;
282}
283
284static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
285{
286 CurlContext *c = userdata;
287 size_t bytes = size * nmemb;
288 size_t space;
289
290 pthread_mutex_lock(&c->mutex);
291
292 if (c->aborted || !c->stream_ok) {
293 pthread_mutex_unlock(&c->mutex);
294 return CURL_WRITEFUNC_ERROR;
295 }
296
297 if (c->seek_queued) {
298 pthread_mutex_unlock(&c->mutex);
299 return bytes; /* discard */
300 }
301
302 /* Prevent overflow / non-addressable byte ranges */
303 if (bytes > INT64_MAX - c->request_start - c->request_received) {
304 av_log(c->h, AV_LOG_ERROR, "Server sent back more data than addressable "
305 "at offset %"PRId64"\n", c->request_start);
306 c->loop->num_errors++;
307 c->stream_ok = 0;
308 if (!c->status)
309 c->status = AVERROR(ERANGE);
311 pthread_mutex_unlock(&c->mutex);
312 return CURL_WRITEFUNC_ERROR;
313 }
314
315 space = av_fifo_can_write(c->fifo);
316 if (space < bytes) {
317 /* pause the transfer and wait for the consumer to drain. */
318 c->paused = 1;
319 pthread_mutex_unlock(&c->mutex);
320 return CURL_WRITEFUNC_PAUSE;
321 }
322
323 av_fifo_write(c->fifo, ptr, bytes);
324 c->paused = 0;
325 c->request_received += bytes;
327 pthread_mutex_unlock(&c->mutex);
328
329 return bytes;
330}
331
332/* Return 1 if an offset was successfully parsed, 0 otherwise */
333static int parse_offset(const char *str, int64_t *out, const char **ptr)
334{
335 if (!av_isdigit(str[0]))
336 return 0;
337
338 errno = 0;
339 char *end;
340 int64_t val = strtoll(str, &end, 10);
341 if (errno == ERANGE)
342 return 0;
343
344 *out = val;
345 *ptr = end;
346 return 1;
347}
348
349/* "bytes $from-$to/$document_size" */
350static void parse_content_range(CurlContext *c, const char *v)
351{
352 int64_t start = -1, end = -1, total = -1;
353 while (av_isspace(*v))
354 v++;
355
356 if (!av_stristart(v, "bytes ", &v))
357 return;
358
359 if (!av_strstart(v, "*", &v)) {
360 if (!parse_offset(v, &start, &v) ||
361 !av_strstart(v, "-", &v) ||
362 !parse_offset(v, &end, &v))
363 return;
364 }
365
366 if (!av_strstart(v, "/", &v))
367 return;
368 if (!av_strstart(v, "*", &v) && !parse_offset(v, &total, &v))
369 return;
370
371 while (av_isspace(*v))
372 v++;
373
374 if (v[0] || (total < 0 && start < 0))
375 return; // reject trailing bytes or "*/*"
376
377 /* only set these fields if the header was recognized; ignore otherwise */
378 c->hdr_content_start = start;
379 c->hdr_content_end = end;
380 c->hdr_content_total = total;
381}
382
383/* Parse a decimal header value, bounded by len since curl does not promise a
384 * NUL terminated header buffer. Returns -1 if absent, malformed or > max. */
385static int64_t parse_header_uint(const char *p, size_t len, int64_t max)
386{
387 int64_t v = 0;
388 size_t i = 0;
389
390 while (i < len && av_isspace((unsigned char)p[i]))
391 i++;
392 if (i == len || !av_isdigit((unsigned char)p[i]))
393 return -1;
394
395 for (; i < len && av_isdigit((unsigned char)p[i]); i++) {
396 int d = p[i] - '0';
397 if (v > (max - d) / 10)
398 return -1;
399 v = v * 10 + d;
400 }
401
402 // Reject 4junk
403 while (i < len && av_isspace((unsigned char)p[i]))
404 i++;
405 if (i != len)
406 return -1;
407
408 return v;
409}
410
411/* Store one "Tag: value" reply header, tolerating a missing space after the
412 * colon and the CRLF curl leaves on the line. */
413static void store_icy_header(AVDictionary **dict, const char *ptr, size_t len)
414{
415 const char *colon = memchr(ptr, ':', len);
416 const char *val, *end = ptr + len;
417 char *key, *value;
418
419 if (!colon)
420 return;
421
422 val = colon + 1;
423 while (val < end && av_isspace(*val))
424 val++;
425 while (end > val && (end[-1] == '\r' || end[-1] == '\n'))
426 end--;
427
428 key = av_strndup(ptr, colon - ptr);
429 value = av_strndup(val, end - val);
430 /* Multikey keeps repeated headers in arrival order, as http.c reports them. */
431 if (key && value)
434 else {
435 av_free(key);
436 av_free(value);
437 }
438}
439
440/* Export the reply's "Icy-*" headers. Called once, before probed is set, so
441 * that from then on only the caller thread touches the exported metadata. */
443{
444 const AVDictionaryEntry *e = NULL;
445 AVBPrint bp;
446
447 if (!c->hdr_icy)
448 return;
449
451 while ((e = av_dict_iterate(c->hdr_icy, e)))
452 av_bprintf(&bp, "%s: %s\n", e->key, e->value);
453
454 av_freep(&c->icy_metadata_headers);
455 if (av_bprint_finalize(&bp, &c->icy_metadata_headers) < 0)
456 c->icy_metadata_headers = NULL;
457 av_dict_copy(&c->metadata, c->hdr_icy, 0);
458}
459
461 int64_t total)
462{
463 if (start < 0 || start != c->request_start) {
464 av_log(c->h, AV_LOG_ERROR, "Server sent back unexpected reply "
465 "with offset %"PRId64" (expected %"PRId64")\n",
466 start, c->request_start);
467 return 0;
468 }
469
470 if (end >= 0 && end < start) {
471 av_log(c->h, AV_LOG_ERROR, "Server sent back backwards content range "
472 "%"PRId64"-%"PRId64"\n", start, end);
473 return 0;
474 }
475
476 /* A 200 HEAD reply for an empty representation has start=0, end=-1, total=0. */
477 if (c->no_body && !total && end < 0)
478 return 1;
479
480 if (total >= 0 && (start >= total || end >= total)) {
481 av_log(c->h, AV_LOG_ERROR, "Server sent back content range "
482 "%"PRId64"-%"PRId64" that exceeds the total size "
483 "%"PRId64"\n", start, end, total);
484 return 0;
485 }
486
487 if (c->hdr_content_length >= 0 && end >= 0 &&
488 (c->hdr_content_length - 1 > INT64_MAX - start ||
489 start + (c->hdr_content_length - 1) != end))
490 {
491 av_log(c->h, AV_LOG_ERROR, "Server sent back content range "
492 "%"PRId64"-%"PRId64" that doesn't match the content length "
493 "%"PRId64"\n", start, end, c->hdr_content_length);
494 return 0;
495 }
496
497 return 1;
498}
499
500static size_t header_callback(char *ptr, size_t size, size_t nitems, void *userdata)
501{
502 CurlContext *c = userdata;
503 size_t len = size * nitems;
504 size_t n = len;
505 long status = 0;
506
507 /* Only "ICY 200" is aliased, so these two prefixes cover every status line
508 * curl lets through. */
509 if (av_strncasecmp(ptr, "HTTP/", 5) == 0 ||
510 av_strncasecmp(ptr, "ICY ", 4) == 0) {
511 c->hdr_accept_ranges = 0;
512 c->hdr_compressed = 0;
513 c->hdr_content_start = -1;
514 c->hdr_content_end = -1;
515 c->hdr_content_total = -1;
516 c->hdr_content_length = -1;
517 c->hdr_icy_metaint = -1;
518 av_dict_free(&c->hdr_icy);
519 return len;
520 }
521 if (av_strncasecmp(ptr, "Accept-Ranges:", 14) == 0) {
522 c->hdr_accept_ranges = !!av_stristr(ptr + 14, "bytes");
523 return len;
524 }
525 if (av_strncasecmp(ptr, "Content-Encoding:", 17) == 0) {
526 c->hdr_compressed = !av_stristr(ptr + 17, "identity");
527 return len;
528 }
529 if (av_strncasecmp(ptr, "Content-Range:", 14) == 0) {
530 parse_content_range(c, ptr + 14);
531 return len;
532 }
533 if (c->no_body && av_strncasecmp(ptr, "Content-Length:", 15) == 0) {
534 /* Some libcurl versions (e.g. 8.7.1) still report
535 * CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = -1 for HEAD throughout
536 * header_callback(), including the final blank line where
537 * content_size is latched. Parse Content-Length here so
538 * avio_size()/AVSEEK_SIZE stays populated. */
539 c->hdr_content_length = parse_header_uint(ptr + 15, len - 15, INT64_MAX);
540 return len;
541 }
542 if (av_strncasecmp(ptr, "icy-metaint:", 12) == 0) {
543 c->hdr_icy_metaint = parse_header_uint(ptr + 12, len - 12, INT_MAX);
544 return len;
545 }
546 /* Collected per block so that headers from a redirect hop, which the
547 * interim early return below discards, do not reach the caller. */
548 if (av_strncasecmp(ptr, "icy-", 4) == 0) {
549 store_icy_header(&c->hdr_icy, ptr, len);
550 return len;
551 }
552
553 /* Otherwise act only on the blank line that terminates the header block. */
554 while (n && (ptr[n - 1] == '\r' || ptr[n - 1] == '\n'))
555 n--;
556 if (n)
557 return len;
558
559 curl_easy_getinfo(c->easy, CURLINFO_RESPONSE_CODE, &status);
560
561 /* Interim (1xx) and redirect (3xx) responses produce an intermediate header
562 * block, wait for the final one. */
563 if (status < 200 || (status >= 300 && status < 400))
564 return len;
565
566 curl_off_t cl = -1;
567 /* Do not clobber a Content-Length parsed above when getinfo is still -1. */
568 if (curl_easy_getinfo(c->easy, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl) == CURLE_OK &&
569 cl >= 0)
570 c->hdr_content_length = cl;
571
572 pthread_mutex_lock(&c->mutex);
573 if (status >= 200 && status < 300) {
574 int64_t content_start = status == 206 ? c->hdr_content_start : 0;
575 int64_t content_end = status == 206 ? c->hdr_content_end : -1;
576 int64_t content_total = status == 206 ? c->hdr_content_total : c->hdr_content_length;
577 /* Content-Encoding describes a body. HEAD has none, so its
578 * Content-Length is the resource size. */
579 int keep_size;
580 if (content_end < 0 && content_total > 0)
581 content_end = content_total - 1;
582
583 if (!verify_content_range(c, content_start, content_end, content_total)) {
584 c->loop->num_errors++;
585 c->stream_ok = 0;
586 update_status_locked(c, AVERROR(EIO), CURLE_OK);
588 pthread_mutex_unlock(&c->mutex);
589 return len;
590 }
591
592 keep_size = !c->hdr_compressed || c->no_body;
593
594 /* Don't unlearn a known size when a reply omits it. */
595 if (keep_size && content_total >= 0)
596 c->content_size = content_total;
597
598 if (keep_size) {
599 int64_t total = content_total;
600 if (total < 0 && status != 206)
601 total = c->hdr_content_length;
602 /* Don't unlearn a known size when a reply omits it. */
603 if (total >= 0)
604 c->content_size = total;
605 if (content_end < 0)
606 content_end = c->content_size > 0 ? c->content_size - 1 : -1;
607 }
608
609 c->stream_ok = 1;
610 c->request_end = keep_size ? content_end : -1;
611 /* Capture the post-redirect URL, this is exposed as "location" AVOption
612 * for compatibility with http.c. */
613 if (!c->probed) {
614 const char *eff = NULL;
615 if (curl_easy_getinfo(c->easy, CURLINFO_EFFECTIVE_URL, &eff) == CURLE_OK
616 && eff) {
617 char *dup = av_strdup(eff);
618 if (dup) {
619 av_free(c->location);
620 c->location = dup;
621 }
622 }
624 }
625 /* A compressed body is addressed in encoded form, so byte offsets are
626 * meaningless: not seekable. Note that we prefer compression over
627 * seekability, servers don't offer media in compressed form, so it
628 * gives us free compression for other payloads like text playlist. */
629 c->seekable = !c->hdr_compressed &&
630 (status == 206 || c->hdr_accept_ranges);
631 /* Apply the user override on every reply so re-evaluation of a
632 * follow-up reply doesn't clobber it. */
633 if (c->seekable_opt >= 0)
634 c->seekable = c->seekable_opt;
635
636 c->icy_metaint = 0;
637 if (c->hdr_icy_metaint > 0) {
638 c->icy_metaint = c->hdr_icy_metaint;
639 if (c->seekable_opt > 0)
640 av_log(c->h, AV_LOG_WARNING, "Ignoring seekable=1, the "
641 "reply carries in-band ICY metadata\n");
642 /* In-band metadata makes byte offsets meaningless. Staying
643 * non-seekable also keeps on_done() from restarting a request
644 * without draining the FIFO, which would desync the
645 * interleave. */
646 c->seekable = 0;
647 c->content_size = -1;
648 }
649 } else if (status == 416 && c->probed && c->content_size < 0 &&
650 (c->hdr_content_total < 0 ||
651 c->hdr_content_total <= c->request_start)) {
652 /* A 416 on a follow-up request of a file of unknown size is EOF, unless
653 * it states a size past the requested offset. */
654 c->content_size = c->hdr_content_total;
655 c->stream_ok = 0;
657 } else {
658 c->loop->num_errors++;
659 c->stream_ok = 0;
660 update_status_locked(c, ff_http_averror(status, AVERROR(EIO)), CURLE_OK);
661 }
662 if (!c->probed) {
663 c->probe_ok = c->stream_ok;
664 c->probed = 1;
665 }
667 pthread_mutex_unlock(&c->mutex);
668
669 return len;
670}
671
672static int xferinfo_callback(void *userdata, curl_off_t dltotal, curl_off_t dlnow,
673 curl_off_t ultotal, curl_off_t ulnow)
674{
675 CurlContext *c = userdata;
676 int aborted;
677 pthread_mutex_lock(&c->mutex);
678 aborted = c->aborted;
679 pthread_mutex_unlock(&c->mutex);
680 return aborted; /* non-zero aborts the transfer */
681}
682
683/* (Re)issue the request for the current offset and add it to the multi. Loop
684 * thread only. */
686{
687 char range[48];
688 const char *range_value = NULL;
689 CURLcode cc;
690 int ret;
691
692 /* At or past the end of the file, report EOF without a request. */
693 if (c->probed && c->seekable &&
694 ((c->content_size >= 0 && c->request_start >= c->content_size) ||
695 (c->end_off > 0 && c->request_start >= c->end_off))) {
696 pthread_mutex_lock(&c->mutex);
699 pthread_mutex_unlock(&c->mutex);
700 return;
701 }
702
703 if (!c->no_body && (!c->probed || c->seekable)) {
704 int64_t start = c->request_start;
705 int64_t request_size = c->request_size;
706 if (c->is_initial && c->initial_request_size > 0)
707 request_size = c->initial_request_size;
708 if (request_size > 0 || c->end_off > 0) {
709 int64_t end = INT64_MAX;
710 if (request_size > 0 && start <= INT64_MAX - request_size)
711 end = start + request_size - 1;
712 if (c->content_size > 0)
713 end = FFMIN(end, c->content_size - 1);
714 if (c->end_off > 0)
715 end = FFMIN(end, c->end_off - 1);
716 snprintf(range, sizeof(range), "%"PRId64"-%"PRId64, start, end);
717 } else {
718 snprintf(range, sizeof(range), "%"PRId64"-", start);
719 }
720 range_value = range;
721 }
722 cc = curl_easy_setopt(c->easy, CURLOPT_RANGE, range_value);
723 if ((ret = curl_setopt_checked(c, "CURLOPT_RANGE", cc)) < 0) {
724 c->loop->num_errors++;
725 pthread_mutex_lock(&c->mutex);
728 pthread_mutex_unlock(&c->mutex);
729 return;
730 }
731 c->loop->num_requests++;
732 c->request_received = 0;
733 c->request_end = -1;
734 c->active = 1;
735 CURLMcode res = curl_multi_add_handle(c->loop->multi, c->easy);
736 if (res != CURLM_OK) {
737 av_log(c->h, AV_LOG_ERROR, "curl_multi_add_handle: %s\n",
738 curl_multi_strerror(res));
739 c->active = 0;
740 pthread_mutex_lock(&c->mutex);
743 pthread_mutex_unlock(&c->mutex);
744 }
745}
746
748{
749 CurlLoop *loop = c->loop;
750 CURL *e = c->easy;
751
752 curl_off_t recv = 0, time = 0;
753 curl_easy_getinfo(e, CURLINFO_SIZE_DOWNLOAD_T, &recv);
754 curl_easy_getinfo(e, CURLINFO_TOTAL_TIME_T, &time);
755
756 if (recv) {
757 av_log(c->h, AV_LOG_DEBUG, "%"PRId64" bytes received in %"PRId64" ms\n",
758 (int64_t) recv, (int64_t) time / 1000);
759
760 loop->total_bytes += recv;
761 loop->total_time_us += time;
762 }
763
764 long num_conns = 0, num_redirs = 0;
765 curl_easy_getinfo(e, CURLINFO_NUM_CONNECTS, &num_conns);
766 curl_easy_getinfo(e, CURLINFO_REDIRECT_COUNT, &num_redirs);
767 loop->num_connections += (int) num_conns;
768 loop->num_redirects += (int) num_redirs;
769}
770
771/* Transfer finished (or failed) */
772static void on_done(CurlContext *c, CURLcode code)
773{
774 int64_t received;
775 int aborted;
776
777 pthread_mutex_lock(&c->mutex);
778 aborted = c->aborted;
779 received = c->request_received;
780 /* Advance past delivered bytes so a retry or seek resumes at the right offset. */
781 if (received > INT64_MAX - c->request_start) {
782 received = 0;
783 aborted = 1;
786 }
787 c->request_start += received;
788 c->request_received = 0;
789 pthread_mutex_unlock(&c->mutex);
791
792 if (!c->probed) {
793 /* Connection died before any usable header arrived. */
794 pthread_mutex_lock(&c->mutex);
795 c->probed = 1;
796 c->stream_ok = 0;
797 c->loop->num_errors++;
800 pthread_mutex_unlock(&c->mutex);
801 return;
802 }
803
804 if (aborted)
805 return;
806
807 if (c->no_body) {
808 /* A HEAD reply carries no body. Do not restart the request or
809 * escalate an empty transfer to EIO ("Server sent back no data at
810 * offset"), and do not treat the clean EOF as a recoverable error. */
811 pthread_mutex_lock(&c->mutex);
812 if (code == CURLE_OK && c->stream_ok) {
813 c->status = AVERROR_EOF;
814 c->curl_status = CURLE_OK;
815 } else if (!c->status) {
816 c->loop->num_errors++;
817 update_status_locked(c, code == CURLE_OK ? AVERROR(EIO)
819 }
821 pthread_mutex_unlock(&c->mutex);
822 return;
823 }
824
825 if (c->seek_queued) {
826 /* previous soft seek drain finished; can start new request now */
827 c->seek_queued = 0;
829 return;
830 }
831
832 if (code == CURLE_OK && c->stream_ok) {
833 int64_t file_end = c->content_size >= 0 ? c->content_size - 1 : INT64_MAX;
834 if (c->end_off > 0)
835 file_end = FFMIN(file_end, c->end_off - 1);
836 if (c->seekable && c->request_end >= 0 && c->request_end < file_end) {
837 if (!received) {
838 av_log(c->h, AV_LOG_ERROR, "Server sent back no data at offset "
839 "%"PRId64"\n", c->request_start);
840 c->loop->num_errors++;
841 pthread_mutex_lock(&c->mutex);
842 update_status_locked(c, AVERROR(EIO), CURLE_OK);
844 pthread_mutex_unlock(&c->mutex);
845 return;
846 }
847 c->is_initial = 0;
849 return;
850 }
851 pthread_mutex_lock(&c->mutex);
852 c->status = AVERROR_EOF;
853 c->curl_status = CURLE_OK;
855 pthread_mutex_unlock(&c->mutex);
856 return;
857 }
858
859 if (c->stream_ok) {
860 av_log(c->h, AV_LOG_WARNING, "%s\n", curl_easy_strerror(code));
861 c->loop->num_errors++;
862 }
863
864 /* Unhandled generic curl error */
865 pthread_mutex_lock(&c->mutex);
868 pthread_mutex_unlock(&c->mutex);
869}
870
871/* ------------------------------------------------------------------------- */
872/* event loop thread + command queue */
873/* ------------------------------------------------------------------------- */
874
876{
877 if (c->seek_queued)
878 return 1; /* short seek already queued */
879
880 if (c->short_seek_size <= 0 || /* short seek disabled */
881 c->request_end < 0) /* content size not known */
882 return 0;
883
884 const int64_t last = c->request_end - c->request_start;
885 return last - c->request_received < c->short_seek_size;
886}
887
889{
890 CurlContext *c = cmd->ctx;
891
892 switch (cmd->kind) {
893 case CMD_ADD:
895 break;
896 case CMD_REMOVE:
897 if (c->active) {
898 curl_multi_remove_handle(loop->multi, c->easy);
900 c->active = 0;
901 }
902 break;
903 case CMD_UNPAUSE:
904 pthread_mutex_lock(&c->mutex);
905 c->paused = 0;
906 pthread_mutex_unlock(&c->mutex);
907 curl_easy_pause(c->easy, CURLPAUSE_CONT);
908 break;
909 case CMD_SEEK:
910 if (c->active && test_short_seek(c)) {
911 c->seek_queued = 1;
912 } else if (c->active) {
913 curl_multi_remove_handle(loop->multi, c->easy);
914 c->active = 0;
915 }
916 pthread_mutex_lock(&c->mutex);
917 av_fifo_reset2(c->fifo);
918 const int was_paused = c->paused;
919 c->aborted = 0;
920 c->paused = 0;
921 c->status = 0;
922 c->curl_status = 0;
923 pthread_mutex_unlock(&c->mutex);
924 c->request_start = cmd->pos;
925 c->request_received = 0;
926 if (!c->seek_queued)
928 else if (was_paused)
929 curl_easy_pause(c->easy, CURLPAUSE_CONT);
930 break;
931 }
932}
933
934static void *curl_worker(void *arg)
935{
936 CurlLoop *loop = arg;
937
938 ff_thread_setname("curl");
939
940 while (1) {
941 CurlCmd *cmd;
942 CURLMsg *msg;
943 int running = 0, left = 0, do_exit;
944
945 pthread_mutex_lock(&loop->mutex);
946 cmd = loop->cmd_head;
947 if (cmd) {
948 loop->cmd_head = cmd->next;
949 if (!loop->cmd_head)
950 loop->cmd_tail = NULL;
951 }
952 do_exit = loop->exit;
953 pthread_mutex_unlock(&loop->mutex);
954
955 if (cmd) {
956 execute_command(loop, cmd);
957 if (cmd->sync) {
958 pthread_mutex_lock(&loop->mutex);
959 cmd->done = 1;
961 pthread_mutex_unlock(&loop->mutex);
962 } else {
963 av_free(cmd);
964 }
965 continue; /* drain the whole queue before pumping curl */
966 }
967
968 if (do_exit)
969 break;
970
971 curl_multi_perform(loop->multi, &running);
972
973 while ((msg = curl_multi_info_read(loop->multi, &left))) {
974 CurlContext *c = NULL;
975 if (msg->msg != CURLMSG_DONE)
976 continue;
977 curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &c);
978 curl_multi_remove_handle(loop->multi, msg->easy_handle);
979 if (c) {
980 c->active = 0;
981 on_done(c, msg->data.result);
982 }
983 }
984
985 curl_multi_poll(loop->multi, NULL, 0, 1000, NULL);
986 }
987
988 return NULL;
989}
990
991/* Dispatch a command to the loop. For sync commands the caller blocks until the
992 * loop thread has executed it. Returns 0 or a negative AVERROR. */
994 int64_t pos, int sync)
995{
996 CurlCmd stackcmd = {0};
997 CurlCmd *cmd = sync ? &stackcmd : av_mallocz(sizeof(*cmd));
998
999 if (!cmd)
1000 return AVERROR(ENOMEM);
1001
1002 cmd->kind = kind;
1003 cmd->ctx = c;
1004 cmd->pos = pos;
1005 cmd->sync = sync;
1006
1007 pthread_mutex_lock(&loop->mutex);
1008 if (loop->cmd_tail)
1009 loop->cmd_tail->next = cmd;
1010 else
1011 loop->cmd_head = cmd;
1012 loop->cmd_tail = cmd;
1013 curl_multi_wakeup(loop->multi);
1014 if (sync) {
1015 while (!cmd->done)
1016 pthread_cond_wait(&loop->cond, &loop->mutex);
1017 }
1018 pthread_mutex_unlock(&loop->mutex);
1019
1020 return 0;
1021}
1022
1023static void share_lock_callback(CURL *handle, curl_lock_data data,
1024 curl_lock_access access, void *userdata)
1025{
1026 CurlLoop *loop = userdata;
1027 pthread_mutex_lock(&loop->mutex);
1028}
1029
1030static void share_unlock_callback(CURL *handle, curl_lock_data data,
1031 void *userdata)
1032{
1033 CurlLoop *loop = userdata;
1034 pthread_mutex_unlock(&loop->mutex);
1035}
1036
1038{
1039 CurlLoop *loop = av_mallocz(sizeof(*loop));
1040 CURLSHcode res;
1041 if (!loop)
1042 return NULL;
1043 loop->avfc = avfc;
1044
1045 if (pthread_mutex_init(&loop->mutex, NULL))
1046 goto fail;
1047 if (pthread_cond_init(&loop->cond, NULL)) {
1048 pthread_mutex_destroy(&loop->mutex);
1049 goto fail;
1050 }
1051
1052 if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK)
1053 goto fail2;
1054
1055 loop->multi = curl_multi_init();
1056 if (!loop->multi)
1057 goto fail3;
1058 if (curl_multi_setopt(loop->multi, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX) != CURLM_OK)
1059 goto fail3;
1060
1061 loop->share = curl_share_init();
1062 if (!loop->share)
1063 goto fail3;
1064 if (curl_share_setopt(loop->share, CURLSHOPT_USERDATA, loop) != CURLSHE_OK ||
1065 curl_share_setopt(loop->share, CURLSHOPT_LOCKFUNC, share_lock_callback) != CURLSHE_OK ||
1066 curl_share_setopt(loop->share, CURLSHOPT_UNLOCKFUNC, share_unlock_callback) != CURLSHE_OK)
1067 goto fail3;
1068 res = curl_share_setopt(loop->share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
1069 if (res != CURLSHE_OK && res != CURLSHE_NOT_BUILT_IN)
1070 goto fail3;
1071 loop->has_cookies = res == CURLSHE_OK;
1072 res = curl_share_setopt(loop->share, CURLSHOPT_SHARE, CURL_LOCK_DATA_HSTS);
1073 if (res != CURLSHE_OK && res != CURLSHE_NOT_BUILT_IN)
1074 goto fail3;
1075
1076 if (pthread_create(&loop->thread, NULL, curl_worker, loop))
1077 goto fail3;
1078
1079 return loop;
1080
1081fail3:
1082 curl_multi_cleanup(loop->multi);
1083 curl_share_cleanup(loop->share);
1084 curl_global_cleanup();
1085fail2:
1086 pthread_cond_destroy(&loop->cond);
1087 pthread_mutex_destroy(&loop->mutex);
1088fail:
1089 av_free(loop);
1090 return NULL;
1091}
1092
1094{
1095 AVFormatContext *avfc = loop->avfc;
1096
1097 if (loop->total_bytes) {
1098 double time = loop->total_time_us / 1000000.0;
1099 double avg = time ? loop->total_bytes / time : 0;
1100 av_log(avfc, AV_LOG_VERBOSE,
1101 "libcurl: Overall %"PRId64" bytes received in %.0f ms = %.0f kB/s\n",
1102 loop->total_bytes, time * 1e3, avg / 1e3);
1103 }
1104
1105 if (loop->num_connections || loop->num_errors) {
1106 av_log(avfc, AV_LOG_VERBOSE,
1107 "libcurl: %d connections, %d redirects, %d requests, %d errors\n",
1108 loop->num_connections, loop->num_redirects, loop->num_requests,
1109 loop->num_errors);
1110 }
1111}
1112
1114{
1115 pthread_mutex_lock(&loop->mutex);
1116 loop->exit = 1;
1117 curl_multi_wakeup(loop->multi);
1118 pthread_mutex_unlock(&loop->mutex);
1119
1120 pthread_join(loop->thread, NULL);
1122
1123 curl_multi_cleanup(loop->multi);
1124 curl_share_cleanup(loop->share);
1125 pthread_cond_destroy(&loop->cond);
1126 pthread_mutex_destroy(&loop->mutex);
1127 av_free(loop);
1128
1129 /* Released after the thread is joined and the multi handle is gone. */
1130 curl_global_cleanup();
1131}
1132
1133/* Attach a context to its event loop. With an owning AVFormatContext the loop is
1134 * created lazily, cached on it, and shared across the demuxer's transfers so curl
1135 * reuses connections; it is freed at format teardown. Without one the context
1136 * gets a private loop freed on close. */
1138{
1139 if (!avfc) {
1140 c->loop = curl_loop_create(NULL);
1141 c->private_loop = 1;
1142 return c->loop ? 0 : AVERROR(ENOMEM);
1143 }
1144
1146 c->loop = ffformatcontext(avfc)->curl_loop;
1147 if (!c->loop) {
1148 c->loop = curl_loop_create(avfc);
1149 ffformatcontext(avfc)->curl_loop = c->loop;
1150 }
1152
1153 return c->loop ? 0 : AVERROR(ENOMEM);
1154}
1155
1157{
1158 if (loop && *loop) {
1160 *loop = NULL;
1161 }
1162}
1163
1164/* ------------------------------------------------------------------------- */
1165/* URLProtocol callbacks */
1166/* ------------------------------------------------------------------------- */
1167
1168static int libcurl_close(URLContext *h);
1169
1170static int debug_callback(CURL *easy, curl_infotype type, char *data,
1171 size_t size, void *userdata)
1172{
1173 CurlContext *c = userdata;
1174 const char *prefix, *p = data, *end = data + size;
1175
1176 switch (type) {
1177 case CURLINFO_TEXT: prefix = "* "; break;
1178 case CURLINFO_HEADER_IN: prefix = "< "; break;
1179 case CURLINFO_HEADER_OUT: prefix = "> "; break;
1180 default: return 0;
1181 }
1182
1183 /* Split multiline payload into each log. */
1184 while (p < end) {
1185 const char *nl = memchr(p, '\n', end - p);
1186 size_t len = (nl ? nl : end) - p;
1187 while (len && p[len - 1] == '\r')
1188 len--;
1189 av_log(c->h, AV_LOG_DEBUG, "%s%.*s\n", prefix, (int)len, p);
1190 if (!nl)
1191 break;
1192 p = nl + 1;
1193 }
1194 return 0;
1195}
1196
1197static int slist_append(struct curl_slist **list, const char *str)
1198{
1199 struct curl_slist *tmp = curl_slist_append(*list, str);
1200 if (!tmp)
1201 return AVERROR(ENOMEM);
1202 *list = tmp;
1203 return 0;
1204}
1205
1206/* Build the custom request header list from the referer and headers options. */
1208{
1209 int user_set_icy = 0, ret = 0;
1210
1211 if (c->referer && c->referer[0]) {
1212 char *h = av_asprintf("Referer: %s", c->referer);
1213 if (!h)
1214 return AVERROR(ENOMEM);
1215 ret = slist_append(&c->header_list, h);
1216 av_free(h);
1217 if (ret < 0)
1218 return ret;
1219 }
1220 if (c->headers && c->headers[0]) {
1221 char *copy = av_strdup(c->headers);
1222 char *line, *saveptr = NULL;
1223 if (!copy)
1224 return AVERROR(ENOMEM);
1225 for (line = av_strtok(copy, "\r\n", &saveptr); line && ret >= 0;
1226 line = av_strtok(NULL, "\r\n", &saveptr)) {
1227 if (!av_strncasecmp(line, "Icy-MetaData:", 13))
1228 user_set_icy = 1;
1229 ret = slist_append(&c->header_list, line);
1230 }
1231 av_free(copy);
1232 if (ret < 0)
1233 return ret;
1234 }
1235 /* libcurl does not deduplicate the list, so only add ours if the user
1236 * did not already ask for one. */
1237 if (c->icy && !user_set_icy)
1238 return slist_append(&c->header_list, "Icy-MetaData: 1");
1239 return 0;
1240}
1241
1243{
1244 const char *wl = c->h->protocol_whitelist;
1245 const char *bl = c->h->protocol_blacklist;
1246 int ret;
1247 if (!wl && !bl)
1248 return 0;
1249
1250 AVBPrint bp;
1252
1253 curl_version_info_data *info = curl_version_info(CURLVERSION_NOW);
1254 for (const char *const *p = info->protocols; *p; p++) {
1255 const char *proto = *p;
1256 if (av_strcasecmp(proto, "http") && av_strcasecmp(proto, "https"))
1257 continue; /* only http(s) are supported by libcurl.c at the moment */
1258 if (wl && av_match_list(proto, wl, ',') <= 0)
1259 continue;
1260 if (bl && av_match_list(proto, bl, ',') > 0)
1261 continue;
1262 if (bp.len)
1263 av_bprint_chars(&bp, ',', 1);
1264 av_bprintf(&bp, "%s", proto);
1265 }
1266
1267 if (!av_bprint_is_complete(&bp)) {
1269 return AVERROR(ENOMEM);
1270 }
1271
1272 if (!bp.len) {
1273 av_log(c->h, AV_LOG_ERROR, "Set of allowed protocols is empty.\n");
1275 return AVERROR(EINVAL);
1276 }
1277
1278 ret = curl_setopt_checked(c, "CURLOPT_PROTOCOLS_STR",
1279 curl_easy_setopt(c->easy, CURLOPT_PROTOCOLS_STR, bp.str));
1280 if (!ret)
1281 ret = curl_setopt_checked(c, "CURLOPT_REDIR_PROTOCOLS_STR",
1282 curl_easy_setopt(c->easy, CURLOPT_REDIR_PROTOCOLS_STR, bp.str));
1284 return ret;
1285}
1286
1287/* The host as libcurl matches it against cookies. */
1288static int curl_url_host(char *host, size_t host_size, const char *url)
1289{
1290 unsigned flags = curl_version_info(CURLVERSION_NOW)->features & CURL_VERSION_IDN ? CURLU_PUNYCODE : 0;
1291 CURLU *u = curl_url();
1292 char *curl_host = NULL;
1293 CURLUcode uc;
1294 int ret;
1295
1296 if (!u)
1297 return AVERROR(ENOMEM);
1298 uc = curl_url_set(u, CURLUPART_URL, url, 0);
1299 if (uc == CURLUE_OK)
1300 uc = curl_url_get(u, CURLUPART_HOST, &curl_host, flags);
1301 if (uc == CURLUE_OK) {
1302 size_t len = strlen(curl_host);
1303 int brackets = len >= 2 && curl_host[0] == '[' && curl_host[len - 1] == ']';
1304 len -= 2 * brackets;
1305 ret = len < host_size ? 0 : AVERROR(EINVAL);
1306 if (!ret)
1307 av_strlcpy(host, curl_host + brackets, len + 1);
1308 } else
1309 ret = uc == CURLUE_OUT_OF_MEMORY ? AVERROR(ENOMEM) : AVERROR(EINVAL);
1310 curl_free(curl_host);
1311 curl_url_cleanup(u);
1312 return ret;
1313}
1314
1315/* CURLOPT_COOKIELIST line for a bound cookies option line, NULL if the line holds
1316 * no cookie libcurl can store unchanged. */
1317static int cookie_list_line(char **line, const char *cookie)
1318{
1319 AVDictionary *cookie_pair = NULL, *attributes = NULL;
1320 const AVDictionaryEntry *pair, *host_only, *path;
1321 const char *domain;
1322 int ret;
1323
1324 *line = NULL;
1325 if ((ret = ff_http_parse_set_cookie(cookie, &cookie_pair, &attributes)) < 0) {
1326 ret = ret == AVERROR_INVALIDDATA ? 0 : ret;
1327 goto end;
1328 }
1329 pair = av_dict_iterate(cookie_pair, NULL);
1330 domain = ff_http_cookie_domain(attributes);
1331 host_only = av_dict_get(attributes, "@hostonly", NULL, 0);
1332 path = av_dict_get(attributes, "path", NULL, 0);
1333 if (host_only && !domain)
1334 domain = host_only->value;
1335 else if (host_only)
1336 goto end;
1337 if (!domain || strchr(".#", *domain) || av_stristart(domain, "Set-Cookie:", NULL) ||
1338 strchr(pair->key, '\t') || strchr(pair->value, '\t') || strchr(domain, '\t') ||
1339 (path && strchr(path->value, '\t')))
1340 goto end;
1341 *line = av_asprintf("%s\t%s\t%s\t%s\t%"PRId64"\t%s\t%s", domain,
1342 host_only || ff_http_host_is_ip_literal(domain) ? "FALSE" : "TRUE",
1343 path && (*path->value == '/' || *path->value == '"') ? path->value : "/",
1344 av_dict_get(attributes, "secure", NULL, 0) ? "TRUE" : "FALSE",
1345 ff_http_cookie_expiry(attributes), pair->key, pair->value);
1346 ret = *line ? 0 : AVERROR(ENOMEM);
1347end:
1348 av_dict_free(&cookie_pair);
1349 av_dict_free(&attributes);
1350 return ret;
1351}
1352
1353#define CURL_SETOPT(opt, val) \
1354 do { \
1355 int ret_ = curl_setopt_checked(c, #opt, \
1356 curl_easy_setopt(e, opt, val)); \
1357 if (ret_ < 0) \
1358 return ret_; \
1359 } while (0)
1360
1362{
1363 const curl_version_info_data *info = curl_version_info(CURLVERSION_NOW);
1364 CURL *e = c->easy;
1365 CURLcode cc;
1366 int ret;
1367 const char *url = c->h->filename;
1368
1369 /* Drop an optional "libcurl:" prefix that forces this protocol. */
1370 av_strstart(url, "libcurl:", &url);
1371
1372 CURL_SETOPT(CURLOPT_URL, url);
1373 CURL_SETOPT(CURLOPT_PRIVATE, c);
1374 CURL_SETOPT(CURLOPT_NOSIGNAL, 1L);
1375 CURL_SETOPT(CURLOPT_SHARE, c->loop->share);
1376
1377 CURL_SETOPT(CURLOPT_WRITEFUNCTION, write_callback);
1378 CURL_SETOPT(CURLOPT_WRITEDATA, c);
1379 CURL_SETOPT(CURLOPT_HEADERFUNCTION, header_callback);
1380 CURL_SETOPT(CURLOPT_HEADERDATA, c);
1381
1382 CURL_SETOPT(CURLOPT_NOPROGRESS, 0L);
1383 CURL_SETOPT(CURLOPT_XFERINFOFUNCTION, xferinfo_callback);
1384 CURL_SETOPT(CURLOPT_XFERINFODATA, c);
1385
1386 if (av_log_get_level() >= AV_LOG_DEBUG) {
1387 CURL_SETOPT(CURLOPT_VERBOSE, 1L);
1388 CURL_SETOPT(CURLOPT_DEBUGFUNCTION, debug_callback);
1389 CURL_SETOPT(CURLOPT_DEBUGDATA, c);
1390 }
1391
1392 CURL_SETOPT(CURLOPT_FOLLOWLOCATION, 1L);
1393 CURL_SETOPT(CURLOPT_MAXREDIRS, (long)c->max_redirects);
1394 CURL_SETOPT(CURLOPT_HTTP_VERSION, (long)c->http_version);
1395 CURL_SETOPT(CURLOPT_TCP_KEEPALIVE, c->multiple_requests ? 1L : 0L);
1396 CURL_SETOPT(CURLOPT_FORBID_REUSE, c->multiple_requests ? 0L : 1L);
1397 if (info->features & CURL_VERSION_HSTS)
1398 CURL_SETOPT(CURLOPT_HSTS_CTRL, (long)CURLHSTS_ENABLE);
1399 CURL_SETOPT(CURLOPT_ACCEPT_ENCODING,
1400 c->off > 0 || c->end_off > 0 ? "identity" : "");
1401 if (c->connect_timeout > 0)
1402 CURL_SETOPT(CURLOPT_CONNECTTIMEOUT_MS,
1403 (long)c->connect_timeout * 1000);
1404
1405 if (c->user_agent && c->user_agent[0])
1406 CURL_SETOPT(CURLOPT_USERAGENT, c->user_agent);
1407 if (c->method && c->method[0]) {
1408 if (!strcmp(c->method, "HEAD")) {
1409 /* NOBODY issues HEAD and skips the body. CUSTOMREQUEST="HEAD"
1410 * alone would leave curl expecting Content-Length bytes and
1411 * raise CURLE_PARTIAL_FILE, which is retryable here. */
1412 c->no_body = 1;
1413 CURL_SETOPT(CURLOPT_NOBODY, 1L);
1414 } else {
1415 CURL_SETOPT(CURLOPT_CUSTOMREQUEST, c->method);
1416 }
1417 }
1418 if (c->http_proxy && c->http_proxy[0])
1419 CURL_SETOPT(CURLOPT_PROXY, c->http_proxy);
1420
1421 if (info->features & CURL_VERSION_SSL)
1422 CURL_SETOPT(CURLOPT_SSL_OPTIONS, (long)CURLSSLOPT_NATIVE_CA);
1423 CURL_SETOPT(CURLOPT_SSL_VERIFYPEER, c->tls_verify ? 1L : 0L);
1424 CURL_SETOPT(CURLOPT_SSL_VERIFYHOST, c->tls_verify ? 2L : 0L);
1425 if (c->ca_file)
1426 CURL_SETOPT(CURLOPT_CAINFO, c->ca_file);
1427 if (c->cert_file)
1428 CURL_SETOPT(CURLOPT_SSLCERT, c->cert_file);
1429 if (c->key_file)
1430 CURL_SETOPT(CURLOPT_SSLKEY, c->key_file);
1431
1432 if (c->loop->has_cookies) {
1433 CURL_SETOPT(CURLOPT_COOKIEFILE, "");
1434 } else if (c->cookies && c->cookies[0]) {
1435 av_log(c->h, AV_LOG_ERROR, "libcurl was built without cookie support\n");
1436 return AVERROR(ENOSYS);
1437 }
1438 if (c->cookies && c->cookies[0]) {
1439 char host[1024], *copy, *line, *saveptr = NULL;
1440
1441 if ((ret = curl_url_host(host, sizeof(host), url)) < 0 ||
1442 (ret = ff_http_bind_cookies_to_host(&c->cookies, host)) < 0)
1443 return ret;
1444 copy = av_strdup(c->cookies);
1445 if (!copy)
1446 return AVERROR(ENOMEM);
1447 for (line = av_strtok(copy, "\n", &saveptr); line;
1448 line = av_strtok(NULL, "\n", &saveptr)) {
1449 char *sc;
1450
1451 if ((ret = cookie_list_line(&sc, line)) < 0) {
1452 av_free(copy);
1453 return ret;
1454 }
1455 if (!sc)
1456 continue;
1457 cc = curl_easy_setopt(e, CURLOPT_COOKIELIST, sc);
1458 av_free(sc);
1459 if ((ret = curl_setopt_checked(c, "CURLOPT_COOKIELIST", cc)) < 0) {
1460 av_free(copy);
1461 return ret;
1462 }
1463 }
1464 av_free(copy);
1465 }
1466
1467 if ((ret = build_headers(c)) < 0)
1468 return ret;
1469 if (c->header_list)
1470 CURL_SETOPT(CURLOPT_HTTPHEADER, c->header_list);
1471
1472 /* Shoutcast v1 answers "ICY 200 OK", which curl would otherwise reject as
1473 * HTTP/0.9 before any header reaches header_callback(). */
1474 if (c->icy_status) {
1475 if ((ret = slist_append(&c->alias_list, "ICY 200")) < 0)
1476 return ret;
1477 CURL_SETOPT(CURLOPT_HTTP200ALIASES, c->alias_list);
1478 }
1479
1480 return 0;
1481}
1482
1483#undef CURL_SETOPT
1484
1486{
1488 struct timespec ts = { .tv_sec = t / 1000000,
1489 .tv_nsec = (t % 1000000) * 1000 };
1490 pthread_cond_timedwait(&c->cond, &c->mutex, &ts);
1491}
1492
1493/* Block until the transfer has been probed, the stream errored, or the open was
1494 * interrupted. Returns 0, or a negative AVERROR. */
1496{
1497 URLContext *h = c->h;
1498 int ret = 0;
1499
1500 pthread_mutex_lock(&c->mutex);
1501 while (!c->probed && !c->status) {
1502 if (ff_check_interrupt(&h->interrupt_callback)) {
1503 c->aborted = 1;
1504 ret = AVERROR_EXIT;
1505 break;
1506 }
1508 }
1509 if (!ret) {
1510 if (!c->probe_ok)
1511 ret = c->status ? c->status : AVERROR(EIO);
1512 }
1513 pthread_mutex_unlock(&c->mutex);
1514
1515 return ret;
1516}
1517
1518/* Scales by the recurrence relationship x := 2x + 1, i.e. 2^n - 1 */
1520{
1521 int64_t factor = INT64_MAX >> FFMAX(63 - c->retry_count, 0);
1523 return CURL_RETRY_MAX_US;
1524 return factor * CURL_RETRY_BASE_US;
1525}
1526
1527static int retry_request_locked(URLContext *h, int nonblock)
1528{
1529 CurlContext *c = h->priv_data;
1530 const int status = c->status;
1531 const CURLcode code = c->curl_status;
1532 pthread_mutex_unlock(&c->mutex);
1533
1534 if (!c->retry_time) {
1535 if (c->retry_count >= c->max_retries) {
1536 av_log(h, AV_LOG_ERROR, "Maximum number of retries (%d) reached\n",
1537 c->max_retries);
1538 return status;
1539 }
1540
1541 const int64_t delay = retry_delay(c);
1542 c->retry_time = av_gettime_relative() + delay;
1543 c->retry_count++;
1544
1545 av_log(h, AV_LOG_WARNING, "Retrying (#%d) from %"PRId64" in %.3fs "
1546 "after: %s (%s)\n", c->retry_count, c->logical_pos,
1547 delay * 1e-6, av_err2str(status),
1548 curl_easy_strerror(code));
1549 }
1550
1551 const int64_t sleep_us = c->retry_time - av_gettime_relative();
1552 if (sleep_us > 0 && !nonblock) {
1553 av_usleep(FFMIN(sleep_us, CURL_WAIT_US));
1554 } else if (sleep_us <= 0) {
1555 /* Use a synchronous request to ensure that the seek is registered, and
1556 * the reset of c->state is observable, before the next libcurl_read()
1557 * call, otherwise this might hit the exact same retry path a second
1558 * time. */
1559 int ret = curl_dispatch(c->loop, CMD_SEEK, c, c->logical_pos, 1);
1560 if (ret < 0)
1561 return ret;
1562 c->retry_time = 0;
1563 }
1564
1565 return AVERROR(EAGAIN); /* allow caller to handle interrupts and retry */
1566}
1567
1568static int libcurl_open(URLContext *h, const char *url, int flags,
1570{
1571 /* Guard against non-thread-safe libcurl builds. This should never happen,
1572 * since libcurl is used only on platforms with thread support, and thread
1573 * safety is enabled unconditionally in libcurl when the platform supports
1574 * threads or atomics. */
1575 curl_version_info_data *info = curl_version_info(CURLVERSION_NOW);
1576 if (!(info->features & CURL_VERSION_THREADSAFE))
1577 return AVERROR(ENOSYS);
1578
1579 CurlContext *c = h->priv_data;
1580 const char *eff_url = h->filename;
1581 int ret;
1582
1583 c->h = h;
1584 c->content_size = -1;
1585 c->request_start = c->off;
1586 c->request_end = -1;
1587 c->logical_pos = c->off;
1588 c->is_initial = 1;
1589 c->icy_block_len = -1;
1590
1591 /* Report the request URL until header_callback replaces it post-redirect. */
1592 av_strstart(eff_url, "libcurl:", &eff_url);
1593 av_freep(&c->location);
1594 c->location = av_strdup(eff_url);
1595
1596 ret = pthread_mutex_init(&c->mutex, NULL);
1597 if (ret)
1598 return AVERROR(ret);
1599 ret = pthread_cond_init(&c->cond, NULL);
1600 if (ret) {
1601 pthread_mutex_destroy(&c->mutex);
1602 return AVERROR(ret);
1603 }
1604
1605 c->fifo = av_fifo_alloc2(c->buffer_size, 1, 0);
1606 if (!c->fifo) {
1607 ret = AVERROR(ENOMEM);
1608 goto fail;
1609 }
1610
1611 ret = curl_loop_attach(c, h->avfc);
1612 if (ret < 0)
1613 goto fail;
1614
1615 c->easy = curl_easy_init();
1616 if (!c->easy) {
1617 ret = AVERROR(ENOMEM);
1618 goto fail;
1619 }
1620
1622 if (ret < 0)
1623 goto fail;
1624
1625 ret = setup_curl(c);
1626 if (ret < 0)
1627 goto fail;
1628
1629 ret = curl_dispatch(c->loop, CMD_ADD, c, 0, 0);
1630 if (ret < 0)
1631 goto fail;
1632
1633 ret = wait_for_probe(c);
1634 if (ret < 0)
1635 goto fail;
1636
1637 pthread_mutex_lock(&c->mutex);
1638 h->is_streamed = !c->seekable;
1639 pthread_mutex_unlock(&c->mutex);
1640
1641 return 0;
1642
1643fail:
1645 return ret;
1646}
1647
1648/* Export the metadata block, which the packet parser splits in place. */
1650{
1651 av_freep(&c->icy_metadata_packet);
1652 c->icy_metadata_packet = av_strdup((char *)c->icy_block);
1653 if (!c->icy_metadata_packet)
1654 return AVERROR(ENOMEM);
1655
1656 ff_http_parse_icy_packet(c->h, &c->metadata, (char *)c->icy_block);
1657 return 0;
1658}
1659
1660/* Consume the metadata block at the current interleave boundary, with the
1661 * mutex held. Returns 1 once a block is complete and ready to export. */
1663{
1664 size_t avail;
1665
1666 while ((avail = av_fifo_can_read(c->fifo))) {
1667 int n;
1668
1669 if (c->icy_block_len < 0) {
1670 uint8_t units;
1671 av_fifo_read(c->fifo, &units, 1);
1672 c->icy_block_len = units * 16;
1673 c->icy_block_filled = 0;
1674 /* A zero length byte means the metadata did not change. */
1675 if (!c->icy_block_len) {
1676 c->icy_block_len = -1;
1677 c->icy_data_read = 0;
1678 return 0;
1679 }
1680 continue;
1681 }
1682
1683 n = FFMIN(avail, (size_t)(c->icy_block_len - c->icy_block_filled));
1684 av_fifo_read(c->fifo, c->icy_block + c->icy_block_filled, n);
1685 c->icy_block_filled += n;
1686 if (c->icy_block_filled < c->icy_block_len)
1687 return 0;
1688
1689 c->icy_block[c->icy_block_len] = 0;
1690 c->icy_block_len = -1;
1691 c->icy_data_read = 0;
1692 return 1;
1693 }
1694 return 0;
1695}
1696
1697static int libcurl_read(URLContext *h, unsigned char *buf, int size)
1698{
1699 CurlContext *c = h->priv_data;
1700 int nonblock = h->flags & AVIO_FLAG_NONBLOCK;
1701 int unpause, ret;
1702
1703 pthread_mutex_lock(&c->mutex);
1704 while (1) {
1705 size_t avail;
1706
1707 /* A failed export loses one metadata update but leaves the interleave
1708 * in sync, since the block is fully consumed either way. */
1709 if (c->icy_metaint > 0 && c->icy_data_read == c->icy_metaint &&
1711 break;
1712
1713 avail = av_fifo_can_read(c->fifo);
1714 if (c->icy_metaint > 0)
1715 avail = FFMIN(avail, (size_t)(c->icy_metaint - c->icy_data_read));
1716
1717 if (avail) {
1718 ret = FFMIN(avail, (size_t)size);
1719 av_fifo_read(c->fifo, buf, ret);
1720 c->icy_data_read += ret;
1721 c->logical_pos += ret;
1722 c->retry_count = 0;
1723 c->retry_time = 0;
1724 break;
1725 }
1726
1727 if (c->status) {
1728 if (c->seekable && !c->no_body && is_recoverable(c->curl_status))
1729 return retry_request_locked(h, nonblock);
1730 if (c->status == AVERROR_EOF && c->icy_block_len >= 0)
1732 "Stream ended inside an ICY metadata block\n");
1733 ret = c->status;
1734 break;
1735 }
1736 if (nonblock) {
1737 ret = AVERROR(EAGAIN);
1738 break;
1739 }
1741 /* Return to the avio layer so it can poll the interrupt callback. */
1742 nonblock = 1;
1743 }
1744 /* Resume a paused transfer once the FIFO is at least half empty, on every
1745 * exit path because ICY framing can be drained without returning media. */
1746 unpause = c->paused && av_fifo_can_write(c->fifo) * 2 >= c->buffer_size;
1747 pthread_mutex_unlock(&c->mutex);
1748
1749 if (unpause)
1750 curl_dispatch(c->loop, CMD_UNPAUSE, c, 0, 0);
1751
1752 return ret;
1753}
1754
1756{
1757 CurlContext *c = h->priv_data;
1758 int64_t newpos;
1759
1760 pthread_mutex_lock(&c->mutex);
1761 const int64_t content_size = c->content_size;
1762 const int seekable = c->seekable;
1763 pthread_mutex_unlock(&c->mutex);
1764
1765 if (whence == AVSEEK_SIZE)
1766 return content_size >= 0 ? content_size : AVERROR(ENOSYS);
1767
1768 if (!seekable)
1769 return AVERROR(ENOSYS);
1770
1771 switch (whence) {
1772 case SEEK_SET:
1773 newpos = pos;
1774 break;
1775 case SEEK_CUR:
1776 if (pos > INT64_MAX - c->logical_pos)
1777 return AVERROR(ERANGE);
1778 newpos = c->logical_pos + pos;
1779 break;
1780 case SEEK_END:
1781 if (content_size < 0)
1782 return AVERROR(ENOSYS);
1783 if (pos > INT64_MAX - content_size)
1784 return AVERROR(ERANGE);
1785 newpos = content_size + pos;
1786 break;
1787 default:
1788 return AVERROR(EINVAL);
1789 }
1790 if (newpos < 0)
1791 return AVERROR(EINVAL);
1792
1793 if (newpos == c->logical_pos)
1794 return newpos;
1795
1796 /* Restart the transfer at the new offset. Any failure of the new request
1797 * surfaces on the following url_read(). */
1798 curl_dispatch(c->loop, CMD_SEEK, c, newpos, 1);
1799 c->logical_pos = newpos;
1800 c->retry_count = 0;
1801 c->retry_time = 0;
1802
1803 return newpos;
1804}
1805
1807{
1808 CurlContext *c = h->priv_data;
1809
1810 if (c->loop) {
1811 if (c->easy) {
1812 /* Ensure the handle is out of the multi before we free it. */
1813 curl_dispatch(c->loop, CMD_REMOVE, c, 0, 1);
1814 curl_easy_cleanup(c->easy);
1815 c->easy = NULL;
1816 }
1817 /* A shared loop outlives the transfer for connection reuse. */
1818 if (c->private_loop)
1819 curl_loop_destroy(c->loop);
1820 c->loop = NULL;
1821 }
1822
1823 if (c->header_list)
1824 curl_slist_free_all(c->header_list);
1825 if (c->alias_list)
1826 curl_slist_free_all(c->alias_list);
1827 av_dict_free(&c->hdr_icy);
1828 av_fifo_freep2(&c->fifo);
1829 pthread_cond_destroy(&c->cond);
1830 pthread_mutex_destroy(&c->mutex);
1831
1832 return 0;
1833}
1834
1836{
1837 CurlContext *c = h->priv_data;
1838 if (c->short_seek_size >= 1)
1839 return FFMIN(c->short_seek_size, INT_MAX);
1840 return AVERROR(ENOSYS);
1841}
1842
1843#define OFFSET(x) offsetof(CurlContext, x)
1844#define D AV_OPT_FLAG_DECODING_PARAM
1845#define E AV_OPT_FLAG_ENCODING_PARAM
1846static const AVOption options[] = {
1847 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
1848 { "method", "Override the HTTP method used for the request", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
1849 { "referer", "override Referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
1850 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
1851 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
1852 { "cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
1853 { "location", "the actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
1854 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
1855 { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
1856 { "seekable", "control seekability of connection", OFFSET(seekable_opt), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
1857 { "tls_verify", "verify the peer certificate and hostname", OFFSET(tls_verify), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D | E },
1858 { "ca_file", "certificate authority bundle file", OFFSET(ca_file), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
1859 { "cert_file", "client certificate file", OFFSET(cert_file), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
1860 { "key_file", "client private key file", OFFSET(key_file), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
1861 { "connect_timeout", "connection timeout in seconds (0 = libcurl default)", OFFSET(connect_timeout), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX / 1000, D | E },
1862 { "max_redirects", "maximum number of redirects to follow", OFFSET(max_redirects), AV_OPT_TYPE_INT, { .i64 = 16 }, 0, INT_MAX, D },
1863 { "multiple_requests", "reuse the connection across requests (HTTP keep-alive)", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D | E },
1864 { "max_retries", "maximum number of retries after a recoverable error", OFFSET(max_retries), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, D },
1865 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
1866 { "icy_status", "accept legacy Shoutcast \"ICY 200 OK\" status lines", OFFSET(icy_status), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
1867 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
1868 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
1869 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
1870 { "buffer_size", "receive buffer size in bytes", OFFSET(buffer_size), AV_OPT_TYPE_INT64, { .i64 = CURL_DEFAULT_BUFFER_SIZE }, CURL_MAX_WRITE_SIZE, INT_MAX, D },
1871 { "request_size", "split a transfer into ranged requests of at most this many bytes (0 = unlimited)", OFFSET(request_size), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
1872 { "initial_request_size", "size (in bytes) of initial requests made during probing / header parsing", OFFSET(initial_request_size), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
1873 { "http_version", "HTTP version to use", OFFSET(http_version), AV_OPT_TYPE_INT, { .i64 = CURL_HTTP_VERSION_NONE }, 0, INT_MAX, D, .unit = "http_version" },
1874 { "auto", "negotiate the best supported version", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_NONE }, 0, 0, D, .unit = "http_version" },
1875 { "1.0", "HTTP/1.0", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_1_0 }, 0, 0, D, .unit = "http_version" },
1876 { "1.1", "HTTP/1.1", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_1_1 }, 0, 0, D, .unit = "http_version" },
1877 { "2", "HTTP/2", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_2 }, 0, 0, D, .unit = "http_version" },
1878 { "2tls", "HTTP/2 over TLS only", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_2TLS }, 0, 0, D, .unit = "http_version" },
1879 { "2-prior-knowledge", "HTTP/2 without an upgrade handshake", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE }, 0, 0, D, .unit = "http_version" },
1880 { "3", "HTTP/3, fall back to earlier versions", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_3 }, 0, 0, D, .unit = "http_version" },
1881 { "3only", "HTTP/3 only", 0, AV_OPT_TYPE_CONST, { .i64 = CURL_HTTP_VERSION_3ONLY }, 0, 0, D, .unit = "http_version" },
1882 { "short_seek_size", "threshold to favor readahead over seek", OFFSET(short_seek_size), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
1883 { NULL }
1884};
1885
1887 .class_name = "libcurl",
1888 .item_name = av_default_item_name,
1889 .option = options,
1890 .version = LIBAVUTIL_VERSION_INT,
1891};
1892
1894 .name = "libcurl",
1895 .url_open2 = libcurl_open,
1896 .url_read = libcurl_read,
1897 .url_seek = libcurl_seek,
1898 .url_close = libcurl_close,
1899 .url_get_short_seek = libcurl_get_short_seek,
1900 .priv_data_size = sizeof(CurlContext),
1901 .priv_data_class = &libcurl_context_class,
1903 .default_whitelist = "http,https,libcurl",
1904};
static double val(void *priv, double ch)
Definition aeval.c:77
static FILE * out
#define L(x)
Definition vpx_arith.h:36
#define E
Definition avdct.c:34
#define D
Definition avdct.c:35
Main libavformat public API header.
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrupt a blocking function associated with cb.
Definition avio.c:935
#define AVSEEK_SIZE
Passing this as the "whence" parameter to a seek function causes it to return the filesize without se...
Definition avio.h:481
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition avio.h:649
char * av_asprintf(const char *fmt,...)
Definition avstring.c:115
static int BS_FUNC left(const BSCTX *bc)
Return the number of the bits left in a buffer.
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:121
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:68
AVBPrint public header.
#define AV_BPRINT_SIZE_AUTOMATIC
static int FUNC metadata(CodedBitstreamContext *ctx, RWContext *rw, APVRawMetadata *current)
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define avg(a, b, c, d)
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define max(a, b)
Public dictionary API.
error code definitions
double value
Definition eval.c:102
const char * key
static void do_exit(VideoState *is)
Definition ffplay.c:1496
char * path
Definition ffplay.c:385
int ret
Definition ffplay.c:391
static ListView * list
Definition ffplay.c:377
static int loop
Definition ffplay.c:367
A generic FIFO API.
#define fail
Definition test.h:479
#define AV_OPT_FLAG_EXPORT
The option is intended for exporting values to the caller.
Definition opt.h:362
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition opt.h:298
@ AV_OPT_TYPE_INT64
Underlying C type is int64_t.
Definition opt.h:262
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_DICT
Underlying C type is AVDictionary*.
Definition opt.h:289
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition bprint.h:218
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:234
void av_bprint_chars(AVBPrint *buf, char c, unsigned n)
Append char c n times to a print buffer.
Definition bprint.c:129
#define AV_DICT_MULTIKEY
Allow to store several equal keys in the dictionary.
Definition dict.h:84
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:236
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:61
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition dict.c:43
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition dict.c:250
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition dict.h:79
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
#define AV_DICT_DONT_STRDUP_KEY
Take ownership of a key that's been allocated with av_malloc() or another memory allocation function.
Definition dict.h:77
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition error.h:58
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR(e)
Definition error.h:45
AVFifo * av_fifo_alloc2(size_t nb_elems, size_t elem_size, unsigned int flags)
Allocate and initialize an AVFifo with a given element size.
Definition fifo.c:47
void av_fifo_freep2(AVFifo **f)
Free an AVFifo and reset pointer to NULL.
Definition fifo.c:286
void av_fifo_reset2(AVFifo *f)
Definition fifo.c:280
size_t av_fifo_can_write(const AVFifo *f)
Definition fifo.c:94
size_t av_fifo_can_read(const AVFifo *f)
Definition fifo.c:87
int av_fifo_write(AVFifo *f, const void *buf, size_t nb_elems)
Write data into a FIFO.
Definition fifo.c:188
int av_fifo_read(AVFifo *f, void *buf, size_t nb_elems)
Read data from a FIFO.
Definition fifo.c:240
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
int av_log_get_level(void)
Get the current log level.
Definition log.c:477
char * av_strndup(const char *s, size_t len)
Duplicate a substring of a string.
Definition mem.c:390
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle.
Definition avstring.c:58
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok().
Definition avstring.c:179
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition avstring.c:208
static av_const int av_isdigit(int c)
Locale-independent conversion of ASCII isdigit.
Definition avstring.h:202
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition avstring.c:36
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition avstring.c:85
static av_const int av_isspace(int c)
Locale-independent conversion of ASCII isspace.
Definition avstring.h:218
int av_match_list(const char *name, const char *list, char separator)
Check if a name is in a list.
Definition avstring.c:443
int av_stristart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str independent of case.
Definition avstring.c:47
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition avstring.c:218
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
static uint64_t request_size(URLContext *h)
Definition http.c:1620
#define DEFAULT_USER_AGENT
Definition http.c:191
static void ff_http_parse_icy_packet(void *logctx, AVDictionary **metadata, char *data)
Split an in-band ICY metadata packet into its "Key='Value';" pairs.
Definition http.h:64
const char * ff_http_cookie_domain(const AVDictionary *cookie_params)
Definition httpcookie.c:187
int ff_http_host_is_ip_literal(const char *host)
Definition httpcookie.c:182
static int ff_http_averror(int status_code, int default_averror)
Definition http.h:161
int64_t ff_http_cookie_expiry(const AVDictionary *attributes)
Definition httpcookie.c:195
int ff_http_parse_set_cookie(const char *set_cookie, AVDictionary **cookie, AVDictionary **attributes)
Parse a Set-Cookie style line.
Definition httpcookie.c:132
int ff_http_bind_cookies_to_host(char **cookies, const char *host)
Restrict the cookies without a Domain to host.
Definition httpcookie.c:211
enum MPFType type
Definition jpegmpfenc.c:55
#define u(width, name, range_min, range_max)
Definition cbs_apv.c:68
const char * arg
Definition jacosubdec.c:66
static const int factor[16]
Definition vf_pp7.c:98
static int is_recoverable(const FifoContext *fifo, int err_no)
Definition fifo.c:284
static av_always_inline FFFormatContext * ffformatcontext(AVFormatContext *s)
Definition internal.h:135
Libavformat version macros.
#define AV_MUTEX_INITIALIZER
Definition thread.h:185
static int ff_thread_setname(const char *name)
Definition thread.h:216
#define AVMutex
Definition thread.h:184
#define CURL_DEFAULT_BUFFER_SIZE
Definition libcurl.c:51
static int setup_protocols(CurlContext *c)
Definition libcurl.c:1242
static int curl_setopt_checked(CurlContext *c, const char *name, CURLcode code)
Definition libcurl.c:221
const URLProtocol ff_libcurl_protocol
Definition libcurl.c:1893
#define CURL_RETRY_MAX_US
Definition libcurl.c:67
static void execute_command(CurlLoop *loop, CurlCmd *cmd)
Definition libcurl.c:888
#define ICY_MAX_BLOCK
Definition libcurl.c:61
static void share_unlock_callback(CURL *handle, curl_lock_data data, void *userdata)
Definition libcurl.c:1030
static int curl_loop_attach(CurlContext *c, AVFormatContext *avfc)
Definition libcurl.c:1137
static int curlmcode_to_curlcode(CURLMcode code)
Definition libcurl.c:241
static void print_statistics(CurlLoop *loop)
Definition libcurl.c:1093
static int wait_for_probe(CurlContext *c)
Definition libcurl.c:1495
static int curlmcode_to_averror(CURLMcode code)
Definition libcurl.c:231
static int slist_append(struct curl_slist **list, const char *str)
Definition libcurl.c:1197
static void share_lock_callback(CURL *handle, curl_lock_data data, curl_lock_access access, void *userdata)
Definition libcurl.c:1023
static void update_statistics(CurlContext *c)
Definition libcurl.c:747
#define CURL_WAIT_US
Definition libcurl.c:55
static int is_recoverable(CURLcode code)
Definition libcurl.c:253
static void start_request(CurlContext *c)
Definition libcurl.c:685
static int verify_content_range(CurlContext *c, int64_t start, int64_t end, int64_t total)
Definition libcurl.c:460
static int drain_icy_block(CurlContext *c)
Definition libcurl.c:1662
#define CURL_RETRY_BASE_US
Definition libcurl.c:66
static int cookie_list_line(char **line, const char *cookie)
Definition libcurl.c:1317
static const AVClass libcurl_context_class
Definition libcurl.c:1886
static int xferinfo_callback(void *userdata, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
Definition libcurl.c:672
#define CURL_SETOPT(opt, val)
Definition libcurl.c:1353
static int debug_callback(CURL *easy, curl_infotype type, char *data, size_t size, void *userdata)
Definition libcurl.c:1170
static int libcurl_open(URLContext *h, const char *url, int flags, AVDictionary **options)
Definition libcurl.c:1568
static int64_t retry_delay(CurlContext *c)
Definition libcurl.c:1519
static void curl_loop_destroy(CurlLoop *loop)
Definition libcurl.c:1113
static void curl_cond_wait(CurlContext *c)
Definition libcurl.c:1485
#define ICY_MAX_HEADERS
Definition libcurl.c:58
static void update_status_locked(CurlContext *c, int status, CURLcode code)
Definition libcurl.c:275
static int parse_offset(const char *str, int64_t *out, const char **ptr)
Definition libcurl.c:333
static int libcurl_close(URLContext *h)
Definition libcurl.c:1806
static void store_icy_header(AVDictionary **dict, const char *ptr, size_t len)
Definition libcurl.c:413
void ff_curl_loop_free(struct CurlLoop **loop)
Release a libcurl event loop and set *loop to NULL.
Definition libcurl.c:1156
static int curl_url_host(char *host, size_t host_size, const char *url)
Definition libcurl.c:1288
static AVMutex curl_loop_lock
Definition libcurl.c:197
static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
Definition libcurl.c:284
static void parse_content_range(CurlContext *c, const char *v)
Definition libcurl.c:350
static void on_done(CurlContext *c, CURLcode code)
Definition libcurl.c:772
static void commit_icy_headers(CurlContext *c)
Definition libcurl.c:442
static int retry_request_locked(URLContext *h, int nonblock)
Definition libcurl.c:1527
static int test_short_seek(CurlContext *c)
Definition libcurl.c:875
static int libcurl_get_short_seek(URLContext *h)
Definition libcurl.c:1835
#define OFFSET(x)
Definition libcurl.c:1843
static int build_headers(CurlContext *c)
Definition libcurl.c:1207
static CurlLoop * curl_loop_create(AVFormatContext *avfc)
Definition libcurl.c:1037
static int64_t parse_header_uint(const char *p, size_t len, int64_t max)
Definition libcurl.c:385
static size_t header_callback(char *ptr, size_t size, size_t nitems, void *userdata)
Definition libcurl.c:500
static void * curl_worker(void *arg)
Definition libcurl.c:934
static int libcurl_read(URLContext *h, unsigned char *buf, int size)
Definition libcurl.c:1697
static int64_t libcurl_seek(URLContext *h, int64_t pos, int whence)
Definition libcurl.c:1755
static int update_icy_metadata(CurlContext *c)
Definition libcurl.c:1649
static int curl_dispatch(CurlLoop *loop, enum cmd_kind kind, CurlContext *c, int64_t pos, int sync)
Definition libcurl.c:993
static int setup_curl(CurlContext *c)
Definition libcurl.c:1361
static int curlcode_to_averror(CURLcode code)
Definition libcurl.c:199
cmd_kind
Definition libcurl.c:71
@ CMD_ADD
Definition libcurl.c:72
@ CMD_UNPAUSE
Definition libcurl.c:74
@ CMD_SEEK
Definition libcurl.c:75
@ CMD_REMOVE
Definition libcurl.c:73
Utility Preprocessor macros.
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
enum AVColorSpace space
enum AVColorRange range
Memory handling functions.
char * host
Definition mscl.c:249
const char data[16]
Definition mxf.c:155
#define av_strdup(s)
Definition ops_static.c:55
AVOptions.
static av_always_inline int pthread_cond_broadcast(pthread_cond_t *cond)
Definition os2threads.h:168
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition os2threads.h:119
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition os2threads.h:150
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition os2threads.h:104
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
Definition os2threads.h:94
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition os2threads.h:139
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
Definition os2threads.h:80
_fmutex pthread_mutex_t
Definition os2threads.h:53
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
Definition os2threads.h:132
static av_always_inline int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
Definition os2threads.h:176
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition os2threads.h:198
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition os2threads.h:112
const char * name
Definition qsvenc.c:142
const uint8_t * code
Definition spdifenc.c:433
unsigned int pos
Definition spdifenc.c:431
Describe the class of an AVClass context structure.
Definition log.h:76
char * key
Definition dict.h:91
char * value
Definition dict.h:92
Definition fifo.c:35
Format I/O context.
Definition avformat.h:1401
AVOption.
Definition opt.h:428
enum cmd_kind kind
Definition libcurl.c:79
int done
Definition libcurl.c:83
int sync
Definition libcurl.c:82
int64_t pos
Definition libcurl.c:81
CurlContext * ctx
Definition libcurl.c:80
struct CurlCmd * next
Definition libcurl.c:84
int64_t request_end
Definition libcurl.c:163
int retry_count
Definition libcurl.c:151
int64_t request_size
Definition libcurl.c:139
char * location
Definition libcurl.c:129
int64_t hdr_content_end
Definition libcurl.c:172
pthread_mutex_t mutex
Definition libcurl.c:186
int is_initial
Definition libcurl.c:164
int icy_status
Definition libcurl.c:144
int http_version
Definition libcurl.c:137
char * cookies
Definition libcurl.c:125
int64_t request_start
Definition libcurl.c:161
char * icy_metadata_headers
Definition libcurl.c:145
int tls_verify
Definition libcurl.c:132
struct curl_slist * header_list
Definition libcurl.c:116
int64_t icy_data_read
Definition libcurl.c:153
char * referer
Definition libcurl.c:122
char * cert_file
Definition libcurl.c:127
int64_t hdr_icy_metaint
Definition libcurl.c:176
pthread_cond_t cond
Definition libcurl.c:187
int64_t initial_request_size
Definition libcurl.c:140
int64_t retry_time
Definition libcurl.c:152
int64_t content_size
Definition libcurl.c:183
int max_retries
Definition libcurl.c:142
int multiple_requests
Definition libcurl.c:136
int64_t short_seek_size
Definition libcurl.c:141
AVFifo * fifo
Definition libcurl.c:188
char * key_file
Definition libcurl.c:128
int64_t end_off
Definition libcurl.c:131
int icy_block_len
Definition libcurl.c:154
int seek_queued
Definition libcurl.c:166
URLContext * h
Definition libcurl.c:111
uint8_t icy_block[ICY_MAX_BLOCK+1]
Definition libcurl.c:156
char * method
Definition libcurl.c:121
char * ca_file
Definition libcurl.c:126
int stream_ok
Definition libcurl.c:181
int connect_timeout
Definition libcurl.c:134
AVDictionary * hdr_icy
Definition libcurl.c:175
int64_t icy_metaint
Definition libcurl.c:193
int icy_block_filled
Definition libcurl.c:155
int64_t buffer_size
Definition libcurl.c:138
char * user_agent
Definition libcurl.c:120
int no_body
Definition libcurl.c:165
int private_loop
Definition libcurl.c:114
int seekable_opt
Definition libcurl.c:133
CurlLoop * loop
Definition libcurl.c:113
int64_t off
Definition libcurl.c:130
int hdr_accept_ranges
Definition libcurl.c:169
char * icy_metadata_packet
Definition libcurl.c:146
AVDictionary * metadata
Definition libcurl.c:147
int64_t logical_pos
Definition libcurl.c:150
int hdr_compressed
Definition libcurl.c:170
int probe_ok
Definition libcurl.c:180
int seekable
Definition libcurl.c:182
int64_t request_received
Definition libcurl.c:162
int64_t hdr_content_total
Definition libcurl.c:173
char * http_proxy
Definition libcurl.c:124
int64_t hdr_content_start
Definition libcurl.c:171
int aborted
Definition libcurl.c:190
CURL * easy
Definition libcurl.c:115
struct curl_slist * alias_list
Definition libcurl.c:117
int64_t hdr_content_length
Definition libcurl.c:174
int max_redirects
Definition libcurl.c:135
CURLcode curl_status
Definition libcurl.c:192
char * headers
Definition libcurl.c:123
AVFormatContext * avfc
Definition libcurl.c:88
pthread_cond_t cond
Definition libcurl.c:96
CURLM * multi
Definition libcurl.c:91
int64_t total_time_us
Definition libcurl.c:102
CurlCmd * cmd_head
Definition libcurl.c:97
pthread_mutex_t mutex
Definition libcurl.c:95
int num_errors
Definition libcurl.c:106
CurlCmd * cmd_tail
Definition libcurl.c:97
int num_requests
Definition libcurl.c:105
int num_connections
Definition libcurl.c:103
int num_redirects
Definition libcurl.c:104
int has_cookies
Definition libcurl.c:93
pthread_t thread
Definition libcurl.c:90
int exit
Definition libcurl.c:98
CURLSH * share
Definition libcurl.c:92
int64_t total_bytes
Definition libcurl.c:101
struct CurlLoop * curl_loop
Shared libcurl event loop, created on demand on the first use.
Definition internal.h:132
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
static const char *const cookies[]
Definition httpcookie.c:27
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition time.c:93
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
int64_t av_gettime(void)
Get the current time in microseconds.
Definition time.c:40
int size
char prefix[8]
unbuffered private I/O API
#define URL_PROTOCOL_FLAG_NETWORK
Definition url.h:33
static void copy(const float *p1, float *p2, const int length)
int len
static double c[64]