[downloader/external] Fix infinite retries for curl (closes #19303)
[youtube-dl] / youtube_dl / downloader / external.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import re
5 import subprocess
6 import sys
7 import time
8
9 from .common import FileDownloader
10 from ..compat import (
11     compat_setenv,
12     compat_str,
13 )
14 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
15 from ..utils import (
16     cli_option,
17     cli_valueless_option,
18     cli_bool_option,
19     cli_configuration_args,
20     encodeFilename,
21     encodeArgument,
22     handle_youtubedl_headers,
23     check_executable,
24     is_outdated_version,
25 )
26
27
28 class ExternalFD(FileDownloader):
29     def real_download(self, filename, info_dict):
30         self.report_destination(filename)
31         tmpfilename = self.temp_name(filename)
32
33         try:
34             started = time.time()
35             retval = self._call_downloader(tmpfilename, info_dict)
36         except KeyboardInterrupt:
37             if not info_dict.get('is_live'):
38                 raise
39             # Live stream downloading cancellation should be considered as
40             # correct and expected termination thus all postprocessing
41             # should take place
42             retval = 0
43             self.to_screen('[%s] Interrupted by user' % self.get_basename())
44
45         if retval == 0:
46             status = {
47                 'filename': filename,
48                 'status': 'finished',
49                 'elapsed': time.time() - started,
50             }
51             if filename != '-':
52                 fsize = os.path.getsize(encodeFilename(tmpfilename))
53                 self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
54                 self.try_rename(tmpfilename, filename)
55                 status.update({
56                     'downloaded_bytes': fsize,
57                     'total_bytes': fsize,
58                 })
59             self._hook_progress(status)
60             return True
61         else:
62             self.to_stderr('\n')
63             self.report_error('%s exited with code %d' % (
64                 self.get_basename(), retval))
65             return False
66
67     @classmethod
68     def get_basename(cls):
69         return cls.__name__[:-2].lower()
70
71     @property
72     def exe(self):
73         return self.params.get('external_downloader')
74
75     @classmethod
76     def available(cls):
77         return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
78
79     @classmethod
80     def supports(cls, info_dict):
81         return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
82
83     @classmethod
84     def can_download(cls, info_dict):
85         return cls.available() and cls.supports(info_dict)
86
87     def _option(self, command_option, param):
88         return cli_option(self.params, command_option, param)
89
90     def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
91         return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
92
93     def _valueless_option(self, command_option, param, expected_value=True):
94         return cli_valueless_option(self.params, command_option, param, expected_value)
95
96     def _configuration_args(self, default=[]):
97         return cli_configuration_args(self.params, 'external_downloader_args', default)
98
99     def _call_downloader(self, tmpfilename, info_dict):
100         """ Either overwrite this or implement _make_cmd """
101         cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
102
103         self._debug_cmd(cmd)
104
105         p = subprocess.Popen(
106             cmd, stderr=subprocess.PIPE)
107         _, stderr = p.communicate()
108         if p.returncode != 0:
109             self.to_stderr(stderr.decode('utf-8', 'replace'))
110         return p.returncode
111
112
113 class CurlFD(ExternalFD):
114     AVAILABLE_OPT = '-V'
115
116     def _make_cmd(self, tmpfilename, info_dict):
117         cmd = [self.exe, '--location', '-o', tmpfilename]
118         for key, val in info_dict['http_headers'].items():
119             cmd += ['--header', '%s: %s' % (key, val)]
120         cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
121         cmd += self._valueless_option('--silent', 'noprogress')
122         cmd += self._valueless_option('--verbose', 'verbose')
123         cmd += self._option('--limit-rate', 'ratelimit')
124         retry = self._option('--retry', 'retries')
125         if len(retry) == 2:
126             if retry[1] in ('inf', 'infinite'):
127                 retry[1] = '2147483647'
128             cmd += retry
129         cmd += self._option('--max-filesize', 'max_filesize')
130         cmd += self._option('--interface', 'source_address')
131         cmd += self._option('--proxy', 'proxy')
132         cmd += self._valueless_option('--insecure', 'nocheckcertificate')
133         cmd += self._configuration_args()
134         cmd += ['--', info_dict['url']]
135         return cmd
136
137     def _call_downloader(self, tmpfilename, info_dict):
138         cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
139
140         self._debug_cmd(cmd)
141
142         # curl writes the progress to stderr so don't capture it.
143         p = subprocess.Popen(cmd)
144         p.communicate()
145         return p.returncode
146
147
148 class AxelFD(ExternalFD):
149     AVAILABLE_OPT = '-V'
150
151     def _make_cmd(self, tmpfilename, info_dict):
152         cmd = [self.exe, '-o', tmpfilename]
153         for key, val in info_dict['http_headers'].items():
154             cmd += ['-H', '%s: %s' % (key, val)]
155         cmd += self._configuration_args()
156         cmd += ['--', info_dict['url']]
157         return cmd
158
159
160 class WgetFD(ExternalFD):
161     AVAILABLE_OPT = '--version'
162
163     def _make_cmd(self, tmpfilename, info_dict):
164         cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
165         for key, val in info_dict['http_headers'].items():
166             cmd += ['--header', '%s: %s' % (key, val)]
167         cmd += self._option('--bind-address', 'source_address')
168         cmd += self._option('--proxy', 'proxy')
169         cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
170         cmd += self._configuration_args()
171         cmd += ['--', info_dict['url']]
172         return cmd
173
174
175 class Aria2cFD(ExternalFD):
176     AVAILABLE_OPT = '-v'
177
178     def _make_cmd(self, tmpfilename, info_dict):
179         cmd = [self.exe, '-c']
180         cmd += self._configuration_args([
181             '--min-split-size', '1M', '--max-connection-per-server', '4'])
182         dn = os.path.dirname(tmpfilename)
183         if dn:
184             cmd += ['--dir', dn]
185         cmd += ['--out', os.path.basename(tmpfilename)]
186         for key, val in info_dict['http_headers'].items():
187             cmd += ['--header', '%s: %s' % (key, val)]
188         cmd += self._option('--interface', 'source_address')
189         cmd += self._option('--all-proxy', 'proxy')
190         cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
191         cmd += ['--', info_dict['url']]
192         return cmd
193
194
195 class HttpieFD(ExternalFD):
196     @classmethod
197     def available(cls):
198         return check_executable('http', ['--version'])
199
200     def _make_cmd(self, tmpfilename, info_dict):
201         cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
202         for key, val in info_dict['http_headers'].items():
203             cmd += ['%s:%s' % (key, val)]
204         return cmd
205
206
207 class FFmpegFD(ExternalFD):
208     @classmethod
209     def supports(cls, info_dict):
210         return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
211
212     @classmethod
213     def available(cls):
214         return FFmpegPostProcessor().available
215
216     def _call_downloader(self, tmpfilename, info_dict):
217         url = info_dict['url']
218         ffpp = FFmpegPostProcessor(downloader=self)
219         if not ffpp.available:
220             self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
221             return False
222         ffpp.check_version()
223
224         args = [ffpp.executable, '-y']
225
226         for log_level in ('quiet', 'verbose'):
227             if self.params.get(log_level, False):
228                 args += ['-loglevel', log_level]
229                 break
230
231         seekable = info_dict.get('_seekable')
232         if seekable is not None:
233             # setting -seekable prevents ffmpeg from guessing if the server
234             # supports seeking(by adding the header `Range: bytes=0-`), which
235             # can cause problems in some cases
236             # https://github.com/rg3/youtube-dl/issues/11800#issuecomment-275037127
237             # http://trac.ffmpeg.org/ticket/6125#comment:10
238             args += ['-seekable', '1' if seekable else '0']
239
240         args += self._configuration_args()
241
242         # start_time = info_dict.get('start_time') or 0
243         # if start_time:
244         #     args += ['-ss', compat_str(start_time)]
245         # end_time = info_dict.get('end_time')
246         # if end_time:
247         #     args += ['-t', compat_str(end_time - start_time)]
248
249         if info_dict['http_headers'] and re.match(r'^https?://', url):
250             # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
251             # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
252             headers = handle_youtubedl_headers(info_dict['http_headers'])
253             args += [
254                 '-headers',
255                 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
256
257         env = None
258         proxy = self.params.get('proxy')
259         if proxy:
260             if not re.match(r'^[\da-zA-Z]+://', proxy):
261                 proxy = 'http://%s' % proxy
262
263             if proxy.startswith('socks'):
264                 self.report_warning(
265                     '%s does not support SOCKS proxies. Downloading is likely to fail. '
266                     'Consider adding --hls-prefer-native to your command.' % self.get_basename())
267
268             # Since December 2015 ffmpeg supports -http_proxy option (see
269             # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
270             # We could switch to the following code if we are able to detect version properly
271             # args += ['-http_proxy', proxy]
272             env = os.environ.copy()
273             compat_setenv('HTTP_PROXY', proxy, env=env)
274             compat_setenv('http_proxy', proxy, env=env)
275
276         protocol = info_dict.get('protocol')
277
278         if protocol == 'rtmp':
279             player_url = info_dict.get('player_url')
280             page_url = info_dict.get('page_url')
281             app = info_dict.get('app')
282             play_path = info_dict.get('play_path')
283             tc_url = info_dict.get('tc_url')
284             flash_version = info_dict.get('flash_version')
285             live = info_dict.get('rtmp_live', False)
286             if player_url is not None:
287                 args += ['-rtmp_swfverify', player_url]
288             if page_url is not None:
289                 args += ['-rtmp_pageurl', page_url]
290             if app is not None:
291                 args += ['-rtmp_app', app]
292             if play_path is not None:
293                 args += ['-rtmp_playpath', play_path]
294             if tc_url is not None:
295                 args += ['-rtmp_tcurl', tc_url]
296             if flash_version is not None:
297                 args += ['-rtmp_flashver', flash_version]
298             if live:
299                 args += ['-rtmp_live', 'live']
300
301         args += ['-i', url, '-c', 'copy']
302
303         if self.params.get('test', False):
304             args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
305
306         if protocol in ('m3u8', 'm3u8_native'):
307             if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
308                 args += ['-f', 'mpegts']
309             else:
310                 args += ['-f', 'mp4']
311                 if (ffpp.basename == 'ffmpeg' and is_outdated_version(ffpp._versions['ffmpeg'], '3.2', False)) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')):
312                     args += ['-bsf:a', 'aac_adtstoasc']
313         elif protocol == 'rtmp':
314             args += ['-f', 'flv']
315         else:
316             args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
317
318         args = [encodeArgument(opt) for opt in args]
319         args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
320
321         self._debug_cmd(args)
322
323         proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
324         try:
325             retval = proc.wait()
326         except KeyboardInterrupt:
327             # subprocces.run would send the SIGKILL signal to ffmpeg and the
328             # mp4 file couldn't be played, but if we ask ffmpeg to quit it
329             # produces a file that is playable (this is mostly useful for live
330             # streams). Note that Windows is not affected and produces playable
331             # files (see https://github.com/rg3/youtube-dl/issues/8300).
332             if sys.platform != 'win32':
333                 proc.communicate(b'q')
334             raise
335         return retval
336
337
338 class AVconvFD(FFmpegFD):
339     pass
340
341
342 _BY_NAME = dict(
343     (klass.get_basename(), klass)
344     for name, klass in globals().items()
345     if name.endswith('FD') and name != 'ExternalFD'
346 )
347
348
349 def list_external_downloaders():
350     return sorted(_BY_NAME.keys())
351
352
353 def get_external_downloader(external_downloader):
354     """ Given the name of the executable, see whether we support the given
355         downloader . """
356     # Drop .exe extension on Windows
357     bn = os.path.splitext(os.path.basename(external_downloader))[0]
358     return _BY_NAME[bn]