The little things give you away... A collection of various small helper stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

553 lines
20 KiB

  1. #!/usr/bin/env python3
  2. # Tiny tool for WARC stuff.
  3. # Operating modes:
  4. # warc-tiny colour FILES -- coloured output of the WARCs for easier reading
  5. # warc-tiny dump-responses [-m|--meta] FILES -- dump the HTTP response bodies to stdout
  6. # With --meta, prefix every line with the filename, record offset, record ID, and target URI; e.g. 'file.warc.gz:123:<urn:uuid:41b76f1f-f946-4723-91f8-cee6491e92f3>:<https://example.org/>: foobar'
  7. # The record offset may be -1 if it is not known.
  8. # The filename is wrapped in angled brackets if it contains a colon; the target URI is always wrapped in angled brackets (since it virtually always contains a colon).
  9. # warc-tiny scrape [-u|--urls] FILES -- extract all links and page requisites from the records; produces lines of filename, record offset, record URI, link type, inline flag, and URL as JSONL
  10. # With --urls, only the URL is printed.
  11. # wpull's scrapers are used for the extraction.
  12. # warc-tiny verify FILES -- verify the integrity of a WARC by comparing the digests
  13. import base64
  14. import contextlib
  15. import enum
  16. import gzip
  17. import hashlib
  18. import json
  19. import sys
  20. import tempfile
  21. import zlib
  22. try:
  23. import wpull.body
  24. import wpull.document.htmlparse.lxml_
  25. try:
  26. import wpull.protocol.http.request as wpull_protocol_http_request # wpull 2.x
  27. except ImportError:
  28. import wpull.http.request as wpull_protocol_http_request # wpull 1.x
  29. import wpull.scraper.base
  30. import wpull.scraper.css
  31. import wpull.scraper.html
  32. import wpull.scraper.javascript
  33. import wpull.scraper.sitemap
  34. except ImportError:
  35. wpull = None
  36. def GzipDecompressor():
  37. return zlib.decompressobj(16 + zlib.MAX_WBITS)
  38. class DummyDecompressor:
  39. def decompress(self, data):
  40. return data
  41. class Event:
  42. pass
  43. class NewFile(Event):
  44. def __init__(self, filename):
  45. self._filename = filename
  46. @property
  47. def filename(self):
  48. return self._filename
  49. class BeginOfRecord(Event):
  50. def __init__(self, warcHeaders, rawData):
  51. self._warcHeaders = warcHeaders
  52. self._rawData = rawData
  53. @property
  54. def warcHeaders(self):
  55. return self._warcHeaders
  56. @property
  57. def rawData(self):
  58. return self._rawData
  59. class HTTPHeaders(Event):
  60. def __init__(self, headers):
  61. self._headers = headers
  62. @property
  63. def headers(self):
  64. return self._headers
  65. class _DataChunk(Event):
  66. def __init__(self, data):
  67. self._data = data
  68. @property
  69. def data(self):
  70. return self._data
  71. def __repr__(self):
  72. return '{}({!r}{})'.format(type(self).__name__, self._data[:50], '...' if len(self._data) > 50 else '')
  73. class WARCBlockChunk(_DataChunk):
  74. def __init__(self, data, isHttpHeader = None):
  75. super().__init__(data)
  76. self._isHttpHeader = isHttpHeader
  77. @property
  78. def isHttpHeader(self):
  79. # True: the chunk represents (part of) the HTTP header; False: the chunk represents (part of) the HTTP body; None: the chunk is not part of an HTTP record
  80. return self._isHttpHeader
  81. class RawHTTPBodyChunk(_DataChunk):
  82. '''
  83. Because many tools misunderstood the WARC specifications, the Payload-Digest was often implemented without stripping transfer encoding.
  84. This is like HTTPBodyChunk but without transfer encoding stripping.
  85. '''
  86. class HTTPBodyChunk(_DataChunk):
  87. '''
  88. Representing a part of the HTTP body with transfer encoding stripped.
  89. '''
  90. class EndOfRecord(Event):
  91. pass
  92. @contextlib.contextmanager
  93. def open_warc(f):
  94. if hasattr(f, 'read'):
  95. yield f
  96. else:
  97. with open(f, 'rb') as fp:
  98. yield fp
  99. def iter_warc(f):
  100. # Yields Events
  101. # BeginOfRecord's rawData does not include the CRLF CRLF at the end of the headers, and WARCBlockChunk does not contain the CRLF CRLF after the block either.
  102. with open_warc(f) as fp:
  103. buf = b''
  104. while True:
  105. # Read WARC header
  106. while b'\r\n\r\n' not in buf:
  107. try:
  108. buf = buf + fp.read(4096)
  109. except EOFError:
  110. break
  111. if not buf:
  112. break
  113. if not buf:
  114. break
  115. warcHeaderBuf, buf = buf.split(b'\r\n\r\n', 1)
  116. assert warcHeaderBuf.startswith(b'WARC/1.0\r\n') or warcHeaderBuf.startswith(b'WARC/1.1\r\n')
  117. assert b'\r\nContent-Length:' in warcHeaderBuf
  118. warcHeaders = tuple(tuple(map(bytes.strip, x.split(b':', 1))) for x in warcHeaderBuf.split(b'\r\n'))
  119. warcContentType = next(x[1] for x in warcHeaders if x[0] == b'Content-Type')
  120. warcContentLength = int(next(x[1] for x in warcHeaders if x[0] == b'Content-Length'))
  121. warcType = next(x[1] for x in warcHeaders if x[0] == b'WARC-Type')
  122. yield BeginOfRecord(warcHeaders, warcHeaderBuf)
  123. recordID = next(x[1] for x in warcHeaders if x[0] == b'WARC-Record-ID')
  124. # Read WARC block (and skip CRLFCRLF at the end of the record)
  125. if len(buf) < warcContentLength + 4:
  126. try:
  127. buf = buf + fp.read(warcContentLength + 4 - len(buf))
  128. except EOFError:
  129. pass
  130. if len(buf) < warcContentLength + 4:
  131. print('Error: truncated WARC', file = sys.stderr)
  132. break
  133. warcContent = buf[:warcContentLength]
  134. buf = buf[warcContentLength + 4:]
  135. # Decode HTTP body if appropriate
  136. if warcContentType in (b'application/http;msgtype=request', b'application/http; msgtype=request') and warcType == b'request':
  137. httpType = 'request'
  138. elif warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response':
  139. httpType = 'response'
  140. else:
  141. httpType = None
  142. if httpType is not None:
  143. if b'\r\n\r\n' in warcContent:
  144. httpHeaders, httpBody = warcContent.split(b'\r\n\r\n', 1)
  145. # Parse headers and extract transfer encoding
  146. httpHeaderLines = [tuple(map(bytes.strip, x.split(b':', 1))) for x in httpHeaders.split(b'\r\n')]
  147. chunked = False
  148. gzipped = False
  149. if b'\r\ntransfer-encoding' in httpHeaders.lower():
  150. transferEncoding = next(x[1] for x in httpHeaderLines if x[0].lower() == b'transfer-encoding')
  151. transferEncodings = set(map(bytes.strip, transferEncoding.split(b',')))
  152. chunked = b'chunked' in transferEncodings
  153. gzipped = b'gzip' in transferEncodings
  154. yield WARCBlockChunk(httpHeaders + b'\r\n\r\n', isHttpHeader = True)
  155. yield HTTPHeaders(httpHeaderLines)
  156. yield WARCBlockChunk(httpBody, isHttpHeader = False)
  157. yield RawHTTPBodyChunk(httpBody)
  158. # Decode body
  159. if gzipped:
  160. httpDecompressor = GzipDecompressor()
  161. else:
  162. httpDecompressor = DummyDecompressor()
  163. if chunked:
  164. pos = 0
  165. while True:
  166. try:
  167. chunkLineEnd = httpBody.index(b'\r\n', pos)
  168. except ValueError:
  169. print('Error: could not find chunk line end in record {}, skipping'.format(recordID), file = sys.stderr)
  170. break
  171. chunkLine = httpBody[pos:chunkLineEnd]
  172. if b';' in chunkLine:
  173. chunkLength = chunkLine[:chunkLine.index(b';')].strip()
  174. else:
  175. chunkLength = chunkLine.strip()
  176. if chunkLength.lstrip(b'0123456789abcdefABCDEF') != b'':
  177. print('Error: malformed chunk length {!r} in record {}, skipping'.format(chunkLength, recordID), file = sys.stderr)
  178. break
  179. chunkLength = int(chunkLength, base = 16)
  180. if chunkLength == 0:
  181. break
  182. chunk = httpDecompressor.decompress(httpBody[chunkLineEnd + 2 : chunkLineEnd + 2 + chunkLength])
  183. yield HTTPBodyChunk(chunk)
  184. pos = chunkLineEnd + 2 + chunkLength + 2
  185. else:
  186. yield HTTPBodyChunk(httpDecompressor.decompress(httpBody))
  187. else:
  188. print('Warning: malformed HTTP request or response in record {}, skipping'.format(recordID), file = sys.stderr)
  189. yield WARCBlockChunk(warcContent)
  190. else:
  191. yield WARCBlockChunk(warcContent)
  192. yield EndOfRecord()
  193. class ProcessMode:
  194. @classmethod
  195. def split_args(cls, args):
  196. '''Split args into arguments to be passed into __init__ and filenames'''
  197. return (), args
  198. def process_event(self, event):
  199. raise NotImplementedError
  200. class Digest:
  201. def __init__(self, digest):
  202. self._digest = digest
  203. def format(self, digest = None):
  204. raise NotImplementedError
  205. def equals(self, digest):
  206. return self._digest == digest
  207. class Base32Digest(Digest):
  208. def format(self, digest = None):
  209. return base64.b32encode(digest if digest else self._digest)
  210. class HexDigest(Digest):
  211. def format(self, digest = None):
  212. return (digest if digest else self._digest).hex()
  213. class VerifyMode(ProcessMode):
  214. def __init__(self):
  215. self._blockDigester = None
  216. self._recordedBlockDigest = None
  217. self._payloadDigester = None
  218. self._brokenPayloadDigester = None
  219. self._recordedPayloadDigest = None
  220. self._printedBrokenPayloadWarning = False
  221. def parse_digest(self, digest):
  222. if not digest.startswith(b'sha1:'):
  223. print('Warning: don\'t understand hash format: {!r}'.format(digest), file = sys.stderr)
  224. return None
  225. if len(digest) == 37 and digest.rstrip(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567') == b'sha1:': # 5 for 'sha1:' + 32 for base-32 hash
  226. return Base32Digest(base64.b32decode(digest[5:]))
  227. if len(digest) == 45 and digest.rstrip(b'0123456789abcdef') == b'sha1:':
  228. return HexDigest(bytes.fromhex(digest[5:].decode('ascii')))
  229. return None
  230. def process_event(self, event):
  231. if type(event) is NewFile:
  232. self._printedBrokenPayloadWarning = False
  233. elif type(event) is BeginOfRecord:
  234. if any(x[0] == b'WARC-Block-Digest' for x in event.warcHeaders):
  235. self._blockDigester = hashlib.sha1()
  236. self._recordedBlockDigest = self.parse_digest(next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Block-Digest'))
  237. else:
  238. self._blockDigester = None
  239. self._recordedBlockDigest = None
  240. if any(x[0] == b'WARC-Payload-Digest' for x in event.warcHeaders):
  241. self._payloadDigester = hashlib.sha1()
  242. self._brokenPayloadDigester = hashlib.sha1()
  243. self._recordedPayloadDigest = self.parse_digest(next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Payload-Digest'))
  244. else:
  245. self._payloadDigester = None
  246. self._brokenPayloadDigester = None
  247. self._recordedPayloadDigest = None
  248. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID')
  249. self._recordType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  250. elif type(event) is WARCBlockChunk:
  251. if self._blockDigester:
  252. self._blockDigester.update(event.data)
  253. elif type(event) is HTTPBodyChunk:
  254. if self._payloadDigester:
  255. self._payloadDigester.update(event.data)
  256. elif type(event) is RawHTTPBodyChunk:
  257. if self._brokenPayloadDigester:
  258. self._brokenPayloadDigester.update(event.data)
  259. elif type(event) is EndOfRecord:
  260. if self._blockDigester and self._recordedBlockDigest:
  261. if not self._recordedBlockDigest.equals(self._blockDigester.digest()):
  262. print('Block digest mismatch for record {}: recorded {} v calculated {}'.format(self._recordID, self._recordedBlockDigest.format(), self._recordedBlockDigest.format(self._blockDigester.digest())), file = sys.stderr)
  263. if self._payloadDigester and self._recordType in (b'request', b'response'): #TODO: Support revisit
  264. if not self._recordedPayloadDigest.equals(self._payloadDigester.digest()):
  265. if self._recordedPayloadDigest.equals(self._brokenPayloadDigester.digest()):
  266. if not self._printedBrokenPayloadWarning:
  267. print('Warning: WARC uses incorrect payload digests without stripping the transfer encoding', file = sys.stderr)
  268. self._printedBrokenPayloadWarning = True
  269. else:
  270. print('Payload digest mismatch for record {}: recorded {} vs. calculated {} (calculated broken {})'.format(self._recordID, self._recordedPayloadDigest.format(), self._recordedPayloadDigest.format(self._payloadDigester.digest()), self._recordedPayloadDigest.format(self._brokenPayloadDigester.digest())), file = sys.stderr)
  271. class DumpResponsesMode(ProcessMode):
  272. @classmethod
  273. def split_args(cls, args):
  274. if args[0] == '-m' or args[0] == '--meta':
  275. return (True,), args[1:]
  276. return (False,), args
  277. def __init__(self, withMeta):
  278. self._printEOR = False
  279. self._isResponse = False
  280. self._withMeta = withMeta
  281. if withMeta:
  282. self._recordID = None
  283. self._targetURI = None
  284. self._buffer = b''
  285. def _write(self, data):
  286. if not self._withMeta:
  287. sys.stdout.buffer.write(data)
  288. return
  289. buf = self._buffer + data
  290. lines = buf.split(b'\n')
  291. self._buffer = lines.pop() # Since there's an explicit `_write(b'\r\n')` at the end of the record, this implicitly resets the buffer as well
  292. for line in lines:
  293. sys.stdout.buffer.write(':'.join((self._filename, '-1', self._recordID, '<' + self._targetURI + '>', '')).encode('utf-8'))
  294. sys.stdout.buffer.write(line)
  295. sys.stdout.buffer.write(b'\n')
  296. def process_event(self, event):
  297. if type(event) is NewFile:
  298. self._filename = event.filename
  299. if ':' in self._filename:
  300. self._filename = '<' + self._filename + '>'
  301. elif type(event) is BeginOfRecord:
  302. warcContentType = next(x[1] for x in event.warcHeaders if x[0] == b'Content-Type')
  303. warcType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  304. self._isResponse = warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response'
  305. self._printEOR = False
  306. if self._withMeta:
  307. # Both of these are URIs, and per RFC 3986, those can only contain ASCII characters.
  308. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID').decode('ascii')
  309. self._targetURI = next((x[1] for x in event.warcHeaders if x[0] == b'WARC-Target-URI'), b'').decode('ascii')
  310. self._buffer = b''
  311. elif type(event) is HTTPBodyChunk:
  312. if self._isResponse:
  313. self._printEOR = True
  314. self._write(event.data)
  315. elif type(event) is EndOfRecord:
  316. if self._printEOR:
  317. self._write(b'\r\n')
  318. class COLOURS:
  319. RESET = b'\x1b[0m'
  320. GREEN = b'\x1b[0;32m'
  321. LIGHTGREEN = b'\x1b[1;32m'
  322. PURPLE = b'\x1b[0;35m'
  323. LIGHTPURPLE = b'\x1b[1;35m'
  324. RED = b'\x1b[0;31m'
  325. INVERTED = b'\x1b[7m'
  326. class ColourMode(ProcessMode):
  327. def __init__(self):
  328. self._hadHttpStatusLine = False
  329. def _replace_esc(self, data):
  330. return data.replace(b'\x1b', COLOURS.INVERTED + b'ESC' + COLOURS.RESET)
  331. def _print_line(self, line, colour, withLF = True, colourOnlyBeforeColon = False):
  332. if colourOnlyBeforeColon:
  333. if b':' in line:
  334. offset = line.index(b':')
  335. else:
  336. offset = 0
  337. else:
  338. offset = len(line)
  339. if offset > 0:
  340. sys.stdout.buffer.write(colour)
  341. sys.stdout.buffer.write(self._replace_esc(line[:offset]))
  342. sys.stdout.buffer.write(COLOURS.RESET)
  343. sys.stdout.buffer.write(line[offset:])
  344. if withLF:
  345. sys.stdout.buffer.write(b'\n')
  346. def _print_data(self, data, colour, colourOnlyBeforeColon):
  347. later = False
  348. for line in data.split(b'\r\n'):
  349. if later:
  350. sys.stdout.buffer.write(b'\n')
  351. self._print_line(line, colour, withLF = False, colourOnlyBeforeColon = colourOnlyBeforeColon)
  352. later = True
  353. def process_event(self, event):
  354. if type(event) is BeginOfRecord:
  355. firstNewline = event.rawData.index(b'\r\n')
  356. self._print_line(event.rawData[:firstNewline], COLOURS.LIGHTGREEN)
  357. self._print_data(event.rawData[firstNewline + 2:], COLOURS.GREEN, True)
  358. sys.stdout.buffer.write(b'\n\n') # separator between header and block
  359. self._hadHttpStatusLine = False
  360. elif type(event) is WARCBlockChunk:
  361. if event.isHttpHeader is True:
  362. if not self._hadHttpStatusLine:
  363. firstNewline = event.data.index(b'\r\n')
  364. self._print_line(event.data[:firstNewline], COLOURS.LIGHTPURPLE)
  365. offset = firstNewline + 2
  366. self._hadHttpStatusLine = True
  367. else:
  368. offset = 0
  369. self._print_data(event.data[offset:], COLOURS.PURPLE, True)
  370. elif event.isHttpHeader is False:
  371. self._print_data(event.data, COLOURS.RED, False)
  372. elif event.isHttpHeader is None:
  373. sys.stdout.buffer.write(self._replace_esc(event.data))
  374. elif type(event) is EndOfRecord:
  375. sys.stdout.buffer.write(b'\n\n')
  376. class ScrapeMode(ProcessMode):
  377. @classmethod
  378. def split_args(cls, args):
  379. if args[0] == '-u' or args[0] == '--urls':
  380. return (True,), args[1:]
  381. return (False,), args
  382. def __init__(self, urlsOnly):
  383. self._urlsOnly = urlsOnly
  384. assert wpull is not None, 'Scrape mode requires wpull and lxml'
  385. htmlParser = wpull.document.htmlparse.lxml_.HTMLParser()
  386. elementWalker = wpull.scraper.html.ElementWalker()
  387. scrapers = []
  388. scrapers.append(wpull.scraper.html.HTMLScraper(htmlParser, elementWalker))
  389. scrapers.append(wpull.scraper.css.CSSScraper())
  390. elementWalker.css_scraper = scrapers[-1]
  391. scrapers.append(wpull.scraper.javascript.JavaScriptScraper())
  392. elementWalker.javascript_scraper = scrapers[-1]
  393. scrapers.append(wpull.scraper.sitemap.SitemapScraper(htmlParser))
  394. self._scraper = wpull.scraper.base.DemuxDocumentScraper(scrapers)
  395. self._isResponse = None
  396. self._body = None
  397. self._recordURI = None
  398. self._statusCode = None
  399. self._statusReason = None
  400. if not self._urlsOnly:
  401. self._filename = None
  402. self._recordID = None
  403. def process_event(self, event):
  404. if type(event) is NewFile and not self._urlsOnly:
  405. self._filename = event.filename
  406. elif type(event) is BeginOfRecord:
  407. warcContentType = next(x[1] for x in event.warcHeaders if x[0] == b'Content-Type')
  408. warcType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  409. self._isResponse = warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response'
  410. if self._isResponse:
  411. self._body = wpull.body.Body(file = tempfile.SpooledTemporaryFile(max_size = 10485760)) # Up to 10 MiB in memory
  412. self._printEOR = False
  413. if not self._urlsOnly:
  414. # Both of these are URIs, and per RFC 3986, those can only contain ASCII characters.
  415. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID').decode('ascii')
  416. self._recordURI = next((x[1] for x in event.warcHeaders if x[0] == b'WARC-Target-URI'), b'').decode('ascii')
  417. elif type(event) is HTTPHeaders and self._isResponse:
  418. assert len(event.headers[0]) == 1 and event.headers[0][0].startswith(b'HTTP/'), 'malformed HTTP response'
  419. _, statusCode, reason = event.headers[0][0].decode('ascii').split(' ', 2)
  420. self._statusCode = int(statusCode)
  421. self._statusReason = reason
  422. elif type(event) is HTTPBodyChunk and self._isResponse:
  423. self._body.write(event.data)
  424. elif type(event) is EndOfRecord and self._isResponse:
  425. request = wpull_protocol_http_request.Request(self._recordURI)
  426. response = wpull_protocol_http_request.Response(self._statusCode, self._statusReason)
  427. response.body = self._body
  428. response.body.seek(0)
  429. for scraper, scrapeResult in self._scraper.scrape_info(request, response).items():
  430. if not scrapeResult:
  431. continue
  432. for linkContext in scrapeResult.link_contexts:
  433. if self._urlsOnly:
  434. print(linkContext.link)
  435. continue
  436. o = {
  437. 'filename': self._filename,
  438. 'recordOffset': None,
  439. 'recordID': self._recordID,
  440. 'recordURI': self._recordURI,
  441. 'linkType': linkContext.link_type.value if isinstance(linkContext.link_type, enum.Enum) else linkContext.link_type,
  442. 'inline': bool(linkContext.inline), # Needs manual casting; https://github.com/ArchiveTeam/wpull/issues/458
  443. 'linked': bool(linkContext.linked),
  444. 'url': linkContext.link,
  445. }
  446. print(json.dumps(o))
  447. def main():
  448. processorMap = {'verify': VerifyMode, 'dump-responses': DumpResponsesMode, 'colour': ColourMode, 'scrape': ScrapeMode}
  449. assert len(sys.argv) - 1 >= 2
  450. mode = sys.argv[1]
  451. assert mode in processorMap
  452. processorArgs, files = processorMap[mode].split_args(sys.argv[2:])
  453. assert files
  454. processor = processorMap[mode](*processorArgs)
  455. try:
  456. for f in files:
  457. if f.endswith('.warc.gz') or f.endswith('.warc.zst'):
  458. print(f'Warning: warc-tiny does not support decompressing WARCs like {f}. Please use zcat/zstdcat/zstdwarccat and pipe the decompressed stream into warc-tiny instead.', file = sys.stderr)
  459. print('Info: processing {}'.format(f), file = sys.stderr)
  460. processor.process_event(NewFile(f))
  461. if f == '-':
  462. f = sys.stdin.buffer
  463. for event in iter_warc(f):
  464. processor.process_event(event)
  465. except BrokenPipeError:
  466. return
  467. if __name__ == '__main__':
  468. main()