1 /*
2  * This file is part of mpv.
3  *
4  * mpv is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * mpv is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include <libavformat/avformat.h>
19 #include <libavformat/avio.h>
20 #include <libavutil/opt.h>
21 
22 #include "options/path.h"
23 #include "common/common.h"
24 #include "common/msg.h"
25 #include "common/tags.h"
26 #include "common/av_common.h"
27 #include "misc/thread_tools.h"
28 #include "stream.h"
29 #include "options/m_config.h"
30 #include "options/m_option.h"
31 
32 #include "cookies.h"
33 
34 #include "misc/bstr.h"
35 #include "mpv_talloc.h"
36 
37 #define OPT_BASE_STRUCT struct stream_lavf_params
38 struct stream_lavf_params {
39     char **avopts;
40     int cookies_enabled;
41     char *cookies_file;
42     char *useragent;
43     char *referrer;
44     char **http_header_fields;
45     int tls_verify;
46     char *tls_ca_file;
47     char *tls_cert_file;
48     char *tls_key_file;
49     double timeout;
50     char *http_proxy;
51 };
52 
53 const struct m_sub_options stream_lavf_conf = {
54     .opts = (const m_option_t[]) {
55         {"stream-lavf-o", OPT_KEYVALUELIST(avopts)},
56         {"http-header-fields", OPT_STRINGLIST(http_header_fields)},
57         {"user-agent", OPT_STRING(useragent)},
58         {"referrer", OPT_STRING(referrer)},
59         {"cookies", OPT_FLAG(cookies_enabled)},
60         {"cookies-file", OPT_STRING(cookies_file), .flags = M_OPT_FILE},
61         {"tls-verify", OPT_FLAG(tls_verify)},
62         {"tls-ca-file", OPT_STRING(tls_ca_file), .flags = M_OPT_FILE},
63         {"tls-cert-file", OPT_STRING(tls_cert_file), .flags = M_OPT_FILE},
64         {"tls-key-file", OPT_STRING(tls_key_file), .flags = M_OPT_FILE},
65         {"network-timeout", OPT_DOUBLE(timeout), M_RANGE(0, DBL_MAX)},
66         {"http-proxy", OPT_STRING(http_proxy)},
67         {0}
68     },
69     .size = sizeof(struct stream_lavf_params),
70     .defaults = &(const struct stream_lavf_params){
71         .useragent = "libmpv",
72         .timeout = 60,
73     },
74 };
75 
76 static const char *const http_like[] =
77     {"http", "https", "mmsh", "mmshttp", "httproxy", NULL};
78 
79 static int open_f(stream_t *stream);
80 static struct mp_tags *read_icy(stream_t *stream);
81 
fill_buffer(stream_t * s,void * buffer,int max_len)82 static int fill_buffer(stream_t *s, void *buffer, int max_len)
83 {
84     AVIOContext *avio = s->priv;
85     int r = avio_read_partial(avio, buffer, max_len);
86     return (r <= 0) ? -1 : r;
87 }
88 
write_buffer(stream_t * s,void * buffer,int len)89 static int write_buffer(stream_t *s, void *buffer, int len)
90 {
91     AVIOContext *avio = s->priv;
92     avio_write(avio, buffer, len);
93     avio_flush(avio);
94     if (avio->error)
95         return -1;
96     return len;
97 }
98 
seek(stream_t * s,int64_t newpos)99 static int seek(stream_t *s, int64_t newpos)
100 {
101     AVIOContext *avio = s->priv;
102     if (avio_seek(avio, newpos, SEEK_SET) < 0) {
103         return 0;
104     }
105     return 1;
106 }
107 
get_size(stream_t * s)108 static int64_t get_size(stream_t *s)
109 {
110     AVIOContext *avio = s->priv;
111     return avio_size(avio);
112 }
113 
close_f(stream_t * stream)114 static void close_f(stream_t *stream)
115 {
116     AVIOContext *avio = stream->priv;
117     /* NOTE: As of 2011 write streams must be manually flushed before close.
118      * Currently write_buffer() always flushes them after writing.
119      * avio_close() could return an error, but we have no way to return that
120      * with the current stream API.
121      */
122     if (avio)
123         avio_close(avio);
124 }
125 
control(stream_t * s,int cmd,void * arg)126 static int control(stream_t *s, int cmd, void *arg)
127 {
128     AVIOContext *avio = s->priv;
129     switch(cmd) {
130     case STREAM_CTRL_AVSEEK: {
131         struct stream_avseek *c = arg;
132         int64_t r = avio_seek_time(avio, c->stream_index, c->timestamp, c->flags);
133         if (r >= 0) {
134             stream_drop_buffers(s);
135             return 1;
136         }
137         break;
138     }
139     case STREAM_CTRL_HAS_AVSEEK: {
140         // Starting at some point, read_seek is always available, and runtime
141         // behavior decides whether it exists or not. FFmpeg's API doesn't
142         // return anything helpful to determine seekability upfront, so here's
143         // a hardcoded whitelist. Not our fault.
144         // In addition we also have to jump through ridiculous hoops just to
145         // get the fucking protocol name.
146         const char *proto = NULL;
147         if (avio->av_class && avio->av_class->child_next) {
148             // This usually yields the URLContext (why does it even exist?),
149             // which holds the name of the actual protocol implementation.
150             void *child = avio->av_class->child_next(avio, NULL);
151             AVClass *cl = *(AVClass **)child;
152             if (cl && cl->item_name)
153                 proto = cl->item_name(child);
154         }
155         static const char *const has_read_seek[] = {
156             "rtmp", "rtmpt", "rtmpe", "rtmpte", "rtmps", "rtmpts", "mmsh", 0};
157         for (int n = 0; has_read_seek[n]; n++) {
158             if (avio->read_seek && proto && strcmp(proto, has_read_seek[n]) == 0)
159                 return 1;
160         }
161         break;
162     }
163     case STREAM_CTRL_GET_METADATA: {
164         *(struct mp_tags **)arg = read_icy(s);
165         if (!*(struct mp_tags **)arg)
166             break;
167         return 1;
168     }
169     }
170     return STREAM_UNSUPPORTED;
171 }
172 
interrupt_cb(void * ctx)173 static int interrupt_cb(void *ctx)
174 {
175     struct stream *stream = ctx;
176     return mp_cancel_test(stream->cancel);
177 }
178 
179 static const char * const prefix[] = { "lavf://", "ffmpeg://" };
180 
mp_setup_av_network_options(AVDictionary ** dict,const char * target_fmt,struct mpv_global * global,struct mp_log * log)181 void mp_setup_av_network_options(AVDictionary **dict, const char *target_fmt,
182                                  struct mpv_global *global, struct mp_log *log)
183 {
184     void *temp = talloc_new(NULL);
185     struct stream_lavf_params *opts =
186         mp_get_config_group(temp, global, &stream_lavf_conf);
187 
188     // HTTP specific options (other protocols ignore them)
189     if (opts->useragent)
190         av_dict_set(dict, "user_agent", opts->useragent, 0);
191     if (opts->cookies_enabled) {
192         char *file = opts->cookies_file;
193         if (file && file[0])
194             file = mp_get_user_path(temp, global, file);
195         char *cookies = cookies_lavf(temp, log, file);
196         if (cookies && cookies[0])
197             av_dict_set(dict, "cookies", cookies, 0);
198     }
199     av_dict_set(dict, "tls_verify", opts->tls_verify ? "1" : "0", 0);
200     if (opts->tls_ca_file)
201         av_dict_set(dict, "ca_file", opts->tls_ca_file, 0);
202     if (opts->tls_cert_file)
203         av_dict_set(dict, "cert_file", opts->tls_cert_file, 0);
204     if (opts->tls_key_file)
205         av_dict_set(dict, "key_file", opts->tls_key_file, 0);
206     char *cust_headers = talloc_strdup(temp, "");
207     if (opts->referrer) {
208         cust_headers = talloc_asprintf_append(cust_headers, "Referer: %s\r\n",
209                                               opts->referrer);
210     }
211     if (opts->http_header_fields) {
212         for (int n = 0; opts->http_header_fields[n]; n++) {
213             cust_headers = talloc_asprintf_append(cust_headers, "%s\r\n",
214                                                   opts->http_header_fields[n]);
215         }
216     }
217     if (strlen(cust_headers))
218         av_dict_set(dict, "headers", cust_headers, 0);
219     av_dict_set(dict, "icy", "1", 0);
220     // So far, every known protocol uses microseconds for this
221     // Except rtsp.
222     if (opts->timeout > 0) {
223         if (target_fmt && strcmp(target_fmt, "rtsp") == 0) {
224             mp_verbose(log, "Broken FFmpeg RTSP API => not setting timeout.\n");
225         } else {
226             char buf[80];
227             snprintf(buf, sizeof(buf), "%lld", (long long)(opts->timeout * 1e6));
228             av_dict_set(dict, "timeout", buf, 0);
229         }
230     }
231     if (opts->http_proxy && opts->http_proxy[0])
232         av_dict_set(dict, "http_proxy", opts->http_proxy, 0);
233 
234     mp_set_avdict(dict, opts->avopts);
235 
236     talloc_free(temp);
237 }
238 
239 // Escape http URLs with unescaped, invalid characters in them.
240 // libavformat's http protocol does not do this, and a patch to add this
241 // in a 100% safe case (spaces only) was rejected.
normalize_url(void * ta_parent,const char * filename)242 static char *normalize_url(void *ta_parent, const char *filename)
243 {
244     bstr proto = mp_split_proto(bstr0(filename), NULL);
245     for (int n = 0; http_like[n]; n++) {
246         if (bstr_equals0(proto, http_like[n]))
247             // Escape everything but reserved characters.
248             // Also don't double-scape, so include '%'.
249             return mp_url_escape(ta_parent, filename, ":/?#[]@!$&'()*+,;=%");
250     }
251     return (char *)filename;
252 }
253 
open_f(stream_t * stream)254 static int open_f(stream_t *stream)
255 {
256     AVIOContext *avio = NULL;
257     int res = STREAM_ERROR;
258     AVDictionary *dict = NULL;
259     void *temp = talloc_new(NULL);
260 
261     stream->seek = NULL;
262     stream->seekable = false;
263 
264     int flags = stream->mode == STREAM_WRITE ? AVIO_FLAG_WRITE : AVIO_FLAG_READ;
265 
266     const char *filename = stream->url;
267     if (!filename) {
268         MP_ERR(stream, "No URL\n");
269         goto out;
270     }
271     for (int i = 0; i < sizeof(prefix) / sizeof(prefix[0]); i++)
272         if (!strncmp(filename, prefix[i], strlen(prefix[i])))
273             filename += strlen(prefix[i]);
274     if (!strncmp(filename, "rtsp:", 5) || !strncmp(filename, "rtsps:", 6)) {
275         /* This is handled as a special demuxer, without a separate
276          * stream layer. demux_lavf will do all the real work. Note
277          * that libavformat doesn't even provide a protocol entry for
278          * this (the rtsp demuxer's probe function checks for a "rtsp:"
279          * filename prefix), so it has to be handled specially here.
280          */
281         stream->demuxer = "lavf";
282         stream->lavf_type = "rtsp";
283         talloc_free(temp);
284         return STREAM_OK;
285     }
286 
287     // Replace "mms://" with "mmsh://", so that most mms:// URLs just work.
288     bstr b_filename = bstr0(filename);
289     if (bstr_eatstart0(&b_filename, "mms://") ||
290         bstr_eatstart0(&b_filename, "mmshttp://"))
291     {
292         filename = talloc_asprintf(temp, "mmsh://%.*s", BSTR_P(b_filename));
293     }
294 
295     av_dict_set(&dict, "reconnect", "1", 0);
296     av_dict_set(&dict, "reconnect_delay_max", "7", 0);
297 
298     mp_setup_av_network_options(&dict, NULL, stream->global, stream->log);
299 
300     AVIOInterruptCB cb = {
301         .callback = interrupt_cb,
302         .opaque = stream,
303     };
304 
305     filename = normalize_url(stream, filename);
306 
307     if (strncmp(filename, "rtmp", 4) == 0) {
308         stream->demuxer = "lavf";
309         stream->lavf_type = "flv";
310         // Setting timeout enables listen mode - force it to disabled.
311         av_dict_set(&dict, "timeout", "0", 0);
312     }
313 
314     int err = avio_open2(&avio, filename, flags, &cb, &dict);
315     if (err < 0) {
316         if (err == AVERROR_PROTOCOL_NOT_FOUND)
317             MP_ERR(stream, "Protocol not found. Make sure"
318                    " ffmpeg/Libav is compiled with networking support.\n");
319         goto out;
320     }
321 
322     mp_avdict_print_unset(stream->log, MSGL_V, dict);
323 
324     if (avio->av_class) {
325         uint8_t *mt = NULL;
326         if (av_opt_get(avio, "mime_type", AV_OPT_SEARCH_CHILDREN, &mt) >= 0) {
327             stream->mime_type = talloc_strdup(stream, mt);
328             av_free(mt);
329         }
330     }
331 
332     stream->priv = avio;
333     stream->seekable = avio->seekable & AVIO_SEEKABLE_NORMAL;
334     stream->seek = stream->seekable ? seek : NULL;
335     stream->fill_buffer = fill_buffer;
336     stream->write_buffer = write_buffer;
337     stream->get_size = get_size;
338     stream->control = control;
339     stream->close = close_f;
340     // enable cache (should be avoided for files, but no way to detect this)
341     stream->streaming = true;
342     if (stream->info->stream_origin == STREAM_ORIGIN_NET)
343         stream->is_network = true;
344     res = STREAM_OK;
345 
346 out:
347     av_dict_free(&dict);
348     talloc_free(temp);
349     return res;
350 }
351 
read_icy(stream_t * s)352 static struct mp_tags *read_icy(stream_t *s)
353 {
354     AVIOContext *avio = s->priv;
355 
356     if (!avio->av_class)
357         return NULL;
358 
359     uint8_t *icy_header = NULL;
360     if (av_opt_get(avio, "icy_metadata_headers", AV_OPT_SEARCH_CHILDREN,
361                    &icy_header) < 0)
362         icy_header = NULL;
363 
364     uint8_t *icy_packet;
365     if (av_opt_get(avio, "icy_metadata_packet", AV_OPT_SEARCH_CHILDREN,
366                    &icy_packet) < 0)
367         icy_packet = NULL;
368 
369     // Send a metadata update only 1. on start, and 2. on a new metadata packet.
370     // To detect new packages, set the icy_metadata_packet to "-" once we've
371     // read it (a bit hacky, but works).
372 
373     struct mp_tags *res = NULL;
374     if ((!icy_header || !icy_header[0]) && (!icy_packet || !icy_packet[0]))
375         goto done;
376 
377     bstr packet = bstr0(icy_packet);
378     if (bstr_equals0(packet, "-"))
379         goto done;
380 
381     res = talloc_zero(NULL, struct mp_tags);
382 
383     bstr header = bstr0(icy_header);
384     while (header.len) {
385         bstr line = bstr_strip_linebreaks(bstr_getline(header, &header));
386         bstr name, val;
387         if (bstr_split_tok(line, ": ", &name, &val))
388             mp_tags_set_bstr(res, name, val);
389     }
390 
391     bstr head = bstr0("StreamTitle='");
392     int i = bstr_find(packet, head);
393     if (i >= 0) {
394         packet = bstr_cut(packet, i + head.len);
395         int end = bstr_find(packet, bstr0("\';"));
396         packet = bstr_splice(packet, 0, end);
397         mp_tags_set_bstr(res, bstr0("icy-title"), packet);
398     }
399 
400     av_opt_set(avio, "icy_metadata_packet", "-", AV_OPT_SEARCH_CHILDREN);
401 
402 done:
403     av_free(icy_header);
404     av_free(icy_packet);
405     return res;
406 }
407 
408 const stream_info_t stream_info_ffmpeg = {
409   .name = "ffmpeg",
410   .open = open_f,
411   .protocols = (const char *const[]){
412      "rtmp", "rtsp", "rtsps", "http", "https", "mms", "mmst", "mmsh", "mmshttp",
413      "rtp", "httpproxy", "rtmpe", "rtmps", "rtmpt", "rtmpte", "rtmpts", "srt",
414      "srtp", "gopher", "gophers", "data",
415      NULL },
416   .can_write = true,
417   .stream_origin = STREAM_ORIGIN_NET,
418 };
419 
420 // Unlike above, this is not marked as safe, and can contain protocols which
421 // may do insecure things. (Such as "ffmpeg", which can access the "lavfi"
422 // pseudo-demuxer, which in turn gives access to filters that can access the
423 // local filesystem.)
424 const stream_info_t stream_info_ffmpeg_unsafe = {
425   .name = "ffmpeg",
426   .open = open_f,
427   .protocols = (const char *const[]){
428      "lavf", "ffmpeg", "udp", "ftp", "tcp", "tls", "unix", "sftp", "md5",
429      "concat", "smb",
430      NULL },
431   .stream_origin = STREAM_ORIGIN_UNSAFE,
432   .can_write = true,
433 };
434 
435