Debian Codegraph @

gallery_dl/downloader/http.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2014-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Downloader module for http:// and https:// URLs"""
10
11 import time
12 import mimetypes
13 from requests.exceptions import RequestException, ConnectionError, Timeout
14 from .common import DownloaderBase
15 from .. import text, util, output, exception
16 from ssl import SSLError
17 FLAGS = util.FLAGS
18
19
20 class HttpDownloader(DownloaderBase):
21 scheme = "http"
22
23 def __init__(self, job):
24 DownloaderBase.__init__(self, job)
25 extractor = job.extractor
26 self.downloading = False
27
28 self.adjust_extension = self.config("adjust-extensions", True)
29 self.chunk_size = self.config("chunk-size", 32768)
30 self.metadata = extractor.config("http-metadata")
31 self.progress = self.config("progress", 3.0)
32 self.validate = self.config("validate", True)
33 self.validate_html = self.config("validate-html", True)
34 self.headers = self.config("headers")
35 self.minsize = self.config("filesize-min")
36 self.maxsize = self.config("filesize-max")
37 self.retries = self.config("retries", extractor._retries)
38 self.retry_codes = self.config("retry-codes", extractor._retry_codes)
39 self.timeout = self.config("timeout", extractor._timeout)
40 self.verify = self.config("verify", extractor._verify)
41 self.mtime = self.config("mtime", True)
42 self.rate = self.config("rate")
43 interval_429 = self.config("sleep-429")
44
45 if self.config("consume-content", False):
46 self.release_conn = self._release_conn_impl
47 else:
48 # this resets the underlying TCP connection, and therefore
49 # if the program makes another request to the same domain,
50 # a new connection (either TLS or plain TCP) must be made
51 self.release_conn = lambda resp: resp.close()
52
53 if self.retries < 0:
54 self.retries = float("inf")
55 if self.minsize:
56 minsize = text.parse_bytes(self.minsize)
57 if not minsize:
58 self.log.warning(
59 "Invalid minimum file size (%r)", self.minsize)
60 self.minsize = minsize
61 if self.maxsize:
62 maxsize = text.parse_bytes(self.maxsize)
63 if not maxsize:
64 self.log.warning(
65 "Invalid maximum file size (%r)", self.maxsize)
66 self.maxsize = maxsize
67 if isinstance(self.chunk_size, str):
68 chunk_size = text.parse_bytes(self.chunk_size)
69 if not chunk_size:
70 self.log.warning(
71 "Invalid chunk size (%r)", self.chunk_size)
72 chunk_size = 32768
73 self.chunk_size = chunk_size
74 if self.rate:
75 func = util.build_selection_func(self.rate, 0, text.parse_bytes)
76 if rmax := func.args[1] if hasattr(func, "args") else func():
77 if rmax < self.chunk_size:
78 # reduce chunk_size to allow for one iteration each second
79 self.chunk_size = rmax
80 self.rate = func
81 self.receive = self._receive_rate
82 else:
83 self.log.warning("Invalid rate limit (%r)", self.rate)
84 self.rate = False
85 if self.progress is not None:
86 self.receive = self._receive_rate
87 if self.progress < 0.0:
88 self.progress = 0.0
89 if interval_429 is None:
90 self.interval_429 = extractor._interval_429
91 else:
92 try:
93 self.interval_429 = util.build_duration_func_ex(interval_429)
94 except Exception as exc:
95 self.log.error("Invalid 'sleep-429' value '%s' (%s: %s)",
96 interval_429, exc.__class__.__name__, exc)
97 self.interval_429 = extractor._interval_429
98
99 def download(self, url, pathfmt):
100 try:
101 return self._download_impl(url, pathfmt)
102 except Exception as exc:
103 if self.downloading:
104 output.stderr_write("\n")
105 self.log.traceback(exc)
106 raise
107 finally:
108 # remove file from incomplete downloads
109 if self.downloading and not self.part:
110 util.remove_file(pathfmt.temppath)
111
112 def _download_impl(self, url, pathfmt):
113 response = None
114 tries = code = 0
115 msg = ""
116
117 metadata = self.metadata
118 kwdict = pathfmt.kwdict
119 expected_status = kwdict.get(
120 "_http_expected_status", ())
121 adjust_extension = kwdict.get(
122 "_http_adjust_extension", self.adjust_extension)
123
124 if self.part and not metadata:
125 pathfmt.part_enable(self.partdir)
126
127 while True:
128 if FLAGS.DOWNLOAD is not None:
129 return FLAGS.process("DOWNLOAD")
130
131 if tries:
132 if response:
133 self.release_conn(response)
134 response = None
135
136 self.log.warning("%s (%s/%s)", msg, tries, self.retries+1)
137 if tries > self.retries:
138 return False
139
140 if code == 429 and self.interval_429:
141 s = self.interval_429(tries)
142 time.sleep(s if s > tries else tries)
143 else:
144 time.sleep(tries)
145 code = 0
146
147 tries += 1
148 file_header = None
149
150 # collect HTTP headers
151 headers = {"Accept": "*/*"}
152 # file-specific headers
153 if extra := kwdict.get("_http_headers"):
154 headers.update(extra)
155 # general headers
156 if self.headers:
157 headers.update(self.headers)
158 # partial content
159 if file_size := pathfmt.part_size():
160 headers["Range"] = f"bytes={file_size}-"
161
162 # connect to (remote) source
163 try:
164 response = self.session.request(
165 kwdict.get("_http_method", "GET"), url,
166 stream=True,
167 headers=headers,
168 data=kwdict.get("_http_data"),
169 timeout=self.timeout,
170 proxies=self.proxies,
171 verify=self.verify,
172 )
173 except ConnectionError as exc:
174 try:
175 reason = exc.args[0].reason
176 cls = reason.__class__.__name__
177 pre, _, err = str(reason.args[-1]).partition(":")
178 msg = f"{cls}: {(err or pre).lstrip()}"
179 except Exception:
180 msg = str(exc)
181 continue
182 except Timeout as exc:
183 msg = str(exc)
184 continue
185 except Exception as exc:
186 self.log.warning(exc)
187 return False
188
189 # check response
190 code = response.status_code
191 if code == 200 or code in expected_status: # OK
192 offset = 0
193 size = response.headers.get("Content-Length")
194 elif code == 206: # Partial Content
195 offset = file_size
196 size = response.headers["Content-Range"].rpartition("/")[2]
197 elif code == 416 and file_size: # Range Not Satisfiable
198 self._release_conn_impl(response)
199 break
200 else:
201 msg = f"'{code} {response.reason}' for '{url}'"
202
203 challenge = util.detect_challenge(response)
204 if challenge is not None:
205 self.log.warning(challenge)
206
207 if code in self.retry_codes or 500 <= code < 600:
208 continue
209 retry = kwdict.get("_http_retry")
210 if retry and retry(response):
211 continue
212 self.release_conn(response)
213 self.log.warning(msg)
214 return False
215
216 # check for invalid responses
217 if self.validate and \
218 (validate := kwdict.get("_http_validate")) is not None:
219 try:
220 result = validate(response)
221 except Exception:
222 self.release_conn(response)
223 raise
224 if isinstance(result, str):
225 url = result
226 tries -= 1
227 continue
228 if not result:
229 self.release_conn(response)
230 self.log.warning("Invalid response")
231 return False
232 if self.validate_html and response.headers.get(
233 "content-type", "").startswith("text/html") and \
234 pathfmt.extension not in ("html", "htm"):
235 if response.history:
236 self.log.warning("HTTP redirect to '%s'", response.url)
237 else:
238 self.log.warning("HTML response")
239 return False
240
241 # check file size
242 size = text.parse_int(size, None)
243 if size is not None:
244 if not size:
245 self.release_conn(response)
246 self.log.warning("Empty file")
247 return False
248 if self.minsize and size < self.minsize:
249 self.release_conn(response)
250 self.log.warning(
251 "File size smaller than allowed minimum (%s < %s)",
252 size, self.minsize)
253 pathfmt.temppath = ""
254 return True
255 if self.maxsize and size > self.maxsize:
256 self.release_conn(response)
257 self.log.warning(
258 "File size larger than allowed maximum (%s > %s)",
259 size, self.maxsize)
260 pathfmt.temppath = ""
261 return True
262
263 build_path = False
264
265 # set missing filename extension from MIME type
266 if not pathfmt.extension:
267 pathfmt.set_extension(self._find_extension(response))
268 build_path = True
269
270 # set metadata from HTTP headers
271 if metadata:
272 kwdict[metadata] = util.extract_headers(response)
273 build_path = True
274
275 # build and check file path
276 if build_path:
277 pathfmt.build_path()
278 if pathfmt.exists():
279 pathfmt.temppath = ""
280 # release the connection back to pool by explicitly
281 # calling .close()
282 # see https://requests.readthedocs.io/en/latest/user
283 # /advanced/#body-content-workflow
284 # when the image size is on the order of megabytes,
285 # re-establishing a TLS connection will typically be faster
286 # than consuming the whole response
287 response.close()
288 return True
289 if self.part and metadata:
290 pathfmt.part_enable(self.partdir)
291 metadata = False
292
293 content = response.iter_content(self.chunk_size)
294
295 validate_sig = kwdict.get("_http_signature")
296 validate_ext = (adjust_extension and
297 pathfmt.extension in SIGNATURE_CHECKS)
298
299 # check filename extension against file header
300 if not offset and (validate_ext or validate_sig):
301 try:
302 file_header = next(
303 content if response.raw.chunked
304 else response.iter_content(16), b"")
305 except (RequestException, SSLError) as exc:
306 msg = str(exc)
307 continue
308 if validate_sig:
309 result = validate_sig(file_header)
310 if result is not True:
311 self.release_conn(response)
312 self.log.warning(
313 result or "Invalid file signature bytes")
314 return False
315 if validate_ext and self._adjust_extension(
316 pathfmt, file_header) and pathfmt.exists():
317 pathfmt.temppath = ""
318 response.close()
319 return True
320
321 # set open mode
322 if not offset:
323 mode = "w+b"
324 if file_size:
325 self.log.debug("Unable to resume partial download")
326 else:
327 mode = "r+b"
328 self.log.debug("Resuming download at byte %d", offset)
329
330 # download content
331 self.downloading = True
332 with pathfmt.open(mode) as fp:
333 if fp is None:
334 # '.part' file no longer exists
335 break
336 if file_header:
337 fp.write(file_header)
338 offset += len(file_header)
339 elif offset:
340 if adjust_extension and \
341 pathfmt.extension in SIGNATURE_CHECKS:
342 self._adjust_extension(pathfmt, fp.read(16))
343 fp.seek(offset)
344
345 self.out.start(pathfmt.path)
346 try:
347 self.receive(fp, content, size, offset)
348 except (RequestException, SSLError) as exc:
349 msg = str(exc)
350 output.stderr_write("\n")
351 continue
352 except exception.StopExtraction:
353 response.close()
354 return False
355 except exception.ControlException:
356 response.close()
357 raise
358
359 # check file size
360 if size and (fsize := fp.tell()) < size:
361 if (segmented := kwdict.get("_http_segmented")) and \
362 segmented is True or segmented == fsize:
363 tries -= 1
364 msg = "Resuming segmented download"
365 output.stdout_write("\r")
366 else:
367 msg = f"file size mismatch ({fsize} < {size})"
368 output.stderr_write("\n")
369 continue
370
371 break
372
373 self.downloading = False
374 if self.mtime:
375 if "_http_lastmodified" in kwdict:
376 kwdict["_mtime_http"] = kwdict["_http_lastmodified"]
377 else:
378 kwdict["_mtime_http"] = response.headers.get("Last-Modified")
379 else:
380 kwdict["_mtime_http"] = None
381
382 return True
383
384 def _release_conn_impl(self, response):
385 """Release connection back to pool by consuming response body"""
386 try:
387 for _ in response.iter_content(self.chunk_size):
388 pass
389 except (RequestException, SSLError) as exc:
390 output.stderr_write("\n")
391 self.log.debug(
392 "Unable to consume response body (%s: %s); "
393 "closing the connection anyway", exc.__class__.__name__, exc)
394 response.close()
395
396 def receive(self, fp, content, bytes_total, bytes_start):
397 write = fp.write
398 for data in content:
399 if FLAGS.DOWNLOAD is not None:
400 return FLAGS.process("DOWNLOAD")
401 write(data)
402
403 def _receive_rate(self, fp, content, bytes_total, bytes_start):
404 rate = self.rate() if self.rate else None
405 write = fp.write
406 progress = self.progress
407
408 bytes_downloaded = 0
409 time_start = time.monotonic()
410
411 for data in content:
412 if FLAGS.DOWNLOAD is not None:
413 return FLAGS.process("DOWNLOAD")
414 time_elapsed = time.monotonic() - time_start
415 bytes_downloaded += len(data)
416
417 write(data)
418
419 if progress is not None:
420 if time_elapsed > progress:
421 self.out.progress(
422 bytes_total,
423 bytes_start + bytes_downloaded,
424 int(bytes_downloaded / time_elapsed),
425 )
426
427 if rate is not None:
428 time_expected = bytes_downloaded / rate
429 if time_expected > time_elapsed:
430 time.sleep(time_expected - time_elapsed)
431
432 def _find_extension(self, response):
433 """Get filename extension from MIME type"""
434 mtype = response.headers.get("Content-Type", "image/jpeg")
435 mtype = mtype.partition(";")[0].lower()
436
437 if "/" not in mtype:
438 mtype = "image/" + mtype
439
440 if mtype in MIME_TYPES:
441 return MIME_TYPES[mtype]
442
443 if ext := mimetypes.guess_extension(mtype, strict=False):
444 return ext[1:]
445
446 self.log.warning("Unknown MIME type '%s'", mtype)
447 return "bin"
448
449 def _adjust_extension(self, pathfmt, file_header):
450 """Check filename extension against file header"""
451 if not SIGNATURE_CHECKS[pathfmt.extension](file_header):
452 for ext, check in SIGNATURE_CHECKS.items():
453 if check(file_header):
454 self.log.debug(
455 "Adjusting filename extension of '%s' to '%s'",
456 pathfmt.filename, ext)
457 pathfmt.set_extension(ext)
458 pathfmt.build_path()
459 return True
460 return False
461
462
463 MIME_TYPES = {
464 "image/jpeg" : "jpg",
465 "image/jpg" : "jpg",
466 "image/png" : "png",
467 "image/gif" : "gif",
468 "image/bmp" : "bmp",
469 "image/x-bmp" : "bmp",
470 "image/x-ms-bmp": "bmp",
471 "image/webp" : "webp",
472 "image/avif" : "avif",
473 "image/heic" : "heic",
474 "image/heif" : "heif",
475 "image/svg+xml" : "svg",
476 "image/ico" : "ico",
477 "image/icon" : "ico",
478 "image/x-icon" : "ico",
479 "image/vnd.microsoft.icon" : "ico",
480 "image/x-photoshop" : "psd",
481 "application/x-photoshop" : "psd",
482 "image/vnd.adobe.photoshop": "psd",
483
484 "video/webm": "webm",
485 "video/ogg" : "ogg",
486 "video/mp4" : "mp4",
487 "video/m4v" : "m4v",
488 "video/x-m4v": "m4v",
489 "video/quicktime": "mov",
490
491 "audio/wav" : "wav",
492 "audio/x-wav": "wav",
493 "audio/webm" : "webm",
494 "audio/ogg" : "ogg",
495 "audio/mpeg" : "mp3",
496 "audio/aac" : "aac",
497 "audio/x-aac": "aac",
498
499 "application/vnd.apple.mpegurl": "m3u8",
500 "application/x-mpegurl" : "m3u8",
501 "application/dash+xml" : "mpd",
502
503 "application/zip" : "zip",
504 "application/x-zip": "zip",
505 "application/x-zip-compressed": "zip",
506 "application/rar" : "rar",
507 "application/x-rar": "rar",
508 "application/x-rar-compressed": "rar",
509 "application/x-7z-compressed" : "7z",
510
511 "application/pdf" : "pdf",
512 "application/x-pdf": "pdf",
513 "application/x-shockwave-flash": "swf",
514
515 "text/html": "html",
516
517 "application/ogg": "ogg",
518 # https://www.iana.org/assignments/media-types/model/obj
519 "model/obj": "obj",
520 "application/octet-stream": "bin",
521 }
522
523
524 def _signature_html(s):
525 s = s[:14].lstrip()
526 return s and b"<!doctype html".startswith(s.lower())
527
528
529 # https://en.wikipedia.org/wiki/List_of_file_signatures
530 SIGNATURE_CHECKS = {
531 "jpg" : lambda s: s[0:3] == b"\xFF\xD8\xFF",
532 "png" : lambda s: s[0:8] == b"\x89PNG\r\n\x1A\n",
533 "gif" : lambda s: s[0:6] in (b"GIF87a", b"GIF89a"),
534 "bmp" : lambda s: s[0:2] == b"BM",
535 "webp": lambda s: (s[0:4] == b"RIFF" and
536 s[8:12] == b"WEBP"),
537 "avif": lambda s: s[4:11] == b"ftypavi" and s[11] in b"fs",
538 "heic": lambda s: (s[4:10] == b"ftyphe" and s[10:12] in (
539 b"ic", b"im", b"is", b"ix", b"vc", b"vm", b"vs")),
540 "svg" : lambda s: s[0:5] == b"<?xml",
541 "ico" : lambda s: s[0:4] == b"\x00\x00\x01\x00",
542 "cur" : lambda s: s[0:4] == b"\x00\x00\x02\x00",
543 "psd" : lambda s: s[0:4] == b"8BPS",
544 "mp4" : lambda s: (s[4:8] == b"ftyp" and s[8:11] in (
545 b"mp4", b"avc", b"iso")),
546 "m4v" : lambda s: s[4:11] == b"ftypM4V",
547 "mov" : lambda s: s[4:12] == b"ftypqt ",
548 "webm": lambda s: s[0:4] == b"\x1A\x45\xDF\xA3",
549 "ogg" : lambda s: s[0:4] == b"OggS",
550 "wav" : lambda s: (s[0:4] == b"RIFF" and
551 s[8:12] == b"WAVE"),
552 "mp3" : lambda s: (s[0:3] == b"ID3" or
553 s[0:2] in (b"\xFF\xFB", b"\xFF\xF3", b"\xFF\xF2")),
554 "aac" : lambda s: s[0:2] in (b"\xFF\xF9", b"\xFF\xF1"),
555 "m3u8": lambda s: s[0:7] == b"#EXTM3U",
556 "mpd" : lambda s: b"<MPD" in s,
557 "zip" : lambda s: s[0:4] in (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"),
558 "rar" : lambda s: s[0:6] == b"Rar!\x1A\x07",
559 "7z" : lambda s: s[0:6] == b"\x37\x7A\xBC\xAF\x27\x1C",
560 "pdf" : lambda s: s[0:5] == b"%PDF-",
561 "swf" : lambda s: s[0:3] in (b"CWS", b"FWS"),
562 "html": _signature_html,
563 "htm" : _signature_html,
564 "blend": lambda s: s[0:7] == b"BLENDER",
565 # unfortunately the Wavefront .obj format doesn't have a signature,
566 # so we check for the existence of Blender's comment
567 "obj" : lambda s: s[0:11] == b"# Blender v",
568 # Celsys Clip Studio Paint format
569 # https://github.com/rasensuihei/cliputils/blob/master/README.md
570 "clip": lambda s: s[0:8] == b"CSFCHUNK",
571 # check 'bin' files against all other file signatures
572 "bin" : lambda s: False,
573 }
574
575 __downloader__ = HttpDownloader