logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

cookies.py (52715B)


  1. import base64
  2. import collections
  3. import contextlib
  4. import datetime as dt
  5. import functools
  6. import glob
  7. import hashlib
  8. import http.cookiejar
  9. import http.cookies
  10. import io
  11. import json
  12. import os
  13. import re
  14. import shutil
  15. import struct
  16. import subprocess
  17. import sys
  18. import tempfile
  19. import time
  20. import urllib.request
  21. from enum import Enum, auto
  22. from .aes import (
  23. aes_cbc_decrypt_bytes,
  24. aes_gcm_decrypt_and_verify_bytes,
  25. unpad_pkcs7,
  26. )
  27. from .dependencies import (
  28. _SECRETSTORAGE_UNAVAILABLE_REASON,
  29. secretstorage,
  30. sqlite3,
  31. )
  32. from .minicurses import MultilinePrinter, QuietMultilinePrinter
  33. from .utils import (
  34. DownloadError,
  35. YoutubeDLError,
  36. Popen,
  37. error_to_str,
  38. expand_path,
  39. is_path_like,
  40. sanitize_url,
  41. str_or_none,
  42. try_call,
  43. write_string,
  44. )
  45. from .utils._utils import _YDLLogger
  46. from .utils.networking import normalize_url
  47. CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi', 'whale'}
  48. SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'}
  49. class YDLLogger(_YDLLogger):
  50. def warning(self, message, only_once=False): # compat
  51. return super().warning(message, once=only_once)
  52. class ProgressBar(MultilinePrinter):
  53. _DELAY, _timer = 0.1, 0
  54. def print(self, message):
  55. if time.time() - self._timer > self._DELAY:
  56. self.print_at_line(f'[Cookies] {message}', 0)
  57. self._timer = time.time()
  58. def progress_bar(self):
  59. """Return a context manager with a print method. (Optional)"""
  60. # Do not print to files/pipes, loggers, or when --no-progress is used
  61. if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'):
  62. return
  63. file = self._ydl._out_files.error
  64. try:
  65. if not file.isatty():
  66. return
  67. except BaseException:
  68. return
  69. return self.ProgressBar(file, preserve_output=False)
  70. def _create_progress_bar(logger):
  71. if hasattr(logger, 'progress_bar'):
  72. printer = logger.progress_bar()
  73. if printer:
  74. return printer
  75. printer = QuietMultilinePrinter()
  76. printer.print = lambda _: None
  77. return printer
  78. class CookieLoadError(YoutubeDLError):
  79. pass
  80. def load_cookies(cookie_file, browser_specification, ydl):
  81. try:
  82. cookie_jars = []
  83. if browser_specification is not None:
  84. browser_name, profile, keyring, container = _parse_browser_specification(*browser_specification)
  85. cookie_jars.append(
  86. extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring, container=container))
  87. if cookie_file is not None:
  88. is_filename = is_path_like(cookie_file)
  89. if is_filename:
  90. cookie_file = expand_path(cookie_file)
  91. jar = YoutubeDLCookieJar(cookie_file)
  92. if not is_filename or os.access(cookie_file, os.R_OK):
  93. jar.load()
  94. cookie_jars.append(jar)
  95. return _merge_cookie_jars(cookie_jars)
  96. except Exception:
  97. raise CookieLoadError('failed to load cookies')
  98. def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None, container=None):
  99. if browser_name == 'firefox':
  100. return _extract_firefox_cookies(profile, container, logger)
  101. elif browser_name == 'safari':
  102. return _extract_safari_cookies(profile, logger)
  103. elif browser_name in CHROMIUM_BASED_BROWSERS:
  104. return _extract_chrome_cookies(browser_name, profile, keyring, logger)
  105. else:
  106. raise ValueError(f'unknown browser: {browser_name}')
  107. def _extract_firefox_cookies(profile, container, logger):
  108. logger.info('Extracting cookies from firefox')
  109. if not sqlite3:
  110. logger.warning('Cannot extract cookies from firefox without sqlite3 support. '
  111. 'Please use a Python interpreter compiled with sqlite3 support')
  112. return YoutubeDLCookieJar()
  113. if profile is None:
  114. search_roots = list(_firefox_browser_dirs())
  115. elif _is_path(profile):
  116. search_roots = [profile]
  117. else:
  118. search_roots = [os.path.join(path, profile) for path in _firefox_browser_dirs()]
  119. search_root = ', '.join(map(repr, search_roots))
  120. cookie_database_path = _newest(_firefox_cookie_dbs(search_roots))
  121. if cookie_database_path is None:
  122. raise FileNotFoundError(f'could not find firefox cookies database in {search_root}')
  123. logger.debug(f'Extracting cookies from: "{cookie_database_path}"')
  124. container_id = None
  125. if container not in (None, 'none'):
  126. containers_path = os.path.join(os.path.dirname(cookie_database_path), 'containers.json')
  127. if not os.path.isfile(containers_path) or not os.access(containers_path, os.R_OK):
  128. raise FileNotFoundError(f'could not read containers.json in {search_root}')
  129. with open(containers_path, encoding='utf8') as containers:
  130. identities = json.load(containers).get('identities', [])
  131. container_id = next((context.get('userContextId') for context in identities if container in (
  132. context.get('name'),
  133. try_call(lambda: re.fullmatch(r'userContext([^\.]+)\.label', context['l10nID']).group()),
  134. )), None)
  135. if not isinstance(container_id, int):
  136. raise ValueError(f'could not find firefox container "{container}" in containers.json')
  137. with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:
  138. cursor = None
  139. try:
  140. cursor = _open_database_copy(cookie_database_path, tmpdir)
  141. if isinstance(container_id, int):
  142. logger.debug(
  143. f'Only loading cookies from firefox container "{container}", ID {container_id}')
  144. cursor.execute(
  145. 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE originAttributes LIKE ? OR originAttributes LIKE ?',
  146. (f'%userContextId={container_id}', f'%userContextId={container_id}&%'))
  147. elif container == 'none':
  148. logger.debug('Only loading cookies not belonging to any container')
  149. cursor.execute(
  150. 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE NOT INSTR(originAttributes,"userContextId=")')
  151. else:
  152. cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies')
  153. jar = YoutubeDLCookieJar()
  154. with _create_progress_bar(logger) as progress_bar:
  155. table = cursor.fetchall()
  156. total_cookie_count = len(table)
  157. for i, (host, name, value, path, expiry, is_secure) in enumerate(table):
  158. progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
  159. cookie = http.cookiejar.Cookie(
  160. version=0, name=name, value=value, port=None, port_specified=False,
  161. domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'),
  162. path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False,
  163. comment=None, comment_url=None, rest={})
  164. jar.set_cookie(cookie)
  165. logger.info(f'Extracted {len(jar)} cookies from firefox')
  166. return jar
  167. finally:
  168. if cursor is not None:
  169. cursor.connection.close()
  170. def _firefox_browser_dirs():
  171. if sys.platform in ('cygwin', 'win32'):
  172. yield from map(os.path.expandvars, (
  173. R'%APPDATA%\Mozilla\Firefox\Profiles',
  174. R'%LOCALAPPDATA%\Packages\Mozilla.Firefox_n80bbvh6b1yt2\LocalCache\Roaming\Mozilla\Firefox\Profiles',
  175. ))
  176. elif sys.platform == 'darwin':
  177. yield os.path.expanduser('~/Library/Application Support/Firefox/Profiles')
  178. else:
  179. yield from map(os.path.expanduser, (
  180. '~/.mozilla/firefox',
  181. '~/snap/firefox/common/.mozilla/firefox',
  182. '~/.var/app/org.mozilla.firefox/.mozilla/firefox',
  183. ))
  184. def _firefox_cookie_dbs(roots):
  185. for root in map(os.path.abspath, roots):
  186. for pattern in ('', '*/', 'Profiles/*/'):
  187. yield from glob.iglob(os.path.join(root, pattern, 'cookies.sqlite'))
  188. def _get_chromium_based_browser_settings(browser_name):
  189. # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md
  190. if sys.platform in ('cygwin', 'win32'):
  191. appdata_local = os.path.expandvars('%LOCALAPPDATA%')
  192. appdata_roaming = os.path.expandvars('%APPDATA%')
  193. browser_dir = {
  194. 'brave': os.path.join(appdata_local, R'BraveSoftware\Brave-Browser\User Data'),
  195. 'chrome': os.path.join(appdata_local, R'Google\Chrome\User Data'),
  196. 'chromium': os.path.join(appdata_local, R'Chromium\User Data'),
  197. 'edge': os.path.join(appdata_local, R'Microsoft\Edge\User Data'),
  198. 'opera': os.path.join(appdata_roaming, R'Opera Software\Opera Stable'),
  199. 'vivaldi': os.path.join(appdata_local, R'Vivaldi\User Data'),
  200. 'whale': os.path.join(appdata_local, R'Naver\Naver Whale\User Data'),
  201. }[browser_name]
  202. elif sys.platform == 'darwin':
  203. appdata = os.path.expanduser('~/Library/Application Support')
  204. browser_dir = {
  205. 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'),
  206. 'chrome': os.path.join(appdata, 'Google/Chrome'),
  207. 'chromium': os.path.join(appdata, 'Chromium'),
  208. 'edge': os.path.join(appdata, 'Microsoft Edge'),
  209. 'opera': os.path.join(appdata, 'com.operasoftware.Opera'),
  210. 'vivaldi': os.path.join(appdata, 'Vivaldi'),
  211. 'whale': os.path.join(appdata, 'Naver/Whale'),
  212. }[browser_name]
  213. else:
  214. config = _config_home()
  215. browser_dir = {
  216. 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'),
  217. 'chrome': os.path.join(config, 'google-chrome'),
  218. 'chromium': os.path.join(config, 'chromium'),
  219. 'edge': os.path.join(config, 'microsoft-edge'),
  220. 'opera': os.path.join(config, 'opera'),
  221. 'vivaldi': os.path.join(config, 'vivaldi'),
  222. 'whale': os.path.join(config, 'naver-whale'),
  223. }[browser_name]
  224. # Linux keyring names can be determined by snooping on dbus while opening the browser in KDE:
  225. # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
  226. keyring_name = {
  227. 'brave': 'Brave',
  228. 'chrome': 'Chrome',
  229. 'chromium': 'Chromium',
  230. 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium',
  231. 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium',
  232. 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome',
  233. 'whale': 'Whale',
  234. }[browser_name]
  235. browsers_without_profiles = {'opera'}
  236. return {
  237. 'browser_dir': browser_dir,
  238. 'keyring_name': keyring_name,
  239. 'supports_profiles': browser_name not in browsers_without_profiles,
  240. }
  241. def _extract_chrome_cookies(browser_name, profile, keyring, logger):
  242. logger.info(f'Extracting cookies from {browser_name}')
  243. if not sqlite3:
  244. logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. '
  245. 'Please use a Python interpreter compiled with sqlite3 support')
  246. return YoutubeDLCookieJar()
  247. config = _get_chromium_based_browser_settings(browser_name)
  248. if profile is None:
  249. search_root = config['browser_dir']
  250. elif _is_path(profile):
  251. search_root = profile
  252. config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile
  253. else:
  254. if config['supports_profiles']:
  255. search_root = os.path.join(config['browser_dir'], profile)
  256. else:
  257. logger.error(f'{browser_name} does not support profiles')
  258. search_root = config['browser_dir']
  259. cookie_database_path = _newest(_find_files(search_root, 'Cookies', logger))
  260. if cookie_database_path is None:
  261. raise FileNotFoundError(f'could not find {browser_name} cookies database in "{search_root}"')
  262. logger.debug(f'Extracting cookies from: "{cookie_database_path}"')
  263. with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:
  264. cursor = None
  265. try:
  266. cursor = _open_database_copy(cookie_database_path, tmpdir)
  267. # meta_version is necessary to determine if we need to trim the hash prefix from the cookies
  268. # Ref: https://chromium.googlesource.com/chromium/src/+/b02dcebd7cafab92770734dc2bc317bd07f1d891/net/extras/sqlite/sqlite_persistent_cookie_store.cc#223
  269. meta_version = int(cursor.execute('SELECT value FROM meta WHERE key = "version"').fetchone()[0])
  270. decryptor = get_cookie_decryptor(
  271. config['browser_dir'], config['keyring_name'], logger,
  272. keyring=keyring, meta_version=meta_version)
  273. cursor.connection.text_factory = bytes
  274. column_names = _get_column_names(cursor, 'cookies')
  275. secure_column = 'is_secure' if 'is_secure' in column_names else 'secure'
  276. cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies')
  277. jar = YoutubeDLCookieJar()
  278. failed_cookies = 0
  279. unencrypted_cookies = 0
  280. with _create_progress_bar(logger) as progress_bar:
  281. table = cursor.fetchall()
  282. total_cookie_count = len(table)
  283. for i, line in enumerate(table):
  284. progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
  285. is_encrypted, cookie = _process_chrome_cookie(decryptor, *line)
  286. if not cookie:
  287. failed_cookies += 1
  288. continue
  289. elif not is_encrypted:
  290. unencrypted_cookies += 1
  291. jar.set_cookie(cookie)
  292. if failed_cookies > 0:
  293. failed_message = f' ({failed_cookies} could not be decrypted)'
  294. else:
  295. failed_message = ''
  296. logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}')
  297. counts = decryptor._cookie_counts.copy()
  298. counts['unencrypted'] = unencrypted_cookies
  299. logger.debug(f'cookie version breakdown: {counts}')
  300. return jar
  301. except PermissionError as error:
  302. if os.name == 'nt' and error.errno == 13:
  303. message = 'Could not copy Chrome cookie database. See https://github.com/yt-dlp/yt-dlp/issues/7271 for more info'
  304. logger.error(message)
  305. raise DownloadError(message) # force exit
  306. raise
  307. finally:
  308. if cursor is not None:
  309. cursor.connection.close()
  310. def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure):
  311. host_key = host_key.decode()
  312. name = name.decode()
  313. value = value.decode()
  314. path = path.decode()
  315. is_encrypted = not value and encrypted_value
  316. if is_encrypted:
  317. value = decryptor.decrypt(encrypted_value)
  318. if value is None:
  319. return is_encrypted, None
  320. # In chrome, session cookies have expires_utc set to 0
  321. # In our cookie-store, cookies that do not expire should have expires set to None
  322. if not expires_utc:
  323. expires_utc = None
  324. return is_encrypted, http.cookiejar.Cookie(
  325. version=0, name=name, value=value, port=None, port_specified=False,
  326. domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'),
  327. path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False,
  328. comment=None, comment_url=None, rest={})
  329. class ChromeCookieDecryptor:
  330. """
  331. Overview:
  332. Linux:
  333. - cookies are either v10 or v11
  334. - v10: AES-CBC encrypted with a fixed key
  335. - also attempts empty password if decryption fails
  336. - v11: AES-CBC encrypted with an OS protected key (keyring)
  337. - also attempts empty password if decryption fails
  338. - v11 keys can be stored in various places depending on the activate desktop environment [2]
  339. Mac:
  340. - cookies are either v10 or not v10
  341. - v10: AES-CBC encrypted with an OS protected key (keyring) and more key derivation iterations than linux
  342. - not v10: 'old data' stored as plaintext
  343. Windows:
  344. - cookies are either v10 or not v10
  345. - v10: AES-GCM encrypted with a key which is encrypted with DPAPI
  346. - not v10: encrypted with DPAPI
  347. Sources:
  348. - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/
  349. - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_linux.cc
  350. - KeyStorageLinux::CreateService
  351. """
  352. _cookie_counts = {}
  353. def decrypt(self, encrypted_value):
  354. raise NotImplementedError('Must be implemented by sub classes')
  355. def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None, meta_version=None):
  356. if sys.platform == 'darwin':
  357. return MacChromeCookieDecryptor(browser_keyring_name, logger, meta_version=meta_version)
  358. return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring, meta_version=meta_version)
  359. class LinuxChromeCookieDecryptor(ChromeCookieDecryptor):
  360. def __init__(self, browser_keyring_name, logger, *, keyring=None, meta_version=None):
  361. self._logger = logger
  362. self._v10_key = self.derive_key(b'peanuts')
  363. self._empty_key = self.derive_key(b'')
  364. self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0}
  365. self._browser_keyring_name = browser_keyring_name
  366. self._keyring = keyring
  367. self._meta_version = meta_version or 0
  368. @functools.cached_property
  369. def _v11_key(self):
  370. password = _get_linux_keyring_password(self._browser_keyring_name, self._keyring, self._logger)
  371. return None if password is None else self.derive_key(password)
  372. @staticmethod
  373. def derive_key(password):
  374. # values from
  375. # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_linux.cc
  376. return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1, key_length=16)
  377. def decrypt(self, encrypted_value):
  378. """
  379. following the same approach as the fix in [1]: if cookies fail to decrypt then attempt to decrypt
  380. with an empty password. The failure detection is not the same as what chromium uses so the
  381. results won't be perfect
  382. References:
  383. - [1] https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/
  384. - a bugfix to try an empty password as a fallback
  385. """
  386. version = encrypted_value[:3]
  387. ciphertext = encrypted_value[3:]
  388. if version == b'v10':
  389. self._cookie_counts['v10'] += 1
  390. return _decrypt_aes_cbc_multi(
  391. ciphertext, (self._v10_key, self._empty_key), self._logger,
  392. hash_prefix=self._meta_version >= 24)
  393. elif version == b'v11':
  394. self._cookie_counts['v11'] += 1
  395. if self._v11_key is None:
  396. self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True)
  397. return None
  398. return _decrypt_aes_cbc_multi(
  399. ciphertext, (self._v11_key, self._empty_key), self._logger,
  400. hash_prefix=self._meta_version >= 24)
  401. else:
  402. self._logger.warning(f'unknown cookie version: "{version}"', only_once=True)
  403. self._cookie_counts['other'] += 1
  404. return None
  405. class MacChromeCookieDecryptor(ChromeCookieDecryptor):
  406. def __init__(self, browser_keyring_name, logger, meta_version=None):
  407. self._logger = logger
  408. password = _get_mac_keyring_password(browser_keyring_name, logger)
  409. self._v10_key = None if password is None else self.derive_key(password)
  410. self._cookie_counts = {'v10': 0, 'other': 0}
  411. self._meta_version = meta_version or 0
  412. @staticmethod
  413. def derive_key(password):
  414. # values from
  415. # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm
  416. return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1003, key_length=16)
  417. def decrypt(self, encrypted_value):
  418. version = encrypted_value[:3]
  419. ciphertext = encrypted_value[3:]
  420. if version == b'v10':
  421. self._cookie_counts['v10'] += 1
  422. if self._v10_key is None:
  423. self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True)
  424. return None
  425. return _decrypt_aes_cbc_multi(
  426. ciphertext, (self._v10_key,), self._logger, hash_prefix=self._meta_version >= 24)
  427. else:
  428. self._cookie_counts['other'] += 1
  429. # other prefixes are considered 'old data' which were stored as plaintext
  430. # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm
  431. return encrypted_value
  432. def _extract_safari_cookies(profile, logger):
  433. if sys.platform != 'darwin':
  434. raise ValueError(f'unsupported platform: {sys.platform}')
  435. if profile:
  436. cookies_path = os.path.expanduser(profile)
  437. if not os.path.isfile(cookies_path):
  438. raise FileNotFoundError('custom safari cookies database not found')
  439. else:
  440. cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies')
  441. if not os.path.isfile(cookies_path):
  442. logger.debug('Trying secondary cookie location')
  443. cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies')
  444. if not os.path.isfile(cookies_path):
  445. raise FileNotFoundError('could not find safari cookies database')
  446. with open(cookies_path, 'rb') as f:
  447. cookies_data = f.read()
  448. jar = parse_safari_cookies(cookies_data, logger=logger)
  449. logger.info(f'Extracted {len(jar)} cookies from safari')
  450. return jar
  451. class ParserError(Exception):
  452. pass
  453. class DataParser:
  454. def __init__(self, data, logger):
  455. self._data = data
  456. self.cursor = 0
  457. self._logger = logger
  458. def read_bytes(self, num_bytes):
  459. if num_bytes < 0:
  460. raise ParserError(f'invalid read of {num_bytes} bytes')
  461. end = self.cursor + num_bytes
  462. if end > len(self._data):
  463. raise ParserError('reached end of input')
  464. data = self._data[self.cursor:end]
  465. self.cursor = end
  466. return data
  467. def expect_bytes(self, expected_value, message):
  468. value = self.read_bytes(len(expected_value))
  469. if value != expected_value:
  470. raise ParserError(f'unexpected value: {value} != {expected_value} ({message})')
  471. def read_uint(self, big_endian=False):
  472. data_format = '>I' if big_endian else '<I'
  473. return struct.unpack(data_format, self.read_bytes(4))[0]
  474. def read_double(self, big_endian=False):
  475. data_format = '>d' if big_endian else '<d'
  476. return struct.unpack(data_format, self.read_bytes(8))[0]
  477. def read_cstring(self):
  478. buffer = []
  479. while True:
  480. c = self.read_bytes(1)
  481. if c == b'\x00':
  482. return b''.join(buffer).decode()
  483. else:
  484. buffer.append(c)
  485. def skip(self, num_bytes, description='unknown'):
  486. if num_bytes > 0:
  487. self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')
  488. elif num_bytes < 0:
  489. raise ParserError(f'invalid skip of {num_bytes} bytes')
  490. def skip_to(self, offset, description='unknown'):
  491. self.skip(offset - self.cursor, description)
  492. def skip_to_end(self, description='unknown'):
  493. self.skip_to(len(self._data), description)
  494. def _mac_absolute_time_to_posix(timestamp):
  495. return int((dt.datetime(2001, 1, 1, 0, 0, tzinfo=dt.timezone.utc) + dt.timedelta(seconds=timestamp)).timestamp())
  496. def _parse_safari_cookies_header(data, logger):
  497. p = DataParser(data, logger)
  498. p.expect_bytes(b'cook', 'database signature')
  499. number_of_pages = p.read_uint(big_endian=True)
  500. page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)]
  501. return page_sizes, p.cursor
  502. def _parse_safari_cookies_page(data, jar, logger):
  503. p = DataParser(data, logger)
  504. p.expect_bytes(b'\x00\x00\x01\x00', 'page signature')
  505. number_of_cookies = p.read_uint()
  506. record_offsets = [p.read_uint() for _ in range(number_of_cookies)]
  507. if number_of_cookies == 0:
  508. logger.debug(f'a cookies page of size {len(data)} has no cookies')
  509. return
  510. p.skip_to(record_offsets[0], 'unknown page header field')
  511. with _create_progress_bar(logger) as progress_bar:
  512. for i, record_offset in enumerate(record_offsets):
  513. progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}')
  514. p.skip_to(record_offset, 'space between records')
  515. record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger)
  516. p.read_bytes(record_length)
  517. p.skip_to_end('space in between pages')
  518. def _parse_safari_cookies_record(data, jar, logger):
  519. p = DataParser(data, logger)
  520. record_size = p.read_uint()
  521. p.skip(4, 'unknown record field 1')
  522. flags = p.read_uint()
  523. is_secure = bool(flags & 0x0001)
  524. p.skip(4, 'unknown record field 2')
  525. domain_offset = p.read_uint()
  526. name_offset = p.read_uint()
  527. path_offset = p.read_uint()
  528. value_offset = p.read_uint()
  529. p.skip(8, 'unknown record field 3')
  530. expiration_date = _mac_absolute_time_to_posix(p.read_double())
  531. _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841
  532. try:
  533. p.skip_to(domain_offset)
  534. domain = p.read_cstring()
  535. p.skip_to(name_offset)
  536. name = p.read_cstring()
  537. p.skip_to(path_offset)
  538. path = p.read_cstring()
  539. p.skip_to(value_offset)
  540. value = p.read_cstring()
  541. except UnicodeDecodeError:
  542. logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True)
  543. return record_size
  544. p.skip_to(record_size, 'space at the end of the record')
  545. cookie = http.cookiejar.Cookie(
  546. version=0, name=name, value=value, port=None, port_specified=False,
  547. domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'),
  548. path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False,
  549. comment=None, comment_url=None, rest={})
  550. jar.set_cookie(cookie)
  551. return record_size
  552. def parse_safari_cookies(data, jar=None, logger=YDLLogger()):
  553. """
  554. References:
  555. - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc
  556. - this data appears to be out of date but the important parts of the database structure is the same
  557. - there are a few bytes here and there which are skipped during parsing
  558. """
  559. if jar is None:
  560. jar = YoutubeDLCookieJar()
  561. page_sizes, body_start = _parse_safari_cookies_header(data, logger)
  562. p = DataParser(data[body_start:], logger)
  563. for page_size in page_sizes:
  564. _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger)
  565. p.skip_to_end('footer')
  566. return jar
  567. class _LinuxDesktopEnvironment(Enum):
  568. """
  569. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h
  570. DesktopEnvironment
  571. """
  572. OTHER = auto()
  573. CINNAMON = auto()
  574. DEEPIN = auto()
  575. GNOME = auto()
  576. KDE3 = auto()
  577. KDE4 = auto()
  578. KDE5 = auto()
  579. KDE6 = auto()
  580. PANTHEON = auto()
  581. UKUI = auto()
  582. UNITY = auto()
  583. XFCE = auto()
  584. LXQT = auto()
  585. class _LinuxKeyring(Enum):
  586. """
  587. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.h
  588. SelectedLinuxBackend
  589. """
  590. KWALLET = auto() # KDE4
  591. KWALLET5 = auto()
  592. KWALLET6 = auto()
  593. GNOMEKEYRING = auto()
  594. BASICTEXT = auto()
  595. SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys()
  596. def _get_linux_desktop_environment(env, logger):
  597. """
  598. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc
  599. GetDesktopEnvironment
  600. """
  601. xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None)
  602. desktop_session = env.get('DESKTOP_SESSION', None)
  603. if xdg_current_desktop is not None:
  604. for part in map(str.strip, xdg_current_desktop.split(':')):
  605. if part == 'Unity':
  606. if desktop_session is not None and 'gnome-fallback' in desktop_session:
  607. return _LinuxDesktopEnvironment.GNOME
  608. else:
  609. return _LinuxDesktopEnvironment.UNITY
  610. elif part == 'Deepin':
  611. return _LinuxDesktopEnvironment.DEEPIN
  612. elif part == 'GNOME':
  613. return _LinuxDesktopEnvironment.GNOME
  614. elif part == 'X-Cinnamon':
  615. return _LinuxDesktopEnvironment.CINNAMON
  616. elif part == 'KDE':
  617. kde_version = env.get('KDE_SESSION_VERSION', None)
  618. if kde_version == '5':
  619. return _LinuxDesktopEnvironment.KDE5
  620. elif kde_version == '6':
  621. return _LinuxDesktopEnvironment.KDE6
  622. elif kde_version == '4':
  623. return _LinuxDesktopEnvironment.KDE4
  624. else:
  625. logger.info(f'unknown KDE version: "{kde_version}". Assuming KDE4')
  626. return _LinuxDesktopEnvironment.KDE4
  627. elif part == 'Pantheon':
  628. return _LinuxDesktopEnvironment.PANTHEON
  629. elif part == 'XFCE':
  630. return _LinuxDesktopEnvironment.XFCE
  631. elif part == 'UKUI':
  632. return _LinuxDesktopEnvironment.UKUI
  633. elif part == 'LXQt':
  634. return _LinuxDesktopEnvironment.LXQT
  635. logger.info(f'XDG_CURRENT_DESKTOP is set to an unknown value: "{xdg_current_desktop}"')
  636. elif desktop_session is not None:
  637. if desktop_session == 'deepin':
  638. return _LinuxDesktopEnvironment.DEEPIN
  639. elif desktop_session in ('mate', 'gnome'):
  640. return _LinuxDesktopEnvironment.GNOME
  641. elif desktop_session in ('kde4', 'kde-plasma'):
  642. return _LinuxDesktopEnvironment.KDE4
  643. elif desktop_session == 'kde':
  644. if 'KDE_SESSION_VERSION' in env:
  645. return _LinuxDesktopEnvironment.KDE4
  646. else:
  647. return _LinuxDesktopEnvironment.KDE3
  648. elif 'xfce' in desktop_session or desktop_session == 'xubuntu':
  649. return _LinuxDesktopEnvironment.XFCE
  650. elif desktop_session == 'ukui':
  651. return _LinuxDesktopEnvironment.UKUI
  652. else:
  653. logger.info(f'DESKTOP_SESSION is set to an unknown value: "{desktop_session}"')
  654. else:
  655. if 'GNOME_DESKTOP_SESSION_ID' in env:
  656. return _LinuxDesktopEnvironment.GNOME
  657. elif 'KDE_FULL_SESSION' in env:
  658. if 'KDE_SESSION_VERSION' in env:
  659. return _LinuxDesktopEnvironment.KDE4
  660. else:
  661. return _LinuxDesktopEnvironment.KDE3
  662. return _LinuxDesktopEnvironment.OTHER
  663. def _choose_linux_keyring(logger):
  664. """
  665. SelectBackend in [1]
  666. There is currently support for forcing chromium to use BASIC_TEXT by creating a file called
  667. `Disable Local Encryption` [1] in the user data dir. The function to write this file (`WriteBackendUse()` [1])
  668. does not appear to be called anywhere other than in tests, so the user would have to create this file manually
  669. and so would be aware enough to tell yt-dlp to use the BASIC_TEXT keyring.
  670. References:
  671. - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.cc
  672. """
  673. desktop_environment = _get_linux_desktop_environment(os.environ, logger)
  674. logger.debug(f'detected desktop environment: {desktop_environment.name}')
  675. if desktop_environment == _LinuxDesktopEnvironment.KDE4:
  676. linux_keyring = _LinuxKeyring.KWALLET
  677. elif desktop_environment == _LinuxDesktopEnvironment.KDE5:
  678. linux_keyring = _LinuxKeyring.KWALLET5
  679. elif desktop_environment == _LinuxDesktopEnvironment.KDE6:
  680. linux_keyring = _LinuxKeyring.KWALLET6
  681. elif desktop_environment in (
  682. _LinuxDesktopEnvironment.KDE3, _LinuxDesktopEnvironment.LXQT, _LinuxDesktopEnvironment.OTHER,
  683. ):
  684. linux_keyring = _LinuxKeyring.BASICTEXT
  685. else:
  686. linux_keyring = _LinuxKeyring.GNOMEKEYRING
  687. return linux_keyring
  688. def _get_kwallet_network_wallet(keyring, logger):
  689. """ The name of the wallet used to store network passwords.
  690. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/kwallet_dbus.cc
  691. KWalletDBus::NetworkWallet
  692. which does a dbus call to the following function:
  693. https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html
  694. Wallet::NetworkWallet
  695. """
  696. default_wallet = 'kdewallet'
  697. try:
  698. if keyring == _LinuxKeyring.KWALLET:
  699. service_name = 'org.kde.kwalletd'
  700. wallet_path = '/modules/kwalletd'
  701. elif keyring == _LinuxKeyring.KWALLET5:
  702. service_name = 'org.kde.kwalletd5'
  703. wallet_path = '/modules/kwalletd5'
  704. elif keyring == _LinuxKeyring.KWALLET6:
  705. service_name = 'org.kde.kwalletd6'
  706. wallet_path = '/modules/kwalletd6'
  707. else:
  708. raise ValueError(keyring)
  709. stdout, _, returncode = Popen.run([
  710. 'dbus-send', '--session', '--print-reply=literal',
  711. f'--dest={service_name}',
  712. wallet_path,
  713. 'org.kde.KWallet.networkWallet',
  714. ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  715. if returncode:
  716. logger.warning('failed to read NetworkWallet')
  717. return default_wallet
  718. else:
  719. logger.debug(f'NetworkWallet = "{stdout.strip()}"')
  720. return stdout.strip()
  721. except Exception as e:
  722. logger.warning(f'exception while obtaining NetworkWallet: {e}')
  723. return default_wallet
  724. def _get_kwallet_password(browser_keyring_name, keyring, logger):
  725. logger.debug(f'using kwallet-query to obtain password from {keyring.name}')
  726. if shutil.which('kwallet-query') is None:
  727. logger.error('kwallet-query command not found. KWallet and kwallet-query '
  728. 'must be installed to read from KWallet. kwallet-query should be'
  729. 'included in the kwallet package for your distribution')
  730. return b''
  731. network_wallet = _get_kwallet_network_wallet(keyring, logger)
  732. try:
  733. stdout, _, returncode = Popen.run([
  734. 'kwallet-query',
  735. '--read-password', f'{browser_keyring_name} Safe Storage',
  736. '--folder', f'{browser_keyring_name} Keys',
  737. network_wallet,
  738. ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  739. if returncode:
  740. logger.error(f'kwallet-query failed with return code {returncode}. '
  741. 'Please consult the kwallet-query man page for details')
  742. return b''
  743. else:
  744. if stdout.lower().startswith(b'failed to read'):
  745. logger.debug('failed to read password from kwallet. Using empty string instead')
  746. # this sometimes occurs in KDE because chrome does not check hasEntry and instead
  747. # just tries to read the value (which kwallet returns "") whereas kwallet-query
  748. # checks hasEntry. To verify this:
  749. # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
  750. # while starting chrome.
  751. # this was identified as a bug later and fixed in
  752. # https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/#F0
  753. # https://chromium.googlesource.com/chromium/src/+/5463af3c39d7f5b6d11db7fbd51e38cc1974d764
  754. return b''
  755. else:
  756. logger.debug('password found')
  757. return stdout.rstrip(b'\n')
  758. except Exception as e:
  759. logger.warning(f'exception running kwallet-query: {error_to_str(e)}')
  760. return b''
  761. def _get_gnome_keyring_password(browser_keyring_name, logger):
  762. if not secretstorage:
  763. logger.error(f'secretstorage not available {_SECRETSTORAGE_UNAVAILABLE_REASON}')
  764. return b''
  765. # the Gnome keyring does not seem to organise keys in the same way as KWallet,
  766. # using `dbus-monitor` during startup, it can be observed that chromium lists all keys
  767. # and presumably searches for its key in the list. It appears that we must do the same.
  768. # https://github.com/jaraco/keyring/issues/556
  769. with contextlib.closing(secretstorage.dbus_init()) as con:
  770. col = secretstorage.get_default_collection(con)
  771. for item in col.get_all_items():
  772. if item.get_label() == f'{browser_keyring_name} Safe Storage':
  773. return item.get_secret()
  774. logger.error('failed to read from keyring')
  775. return b''
  776. def _get_linux_keyring_password(browser_keyring_name, keyring, logger):
  777. # note: chrome/chromium can be run with the following flags to determine which keyring backend
  778. # it has chosen to use
  779. # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_
  780. # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection
  781. # will not be sufficient in all cases.
  782. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger)
  783. logger.debug(f'Chosen keyring: {keyring.name}')
  784. if keyring in (_LinuxKeyring.KWALLET, _LinuxKeyring.KWALLET5, _LinuxKeyring.KWALLET6):
  785. return _get_kwallet_password(browser_keyring_name, keyring, logger)
  786. elif keyring == _LinuxKeyring.GNOMEKEYRING:
  787. return _get_gnome_keyring_password(browser_keyring_name, logger)
  788. elif keyring == _LinuxKeyring.BASICTEXT:
  789. # when basic text is chosen, all cookies are stored as v10 (so no keyring password is required)
  790. return None
  791. assert False, f'Unknown keyring {keyring}'
  792. def _get_mac_keyring_password(browser_keyring_name, logger):
  793. logger.debug('using find-generic-password to obtain password from OSX keychain')
  794. try:
  795. stdout, _, returncode = Popen.run(
  796. ['security', 'find-generic-password',
  797. '-w', # write password to stdout
  798. '-a', browser_keyring_name, # match 'account'
  799. '-s', f'{browser_keyring_name} Safe Storage'], # match 'service'
  800. stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  801. if returncode:
  802. logger.warning('find-generic-password failed')
  803. return None
  804. return stdout.rstrip(b'\n')
  805. except Exception as e:
  806. logger.warning(f'exception running find-generic-password: {error_to_str(e)}')
  807. return None
  808. def pbkdf2_sha1(password, salt, iterations, key_length):
  809. return hashlib.pbkdf2_hmac('sha1', password, salt, iterations, key_length)
  810. def _decrypt_aes_cbc_multi(ciphertext, keys, logger, initialization_vector=b' ' * 16, hash_prefix=False):
  811. for key in keys:
  812. plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector))
  813. try:
  814. if hash_prefix:
  815. return plaintext[32:].decode()
  816. return plaintext.decode()
  817. except UnicodeDecodeError:
  818. pass
  819. logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)
  820. return None
  821. def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger, hash_prefix=False):
  822. try:
  823. plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce)
  824. except ValueError:
  825. logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once=True)
  826. return None
  827. try:
  828. if hash_prefix:
  829. return plaintext[32:].decode()
  830. return plaintext.decode()
  831. except UnicodeDecodeError:
  832. logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)
  833. return None
  834. def _config_home():
  835. return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
  836. def _open_database_copy(database_path, tmpdir):
  837. # cannot open sqlite databases if they are already in use (e.g. by the browser)
  838. database_copy_path = os.path.join(tmpdir, 'temporary.sqlite')
  839. shutil.copy(database_path, database_copy_path)
  840. conn = sqlite3.connect(database_copy_path)
  841. return conn.cursor()
  842. def _get_column_names(cursor, table_name):
  843. table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall()
  844. return [row[1].decode() for row in table_info]
  845. def _newest(files):
  846. return max(files, key=lambda path: os.lstat(path).st_mtime, default=None)
  847. def _find_files(root, filename, logger):
  848. # if there are multiple browser profiles, take the most recently used one
  849. i = 0
  850. with _create_progress_bar(logger) as progress_bar:
  851. for curr_root, _, files in os.walk(root):
  852. for file in files:
  853. i += 1
  854. progress_bar.print(f'Searching for "{filename}": {i: 6d} files searched')
  855. if file == filename:
  856. yield os.path.join(curr_root, file)
  857. def _merge_cookie_jars(jars):
  858. output_jar = YoutubeDLCookieJar()
  859. for jar in jars:
  860. for cookie in jar:
  861. output_jar.set_cookie(cookie)
  862. if jar.filename is not None:
  863. output_jar.filename = jar.filename
  864. return output_jar
  865. def _is_path(value):
  866. return any(sep in value for sep in (os.path.sep, os.path.altsep) if sep)
  867. def _parse_browser_specification(browser_name, profile=None, keyring=None, container=None):
  868. if browser_name not in SUPPORTED_BROWSERS:
  869. raise ValueError(f'unsupported browser: "{browser_name}"')
  870. if keyring not in (None, *SUPPORTED_KEYRINGS):
  871. raise ValueError(f'unsupported keyring: "{keyring}"')
  872. if profile is not None and _is_path(expand_path(profile)):
  873. profile = expand_path(profile)
  874. return browser_name, profile, keyring, container
  875. class LenientSimpleCookie(http.cookies.SimpleCookie):
  876. """More lenient version of http.cookies.SimpleCookie"""
  877. # From https://github.com/python/cpython/blob/v3.10.7/Lib/http/cookies.py
  878. # We use Morsel's legal key chars to avoid errors on setting values
  879. _LEGAL_KEY_CHARS = r'\w\d' + re.escape('!#$%&\'*+-.:^_`|~')
  880. _LEGAL_VALUE_CHARS = _LEGAL_KEY_CHARS + re.escape('(),/<=>?@[]{}')
  881. _RESERVED = {
  882. 'expires',
  883. 'path',
  884. 'comment',
  885. 'domain',
  886. 'max-age',
  887. 'secure',
  888. 'httponly',
  889. 'version',
  890. 'samesite',
  891. }
  892. _FLAGS = {'secure', 'httponly'}
  893. # Added 'bad' group to catch the remaining value
  894. _COOKIE_PATTERN = re.compile(r'''
  895. \s* # Optional whitespace at start of cookie
  896. (?P<key> # Start of group 'key'
  897. [''' + _LEGAL_KEY_CHARS + r''']+?# Any word of at least one letter
  898. ) # End of group 'key'
  899. ( # Optional group: there may not be a value.
  900. \s*=\s* # Equal Sign
  901. ( # Start of potential value
  902. (?P<val> # Start of group 'val'
  903. "(?:[^\\"]|\\.)*" # Any doublequoted string
  904. | # or
  905. \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr
  906. | # or
  907. [''' + _LEGAL_VALUE_CHARS + r''']* # Any word or empty string
  908. ) # End of group 'val'
  909. | # or
  910. (?P<bad>(?:\\;|[^;])*?) # 'bad' group fallback for invalid values
  911. ) # End of potential value
  912. )? # End of optional value group
  913. \s* # Any number of spaces.
  914. (\s+|;|$) # Ending either at space, semicolon, or EOS.
  915. ''', re.ASCII | re.VERBOSE)
  916. def load(self, data):
  917. # Workaround for https://github.com/yt-dlp/yt-dlp/issues/4776
  918. if not isinstance(data, str):
  919. return super().load(data)
  920. morsel = None
  921. for match in self._COOKIE_PATTERN.finditer(data):
  922. if match.group('bad'):
  923. morsel = None
  924. continue
  925. key, value = match.group('key', 'val')
  926. is_attribute = False
  927. if key.startswith('$'):
  928. key = key[1:]
  929. is_attribute = True
  930. lower_key = key.lower()
  931. if lower_key in self._RESERVED:
  932. if morsel is None:
  933. continue
  934. if value is None:
  935. if lower_key not in self._FLAGS:
  936. morsel = None
  937. continue
  938. value = True
  939. else:
  940. value, _ = self.value_decode(value)
  941. morsel[key] = value
  942. elif is_attribute:
  943. morsel = None
  944. elif value is not None:
  945. morsel = self.get(key, http.cookies.Morsel())
  946. real_value, coded_value = self.value_decode(value)
  947. morsel.set(key, real_value, coded_value)
  948. self[key] = morsel
  949. else:
  950. morsel = None
  951. class YoutubeDLCookieJar(http.cookiejar.MozillaCookieJar):
  952. """
  953. See [1] for cookie file format.
  954. 1. https://curl.haxx.se/docs/http-cookies.html
  955. """
  956. _HTTPONLY_PREFIX = '#HttpOnly_'
  957. _ENTRY_LEN = 7
  958. _HEADER = '''# Netscape HTTP Cookie File
  959. # This file is generated by yt-dlp. Do not edit.
  960. '''
  961. _CookieFileEntry = collections.namedtuple(
  962. 'CookieFileEntry',
  963. ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
  964. def __init__(self, filename=None, *args, **kwargs):
  965. super().__init__(None, *args, **kwargs)
  966. if is_path_like(filename):
  967. filename = os.fspath(filename)
  968. self.filename = filename
  969. @staticmethod
  970. def _true_or_false(cndn):
  971. return 'TRUE' if cndn else 'FALSE'
  972. @contextlib.contextmanager
  973. def open(self, file, *, write=False):
  974. if is_path_like(file):
  975. with open(file, 'w' if write else 'r', encoding='utf-8') as f:
  976. yield f
  977. else:
  978. if write:
  979. file.truncate(0)
  980. yield file
  981. def _really_save(self, f, ignore_discard, ignore_expires):
  982. now = time.time()
  983. for cookie in self:
  984. if ((not ignore_discard and cookie.discard)
  985. or (not ignore_expires and cookie.is_expired(now))):
  986. continue
  987. name, value = cookie.name, cookie.value
  988. if value is None:
  989. # cookies.txt regards 'Set-Cookie: foo' as a cookie
  990. # with no name, whereas http.cookiejar regards it as a
  991. # cookie with no value.
  992. name, value = '', name
  993. f.write('{}\n'.format('\t'.join((
  994. cookie.domain,
  995. self._true_or_false(cookie.domain.startswith('.')),
  996. cookie.path,
  997. self._true_or_false(cookie.secure),
  998. str_or_none(cookie.expires, default=''),
  999. name, value,
  1000. ))))
  1001. def save(self, filename=None, ignore_discard=True, ignore_expires=True):
  1002. """
  1003. Save cookies to a file.
  1004. Code is taken from CPython 3.6
  1005. https://github.com/python/cpython/blob/8d999cbf4adea053be6dbb612b9844635c4dfb8e/Lib/http/cookiejar.py#L2091-L2117 """
  1006. if filename is None:
  1007. if self.filename is not None:
  1008. filename = self.filename
  1009. else:
  1010. raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
  1011. # Store session cookies with `expires` set to 0 instead of an empty string
  1012. for cookie in self:
  1013. if cookie.expires is None:
  1014. cookie.expires = 0
  1015. with self.open(filename, write=True) as f:
  1016. f.write(self._HEADER)
  1017. self._really_save(f, ignore_discard, ignore_expires)
  1018. def load(self, filename=None, ignore_discard=True, ignore_expires=True):
  1019. """Load cookies from a file."""
  1020. if filename is None:
  1021. if self.filename is not None:
  1022. filename = self.filename
  1023. else:
  1024. raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
  1025. def prepare_line(line):
  1026. if line.startswith(self._HTTPONLY_PREFIX):
  1027. line = line[len(self._HTTPONLY_PREFIX):]
  1028. # comments and empty lines are fine
  1029. if line.startswith('#') or not line.strip():
  1030. return line
  1031. cookie_list = line.split('\t')
  1032. if len(cookie_list) != self._ENTRY_LEN:
  1033. raise http.cookiejar.LoadError(f'invalid length {len(cookie_list)}')
  1034. cookie = self._CookieFileEntry(*cookie_list)
  1035. if cookie.expires_at and not cookie.expires_at.isdigit():
  1036. raise http.cookiejar.LoadError(f'invalid expires at {cookie.expires_at}')
  1037. return line
  1038. cf = io.StringIO()
  1039. with self.open(filename) as f:
  1040. for line in f:
  1041. try:
  1042. cf.write(prepare_line(line))
  1043. except http.cookiejar.LoadError as e:
  1044. if f'{line.strip()} '[0] in '[{"':
  1045. raise http.cookiejar.LoadError(
  1046. 'Cookies file must be Netscape formatted, not JSON. See '
  1047. 'https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp')
  1048. write_string(f'WARNING: skipping cookie file entry due to {e}: {line!r}\n')
  1049. continue
  1050. cf.seek(0)
  1051. self._really_load(cf, filename, ignore_discard, ignore_expires)
  1052. # Session cookies are denoted by either `expires` field set to
  1053. # an empty string or 0. MozillaCookieJar only recognizes the former
  1054. # (see [1]). So we need force the latter to be recognized as session
  1055. # cookies on our own.
  1056. # Session cookies may be important for cookies-based authentication,
  1057. # e.g. usually, when user does not check 'Remember me' check box while
  1058. # logging in on a site, some important cookies are stored as session
  1059. # cookies so that not recognizing them will result in failed login.
  1060. # 1. https://bugs.python.org/issue17164
  1061. for cookie in self:
  1062. # Treat `expires=0` cookies as session cookies
  1063. if cookie.expires == 0:
  1064. cookie.expires = None
  1065. cookie.discard = True
  1066. def get_cookie_header(self, url):
  1067. """Generate a Cookie HTTP header for a given url"""
  1068. cookie_req = urllib.request.Request(normalize_url(sanitize_url(url)))
  1069. self.add_cookie_header(cookie_req)
  1070. return cookie_req.get_header('Cookie')
  1071. def get_cookies_for_url(self, url):
  1072. """Generate a list of Cookie objects for a given url"""
  1073. # Policy `_now` attribute must be set before calling `_cookies_for_request`
  1074. # Ref: https://github.com/python/cpython/blob/3.7/Lib/http/cookiejar.py#L1360
  1075. self._policy._now = self._now = int(time.time())
  1076. return self._cookies_for_request(urllib.request.Request(normalize_url(sanitize_url(url))))
  1077. def clear(self, *args, **kwargs):
  1078. with contextlib.suppress(KeyError):
  1079. return super().clear(*args, **kwargs)