LCOV - code coverage report
Current view: top level - libavformat - http.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 0 936 0.0 %
Date: 2017-12-11 04:34:20 Functions: 0 44 0.0 %

          Line data    Source code
       1             : /*
       2             :  * HTTP protocol for ffmpeg client
       3             :  * Copyright (c) 2000, 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 "config.h"
      23             : 
      24             : #if CONFIG_ZLIB
      25             : #include <zlib.h>
      26             : #endif /* CONFIG_ZLIB */
      27             : 
      28             : #include "libavutil/avassert.h"
      29             : #include "libavutil/avstring.h"
      30             : #include "libavutil/opt.h"
      31             : #include "libavutil/time.h"
      32             : #include "libavutil/parseutils.h"
      33             : 
      34             : #include "avformat.h"
      35             : #include "http.h"
      36             : #include "httpauth.h"
      37             : #include "internal.h"
      38             : #include "network.h"
      39             : #include "os_support.h"
      40             : #include "url.h"
      41             : 
      42             : /* XXX: POST protocol is not completely implemented because ffmpeg uses
      43             :  * only a subset of it. */
      44             : 
      45             : /* The IO buffer size is unrelated to the max URL size in itself, but needs
      46             :  * to be large enough to fit the full request headers (including long
      47             :  * path names). */
      48             : #define BUFFER_SIZE   MAX_URL_SIZE
      49             : #define MAX_REDIRECTS 8
      50             : #define HTTP_SINGLE   1
      51             : #define HTTP_MUTLI    2
      52             : #define MAX_EXPIRY    19
      53             : #define WHITESPACES " \n\t\r"
      54             : typedef enum {
      55             :     LOWER_PROTO,
      56             :     READ_HEADERS,
      57             :     WRITE_REPLY_HEADERS,
      58             :     FINISH
      59             : }HandshakeState;
      60             : 
      61             : typedef struct HTTPContext {
      62             :     const AVClass *class;
      63             :     URLContext *hd;
      64             :     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
      65             :     int line_count;
      66             :     int http_code;
      67             :     /* Used if "Transfer-Encoding: chunked" otherwise -1. */
      68             :     uint64_t chunksize;
      69             :     int chunkend;
      70             :     uint64_t off, end_off, filesize;
      71             :     char *location;
      72             :     HTTPAuthState auth_state;
      73             :     HTTPAuthState proxy_auth_state;
      74             :     char *http_proxy;
      75             :     char *headers;
      76             :     char *mime_type;
      77             :     char *user_agent;
      78             : #if FF_API_HTTP_USER_AGENT
      79             :     char *user_agent_deprecated;
      80             : #endif
      81             :     char *content_type;
      82             :     /* Set if the server correctly handles Connection: close and will close
      83             :      * the connection after feeding us the content. */
      84             :     int willclose;
      85             :     int seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
      86             :     int chunked_post;
      87             :     /* A flag which indicates if the end of chunked encoding has been sent. */
      88             :     int end_chunked_post;
      89             :     /* A flag which indicates we have finished to read POST reply. */
      90             :     int end_header;
      91             :     /* A flag which indicates if we use persistent connections. */
      92             :     int multiple_requests;
      93             :     uint8_t *post_data;
      94             :     int post_datalen;
      95             :     int is_akamai;
      96             :     int is_mediagateway;
      97             :     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
      98             :     /* A dictionary containing cookies keyed by cookie name */
      99             :     AVDictionary *cookie_dict;
     100             :     int icy;
     101             :     /* how much data was read since the last ICY metadata packet */
     102             :     uint64_t icy_data_read;
     103             :     /* after how many bytes of read data a new metadata packet will be found */
     104             :     uint64_t icy_metaint;
     105             :     char *icy_metadata_headers;
     106             :     char *icy_metadata_packet;
     107             :     AVDictionary *metadata;
     108             : #if CONFIG_ZLIB
     109             :     int compressed;
     110             :     z_stream inflate_stream;
     111             :     uint8_t *inflate_buffer;
     112             : #endif /* CONFIG_ZLIB */
     113             :     AVDictionary *chained_options;
     114             :     int send_expect_100;
     115             :     char *method;
     116             :     int reconnect;
     117             :     int reconnect_at_eof;
     118             :     int reconnect_streamed;
     119             :     int reconnect_delay;
     120             :     int reconnect_delay_max;
     121             :     int listen;
     122             :     char *resource;
     123             :     int reply_code;
     124             :     int is_multi_client;
     125             :     HandshakeState handshake_step;
     126             :     int is_connected_server;
     127             : } HTTPContext;
     128             : 
     129             : #define OFFSET(x) offsetof(HTTPContext, x)
     130             : #define D AV_OPT_FLAG_DECODING_PARAM
     131             : #define E AV_OPT_FLAG_ENCODING_PARAM
     132             : #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
     133             : 
     134             : static const AVOption options[] = {
     135             :     { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
     136             :     { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
     137             :     { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
     138             :     { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
     139             :     { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
     140             :     { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
     141             : #if FF_API_HTTP_USER_AGENT
     142             :     { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
     143             : #endif
     144             :     { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
     145             :     { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
     146             :     { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
     147             :     { "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 },
     148             :     { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
     149             :     { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
     150             :     { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
     151             :     { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
     152             :     { "auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, { .i64 = HTTP_AUTH_NONE }, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D | E, "auth_type"},
     153             :     { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
     154             :     { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
     155             :     { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
     156             :     { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
     157             :     { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
     158             :     { "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 },
     159             :     { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
     160             :     { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
     161             :     { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
     162             :     { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
     163             :     { "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D },
     164             :     { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
     165             :     { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
     166             :     { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
     167             :     { NULL }
     168             : };
     169             : 
     170             : static int http_connect(URLContext *h, const char *path, const char *local_path,
     171             :                         const char *hoststr, const char *auth,
     172             :                         const char *proxyauth, int *new_location);
     173             : static int http_read_header(URLContext *h, int *new_location);
     174             : static int http_shutdown(URLContext *h, int flags);
     175             : 
     176           0 : void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
     177             : {
     178           0 :     memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
     179           0 :            &((HTTPContext *)src->priv_data)->auth_state,
     180             :            sizeof(HTTPAuthState));
     181           0 :     memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
     182           0 :            &((HTTPContext *)src->priv_data)->proxy_auth_state,
     183             :            sizeof(HTTPAuthState));
     184           0 : }
     185             : 
     186           0 : static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
     187             : {
     188           0 :     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
     189             :     char hostname[1024], hoststr[1024], proto[10];
     190           0 :     char auth[1024], proxyauth[1024] = "";
     191             :     char path1[MAX_URL_SIZE];
     192             :     char buf[1024], urlbuf[MAX_URL_SIZE];
     193           0 :     int port, use_proxy, err, location_changed = 0;
     194           0 :     HTTPContext *s = h->priv_data;
     195             : 
     196           0 :     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
     197             :                  hostname, sizeof(hostname), &port,
     198           0 :                  path1, sizeof(path1), s->location);
     199           0 :     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
     200             : 
     201           0 :     proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
     202           0 :     use_proxy  = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
     203           0 :                  proxy_path && av_strstart(proxy_path, "http://", NULL);
     204             : 
     205           0 :     if (!strcmp(proto, "https")) {
     206           0 :         lower_proto = "tls";
     207           0 :         use_proxy   = 0;
     208           0 :         if (port < 0)
     209           0 :             port = 443;
     210             :     }
     211           0 :     if (port < 0)
     212           0 :         port = 80;
     213             : 
     214           0 :     if (path1[0] == '\0')
     215           0 :         path = "/";
     216             :     else
     217           0 :         path = path1;
     218           0 :     local_path = path;
     219           0 :     if (use_proxy) {
     220             :         /* Reassemble the request URL without auth string - we don't
     221             :          * want to leak the auth to the proxy. */
     222           0 :         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
     223             :                     path1);
     224           0 :         path = urlbuf;
     225           0 :         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
     226             :                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
     227             :     }
     228             : 
     229           0 :     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
     230             : 
     231           0 :     if (!s->hd) {
     232           0 :         err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
     233           0 :                                    &h->interrupt_callback, options,
     234             :                                    h->protocol_whitelist, h->protocol_blacklist, h);
     235           0 :         if (err < 0)
     236           0 :             return err;
     237             :     }
     238             : 
     239           0 :     err = http_connect(h, path, local_path, hoststr,
     240             :                        auth, proxyauth, &location_changed);
     241           0 :     if (err < 0)
     242           0 :         return err;
     243             : 
     244           0 :     return location_changed;
     245             : }
     246             : 
     247             : /* return non zero if error */
     248           0 : static int http_open_cnx(URLContext *h, AVDictionary **options)
     249             : {
     250             :     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
     251           0 :     HTTPContext *s = h->priv_data;
     252           0 :     int location_changed, attempts = 0, redirects = 0;
     253           0 : redo:
     254           0 :     av_dict_copy(options, s->chained_options, 0);
     255             : 
     256           0 :     cur_auth_type       = s->auth_state.auth_type;
     257           0 :     cur_proxy_auth_type = s->auth_state.auth_type;
     258             : 
     259           0 :     location_changed = http_open_cnx_internal(h, options);
     260           0 :     if (location_changed < 0)
     261           0 :         goto fail;
     262             : 
     263           0 :     attempts++;
     264           0 :     if (s->http_code == 401) {
     265           0 :         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
     266           0 :             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
     267           0 :             ffurl_closep(&s->hd);
     268           0 :             goto redo;
     269             :         } else
     270             :             goto fail;
     271             :     }
     272           0 :     if (s->http_code == 407) {
     273           0 :         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
     274           0 :             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
     275           0 :             ffurl_closep(&s->hd);
     276           0 :             goto redo;
     277             :         } else
     278             :             goto fail;
     279             :     }
     280           0 :     if ((s->http_code == 301 || s->http_code == 302 ||
     281           0 :          s->http_code == 303 || s->http_code == 307) &&
     282             :         location_changed == 1) {
     283             :         /* url moved, get next */
     284           0 :         ffurl_closep(&s->hd);
     285           0 :         if (redirects++ >= MAX_REDIRECTS)
     286           0 :             return AVERROR(EIO);
     287             :         /* Restart the authentication process with the new target, which
     288             :          * might use a different auth mechanism. */
     289           0 :         memset(&s->auth_state, 0, sizeof(s->auth_state));
     290           0 :         attempts         = 0;
     291           0 :         location_changed = 0;
     292           0 :         goto redo;
     293             :     }
     294           0 :     return 0;
     295             : 
     296           0 : fail:
     297           0 :     if (s->hd)
     298           0 :         ffurl_closep(&s->hd);
     299           0 :     if (location_changed < 0)
     300           0 :         return location_changed;
     301           0 :     return ff_http_averror(s->http_code, AVERROR(EIO));
     302             : }
     303             : 
     304           0 : int ff_http_do_new_request(URLContext *h, const char *uri)
     305             : {
     306           0 :     HTTPContext *s = h->priv_data;
     307           0 :     AVDictionary *options = NULL;
     308             :     int ret;
     309             : 
     310           0 :     ret = http_shutdown(h, h->flags);
     311           0 :     if (ret < 0)
     312           0 :         return ret;
     313             : 
     314           0 :     s->end_chunked_post = 0;
     315           0 :     s->chunkend      = 0;
     316           0 :     s->off           = 0;
     317           0 :     s->icy_data_read = 0;
     318           0 :     av_free(s->location);
     319           0 :     s->location = av_strdup(uri);
     320           0 :     if (!s->location)
     321           0 :         return AVERROR(ENOMEM);
     322             : 
     323           0 :     ret = http_open_cnx(h, &options);
     324           0 :     av_dict_free(&options);
     325           0 :     return ret;
     326             : }
     327             : 
     328           0 : int ff_http_averror(int status_code, int default_averror)
     329             : {
     330           0 :     switch (status_code) {
     331           0 :         case 400: return AVERROR_HTTP_BAD_REQUEST;
     332           0 :         case 401: return AVERROR_HTTP_UNAUTHORIZED;
     333           0 :         case 403: return AVERROR_HTTP_FORBIDDEN;
     334           0 :         case 404: return AVERROR_HTTP_NOT_FOUND;
     335           0 :         default: break;
     336             :     }
     337           0 :     if (status_code >= 400 && status_code <= 499)
     338           0 :         return AVERROR_HTTP_OTHER_4XX;
     339           0 :     else if (status_code >= 500)
     340           0 :         return AVERROR_HTTP_SERVER_ERROR;
     341             :     else
     342           0 :         return default_averror;
     343             : }
     344             : 
     345           0 : static int http_write_reply(URLContext* h, int status_code)
     346             : {
     347           0 :     int ret, body = 0, reply_code, message_len;
     348             :     const char *reply_text, *content_type;
     349           0 :     HTTPContext *s = h->priv_data;
     350             :     char message[BUFFER_SIZE];
     351           0 :     content_type = "text/plain";
     352             : 
     353           0 :     if (status_code < 0)
     354           0 :         body = 1;
     355           0 :     switch (status_code) {
     356           0 :     case AVERROR_HTTP_BAD_REQUEST:
     357             :     case 400:
     358           0 :         reply_code = 400;
     359           0 :         reply_text = "Bad Request";
     360           0 :         break;
     361           0 :     case AVERROR_HTTP_FORBIDDEN:
     362             :     case 403:
     363           0 :         reply_code = 403;
     364           0 :         reply_text = "Forbidden";
     365           0 :         break;
     366           0 :     case AVERROR_HTTP_NOT_FOUND:
     367             :     case 404:
     368           0 :         reply_code = 404;
     369           0 :         reply_text = "Not Found";
     370           0 :         break;
     371           0 :     case 200:
     372           0 :         reply_code = 200;
     373           0 :         reply_text = "OK";
     374           0 :         content_type = s->content_type ? s->content_type : "application/octet-stream";
     375           0 :         break;
     376           0 :     case AVERROR_HTTP_SERVER_ERROR:
     377             :     case 500:
     378           0 :         reply_code = 500;
     379           0 :         reply_text = "Internal server error";
     380           0 :         break;
     381           0 :     default:
     382           0 :         return AVERROR(EINVAL);
     383             :     }
     384           0 :     if (body) {
     385           0 :         s->chunked_post = 0;
     386           0 :         message_len = snprintf(message, sizeof(message),
     387             :                  "HTTP/1.1 %03d %s\r\n"
     388             :                  "Content-Type: %s\r\n"
     389             :                  "Content-Length: %"SIZE_SPECIFIER"\r\n"
     390             :                  "%s"
     391             :                  "\r\n"
     392             :                  "%03d %s\r\n",
     393             :                  reply_code,
     394             :                  reply_text,
     395             :                  content_type,
     396           0 :                  strlen(reply_text) + 6, // 3 digit status code + space + \r\n
     397           0 :                  s->headers ? s->headers : "",
     398             :                  reply_code,
     399             :                  reply_text);
     400             :     } else {
     401           0 :         s->chunked_post = 1;
     402           0 :         message_len = snprintf(message, sizeof(message),
     403             :                  "HTTP/1.1 %03d %s\r\n"
     404             :                  "Content-Type: %s\r\n"
     405             :                  "Transfer-Encoding: chunked\r\n"
     406             :                  "%s"
     407             :                  "\r\n",
     408             :                  reply_code,
     409             :                  reply_text,
     410             :                  content_type,
     411           0 :                  s->headers ? s->headers : "");
     412             :     }
     413           0 :     av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
     414           0 :     if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
     415           0 :         return ret;
     416           0 :     return 0;
     417             : }
     418             : 
     419           0 : static void handle_http_errors(URLContext *h, int error)
     420             : {
     421           0 :     av_assert0(error < 0);
     422           0 :     http_write_reply(h, error);
     423           0 : }
     424             : 
     425           0 : static int http_handshake(URLContext *c)
     426             : {
     427             :     int ret, err, new_location;
     428           0 :     HTTPContext *ch = c->priv_data;
     429           0 :     URLContext *cl = ch->hd;
     430           0 :     switch (ch->handshake_step) {
     431           0 :     case LOWER_PROTO:
     432           0 :         av_log(c, AV_LOG_TRACE, "Lower protocol\n");
     433           0 :         if ((ret = ffurl_handshake(cl)) > 0)
     434           0 :             return 2 + ret;
     435           0 :         if (ret < 0)
     436           0 :             return ret;
     437           0 :         ch->handshake_step = READ_HEADERS;
     438           0 :         ch->is_connected_server = 1;
     439           0 :         return 2;
     440           0 :     case READ_HEADERS:
     441           0 :         av_log(c, AV_LOG_TRACE, "Read headers\n");
     442           0 :         if ((err = http_read_header(c, &new_location)) < 0) {
     443           0 :             handle_http_errors(c, err);
     444           0 :             return err;
     445             :         }
     446           0 :         ch->handshake_step = WRITE_REPLY_HEADERS;
     447           0 :         return 1;
     448           0 :     case WRITE_REPLY_HEADERS:
     449           0 :         av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
     450           0 :         if ((err = http_write_reply(c, ch->reply_code)) < 0)
     451           0 :             return err;
     452           0 :         ch->handshake_step = FINISH;
     453           0 :         return 1;
     454           0 :     case FINISH:
     455           0 :         return 0;
     456             :     }
     457             :     // this should never be reached.
     458           0 :     return AVERROR(EINVAL);
     459             : }
     460             : 
     461           0 : static int http_listen(URLContext *h, const char *uri, int flags,
     462             :                        AVDictionary **options) {
     463           0 :     HTTPContext *s = h->priv_data;
     464             :     int ret;
     465             :     char hostname[1024], proto[10];
     466             :     char lower_url[100];
     467           0 :     const char *lower_proto = "tcp";
     468             :     int port;
     469           0 :     av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
     470             :                  NULL, 0, uri);
     471           0 :     if (!strcmp(proto, "https"))
     472           0 :         lower_proto = "tls";
     473           0 :     ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
     474             :                 NULL);
     475           0 :     if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
     476           0 :         goto fail;
     477           0 :     if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
     478           0 :                                     &h->interrupt_callback, options,
     479             :                                     h->protocol_whitelist, h->protocol_blacklist, h
     480             :                                    )) < 0)
     481           0 :         goto fail;
     482           0 :     s->handshake_step = LOWER_PROTO;
     483           0 :     if (s->listen == HTTP_SINGLE) { /* single client */
     484           0 :         s->reply_code = 200;
     485           0 :         while ((ret = http_handshake(h)) > 0);
     486             :     }
     487           0 : fail:
     488           0 :     av_dict_free(&s->chained_options);
     489           0 :     return ret;
     490             : }
     491             : 
     492           0 : static int http_open(URLContext *h, const char *uri, int flags,
     493             :                      AVDictionary **options)
     494             : {
     495           0 :     HTTPContext *s = h->priv_data;
     496             :     int ret;
     497             : 
     498           0 :     if( s->seekable == 1 )
     499           0 :         h->is_streamed = 0;
     500             :     else
     501           0 :         h->is_streamed = 1;
     502             : 
     503           0 :     s->filesize = UINT64_MAX;
     504           0 :     s->location = av_strdup(uri);
     505           0 :     if (!s->location)
     506           0 :         return AVERROR(ENOMEM);
     507           0 :     if (options)
     508           0 :         av_dict_copy(&s->chained_options, *options, 0);
     509             : 
     510           0 :     if (s->headers) {
     511           0 :         int len = strlen(s->headers);
     512           0 :         if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
     513           0 :             av_log(h, AV_LOG_WARNING,
     514             :                    "No trailing CRLF found in HTTP header.\n");
     515           0 :             ret = av_reallocp(&s->headers, len + 3);
     516           0 :             if (ret < 0)
     517           0 :                 return ret;
     518           0 :             s->headers[len]     = '\r';
     519           0 :             s->headers[len + 1] = '\n';
     520           0 :             s->headers[len + 2] = '\0';
     521             :         }
     522             :     }
     523             : 
     524           0 :     if (s->listen) {
     525           0 :         return http_listen(h, uri, flags, options);
     526             :     }
     527           0 :     ret = http_open_cnx(h, options);
     528           0 :     if (ret < 0)
     529           0 :         av_dict_free(&s->chained_options);
     530           0 :     return ret;
     531             : }
     532             : 
     533           0 : static int http_accept(URLContext *s, URLContext **c)
     534             : {
     535             :     int ret;
     536           0 :     HTTPContext *sc = s->priv_data;
     537             :     HTTPContext *cc;
     538           0 :     URLContext *sl = sc->hd;
     539           0 :     URLContext *cl = NULL;
     540             : 
     541           0 :     av_assert0(sc->listen);
     542           0 :     if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
     543           0 :         goto fail;
     544           0 :     cc = (*c)->priv_data;
     545           0 :     if ((ret = ffurl_accept(sl, &cl)) < 0)
     546           0 :         goto fail;
     547           0 :     cc->hd = cl;
     548           0 :     cc->is_multi_client = 1;
     549           0 : fail:
     550           0 :     return ret;
     551             : }
     552             : 
     553           0 : static int http_getc(HTTPContext *s)
     554             : {
     555             :     int len;
     556           0 :     if (s->buf_ptr >= s->buf_end) {
     557           0 :         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
     558           0 :         if (len < 0) {
     559           0 :             return len;
     560           0 :         } else if (len == 0) {
     561           0 :             return AVERROR_EOF;
     562             :         } else {
     563           0 :             s->buf_ptr = s->buffer;
     564           0 :             s->buf_end = s->buffer + len;
     565             :         }
     566             :     }
     567           0 :     return *s->buf_ptr++;
     568             : }
     569             : 
     570           0 : static int http_get_line(HTTPContext *s, char *line, int line_size)
     571             : {
     572             :     int ch;
     573             :     char *q;
     574             : 
     575           0 :     q = line;
     576             :     for (;;) {
     577           0 :         ch = http_getc(s);
     578           0 :         if (ch < 0)
     579           0 :             return ch;
     580           0 :         if (ch == '\n') {
     581             :             /* process line */
     582           0 :             if (q > line && q[-1] == '\r')
     583           0 :                 q--;
     584           0 :             *q = '\0';
     585             : 
     586           0 :             return 0;
     587             :         } else {
     588           0 :             if ((q - line) < line_size - 1)
     589           0 :                 *q++ = ch;
     590             :         }
     591             :     }
     592             : }
     593             : 
     594           0 : static int check_http_code(URLContext *h, int http_code, const char *end)
     595             : {
     596           0 :     HTTPContext *s = h->priv_data;
     597             :     /* error codes are 4xx and 5xx, but regard 401 as a success, so we
     598             :      * don't abort until all headers have been parsed. */
     599           0 :     if (http_code >= 400 && http_code < 600 &&
     600           0 :         (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
     601           0 :         (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
     602           0 :         end += strspn(end, SPACE_CHARS);
     603           0 :         av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
     604           0 :         return ff_http_averror(http_code, AVERROR(EIO));
     605             :     }
     606           0 :     return 0;
     607             : }
     608             : 
     609           0 : static int parse_location(HTTPContext *s, const char *p)
     610             : {
     611             :     char redirected_location[MAX_URL_SIZE], *new_loc;
     612           0 :     ff_make_absolute_url(redirected_location, sizeof(redirected_location),
     613           0 :                          s->location, p);
     614           0 :     new_loc = av_strdup(redirected_location);
     615           0 :     if (!new_loc)
     616           0 :         return AVERROR(ENOMEM);
     617           0 :     av_free(s->location);
     618           0 :     s->location = new_loc;
     619           0 :     return 0;
     620             : }
     621             : 
     622             : /* "bytes $from-$to/$document_size" */
     623           0 : static void parse_content_range(URLContext *h, const char *p)
     624             : {
     625           0 :     HTTPContext *s = h->priv_data;
     626             :     const char *slash;
     627             : 
     628           0 :     if (!strncmp(p, "bytes ", 6)) {
     629           0 :         p     += 6;
     630           0 :         s->off = strtoull(p, NULL, 10);
     631           0 :         if ((slash = strchr(p, '/')) && strlen(slash) > 0)
     632           0 :             s->filesize = strtoull(slash + 1, NULL, 10);
     633             :     }
     634           0 :     if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
     635           0 :         h->is_streamed = 0; /* we _can_ in fact seek */
     636           0 : }
     637             : 
     638           0 : static int parse_content_encoding(URLContext *h, const char *p)
     639             : {
     640           0 :     if (!av_strncasecmp(p, "gzip", 4) ||
     641           0 :         !av_strncasecmp(p, "deflate", 7)) {
     642             : #if CONFIG_ZLIB
     643           0 :         HTTPContext *s = h->priv_data;
     644             : 
     645           0 :         s->compressed = 1;
     646           0 :         inflateEnd(&s->inflate_stream);
     647           0 :         if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
     648           0 :             av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
     649             :                    s->inflate_stream.msg);
     650           0 :             return AVERROR(ENOSYS);
     651             :         }
     652           0 :         if (zlibCompileFlags() & (1 << 17)) {
     653           0 :             av_log(h, AV_LOG_WARNING,
     654             :                    "Your zlib was compiled without gzip support.\n");
     655           0 :             return AVERROR(ENOSYS);
     656             :         }
     657             : #else
     658             :         av_log(h, AV_LOG_WARNING,
     659             :                "Compressed (%s) content, need zlib with gzip support\n", p);
     660             :         return AVERROR(ENOSYS);
     661             : #endif /* CONFIG_ZLIB */
     662           0 :     } else if (!av_strncasecmp(p, "identity", 8)) {
     663             :         // The normal, no-encoding case (although servers shouldn't include
     664             :         // the header at all if this is the case).
     665             :     } else {
     666           0 :         av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
     667             :     }
     668           0 :     return 0;
     669             : }
     670             : 
     671             : // Concat all Icy- header lines
     672           0 : static int parse_icy(HTTPContext *s, const char *tag, const char *p)
     673             : {
     674           0 :     int len = 4 + strlen(p) + strlen(tag);
     675           0 :     int is_first = !s->icy_metadata_headers;
     676             :     int ret;
     677             : 
     678           0 :     av_dict_set(&s->metadata, tag, p, 0);
     679             : 
     680           0 :     if (s->icy_metadata_headers)
     681           0 :         len += strlen(s->icy_metadata_headers);
     682             : 
     683           0 :     if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
     684           0 :         return ret;
     685             : 
     686           0 :     if (is_first)
     687           0 :         *s->icy_metadata_headers = '\0';
     688             : 
     689           0 :     av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
     690             : 
     691           0 :     return 0;
     692             : }
     693             : 
     694           0 : static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
     695             : {
     696             :     char exp_buf[MAX_EXPIRY];
     697           0 :     int i, j, exp_buf_len = MAX_EXPIRY-1;
     698             :     char *expiry;
     699             : 
     700             :     // strip off any punctuation or whitespace
     701           0 :     for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
     702           0 :         if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
     703           0 :             (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
     704           0 :             (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
     705           0 :             exp_buf[j] = exp_str[i];
     706           0 :             j++;
     707             :         }
     708             :     }
     709           0 :     exp_buf[j] = '\0';
     710           0 :     expiry = exp_buf;
     711             : 
     712             :     // move the string beyond the day of week
     713           0 :     while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
     714           0 :         expiry++;
     715             : 
     716           0 :     return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
     717             : }
     718             : 
     719           0 : static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
     720             : {
     721             :     char *param, *next_param, *cstr, *back;
     722             : 
     723           0 :     if (!(cstr = av_strdup(set_cookie)))
     724           0 :         return AVERROR(EINVAL);
     725             : 
     726             :     // strip any trailing whitespace
     727           0 :     back = &cstr[strlen(cstr)-1];
     728           0 :     while (strchr(WHITESPACES, *back)) {
     729           0 :         *back='\0';
     730           0 :         back--;
     731             :     }
     732             : 
     733           0 :     next_param = cstr;
     734           0 :     while ((param = av_strtok(next_param, ";", &next_param))) {
     735             :         char *name, *value;
     736           0 :         param += strspn(param, WHITESPACES);
     737           0 :         if ((name = av_strtok(param, "=", &value))) {
     738           0 :             if (av_dict_set(dict, name, value, 0) < 0) {
     739           0 :                 av_free(cstr);
     740           0 :                 return -1;
     741             :             }
     742             :         }
     743             :     }
     744             : 
     745           0 :     av_free(cstr);
     746           0 :     return 0;
     747             : }
     748             : 
     749           0 : static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
     750             : {
     751           0 :     AVDictionary *new_params = NULL;
     752             :     AVDictionaryEntry *e, *cookie_entry;
     753             :     char *eql, *name;
     754             : 
     755             :     // ensure the cookie is parsable
     756           0 :     if (parse_set_cookie(p, &new_params))
     757           0 :         return -1;
     758             : 
     759             :     // if there is no cookie value there is nothing to parse
     760           0 :     cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
     761           0 :     if (!cookie_entry || !cookie_entry->value) {
     762           0 :         av_dict_free(&new_params);
     763           0 :         return -1;
     764             :     }
     765             : 
     766             :     // ensure the cookie is not expired or older than an existing value
     767           0 :     if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
     768           0 :         struct tm new_tm = {0};
     769           0 :         if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
     770             :             AVDictionaryEntry *e2;
     771             : 
     772             :             // if the cookie has already expired ignore it
     773           0 :             if (av_timegm(&new_tm) < av_gettime() / 1000000) {
     774           0 :                 av_dict_free(&new_params);
     775           0 :                 return -1;
     776             :             }
     777             : 
     778             :             // only replace an older cookie with the same name
     779           0 :             e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
     780           0 :             if (e2 && e2->value) {
     781           0 :                 AVDictionary *old_params = NULL;
     782           0 :                 if (!parse_set_cookie(p, &old_params)) {
     783           0 :                     e2 = av_dict_get(old_params, "expires", NULL, 0);
     784           0 :                     if (e2 && e2->value) {
     785           0 :                         struct tm old_tm = {0};
     786           0 :                         if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
     787           0 :                             if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
     788           0 :                                 av_dict_free(&new_params);
     789           0 :                                 av_dict_free(&old_params);
     790           0 :                                 return -1;
     791             :                             }
     792             :                         }
     793             :                     }
     794             :                 }
     795           0 :                 av_dict_free(&old_params);
     796             :             }
     797             :         }
     798             :     }
     799             : 
     800             :     // duplicate the cookie name (dict will dupe the value)
     801           0 :     if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
     802           0 :     if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
     803             : 
     804             :     // add the cookie to the dictionary
     805           0 :     av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
     806             : 
     807           0 :     return 0;
     808             : }
     809             : 
     810           0 : static int cookie_string(AVDictionary *dict, char **cookies)
     811             : {
     812           0 :     AVDictionaryEntry *e = NULL;
     813           0 :     int len = 1;
     814             : 
     815             :     // determine how much memory is needed for the cookies string
     816           0 :     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
     817           0 :         len += strlen(e->key) + strlen(e->value) + 1;
     818             : 
     819             :     // reallocate the cookies
     820           0 :     e = NULL;
     821           0 :     if (*cookies) av_free(*cookies);
     822           0 :     *cookies = av_malloc(len);
     823           0 :     if (!*cookies) return AVERROR(ENOMEM);
     824           0 :     *cookies[0] = '\0';
     825             : 
     826             :     // write out the cookies
     827           0 :     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
     828           0 :         av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
     829             : 
     830           0 :     return 0;
     831             : }
     832             : 
     833           0 : static int process_line(URLContext *h, char *line, int line_count,
     834             :                         int *new_location)
     835             : {
     836           0 :     HTTPContext *s = h->priv_data;
     837           0 :     const char *auto_method =  h->flags & AVIO_FLAG_READ ? "POST" : "GET";
     838             :     char *tag, *p, *end, *method, *resource, *version;
     839             :     int ret;
     840             : 
     841             :     /* end of header */
     842           0 :     if (line[0] == '\0') {
     843           0 :         s->end_header = 1;
     844           0 :         return 0;
     845             :     }
     846             : 
     847           0 :     p = line;
     848           0 :     if (line_count == 0) {
     849           0 :         if (s->is_connected_server) {
     850             :             // HTTP method
     851           0 :             method = p;
     852           0 :             while (*p && !av_isspace(*p))
     853           0 :                 p++;
     854           0 :             *(p++) = '\0';
     855           0 :             av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
     856           0 :             if (s->method) {
     857           0 :                 if (av_strcasecmp(s->method, method)) {
     858           0 :                     av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
     859             :                            s->method, method);
     860           0 :                     return ff_http_averror(400, AVERROR(EIO));
     861             :                 }
     862             :             } else {
     863             :                 // use autodetected HTTP method to expect
     864           0 :                 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
     865           0 :                 if (av_strcasecmp(auto_method, method)) {
     866           0 :                     av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
     867             :                            "(%s autodetected %s received)\n", auto_method, method);
     868           0 :                     return ff_http_averror(400, AVERROR(EIO));
     869             :                 }
     870           0 :                 if (!(s->method = av_strdup(method)))
     871           0 :                     return AVERROR(ENOMEM);
     872             :             }
     873             : 
     874             :             // HTTP resource
     875           0 :             while (av_isspace(*p))
     876           0 :                 p++;
     877           0 :             resource = p;
     878           0 :             while (!av_isspace(*p))
     879           0 :                 p++;
     880           0 :             *(p++) = '\0';
     881           0 :             av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
     882           0 :             if (!(s->resource = av_strdup(resource)))
     883           0 :                 return AVERROR(ENOMEM);
     884             : 
     885             :             // HTTP version
     886           0 :             while (av_isspace(*p))
     887           0 :                 p++;
     888           0 :             version = p;
     889           0 :             while (*p && !av_isspace(*p))
     890           0 :                 p++;
     891           0 :             *p = '\0';
     892           0 :             if (av_strncasecmp(version, "HTTP/", 5)) {
     893           0 :                 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
     894           0 :                 return ff_http_averror(400, AVERROR(EIO));
     895             :             }
     896           0 :             av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
     897             :         } else {
     898           0 :             while (!av_isspace(*p) && *p != '\0')
     899           0 :                 p++;
     900           0 :             while (av_isspace(*p))
     901           0 :                 p++;
     902           0 :             s->http_code = strtol(p, &end, 10);
     903             : 
     904           0 :             av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
     905             : 
     906           0 :             if ((ret = check_http_code(h, s->http_code, end)) < 0)
     907           0 :                 return ret;
     908             :         }
     909             :     } else {
     910           0 :         while (*p != '\0' && *p != ':')
     911           0 :             p++;
     912           0 :         if (*p != ':')
     913           0 :             return 1;
     914             : 
     915           0 :         *p  = '\0';
     916           0 :         tag = line;
     917           0 :         p++;
     918           0 :         while (av_isspace(*p))
     919           0 :             p++;
     920           0 :         if (!av_strcasecmp(tag, "Location")) {
     921           0 :             if ((ret = parse_location(s, p)) < 0)
     922           0 :                 return ret;
     923           0 :             *new_location = 1;
     924           0 :         } else if (!av_strcasecmp(tag, "Content-Length") &&
     925           0 :                    s->filesize == UINT64_MAX) {
     926           0 :             s->filesize = strtoull(p, NULL, 10);
     927           0 :         } else if (!av_strcasecmp(tag, "Content-Range")) {
     928           0 :             parse_content_range(h, p);
     929           0 :         } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
     930           0 :                    !strncmp(p, "bytes", 5) &&
     931           0 :                    s->seekable == -1) {
     932           0 :             h->is_streamed = 0;
     933           0 :         } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
     934           0 :                    !av_strncasecmp(p, "chunked", 7)) {
     935           0 :             s->filesize  = UINT64_MAX;
     936           0 :             s->chunksize = 0;
     937           0 :         } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
     938           0 :             ff_http_auth_handle_header(&s->auth_state, tag, p);
     939           0 :         } else if (!av_strcasecmp(tag, "Authentication-Info")) {
     940           0 :             ff_http_auth_handle_header(&s->auth_state, tag, p);
     941           0 :         } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
     942           0 :             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
     943           0 :         } else if (!av_strcasecmp(tag, "Connection")) {
     944           0 :             if (!strcmp(p, "close"))
     945           0 :                 s->willclose = 1;
     946           0 :         } else if (!av_strcasecmp(tag, "Server")) {
     947           0 :             if (!av_strcasecmp(p, "AkamaiGHost")) {
     948           0 :                 s->is_akamai = 1;
     949           0 :             } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
     950           0 :                 s->is_mediagateway = 1;
     951             :             }
     952           0 :         } else if (!av_strcasecmp(tag, "Content-Type")) {
     953           0 :             av_free(s->mime_type);
     954           0 :             s->mime_type = av_strdup(p);
     955           0 :         } else if (!av_strcasecmp(tag, "Set-Cookie")) {
     956           0 :             if (parse_cookie(s, p, &s->cookie_dict))
     957           0 :                 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
     958           0 :         } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
     959           0 :             s->icy_metaint = strtoull(p, NULL, 10);
     960           0 :         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
     961           0 :             if ((ret = parse_icy(s, tag, p)) < 0)
     962           0 :                 return ret;
     963           0 :         } else if (!av_strcasecmp(tag, "Content-Encoding")) {
     964           0 :             if ((ret = parse_content_encoding(h, p)) < 0)
     965           0 :                 return ret;
     966             :         }
     967             :     }
     968           0 :     return 1;
     969             : }
     970             : 
     971             : /**
     972             :  * Create a string containing cookie values for use as a HTTP cookie header
     973             :  * field value for a particular path and domain from the cookie values stored in
     974             :  * the HTTP protocol context. The cookie string is stored in *cookies.
     975             :  *
     976             :  * @return a negative value if an error condition occurred, 0 otherwise
     977             :  */
     978           0 : static int get_cookies(HTTPContext *s, char **cookies, const char *path,
     979             :                        const char *domain)
     980             : {
     981             :     // cookie strings will look like Set-Cookie header field values.  Multiple
     982             :     // Set-Cookie fields will result in multiple values delimited by a newline
     983           0 :     int ret = 0;
     984           0 :     char *cookie, *set_cookies = av_strdup(s->cookies), *next = set_cookies;
     985             : 
     986           0 :     if (!set_cookies) return AVERROR(EINVAL);
     987             : 
     988             :     // destroy any cookies in the dictionary.
     989           0 :     av_dict_free(&s->cookie_dict);
     990             : 
     991           0 :     *cookies = NULL;
     992           0 :     while ((cookie = av_strtok(next, "\n", &next))) {
     993           0 :         AVDictionary *cookie_params = NULL;
     994             :         AVDictionaryEntry *cookie_entry, *e;
     995             : 
     996             :         // store the cookie in a dict in case it is updated in the response
     997           0 :         if (parse_cookie(s, cookie, &s->cookie_dict))
     998           0 :             av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
     999             : 
    1000             :         // continue on to the next cookie if this one cannot be parsed
    1001           0 :         if (parse_set_cookie(cookie, &cookie_params))
    1002           0 :             continue;
    1003             : 
    1004             :         // if the cookie has no value, skip it
    1005           0 :         cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
    1006           0 :         if (!cookie_entry || !cookie_entry->value) {
    1007           0 :             av_dict_free(&cookie_params);
    1008           0 :             continue;
    1009             :         }
    1010             : 
    1011             :         // if the cookie has expired, don't add it
    1012           0 :         if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
    1013           0 :             struct tm tm_buf = {0};
    1014           0 :             if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
    1015           0 :                 if (av_timegm(&tm_buf) < av_gettime() / 1000000) {
    1016           0 :                     av_dict_free(&cookie_params);
    1017           0 :                     continue;
    1018             :                 }
    1019             :             }
    1020             :         }
    1021             : 
    1022             :         // if no domain in the cookie assume it appied to this request
    1023           0 :         if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
    1024             :             // find the offset comparison is on the min domain (b.com, not a.b.com)
    1025           0 :             int domain_offset = strlen(domain) - strlen(e->value);
    1026           0 :             if (domain_offset < 0) {
    1027           0 :                 av_dict_free(&cookie_params);
    1028           0 :                 continue;
    1029             :             }
    1030             : 
    1031             :             // match the cookie domain
    1032           0 :             if (av_strcasecmp(&domain[domain_offset], e->value)) {
    1033           0 :                 av_dict_free(&cookie_params);
    1034           0 :                 continue;
    1035             :             }
    1036             :         }
    1037             : 
    1038             :         // ensure this cookie matches the path
    1039           0 :         e = av_dict_get(cookie_params, "path", NULL, 0);
    1040           0 :         if (!e || av_strncasecmp(path, e->value, strlen(e->value))) {
    1041           0 :             av_dict_free(&cookie_params);
    1042           0 :             continue;
    1043             :         }
    1044             : 
    1045             :         // cookie parameters match, so copy the value
    1046           0 :         if (!*cookies) {
    1047           0 :             if (!(*cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value))) {
    1048           0 :                 ret = AVERROR(ENOMEM);
    1049           0 :                 break;
    1050             :             }
    1051             :         } else {
    1052           0 :             char *tmp = *cookies;
    1053           0 :             size_t str_size = strlen(cookie_entry->key) + strlen(cookie_entry->value) + strlen(*cookies) + 4;
    1054           0 :             if (!(*cookies = av_malloc(str_size))) {
    1055           0 :                 ret = AVERROR(ENOMEM);
    1056           0 :                 av_free(tmp);
    1057           0 :                 break;
    1058             :             }
    1059           0 :             snprintf(*cookies, str_size, "%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
    1060           0 :             av_free(tmp);
    1061             :         }
    1062             :     }
    1063             : 
    1064           0 :     av_free(set_cookies);
    1065             : 
    1066           0 :     return ret;
    1067             : }
    1068             : 
    1069           0 : static inline int has_header(const char *str, const char *header)
    1070             : {
    1071             :     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
    1072           0 :     if (!str)
    1073           0 :         return 0;
    1074           0 :     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
    1075             : }
    1076             : 
    1077           0 : static int http_read_header(URLContext *h, int *new_location)
    1078             : {
    1079           0 :     HTTPContext *s = h->priv_data;
    1080             :     char line[MAX_URL_SIZE];
    1081           0 :     int err = 0;
    1082             : 
    1083           0 :     s->chunksize = UINT64_MAX;
    1084             : 
    1085             :     for (;;) {
    1086           0 :         if ((err = http_get_line(s, line, sizeof(line))) < 0)
    1087           0 :             return err;
    1088             : 
    1089           0 :         av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
    1090             : 
    1091           0 :         err = process_line(h, line, s->line_count, new_location);
    1092           0 :         if (err < 0)
    1093           0 :             return err;
    1094           0 :         if (err == 0)
    1095           0 :             break;
    1096           0 :         s->line_count++;
    1097             :     }
    1098             : 
    1099           0 :     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
    1100           0 :         h->is_streamed = 1; /* we can in fact _not_ seek */
    1101             : 
    1102             :     // add any new cookies into the existing cookie string
    1103           0 :     cookie_string(s->cookie_dict, &s->cookies);
    1104           0 :     av_dict_free(&s->cookie_dict);
    1105             : 
    1106           0 :     return err;
    1107             : }
    1108             : 
    1109           0 : static int http_connect(URLContext *h, const char *path, const char *local_path,
    1110             :                         const char *hoststr, const char *auth,
    1111             :                         const char *proxyauth, int *new_location)
    1112             : {
    1113           0 :     HTTPContext *s = h->priv_data;
    1114             :     int post, err;
    1115           0 :     char headers[HTTP_HEADERS_SIZE] = "";
    1116           0 :     char *authstr = NULL, *proxyauthstr = NULL;
    1117           0 :     uint64_t off = s->off;
    1118           0 :     int len = 0;
    1119             :     const char *method;
    1120           0 :     int send_expect_100 = 0;
    1121             :     int ret;
    1122             : 
    1123             :     /* send http header */
    1124           0 :     post = h->flags & AVIO_FLAG_WRITE;
    1125             : 
    1126           0 :     if (s->post_data) {
    1127             :         /* force POST method and disable chunked encoding when
    1128             :          * custom HTTP post data is set */
    1129           0 :         post            = 1;
    1130           0 :         s->chunked_post = 0;
    1131             :     }
    1132             : 
    1133           0 :     if (s->method)
    1134           0 :         method = s->method;
    1135             :     else
    1136           0 :         method = post ? "POST" : "GET";
    1137             : 
    1138           0 :     authstr      = ff_http_auth_create_response(&s->auth_state, auth,
    1139             :                                                 local_path, method);
    1140           0 :     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
    1141             :                                                 local_path, method);
    1142           0 :     if (post && !s->post_data) {
    1143           0 :         send_expect_100 = s->send_expect_100;
    1144             :         /* The user has supplied authentication but we don't know the auth type,
    1145             :          * send Expect: 100-continue to get the 401 response including the
    1146             :          * WWW-Authenticate header, or an 100 continue if no auth actually
    1147             :          * is needed. */
    1148           0 :         if (auth && *auth &&
    1149           0 :             s->auth_state.auth_type == HTTP_AUTH_NONE &&
    1150           0 :             s->http_code != 401)
    1151           0 :             send_expect_100 = 1;
    1152             :     }
    1153             : 
    1154             : #if FF_API_HTTP_USER_AGENT
    1155           0 :     if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
    1156           0 :         av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
    1157           0 :         s->user_agent = av_strdup(s->user_agent_deprecated);
    1158             :     }
    1159             : #endif
    1160             :     /* set default headers if needed */
    1161           0 :     if (!has_header(s->headers, "\r\nUser-Agent: "))
    1162           0 :         len += av_strlcatf(headers + len, sizeof(headers) - len,
    1163             :                            "User-Agent: %s\r\n", s->user_agent);
    1164           0 :     if (!has_header(s->headers, "\r\nAccept: "))
    1165           0 :         len += av_strlcpy(headers + len, "Accept: */*\r\n",
    1166             :                           sizeof(headers) - len);
    1167             :     // Note: we send this on purpose even when s->off is 0 when we're probing,
    1168             :     // since it allows us to detect more reliably if a (non-conforming)
    1169             :     // server supports seeking by analysing the reply headers.
    1170           0 :     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
    1171           0 :         len += av_strlcatf(headers + len, sizeof(headers) - len,
    1172             :                            "Range: bytes=%"PRIu64"-", s->off);
    1173           0 :         if (s->end_off)
    1174           0 :             len += av_strlcatf(headers + len, sizeof(headers) - len,
    1175           0 :                                "%"PRId64, s->end_off - 1);
    1176           0 :         len += av_strlcpy(headers + len, "\r\n",
    1177             :                           sizeof(headers) - len);
    1178             :     }
    1179           0 :     if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
    1180           0 :         len += av_strlcatf(headers + len, sizeof(headers) - len,
    1181             :                            "Expect: 100-continue\r\n");
    1182             : 
    1183           0 :     if (!has_header(s->headers, "\r\nConnection: ")) {
    1184           0 :         if (s->multiple_requests)
    1185           0 :             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
    1186             :                               sizeof(headers) - len);
    1187             :         else
    1188           0 :             len += av_strlcpy(headers + len, "Connection: close\r\n",
    1189             :                               sizeof(headers) - len);
    1190             :     }
    1191             : 
    1192           0 :     if (!has_header(s->headers, "\r\nHost: "))
    1193           0 :         len += av_strlcatf(headers + len, sizeof(headers) - len,
    1194             :                            "Host: %s\r\n", hoststr);
    1195           0 :     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
    1196           0 :         len += av_strlcatf(headers + len, sizeof(headers) - len,
    1197             :                            "Content-Length: %d\r\n", s->post_datalen);
    1198             : 
    1199           0 :     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
    1200           0 :         len += av_strlcatf(headers + len, sizeof(headers) - len,
    1201             :                            "Content-Type: %s\r\n", s->content_type);
    1202           0 :     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
    1203           0 :         char *cookies = NULL;
    1204           0 :         if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
    1205           0 :             len += av_strlcatf(headers + len, sizeof(headers) - len,
    1206             :                                "Cookie: %s\r\n", cookies);
    1207           0 :             av_free(cookies);
    1208             :         }
    1209             :     }
    1210           0 :     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
    1211           0 :         len += av_strlcatf(headers + len, sizeof(headers) - len,
    1212             :                            "Icy-MetaData: %d\r\n", 1);
    1213             : 
    1214             :     /* now add in custom headers */
    1215           0 :     if (s->headers)
    1216           0 :         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
    1217             : 
    1218           0 :     ret = snprintf(s->buffer, sizeof(s->buffer),
    1219             :              "%s %s HTTP/1.1\r\n"
    1220             :              "%s"
    1221             :              "%s"
    1222             :              "%s"
    1223             :              "%s%s"
    1224             :              "\r\n",
    1225             :              method,
    1226             :              path,
    1227           0 :              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
    1228             :              headers,
    1229           0 :              authstr ? authstr : "",
    1230           0 :              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
    1231             : 
    1232           0 :     av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
    1233             : 
    1234           0 :     if (strlen(headers) + 1 == sizeof(headers) ||
    1235           0 :         ret >= sizeof(s->buffer)) {
    1236           0 :         av_log(h, AV_LOG_ERROR, "overlong headers\n");
    1237           0 :         err = AVERROR(EINVAL);
    1238           0 :         goto done;
    1239             :     }
    1240             : 
    1241             : 
    1242           0 :     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
    1243           0 :         goto done;
    1244             : 
    1245           0 :     if (s->post_data)
    1246           0 :         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
    1247           0 :             goto done;
    1248             : 
    1249             :     /* init input buffer */
    1250           0 :     s->buf_ptr          = s->buffer;
    1251           0 :     s->buf_end          = s->buffer;
    1252           0 :     s->line_count       = 0;
    1253           0 :     s->off              = 0;
    1254           0 :     s->icy_data_read    = 0;
    1255           0 :     s->filesize         = UINT64_MAX;
    1256           0 :     s->willclose        = 0;
    1257           0 :     s->end_chunked_post = 0;
    1258           0 :     s->end_header       = 0;
    1259             : #if CONFIG_ZLIB
    1260           0 :     s->compressed       = 0;
    1261             : #endif
    1262           0 :     if (post && !s->post_data && !send_expect_100) {
    1263             :         /* Pretend that it did work. We didn't read any header yet, since
    1264             :          * we've still to send the POST data, but the code calling this
    1265             :          * function will check http_code after we return. */
    1266           0 :         s->http_code = 200;
    1267           0 :         err = 0;
    1268           0 :         goto done;
    1269             :     }
    1270             : 
    1271             :     /* wait for header */
    1272           0 :     err = http_read_header(h, new_location);
    1273           0 :     if (err < 0)
    1274           0 :         goto done;
    1275             : 
    1276           0 :     if (*new_location)
    1277           0 :         s->off = off;
    1278             : 
    1279           0 :     err = (off == s->off) ? 0 : -1;
    1280           0 : done:
    1281           0 :     av_freep(&authstr);
    1282           0 :     av_freep(&proxyauthstr);
    1283           0 :     return err;
    1284             : }
    1285             : 
    1286           0 : static int http_buf_read(URLContext *h, uint8_t *buf, int size)
    1287             : {
    1288           0 :     HTTPContext *s = h->priv_data;
    1289             :     int len;
    1290             : 
    1291           0 :     if (s->chunksize != UINT64_MAX) {
    1292           0 :         if (s->chunkend) {
    1293           0 :             return AVERROR_EOF;
    1294             :         }
    1295           0 :         if (!s->chunksize) {
    1296             :             char line[32];
    1297             :             int err;
    1298             : 
    1299             :             do {
    1300           0 :                 if ((err = http_get_line(s, line, sizeof(line))) < 0)
    1301           0 :                     return err;
    1302           0 :             } while (!*line);    /* skip CR LF from last chunk */
    1303             : 
    1304           0 :             s->chunksize = strtoull(line, NULL, 16);
    1305             : 
    1306           0 :             av_log(h, AV_LOG_TRACE,
    1307             :                    "Chunked encoding data size: %"PRIu64"\n",
    1308             :                     s->chunksize);
    1309             : 
    1310           0 :             if (!s->chunksize && s->multiple_requests) {
    1311           0 :                 http_get_line(s, line, sizeof(line)); // read empty chunk
    1312           0 :                 s->chunkend = 1;
    1313           0 :                 return 0;
    1314             :             }
    1315           0 :             else if (!s->chunksize) {
    1316           0 :                 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
    1317           0 :                 ffurl_closep(&s->hd);
    1318           0 :                 return 0;
    1319             :             }
    1320           0 :             else if (s->chunksize == UINT64_MAX) {
    1321           0 :                 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
    1322             :                        s->chunksize);
    1323           0 :                 return AVERROR(EINVAL);
    1324             :             }
    1325             :         }
    1326           0 :         size = FFMIN(size, s->chunksize);
    1327             :     }
    1328             : 
    1329             :     /* read bytes from input buffer first */
    1330           0 :     len = s->buf_end - s->buf_ptr;
    1331           0 :     if (len > 0) {
    1332           0 :         if (len > size)
    1333           0 :             len = size;
    1334           0 :         memcpy(buf, s->buf_ptr, len);
    1335           0 :         s->buf_ptr += len;
    1336             :     } else {
    1337           0 :         uint64_t target_end = s->end_off ? s->end_off : s->filesize;
    1338           0 :         if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
    1339           0 :             return AVERROR_EOF;
    1340           0 :         len = ffurl_read(s->hd, buf, size);
    1341           0 :         if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
    1342           0 :             av_log(h, AV_LOG_ERROR,
    1343             :                    "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
    1344             :                    s->off, target_end
    1345             :                   );
    1346           0 :             return AVERROR(EIO);
    1347             :         }
    1348             :     }
    1349           0 :     if (len > 0) {
    1350           0 :         s->off += len;
    1351           0 :         if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
    1352           0 :             av_assert0(s->chunksize >= len);
    1353           0 :             s->chunksize -= len;
    1354             :         }
    1355             :     }
    1356           0 :     return len;
    1357             : }
    1358             : 
    1359             : #if CONFIG_ZLIB
    1360             : #define DECOMPRESS_BUF_SIZE (256 * 1024)
    1361           0 : static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
    1362             : {
    1363           0 :     HTTPContext *s = h->priv_data;
    1364             :     int ret;
    1365             : 
    1366           0 :     if (!s->inflate_buffer) {
    1367           0 :         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
    1368           0 :         if (!s->inflate_buffer)
    1369           0 :             return AVERROR(ENOMEM);
    1370             :     }
    1371             : 
    1372           0 :     if (s->inflate_stream.avail_in == 0) {
    1373           0 :         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
    1374           0 :         if (read <= 0)
    1375           0 :             return read;
    1376           0 :         s->inflate_stream.next_in  = s->inflate_buffer;
    1377           0 :         s->inflate_stream.avail_in = read;
    1378             :     }
    1379             : 
    1380           0 :     s->inflate_stream.avail_out = size;
    1381           0 :     s->inflate_stream.next_out  = buf;
    1382             : 
    1383           0 :     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
    1384           0 :     if (ret != Z_OK && ret != Z_STREAM_END)
    1385           0 :         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
    1386             :                ret, s->inflate_stream.msg);
    1387             : 
    1388           0 :     return size - s->inflate_stream.avail_out;
    1389             : }
    1390             : #endif /* CONFIG_ZLIB */
    1391             : 
    1392             : static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
    1393             : 
    1394           0 : static int http_read_stream(URLContext *h, uint8_t *buf, int size)
    1395             : {
    1396           0 :     HTTPContext *s = h->priv_data;
    1397             :     int err, new_location, read_ret;
    1398             :     int64_t seek_ret;
    1399             : 
    1400           0 :     if (!s->hd)
    1401           0 :         return AVERROR_EOF;
    1402             : 
    1403           0 :     if (s->end_chunked_post && !s->end_header) {
    1404           0 :         err = http_read_header(h, &new_location);
    1405           0 :         if (err < 0)
    1406           0 :             return err;
    1407             :     }
    1408             : 
    1409             : #if CONFIG_ZLIB
    1410           0 :     if (s->compressed)
    1411           0 :         return http_buf_read_compressed(h, buf, size);
    1412             : #endif /* CONFIG_ZLIB */
    1413           0 :     read_ret = http_buf_read(h, buf, size);
    1414           0 :     if (   (read_ret  < 0 && s->reconnect        && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
    1415           0 :         || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
    1416           0 :         uint64_t target = h->is_streamed ? 0 : s->off;
    1417             : 
    1418           0 :         if (s->reconnect_delay > s->reconnect_delay_max)
    1419           0 :             return AVERROR(EIO);
    1420             : 
    1421           0 :         av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
    1422           0 :         av_usleep(1000U*1000*s->reconnect_delay);
    1423           0 :         s->reconnect_delay = 1 + 2*s->reconnect_delay;
    1424           0 :         seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
    1425           0 :         if (seek_ret != target) {
    1426           0 :             av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
    1427           0 :             return read_ret;
    1428             :         }
    1429             : 
    1430           0 :         read_ret = http_buf_read(h, buf, size);
    1431             :     } else
    1432           0 :         s->reconnect_delay = 0;
    1433             : 
    1434           0 :     return read_ret;
    1435             : }
    1436             : 
    1437             : // Like http_read_stream(), but no short reads.
    1438             : // Assumes partial reads are an error.
    1439           0 : static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
    1440             : {
    1441           0 :     int pos = 0;
    1442           0 :     while (pos < size) {
    1443           0 :         int len = http_read_stream(h, buf + pos, size - pos);
    1444           0 :         if (len < 0)
    1445           0 :             return len;
    1446           0 :         pos += len;
    1447             :     }
    1448           0 :     return pos;
    1449             : }
    1450             : 
    1451           0 : static void update_metadata(HTTPContext *s, char *data)
    1452             : {
    1453             :     char *key;
    1454             :     char *val;
    1455             :     char *end;
    1456           0 :     char *next = data;
    1457             : 
    1458           0 :     while (*next) {
    1459           0 :         key = next;
    1460           0 :         val = strstr(key, "='");
    1461           0 :         if (!val)
    1462           0 :             break;
    1463           0 :         end = strstr(val, "';");
    1464           0 :         if (!end)
    1465           0 :             break;
    1466             : 
    1467           0 :         *val = '\0';
    1468           0 :         *end = '\0';
    1469           0 :         val += 2;
    1470             : 
    1471           0 :         av_dict_set(&s->metadata, key, val, 0);
    1472             : 
    1473           0 :         next = end + 2;
    1474             :     }
    1475           0 : }
    1476             : 
    1477           0 : static int store_icy(URLContext *h, int size)
    1478             : {
    1479           0 :     HTTPContext *s = h->priv_data;
    1480             :     /* until next metadata packet */
    1481             :     uint64_t remaining;
    1482             : 
    1483           0 :     if (s->icy_metaint < s->icy_data_read)
    1484           0 :         return AVERROR_INVALIDDATA;
    1485           0 :     remaining = s->icy_metaint - s->icy_data_read;
    1486             : 
    1487           0 :     if (!remaining) {
    1488             :         /* The metadata packet is variable sized. It has a 1 byte header
    1489             :          * which sets the length of the packet (divided by 16). If it's 0,
    1490             :          * the metadata doesn't change. After the packet, icy_metaint bytes
    1491             :          * of normal data follows. */
    1492             :         uint8_t ch;
    1493           0 :         int len = http_read_stream_all(h, &ch, 1);
    1494           0 :         if (len < 0)
    1495           0 :             return len;
    1496           0 :         if (ch > 0) {
    1497             :             char data[255 * 16 + 1];
    1498             :             int ret;
    1499           0 :             len = ch * 16;
    1500           0 :             ret = http_read_stream_all(h, data, len);
    1501           0 :             if (ret < 0)
    1502           0 :                 return ret;
    1503           0 :             data[len + 1] = 0;
    1504           0 :             if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
    1505           0 :                 return ret;
    1506           0 :             update_metadata(s, data);
    1507             :         }
    1508           0 :         s->icy_data_read = 0;
    1509           0 :         remaining        = s->icy_metaint;
    1510             :     }
    1511             : 
    1512           0 :     return FFMIN(size, remaining);
    1513             : }
    1514             : 
    1515           0 : static int http_read(URLContext *h, uint8_t *buf, int size)
    1516             : {
    1517           0 :     HTTPContext *s = h->priv_data;
    1518             : 
    1519           0 :     if (s->icy_metaint > 0) {
    1520           0 :         size = store_icy(h, size);
    1521           0 :         if (size < 0)
    1522           0 :             return size;
    1523             :     }
    1524             : 
    1525           0 :     size = http_read_stream(h, buf, size);
    1526           0 :     if (size > 0)
    1527           0 :         s->icy_data_read += size;
    1528           0 :     return size;
    1529             : }
    1530             : 
    1531             : /* used only when posting data */
    1532           0 : static int http_write(URLContext *h, const uint8_t *buf, int size)
    1533             : {
    1534           0 :     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
    1535             :     int ret;
    1536           0 :     char crlf[] = "\r\n";
    1537           0 :     HTTPContext *s = h->priv_data;
    1538             : 
    1539           0 :     if (!s->chunked_post) {
    1540             :         /* non-chunked data is sent without any special encoding */
    1541           0 :         return ffurl_write(s->hd, buf, size);
    1542             :     }
    1543             : 
    1544             :     /* silently ignore zero-size data since chunk encoding that would
    1545             :      * signal EOF */
    1546           0 :     if (size > 0) {
    1547             :         /* upload data using chunked encoding */
    1548           0 :         snprintf(temp, sizeof(temp), "%x\r\n", size);
    1549             : 
    1550           0 :         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
    1551           0 :             (ret = ffurl_write(s->hd, buf, size)) < 0          ||
    1552           0 :             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
    1553           0 :             return ret;
    1554             :     }
    1555           0 :     return size;
    1556             : }
    1557             : 
    1558           0 : static int http_shutdown(URLContext *h, int flags)
    1559             : {
    1560           0 :     int ret = 0;
    1561           0 :     char footer[] = "0\r\n\r\n";
    1562           0 :     HTTPContext *s = h->priv_data;
    1563             : 
    1564             :     /* signal end of chunked encoding if used */
    1565           0 :     if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
    1566           0 :         ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
    1567           0 :         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
    1568           0 :         ret = ret > 0 ? 0 : ret;
    1569           0 :         s->end_chunked_post = 1;
    1570             :     }
    1571             : 
    1572           0 :     return ret;
    1573             : }
    1574             : 
    1575           0 : static int http_close(URLContext *h)
    1576             : {
    1577           0 :     int ret = 0;
    1578           0 :     HTTPContext *s = h->priv_data;
    1579             : 
    1580             : #if CONFIG_ZLIB
    1581           0 :     inflateEnd(&s->inflate_stream);
    1582           0 :     av_freep(&s->inflate_buffer);
    1583             : #endif /* CONFIG_ZLIB */
    1584             : 
    1585           0 :     if (!s->end_chunked_post)
    1586             :         /* Close the write direction by sending the end of chunked encoding. */
    1587           0 :         ret = http_shutdown(h, h->flags);
    1588             : 
    1589           0 :     if (s->hd)
    1590           0 :         ffurl_closep(&s->hd);
    1591           0 :     av_dict_free(&s->chained_options);
    1592           0 :     return ret;
    1593             : }
    1594             : 
    1595           0 : static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
    1596             : {
    1597           0 :     HTTPContext *s = h->priv_data;
    1598           0 :     URLContext *old_hd = s->hd;
    1599           0 :     uint64_t old_off = s->off;
    1600             :     uint8_t old_buf[BUFFER_SIZE];
    1601             :     int old_buf_size, ret;
    1602           0 :     AVDictionary *options = NULL;
    1603             : 
    1604           0 :     if (whence == AVSEEK_SIZE)
    1605           0 :         return s->filesize;
    1606           0 :     else if (!force_reconnect &&
    1607           0 :              ((whence == SEEK_CUR && off == 0) ||
    1608           0 :               (whence == SEEK_SET && off == s->off)))
    1609           0 :         return s->off;
    1610           0 :     else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
    1611           0 :         return AVERROR(ENOSYS);
    1612             : 
    1613           0 :     if (whence == SEEK_CUR)
    1614           0 :         off += s->off;
    1615           0 :     else if (whence == SEEK_END)
    1616           0 :         off += s->filesize;
    1617           0 :     else if (whence != SEEK_SET)
    1618           0 :         return AVERROR(EINVAL);
    1619           0 :     if (off < 0)
    1620           0 :         return AVERROR(EINVAL);
    1621           0 :     s->off = off;
    1622             : 
    1623           0 :     if (s->off && h->is_streamed)
    1624           0 :         return AVERROR(ENOSYS);
    1625             : 
    1626             :     /* we save the old context in case the seek fails */
    1627           0 :     old_buf_size = s->buf_end - s->buf_ptr;
    1628           0 :     memcpy(old_buf, s->buf_ptr, old_buf_size);
    1629           0 :     s->hd = NULL;
    1630             : 
    1631             :     /* if it fails, continue on old connection */
    1632           0 :     if ((ret = http_open_cnx(h, &options)) < 0) {
    1633           0 :         av_dict_free(&options);
    1634           0 :         memcpy(s->buffer, old_buf, old_buf_size);
    1635           0 :         s->buf_ptr = s->buffer;
    1636           0 :         s->buf_end = s->buffer + old_buf_size;
    1637           0 :         s->hd      = old_hd;
    1638           0 :         s->off     = old_off;
    1639           0 :         return ret;
    1640             :     }
    1641           0 :     av_dict_free(&options);
    1642           0 :     ffurl_close(old_hd);
    1643           0 :     return off;
    1644             : }
    1645             : 
    1646           0 : static int64_t http_seek(URLContext *h, int64_t off, int whence)
    1647             : {
    1648           0 :     return http_seek_internal(h, off, whence, 0);
    1649             : }
    1650             : 
    1651           0 : static int http_get_file_handle(URLContext *h)
    1652             : {
    1653           0 :     HTTPContext *s = h->priv_data;
    1654           0 :     return ffurl_get_file_handle(s->hd);
    1655             : }
    1656             : 
    1657           0 : static int http_get_short_seek(URLContext *h)
    1658             : {
    1659           0 :     HTTPContext *s = h->priv_data;
    1660           0 :     return ffurl_get_short_seek(s->hd);
    1661             : }
    1662             : 
    1663             : #define HTTP_CLASS(flavor)                          \
    1664             : static const AVClass flavor ## _context_class = {   \
    1665             :     .class_name = # flavor,                         \
    1666             :     .item_name  = av_default_item_name,             \
    1667             :     .option     = options,                          \
    1668             :     .version    = LIBAVUTIL_VERSION_INT,            \
    1669             : }
    1670             : 
    1671             : #if CONFIG_HTTP_PROTOCOL
    1672             : HTTP_CLASS(http);
    1673             : 
    1674             : const URLProtocol ff_http_protocol = {
    1675             :     .name                = "http",
    1676             :     .url_open2           = http_open,
    1677             :     .url_accept          = http_accept,
    1678             :     .url_handshake       = http_handshake,
    1679             :     .url_read            = http_read,
    1680             :     .url_write           = http_write,
    1681             :     .url_seek            = http_seek,
    1682             :     .url_close           = http_close,
    1683             :     .url_get_file_handle = http_get_file_handle,
    1684             :     .url_get_short_seek  = http_get_short_seek,
    1685             :     .url_shutdown        = http_shutdown,
    1686             :     .priv_data_size      = sizeof(HTTPContext),
    1687             :     .priv_data_class     = &http_context_class,
    1688             :     .flags               = URL_PROTOCOL_FLAG_NETWORK,
    1689             :     .default_whitelist   = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
    1690             : };
    1691             : #endif /* CONFIG_HTTP_PROTOCOL */
    1692             : 
    1693             : #if CONFIG_HTTPS_PROTOCOL
    1694             : HTTP_CLASS(https);
    1695             : 
    1696             : const URLProtocol ff_https_protocol = {
    1697             :     .name                = "https",
    1698             :     .url_open2           = http_open,
    1699             :     .url_read            = http_read,
    1700             :     .url_write           = http_write,
    1701             :     .url_seek            = http_seek,
    1702             :     .url_close           = http_close,
    1703             :     .url_get_file_handle = http_get_file_handle,
    1704             :     .url_get_short_seek  = http_get_short_seek,
    1705             :     .url_shutdown        = http_shutdown,
    1706             :     .priv_data_size      = sizeof(HTTPContext),
    1707             :     .priv_data_class     = &https_context_class,
    1708             :     .flags               = URL_PROTOCOL_FLAG_NETWORK,
    1709             :     .default_whitelist   = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
    1710             : };
    1711             : #endif /* CONFIG_HTTPS_PROTOCOL */
    1712             : 
    1713             : #if CONFIG_HTTPPROXY_PROTOCOL
    1714           0 : static int http_proxy_close(URLContext *h)
    1715             : {
    1716           0 :     HTTPContext *s = h->priv_data;
    1717           0 :     if (s->hd)
    1718           0 :         ffurl_closep(&s->hd);
    1719           0 :     return 0;
    1720             : }
    1721             : 
    1722           0 : static int http_proxy_open(URLContext *h, const char *uri, int flags)
    1723             : {
    1724           0 :     HTTPContext *s = h->priv_data;
    1725             :     char hostname[1024], hoststr[1024];
    1726             :     char auth[1024], pathbuf[1024], *path;
    1727             :     char lower_url[100];
    1728           0 :     int port, ret = 0, attempts = 0;
    1729             :     HTTPAuthType cur_auth_type;
    1730             :     char *authstr;
    1731             :     int new_loc;
    1732             : 
    1733           0 :     if( s->seekable == 1 )
    1734           0 :         h->is_streamed = 0;
    1735             :     else
    1736           0 :         h->is_streamed = 1;
    1737             : 
    1738           0 :     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
    1739             :                  pathbuf, sizeof(pathbuf), uri);
    1740           0 :     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
    1741           0 :     path = pathbuf;
    1742           0 :     if (*path == '/')
    1743           0 :         path++;
    1744             : 
    1745           0 :     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
    1746             :                 NULL);
    1747           0 : redo:
    1748           0 :     ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
    1749           0 :                                &h->interrupt_callback, NULL,
    1750             :                                h->protocol_whitelist, h->protocol_blacklist, h);
    1751           0 :     if (ret < 0)
    1752           0 :         return ret;
    1753             : 
    1754           0 :     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
    1755             :                                            path, "CONNECT");
    1756           0 :     snprintf(s->buffer, sizeof(s->buffer),
    1757             :              "CONNECT %s HTTP/1.1\r\n"
    1758             :              "Host: %s\r\n"
    1759             :              "Connection: close\r\n"
    1760             :              "%s%s"
    1761             :              "\r\n",
    1762             :              path,
    1763             :              hoststr,
    1764           0 :              authstr ? "Proxy-" : "", authstr ? authstr : "");
    1765           0 :     av_freep(&authstr);
    1766             : 
    1767           0 :     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
    1768           0 :         goto fail;
    1769             : 
    1770           0 :     s->buf_ptr    = s->buffer;
    1771           0 :     s->buf_end    = s->buffer;
    1772           0 :     s->line_count = 0;
    1773           0 :     s->filesize   = UINT64_MAX;
    1774           0 :     cur_auth_type = s->proxy_auth_state.auth_type;
    1775             : 
    1776             :     /* Note: This uses buffering, potentially reading more than the
    1777             :      * HTTP header. If tunneling a protocol where the server starts
    1778             :      * the conversation, we might buffer part of that here, too.
    1779             :      * Reading that requires using the proper ffurl_read() function
    1780             :      * on this URLContext, not using the fd directly (as the tls
    1781             :      * protocol does). This shouldn't be an issue for tls though,
    1782             :      * since the client starts the conversation there, so there
    1783             :      * is no extra data that we might buffer up here.
    1784             :      */
    1785           0 :     ret = http_read_header(h, &new_loc);
    1786           0 :     if (ret < 0)
    1787           0 :         goto fail;
    1788             : 
    1789           0 :     attempts++;
    1790           0 :     if (s->http_code == 407 &&
    1791           0 :         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
    1792           0 :         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
    1793           0 :         ffurl_closep(&s->hd);
    1794           0 :         goto redo;
    1795             :     }
    1796             : 
    1797           0 :     if (s->http_code < 400)
    1798           0 :         return 0;
    1799           0 :     ret = ff_http_averror(s->http_code, AVERROR(EIO));
    1800             : 
    1801           0 : fail:
    1802           0 :     http_proxy_close(h);
    1803           0 :     return ret;
    1804             : }
    1805             : 
    1806           0 : static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
    1807             : {
    1808           0 :     HTTPContext *s = h->priv_data;
    1809           0 :     return ffurl_write(s->hd, buf, size);
    1810             : }
    1811             : 
    1812             : const URLProtocol ff_httpproxy_protocol = {
    1813             :     .name                = "httpproxy",
    1814             :     .url_open            = http_proxy_open,
    1815             :     .url_read            = http_buf_read,
    1816             :     .url_write           = http_proxy_write,
    1817             :     .url_close           = http_proxy_close,
    1818             :     .url_get_file_handle = http_get_file_handle,
    1819             :     .priv_data_size      = sizeof(HTTPContext),
    1820             :     .flags               = URL_PROTOCOL_FLAG_NETWORK,
    1821             : };
    1822             : #endif /* CONFIG_HTTPPROXY_PROTOCOL */

Generated by: LCOV version 1.13