]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
Merge commit 'a8c104a511f97e4ea617df73b31737e28a8a5126'
[ffmpeg] / libavformat / http.c
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/avstring.h"
29 #include "libavutil/opt.h"
30
31 #include "avformat.h"
32 #include "http.h"
33 #include "httpauth.h"
34 #include "internal.h"
35 #include "network.h"
36 #include "os_support.h"
37 #include "url.h"
38
39 /* XXX: POST protocol is not completely implemented because ffmpeg uses
40  * only a subset of it. */
41
42 /* The IO buffer size is unrelated to the max URL size in itself, but needs
43  * to be large enough to fit the full request headers (including long
44  * path names). */
45 #define BUFFER_SIZE   MAX_URL_SIZE
46 #define MAX_REDIRECTS 8
47
48 typedef struct {
49     const AVClass *class;
50     URLContext *hd;
51     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
52     int line_count;
53     int http_code;
54     /* Used if "Transfer-Encoding: chunked" otherwise -1. */
55     int64_t chunksize;
56     int64_t off, end_off, filesize;
57     char *location;
58     HTTPAuthState auth_state;
59     HTTPAuthState proxy_auth_state;
60     char *headers;
61     char *mime_type;
62     char *user_agent;
63     char *content_type;
64     /* Set if the server correctly handles Connection: close and will close
65      * the connection after feeding us the content. */
66     int willclose;
67     int seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
68     int chunked_post;
69     /* A flag which indicates if the end of chunked encoding has been sent. */
70     int end_chunked_post;
71     /* A flag which indicates we have finished to read POST reply. */
72     int end_header;
73     /* A flag which indicates if we use persistent connections. */
74     int multiple_requests;
75     uint8_t *post_data;
76     int post_datalen;
77     int is_akamai;
78     int is_mediagateway;
79     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
80     int icy;
81     /* how much data was read since the last ICY metadata packet */
82     int icy_data_read;
83     /* after how many bytes of read data a new metadata packet will be found */
84     int icy_metaint;
85     char *icy_metadata_headers;
86     char *icy_metadata_packet;
87 #if CONFIG_ZLIB
88     int compressed;
89     z_stream inflate_stream;
90     uint8_t *inflate_buffer;
91 #endif /* CONFIG_ZLIB */
92     AVDictionary *chained_options;
93     int send_expect_100;
94     char *method;
95 } HTTPContext;
96
97 #define OFFSET(x) offsetof(HTTPContext, x)
98 #define D AV_OPT_FLAG_DECODING_PARAM
99 #define E AV_OPT_FLAG_ENCODING_PARAM
100 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
101
102 static const AVOption options[] = {
103     { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
104     { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
105     { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
106     { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
107     { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
108     { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
109     { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
110     { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
111     { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
112     { "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, { 0 }, 0, 0, D },
113     { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
114     { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
115     { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
116     { "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"},
117     { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
118     { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
119     { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
120     { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
121     { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
122     { "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 },
123     { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
124     { NULL }
125 };
126
127 static int http_connect(URLContext *h, const char *path, const char *local_path,
128                         const char *hoststr, const char *auth,
129                         const char *proxyauth, int *new_location);
130
131 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
132 {
133     memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
134            &((HTTPContext *)src->priv_data)->auth_state,
135            sizeof(HTTPAuthState));
136     memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
137            &((HTTPContext *)src->priv_data)->proxy_auth_state,
138            sizeof(HTTPAuthState));
139 }
140
141 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
142 {
143     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
144     char hostname[1024], hoststr[1024], proto[10];
145     char auth[1024], proxyauth[1024] = "";
146     char path1[MAX_URL_SIZE];
147     char buf[1024], urlbuf[MAX_URL_SIZE];
148     int port, use_proxy, err, location_changed = 0;
149     HTTPContext *s = h->priv_data;
150
151     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
152                  hostname, sizeof(hostname), &port,
153                  path1, sizeof(path1), s->location);
154     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
155
156     proxy_path = getenv("http_proxy");
157     use_proxy  = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
158                  proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
159
160     if (!strcmp(proto, "https")) {
161         lower_proto = "tls";
162         use_proxy   = 0;
163         if (port < 0)
164             port = 443;
165     }
166     if (port < 0)
167         port = 80;
168
169     if (path1[0] == '\0')
170         path = "/";
171     else
172         path = path1;
173     local_path = path;
174     if (use_proxy) {
175         /* Reassemble the request URL without auth string - we don't
176          * want to leak the auth to the proxy. */
177         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
178                     path1);
179         path = urlbuf;
180         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
181                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
182     }
183
184     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
185
186     if (!s->hd) {
187         err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
188                          &h->interrupt_callback, options);
189         if (err < 0)
190             return err;
191     }
192
193     err = http_connect(h, path, local_path, hoststr,
194                        auth, proxyauth, &location_changed);
195     if (err < 0)
196         return err;
197
198     return location_changed;
199 }
200
201 /* return non zero if error */
202 static int http_open_cnx(URLContext *h, AVDictionary **options)
203 {
204     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
205     HTTPContext *s = h->priv_data;
206     int location_changed, attempts = 0, redirects = 0;
207 redo:
208     location_changed = http_open_cnx_internal(h, options);
209     if (location_changed < 0)
210         goto fail;
211
212     attempts++;
213     cur_auth_type       = s->auth_state.auth_type;
214     cur_proxy_auth_type = s->auth_state.auth_type;
215
216     if (s->http_code == 401) {
217         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
218             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
219             ffurl_closep(&s->hd);
220             goto redo;
221         } else
222             goto fail;
223     }
224     if (s->http_code == 407) {
225         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
226             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
227             ffurl_closep(&s->hd);
228             goto redo;
229         } else
230             goto fail;
231     }
232     if ((s->http_code == 301 || s->http_code == 302 ||
233          s->http_code == 303 || s->http_code == 307) &&
234         location_changed == 1) {
235         /* url moved, get next */
236         ffurl_closep(&s->hd);
237         if (redirects++ >= MAX_REDIRECTS)
238             return AVERROR(EIO);
239         /* Restart the authentication process with the new target, which
240          * might use a different auth mechanism. */
241         memset(&s->auth_state, 0, sizeof(s->auth_state));
242         attempts         = 0;
243         location_changed = 0;
244         goto redo;
245     }
246     return 0;
247
248 fail:
249     if (s->hd)
250         ffurl_closep(&s->hd);
251     return AVERROR(EIO);
252 }
253
254 int ff_http_do_new_request(URLContext *h, const char *uri)
255 {
256     HTTPContext *s = h->priv_data;
257     AVDictionary *options = NULL;
258     int ret;
259
260     s->off           = 0;
261     s->icy_data_read = 0;
262     av_free(s->location);
263     s->location = av_strdup(uri);
264     if (!s->location)
265         return AVERROR(ENOMEM);
266
267     av_dict_copy(&options, s->chained_options, 0);
268     ret = http_open_cnx(h, &options);
269     av_dict_free(&options);
270     return ret;
271 }
272
273 static int http_open(URLContext *h, const char *uri, int flags,
274                      AVDictionary **options)
275 {
276     HTTPContext *s = h->priv_data;
277     int ret;
278
279     if( s->seekable == 1 )
280         h->is_streamed = 0;
281     else
282         h->is_streamed = 1;
283
284     s->filesize = -1;
285     s->location = av_strdup(uri);
286     if (!s->location)
287         return AVERROR(ENOMEM);
288     if (options)
289         av_dict_copy(&s->chained_options, *options, 0);
290
291     if (s->headers) {
292         int len = strlen(s->headers);
293         if (len < 2 || strcmp("\r\n", s->headers + len - 2))
294             av_log(h, AV_LOG_WARNING,
295                    "No trailing CRLF found in HTTP header.\n");
296     }
297
298     ret = http_open_cnx(h, options);
299     if (ret < 0)
300         av_dict_free(&s->chained_options);
301     return ret;
302 }
303
304 static int http_getc(HTTPContext *s)
305 {
306     int len;
307     if (s->buf_ptr >= s->buf_end) {
308         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
309         if (len < 0) {
310             return len;
311         } else if (len == 0) {
312             return AVERROR_EOF;
313         } else {
314             s->buf_ptr = s->buffer;
315             s->buf_end = s->buffer + len;
316         }
317     }
318     return *s->buf_ptr++;
319 }
320
321 static int http_get_line(HTTPContext *s, char *line, int line_size)
322 {
323     int ch;
324     char *q;
325
326     q = line;
327     for (;;) {
328         ch = http_getc(s);
329         if (ch < 0)
330             return ch;
331         if (ch == '\n') {
332             /* process line */
333             if (q > line && q[-1] == '\r')
334                 q--;
335             *q = '\0';
336
337             return 0;
338         } else {
339             if ((q - line) < line_size - 1)
340                 *q++ = ch;
341         }
342     }
343 }
344
345 static int check_http_code(URLContext *h, int http_code, const char *end)
346 {
347     HTTPContext *s = h->priv_data;
348     /* error codes are 4xx and 5xx, but regard 401 as a success, so we
349      * don't abort until all headers have been parsed. */
350     if (http_code >= 400 && http_code < 600 &&
351         (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
352         (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
353         end += strspn(end, SPACE_CHARS);
354         av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
355         return AVERROR(EIO);
356     }
357     return 0;
358 }
359
360 static int parse_location(HTTPContext *s, const char *p)
361 {
362     char redirected_location[MAX_URL_SIZE], *new_loc;
363     ff_make_absolute_url(redirected_location, sizeof(redirected_location),
364                          s->location, p);
365     new_loc = av_strdup(redirected_location);
366     if (!new_loc)
367         return AVERROR(ENOMEM);
368     av_free(s->location);
369     s->location = new_loc;
370     return 0;
371 }
372
373 /* "bytes $from-$to/$document_size" */
374 static void parse_content_range(URLContext *h, const char *p)
375 {
376     HTTPContext *s = h->priv_data;
377     const char *slash;
378
379     if (!strncmp(p, "bytes ", 6)) {
380         p     += 6;
381         s->off = strtoll(p, NULL, 10);
382         if ((slash = strchr(p, '/')) && strlen(slash) > 0)
383             s->filesize = strtoll(slash + 1, NULL, 10);
384     }
385     if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
386         h->is_streamed = 0; /* we _can_ in fact seek */
387 }
388
389 static int parse_content_encoding(URLContext *h, const char *p)
390 {
391     HTTPContext *s = h->priv_data;
392
393     if (!av_strncasecmp(p, "gzip", 4) ||
394         !av_strncasecmp(p, "deflate", 7)) {
395 #if CONFIG_ZLIB
396         s->compressed = 1;
397         inflateEnd(&s->inflate_stream);
398         if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
399             av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
400                    s->inflate_stream.msg);
401             return AVERROR(ENOSYS);
402         }
403         if (zlibCompileFlags() & (1 << 17)) {
404             av_log(h, AV_LOG_WARNING,
405                    "Your zlib was compiled without gzip support.\n");
406             return AVERROR(ENOSYS);
407         }
408 #else
409         av_log(h, AV_LOG_WARNING,
410                "Compressed (%s) content, need zlib with gzip support\n", p);
411         return AVERROR(ENOSYS);
412 #endif /* CONFIG_ZLIB */
413     } else if (!av_strncasecmp(p, "identity", 8)) {
414         // The normal, no-encoding case (although servers shouldn't include
415         // the header at all if this is the case).
416     } else {
417         av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
418     }
419     return 0;
420 }
421
422 // Concat all Icy- header lines
423 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
424 {
425     int len = 4 + strlen(p) + strlen(tag);
426     int is_first = !s->icy_metadata_headers;
427     int ret;
428
429     if (s->icy_metadata_headers)
430         len += strlen(s->icy_metadata_headers);
431
432     if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
433         return ret;
434
435     if (is_first)
436         *s->icy_metadata_headers = '\0';
437
438     av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
439
440     return 0;
441 }
442
443 static int process_line(URLContext *h, char *line, int line_count,
444                         int *new_location)
445 {
446     HTTPContext *s = h->priv_data;
447     char *tag, *p, *end;
448     int ret;
449
450     /* end of header */
451     if (line[0] == '\0') {
452         s->end_header = 1;
453         return 0;
454     }
455
456     p = line;
457     if (line_count == 0) {
458         while (!av_isspace(*p) && *p != '\0')
459             p++;
460         while (av_isspace(*p))
461             p++;
462         s->http_code = strtol(p, &end, 10);
463
464         av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
465
466         if ((ret = check_http_code(h, s->http_code, end)) < 0)
467             return ret;
468     } else {
469         while (*p != '\0' && *p != ':')
470             p++;
471         if (*p != ':')
472             return 1;
473
474         *p  = '\0';
475         tag = line;
476         p++;
477         while (av_isspace(*p))
478             p++;
479         if (!av_strcasecmp(tag, "Location")) {
480             if ((ret = parse_location(s, p)) < 0)
481                 return ret;
482             *new_location = 1;
483         } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
484             s->filesize = strtoll(p, NULL, 10);
485         } else if (!av_strcasecmp(tag, "Content-Range")) {
486             parse_content_range(h, p);
487         } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
488                    !strncmp(p, "bytes", 5) &&
489                    s->seekable == -1) {
490             h->is_streamed = 0;
491         } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
492                    !av_strncasecmp(p, "chunked", 7)) {
493             s->filesize  = -1;
494             s->chunksize = 0;
495         } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
496             ff_http_auth_handle_header(&s->auth_state, tag, p);
497         } else if (!av_strcasecmp(tag, "Authentication-Info")) {
498             ff_http_auth_handle_header(&s->auth_state, tag, p);
499         } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
500             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
501         } else if (!av_strcasecmp(tag, "Connection")) {
502             if (!strcmp(p, "close"))
503                 s->willclose = 1;
504         } else if (!av_strcasecmp(tag, "Server")) {
505             if (!av_strcasecmp(p, "AkamaiGHost")) {
506                 s->is_akamai = 1;
507             } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
508                 s->is_mediagateway = 1;
509             }
510         } else if (!av_strcasecmp(tag, "Content-Type")) {
511             av_free(s->mime_type);
512             s->mime_type = av_strdup(p);
513         } else if (!av_strcasecmp(tag, "Set-Cookie")) {
514             if (!s->cookies) {
515                 if (!(s->cookies = av_strdup(p)))
516                     return AVERROR(ENOMEM);
517             } else {
518                 char *tmp = s->cookies;
519                 size_t str_size = strlen(tmp) + strlen(p) + 2;
520                 if (!(s->cookies = av_malloc(str_size))) {
521                     s->cookies = tmp;
522                     return AVERROR(ENOMEM);
523                 }
524                 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
525                 av_free(tmp);
526             }
527         } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
528             s->icy_metaint = strtoll(p, NULL, 10);
529         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
530             if ((ret = parse_icy(s, tag, p)) < 0)
531                 return ret;
532         } else if (!av_strcasecmp(tag, "Content-Encoding")) {
533             if ((ret = parse_content_encoding(h, p)) < 0)
534                 return ret;
535         }
536     }
537     return 1;
538 }
539
540 /**
541  * Create a string containing cookie values for use as a HTTP cookie header
542  * field value for a particular path and domain from the cookie values stored in
543  * the HTTP protocol context. The cookie string is stored in *cookies.
544  *
545  * @return a negative value if an error condition occurred, 0 otherwise
546  */
547 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
548                        const char *domain)
549 {
550     // cookie strings will look like Set-Cookie header field values.  Multiple
551     // Set-Cookie fields will result in multiple values delimited by a newline
552     int ret = 0;
553     char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
554
555     if (!set_cookies) return AVERROR(EINVAL);
556
557     *cookies = NULL;
558     while ((cookie = av_strtok(set_cookies, "\n", &next))) {
559         int domain_offset = 0;
560         char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
561         set_cookies = NULL;
562
563         while ((param = av_strtok(cookie, "; ", &next_param))) {
564             cookie = NULL;
565             if        (!av_strncasecmp("path=",   param, 5)) {
566                 av_free(cpath);
567                 cpath = av_strdup(&param[5]);
568             } else if (!av_strncasecmp("domain=", param, 7)) {
569                 // if the cookie specifies a sub-domain, skip the leading dot thereby
570                 // supporting URLs that point to sub-domains and the master domain
571                 int leading_dot = (param[7] == '.');
572                 av_free(cdomain);
573                 cdomain = av_strdup(&param[7+leading_dot]);
574             } else if (!av_strncasecmp("secure",  param, 6) ||
575                        !av_strncasecmp("comment", param, 7) ||
576                        !av_strncasecmp("max-age", param, 7) ||
577                        !av_strncasecmp("version", param, 7)) {
578                 // ignore Comment, Max-Age, Secure and Version
579             } else {
580                 av_free(cvalue);
581                 cvalue = av_strdup(param);
582             }
583         }
584         if (!cdomain)
585             cdomain = av_strdup(domain);
586
587         // ensure all of the necessary values are valid
588         if (!cdomain || !cpath || !cvalue) {
589             av_log(s, AV_LOG_WARNING,
590                    "Invalid cookie found, no value, path or domain specified\n");
591             goto done_cookie;
592         }
593
594         // check if the request path matches the cookie path
595         if (av_strncasecmp(path, cpath, strlen(cpath)))
596             goto done_cookie;
597
598         // the domain should be at least the size of our cookie domain
599         domain_offset = strlen(domain) - strlen(cdomain);
600         if (domain_offset < 0)
601             goto done_cookie;
602
603         // match the cookie domain
604         if (av_strcasecmp(&domain[domain_offset], cdomain))
605             goto done_cookie;
606
607         // cookie parameters match, so copy the value
608         if (!*cookies) {
609             if (!(*cookies = av_strdup(cvalue))) {
610                 ret = AVERROR(ENOMEM);
611                 goto done_cookie;
612             }
613         } else {
614             char *tmp = *cookies;
615             size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
616             if (!(*cookies = av_malloc(str_size))) {
617                 ret = AVERROR(ENOMEM);
618                 goto done_cookie;
619             }
620             snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
621             av_free(tmp);
622         }
623
624         done_cookie:
625         av_free(cdomain);
626         av_free(cpath);
627         av_free(cvalue);
628         if (ret < 0) {
629             if (*cookies) av_freep(cookies);
630             av_free(cset_cookies);
631             return ret;
632         }
633     }
634
635     av_free(cset_cookies);
636
637     return 0;
638 }
639
640 static inline int has_header(const char *str, const char *header)
641 {
642     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
643     if (!str)
644         return 0;
645     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
646 }
647
648 static int http_read_header(URLContext *h, int *new_location)
649 {
650     HTTPContext *s = h->priv_data;
651     char line[MAX_URL_SIZE];
652     int err = 0;
653
654     s->chunksize = -1;
655
656     for (;;) {
657         if ((err = http_get_line(s, line, sizeof(line))) < 0)
658             return err;
659
660         av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
661
662         err = process_line(h, line, s->line_count, new_location);
663         if (err < 0)
664             return err;
665         if (err == 0)
666             break;
667         s->line_count++;
668     }
669
670     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
671         h->is_streamed = 1; /* we can in fact _not_ seek */
672
673     return err;
674 }
675
676 static int http_connect(URLContext *h, const char *path, const char *local_path,
677                         const char *hoststr, const char *auth,
678                         const char *proxyauth, int *new_location)
679 {
680     HTTPContext *s = h->priv_data;
681     int post, err;
682     char headers[HTTP_HEADERS_SIZE] = "";
683     char *authstr = NULL, *proxyauthstr = NULL;
684     int64_t off = s->off;
685     int len = 0;
686     const char *method;
687     int send_expect_100 = 0;
688
689     /* send http header */
690     post = h->flags & AVIO_FLAG_WRITE;
691
692     if (s->post_data) {
693         /* force POST method and disable chunked encoding when
694          * custom HTTP post data is set */
695         post            = 1;
696         s->chunked_post = 0;
697     }
698
699     if (s->method)
700         method = s->method;
701     else
702         method = post ? "POST" : "GET";
703
704     authstr      = ff_http_auth_create_response(&s->auth_state, auth,
705                                                 local_path, method);
706     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
707                                                 local_path, method);
708     if (post && !s->post_data) {
709         send_expect_100 = s->send_expect_100;
710         /* The user has supplied authentication but we don't know the auth type,
711          * send Expect: 100-continue to get the 401 response including the
712          * WWW-Authenticate header, or an 100 continue if no auth actually
713          * is needed. */
714         if (auth && *auth &&
715             s->auth_state.auth_type == HTTP_AUTH_NONE &&
716             s->http_code != 401)
717             send_expect_100 = 1;
718     }
719
720     /* set default headers if needed */
721     if (!has_header(s->headers, "\r\nUser-Agent: "))
722         len += av_strlcatf(headers + len, sizeof(headers) - len,
723                            "User-Agent: %s\r\n", s->user_agent);
724     if (!has_header(s->headers, "\r\nAccept: "))
725         len += av_strlcpy(headers + len, "Accept: */*\r\n",
726                           sizeof(headers) - len);
727     // Note: we send this on purpose even when s->off is 0 when we're probing,
728     // since it allows us to detect more reliably if a (non-conforming)
729     // server supports seeking by analysing the reply headers.
730     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
731         len += av_strlcatf(headers + len, sizeof(headers) - len,
732                            "Range: bytes=%"PRId64"-", s->off);
733         if (s->end_off)
734             len += av_strlcatf(headers + len, sizeof(headers) - len,
735                                "%"PRId64, s->end_off - 1);
736         len += av_strlcpy(headers + len, "\r\n",
737                           sizeof(headers) - len);
738     }
739     if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
740         len += av_strlcatf(headers + len, sizeof(headers) - len,
741                            "Expect: 100-continue\r\n");
742
743     if (!has_header(s->headers, "\r\nConnection: ")) {
744         if (s->multiple_requests)
745             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
746                               sizeof(headers) - len);
747         else
748             len += av_strlcpy(headers + len, "Connection: close\r\n",
749                               sizeof(headers) - len);
750     }
751
752     if (!has_header(s->headers, "\r\nHost: "))
753         len += av_strlcatf(headers + len, sizeof(headers) - len,
754                            "Host: %s\r\n", hoststr);
755     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
756         len += av_strlcatf(headers + len, sizeof(headers) - len,
757                            "Content-Length: %d\r\n", s->post_datalen);
758
759     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
760         len += av_strlcatf(headers + len, sizeof(headers) - len,
761                            "Content-Type: %s\r\n", s->content_type);
762     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
763         char *cookies = NULL;
764         if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
765             len += av_strlcatf(headers + len, sizeof(headers) - len,
766                                "Cookie: %s\r\n", cookies);
767             av_free(cookies);
768         }
769     }
770     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
771         len += av_strlcatf(headers + len, sizeof(headers) - len,
772                            "Icy-MetaData: %d\r\n", 1);
773
774     /* now add in custom headers */
775     if (s->headers)
776         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
777
778     snprintf(s->buffer, sizeof(s->buffer),
779              "%s %s HTTP/1.1\r\n"
780              "%s"
781              "%s"
782              "%s"
783              "%s%s"
784              "\r\n",
785              method,
786              path,
787              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
788              headers,
789              authstr ? authstr : "",
790              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
791
792     av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
793
794     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
795         goto done;
796
797     if (s->post_data)
798         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
799             goto done;
800
801     /* init input buffer */
802     s->buf_ptr          = s->buffer;
803     s->buf_end          = s->buffer;
804     s->line_count       = 0;
805     s->off              = 0;
806     s->icy_data_read    = 0;
807     s->filesize         = -1;
808     s->willclose        = 0;
809     s->end_chunked_post = 0;
810     s->end_header       = 0;
811     if (post && !s->post_data && !send_expect_100) {
812         /* Pretend that it did work. We didn't read any header yet, since
813          * we've still to send the POST data, but the code calling this
814          * function will check http_code after we return. */
815         s->http_code = 200;
816         err = 0;
817         goto done;
818     }
819
820     /* wait for header */
821     err = http_read_header(h, new_location);
822     if (err < 0)
823         goto done;
824
825     err = (off == s->off) ? 0 : -1;
826 done:
827     av_freep(&authstr);
828     av_freep(&proxyauthstr);
829     return err;
830 }
831
832 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
833 {
834     HTTPContext *s = h->priv_data;
835     int len;
836     /* read bytes from input buffer first */
837     len = s->buf_end - s->buf_ptr;
838     if (len > 0) {
839         if (len > size)
840             len = size;
841         memcpy(buf, s->buf_ptr, len);
842         s->buf_ptr += len;
843     } else {
844         if ((!s->willclose || s->chunksize < 0) &&
845             s->filesize >= 0 && s->off >= s->filesize)
846             return AVERROR_EOF;
847         len = ffurl_read(s->hd, buf, size);
848     }
849     if (len > 0) {
850         s->off += len;
851         if (s->chunksize > 0)
852             s->chunksize -= len;
853     }
854     return len;
855 }
856
857 #if CONFIG_ZLIB
858 #define DECOMPRESS_BUF_SIZE (256 * 1024)
859 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
860 {
861     HTTPContext *s = h->priv_data;
862     int ret;
863
864     if (!s->inflate_buffer) {
865         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
866         if (!s->inflate_buffer)
867             return AVERROR(ENOMEM);
868     }
869
870     if (s->inflate_stream.avail_in == 0) {
871         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
872         if (read <= 0)
873             return read;
874         s->inflate_stream.next_in  = s->inflate_buffer;
875         s->inflate_stream.avail_in = read;
876     }
877
878     s->inflate_stream.avail_out = size;
879     s->inflate_stream.next_out  = buf;
880
881     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
882     if (ret != Z_OK && ret != Z_STREAM_END)
883         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
884                ret, s->inflate_stream.msg);
885
886     return size - s->inflate_stream.avail_out;
887 }
888 #endif /* CONFIG_ZLIB */
889
890 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
891 {
892     HTTPContext *s = h->priv_data;
893     int err, new_location;
894
895     if (!s->hd)
896         return AVERROR_EOF;
897
898     if (s->end_chunked_post && !s->end_header) {
899         err = http_read_header(h, &new_location);
900         if (err < 0)
901             return err;
902     }
903
904     if (s->chunksize >= 0) {
905         if (!s->chunksize) {
906             char line[32];
907
908                 do {
909                     if ((err = http_get_line(s, line, sizeof(line))) < 0)
910                         return err;
911                 } while (!*line);    /* skip CR LF from last chunk */
912
913                 s->chunksize = strtoll(line, NULL, 16);
914
915                 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
916                         s->chunksize);
917
918                 if (!s->chunksize)
919                     return 0;
920         }
921         size = FFMIN(size, s->chunksize);
922     }
923 #if CONFIG_ZLIB
924     if (s->compressed)
925         return http_buf_read_compressed(h, buf, size);
926 #endif /* CONFIG_ZLIB */
927     return http_buf_read(h, buf, size);
928 }
929
930 // Like http_read_stream(), but no short reads.
931 // Assumes partial reads are an error.
932 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
933 {
934     int pos = 0;
935     while (pos < size) {
936         int len = http_read_stream(h, buf + pos, size - pos);
937         if (len < 0)
938             return len;
939         pos += len;
940     }
941     return pos;
942 }
943
944 static int store_icy(URLContext *h, int size)
945 {
946     HTTPContext *s = h->priv_data;
947     /* until next metadata packet */
948     int remaining = s->icy_metaint - s->icy_data_read;
949
950     if (remaining < 0)
951         return AVERROR_INVALIDDATA;
952
953     if (!remaining) {
954         /* The metadata packet is variable sized. It has a 1 byte header
955          * which sets the length of the packet (divided by 16). If it's 0,
956          * the metadata doesn't change. After the packet, icy_metaint bytes
957          * of normal data follows. */
958         uint8_t ch;
959         int len = http_read_stream_all(h, &ch, 1);
960         if (len < 0)
961             return len;
962         if (ch > 0) {
963             char data[255 * 16 + 1];
964             int ret;
965             len = ch * 16;
966             ret = http_read_stream_all(h, data, len);
967             if (ret < 0)
968                 return ret;
969             data[len + 1] = 0;
970             if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
971                 return ret;
972         }
973         s->icy_data_read = 0;
974         remaining        = s->icy_metaint;
975     }
976
977     return FFMIN(size, remaining);
978 }
979
980 static int http_read(URLContext *h, uint8_t *buf, int size)
981 {
982     HTTPContext *s = h->priv_data;
983
984     if (s->icy_metaint > 0) {
985         size = store_icy(h, size);
986         if (size < 0)
987             return size;
988     }
989
990     size = http_read_stream(h, buf, size);
991     if (size > 0)
992         s->icy_data_read += size;
993     return size;
994 }
995
996 /* used only when posting data */
997 static int http_write(URLContext *h, const uint8_t *buf, int size)
998 {
999     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
1000     int ret;
1001     char crlf[] = "\r\n";
1002     HTTPContext *s = h->priv_data;
1003
1004     if (!s->chunked_post) {
1005         /* non-chunked data is sent without any special encoding */
1006         return ffurl_write(s->hd, buf, size);
1007     }
1008
1009     /* silently ignore zero-size data since chunk encoding that would
1010      * signal EOF */
1011     if (size > 0) {
1012         /* upload data using chunked encoding */
1013         snprintf(temp, sizeof(temp), "%x\r\n", size);
1014
1015         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1016             (ret = ffurl_write(s->hd, buf, size)) < 0          ||
1017             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1018             return ret;
1019     }
1020     return size;
1021 }
1022
1023 static int http_shutdown(URLContext *h, int flags)
1024 {
1025     int ret = 0;
1026     char footer[] = "0\r\n\r\n";
1027     HTTPContext *s = h->priv_data;
1028
1029     /* signal end of chunked encoding if used */
1030     if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
1031         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1032         ret = ret > 0 ? 0 : ret;
1033         s->end_chunked_post = 1;
1034     }
1035
1036     return ret;
1037 }
1038
1039 static int http_close(URLContext *h)
1040 {
1041     int ret = 0;
1042     HTTPContext *s = h->priv_data;
1043
1044 #if CONFIG_ZLIB
1045     inflateEnd(&s->inflate_stream);
1046     av_freep(&s->inflate_buffer);
1047 #endif /* CONFIG_ZLIB */
1048
1049     if (!s->end_chunked_post)
1050         /* Close the write direction by sending the end of chunked encoding. */
1051         ret = http_shutdown(h, h->flags);
1052
1053     if (s->hd)
1054         ffurl_closep(&s->hd);
1055     av_dict_free(&s->chained_options);
1056     return ret;
1057 }
1058
1059 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1060 {
1061     HTTPContext *s = h->priv_data;
1062     URLContext *old_hd = s->hd;
1063     int64_t old_off = s->off;
1064     uint8_t old_buf[BUFFER_SIZE];
1065     int old_buf_size, ret;
1066     AVDictionary *options = NULL;
1067
1068     if (whence == AVSEEK_SIZE)
1069         return s->filesize;
1070     else if ((whence == SEEK_CUR && off == 0) ||
1071              (whence == SEEK_SET && off == s->off))
1072         return s->off;
1073     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1074         return AVERROR(ENOSYS);
1075
1076     if (whence == SEEK_CUR)
1077         off += s->off;
1078     else if (whence == SEEK_END)
1079         off += s->filesize;
1080     else if (whence != SEEK_SET)
1081         return AVERROR(EINVAL);
1082     if (off < 0)
1083         return AVERROR(EINVAL);
1084     s->off = off;
1085
1086     /* we save the old context in case the seek fails */
1087     old_buf_size = s->buf_end - s->buf_ptr;
1088     memcpy(old_buf, s->buf_ptr, old_buf_size);
1089     s->hd = NULL;
1090
1091     /* if it fails, continue on old connection */
1092     av_dict_copy(&options, s->chained_options, 0);
1093     if ((ret = http_open_cnx(h, &options)) < 0) {
1094         av_dict_free(&options);
1095         memcpy(s->buffer, old_buf, old_buf_size);
1096         s->buf_ptr = s->buffer;
1097         s->buf_end = s->buffer + old_buf_size;
1098         s->hd      = old_hd;
1099         s->off     = old_off;
1100         return ret;
1101     }
1102     av_dict_free(&options);
1103     ffurl_close(old_hd);
1104     return off;
1105 }
1106
1107 static int http_get_file_handle(URLContext *h)
1108 {
1109     HTTPContext *s = h->priv_data;
1110     return ffurl_get_file_handle(s->hd);
1111 }
1112
1113 #define HTTP_CLASS(flavor)                          \
1114 static const AVClass flavor ## _context_class = {   \
1115     .class_name = # flavor,                         \
1116     .item_name  = av_default_item_name,             \
1117     .option     = options,                          \
1118     .version    = LIBAVUTIL_VERSION_INT,            \
1119 }
1120
1121 #if CONFIG_HTTP_PROTOCOL
1122 HTTP_CLASS(http);
1123
1124 URLProtocol ff_http_protocol = {
1125     .name                = "http",
1126     .url_open2           = http_open,
1127     .url_read            = http_read,
1128     .url_write           = http_write,
1129     .url_seek            = http_seek,
1130     .url_close           = http_close,
1131     .url_get_file_handle = http_get_file_handle,
1132     .url_shutdown        = http_shutdown,
1133     .priv_data_size      = sizeof(HTTPContext),
1134     .priv_data_class     = &http_context_class,
1135     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1136 };
1137 #endif /* CONFIG_HTTP_PROTOCOL */
1138
1139 #if CONFIG_HTTPS_PROTOCOL
1140 HTTP_CLASS(https);
1141
1142 URLProtocol ff_https_protocol = {
1143     .name                = "https",
1144     .url_open2           = http_open,
1145     .url_read            = http_read,
1146     .url_write           = http_write,
1147     .url_seek            = http_seek,
1148     .url_close           = http_close,
1149     .url_get_file_handle = http_get_file_handle,
1150     .url_shutdown        = http_shutdown,
1151     .priv_data_size      = sizeof(HTTPContext),
1152     .priv_data_class     = &https_context_class,
1153     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1154 };
1155 #endif /* CONFIG_HTTPS_PROTOCOL */
1156
1157 #if CONFIG_HTTPPROXY_PROTOCOL
1158 static int http_proxy_close(URLContext *h)
1159 {
1160     HTTPContext *s = h->priv_data;
1161     if (s->hd)
1162         ffurl_closep(&s->hd);
1163     return 0;
1164 }
1165
1166 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1167 {
1168     HTTPContext *s = h->priv_data;
1169     char hostname[1024], hoststr[1024];
1170     char auth[1024], pathbuf[1024], *path;
1171     char lower_url[100];
1172     int port, ret = 0, attempts = 0;
1173     HTTPAuthType cur_auth_type;
1174     char *authstr;
1175     int new_loc;
1176
1177     if( s->seekable == 1 )
1178         h->is_streamed = 0;
1179     else
1180         h->is_streamed = 1;
1181
1182     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1183                  pathbuf, sizeof(pathbuf), uri);
1184     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1185     path = pathbuf;
1186     if (*path == '/')
1187         path++;
1188
1189     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1190                 NULL);
1191 redo:
1192     ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1193                      &h->interrupt_callback, NULL);
1194     if (ret < 0)
1195         return ret;
1196
1197     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1198                                            path, "CONNECT");
1199     snprintf(s->buffer, sizeof(s->buffer),
1200              "CONNECT %s HTTP/1.1\r\n"
1201              "Host: %s\r\n"
1202              "Connection: close\r\n"
1203              "%s%s"
1204              "\r\n",
1205              path,
1206              hoststr,
1207              authstr ? "Proxy-" : "", authstr ? authstr : "");
1208     av_freep(&authstr);
1209
1210     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1211         goto fail;
1212
1213     s->buf_ptr    = s->buffer;
1214     s->buf_end    = s->buffer;
1215     s->line_count = 0;
1216     s->filesize   = -1;
1217     cur_auth_type = s->proxy_auth_state.auth_type;
1218
1219     /* Note: This uses buffering, potentially reading more than the
1220      * HTTP header. If tunneling a protocol where the server starts
1221      * the conversation, we might buffer part of that here, too.
1222      * Reading that requires using the proper ffurl_read() function
1223      * on this URLContext, not using the fd directly (as the tls
1224      * protocol does). This shouldn't be an issue for tls though,
1225      * since the client starts the conversation there, so there
1226      * is no extra data that we might buffer up here.
1227      */
1228     ret = http_read_header(h, &new_loc);
1229     if (ret < 0)
1230         goto fail;
1231
1232     attempts++;
1233     if (s->http_code == 407 &&
1234         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1235         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1236         ffurl_closep(&s->hd);
1237         goto redo;
1238     }
1239
1240     if (s->http_code < 400)
1241         return 0;
1242     ret = AVERROR(EIO);
1243
1244 fail:
1245     http_proxy_close(h);
1246     return ret;
1247 }
1248
1249 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1250 {
1251     HTTPContext *s = h->priv_data;
1252     return ffurl_write(s->hd, buf, size);
1253 }
1254
1255 URLProtocol ff_httpproxy_protocol = {
1256     .name                = "httpproxy",
1257     .url_open            = http_proxy_open,
1258     .url_read            = http_buf_read,
1259     .url_write           = http_proxy_write,
1260     .url_close           = http_proxy_close,
1261     .url_get_file_handle = http_get_file_handle,
1262     .priv_data_size      = sizeof(HTTPContext),
1263     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1264 };
1265 #endif /* CONFIG_HTTPPROXY_PROTOCOL */