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.
 
 
 

555 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. d = fp.read(16777216)
  109. except EOFError:
  110. break
  111. if not d:
  112. break
  113. buf += d
  114. if not buf:
  115. break
  116. assert b'\r\n\r\n' in buf
  117. warcHeaderBuf, buf = buf.split(b'\r\n\r\n', 1)
  118. assert warcHeaderBuf.startswith(b'WARC/1.0\r\n') or warcHeaderBuf.startswith(b'WARC/1.1\r\n')
  119. assert b'\r\nContent-Length:' in warcHeaderBuf
  120. warcHeaders = tuple(tuple(map(bytes.strip, x.split(b':', 1))) for x in warcHeaderBuf.split(b'\r\n'))
  121. warcContentType = next(x[1] for x in warcHeaders if x[0] == b'Content-Type')
  122. warcContentLength = int(next(x[1] for x in warcHeaders if x[0] == b'Content-Length'))
  123. warcType = next(x[1] for x in warcHeaders if x[0] == b'WARC-Type')
  124. yield BeginOfRecord(warcHeaders, warcHeaderBuf)
  125. recordID = next(x[1] for x in warcHeaders if x[0] == b'WARC-Record-ID')
  126. # Read WARC block (and skip CRLFCRLF at the end of the record)
  127. if len(buf) < warcContentLength + 4:
  128. try:
  129. buf = buf + fp.read(warcContentLength + 4 - len(buf))
  130. except EOFError:
  131. pass
  132. if len(buf) < warcContentLength + 4:
  133. print('Error: truncated WARC', file = sys.stderr)
  134. break
  135. warcContent = buf[:warcContentLength]
  136. buf = buf[warcContentLength + 4:]
  137. # Decode HTTP body if appropriate
  138. if warcContentType in (b'application/http;msgtype=request', b'application/http; msgtype=request') and warcType == b'request':
  139. httpType = 'request'
  140. elif warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response':
  141. httpType = 'response'
  142. else:
  143. httpType = None
  144. if httpType is not None:
  145. if b'\r\n\r\n' in warcContent:
  146. httpHeaders, httpBody = warcContent.split(b'\r\n\r\n', 1)
  147. # Parse headers and extract transfer encoding
  148. httpHeaderLines = [tuple(map(bytes.strip, x.split(b':', 1))) for x in httpHeaders.split(b'\r\n')]
  149. chunked = False
  150. gzipped = False
  151. if b'\r\ntransfer-encoding' in httpHeaders.lower():
  152. transferEncoding = next(x[1] for x in httpHeaderLines if x[0].lower() == b'transfer-encoding')
  153. transferEncodings = set(map(bytes.strip, transferEncoding.split(b',')))
  154. chunked = b'chunked' in transferEncodings
  155. gzipped = b'gzip' in transferEncodings
  156. yield WARCBlockChunk(httpHeaders + b'\r\n\r\n', isHttpHeader = True)
  157. yield HTTPHeaders(httpHeaderLines)
  158. yield WARCBlockChunk(httpBody, isHttpHeader = False)
  159. yield RawHTTPBodyChunk(httpBody)
  160. # Decode body
  161. if gzipped:
  162. httpDecompressor = GzipDecompressor()
  163. else:
  164. httpDecompressor = DummyDecompressor()
  165. if chunked:
  166. pos = 0
  167. while True:
  168. try:
  169. chunkLineEnd = httpBody.index(b'\r\n', pos)
  170. except ValueError:
  171. print('Error: could not find chunk line end in record {}, skipping'.format(recordID), file = sys.stderr)
  172. break
  173. chunkLine = httpBody[pos:chunkLineEnd]
  174. if b';' in chunkLine:
  175. chunkLength = chunkLine[:chunkLine.index(b';')].strip()
  176. else:
  177. chunkLength = chunkLine.strip()
  178. if chunkLength.lstrip(b'0123456789abcdefABCDEF') != b'':
  179. print('Error: malformed chunk length {!r} in record {}, skipping'.format(chunkLength, recordID), file = sys.stderr)
  180. break
  181. chunkLength = int(chunkLength, base = 16)
  182. if chunkLength == 0:
  183. break
  184. chunk = httpDecompressor.decompress(httpBody[chunkLineEnd + 2 : chunkLineEnd + 2 + chunkLength])
  185. yield HTTPBodyChunk(chunk)
  186. pos = chunkLineEnd + 2 + chunkLength + 2
  187. else:
  188. yield HTTPBodyChunk(httpDecompressor.decompress(httpBody))
  189. else:
  190. print('Warning: malformed HTTP request or response in record {}, skipping'.format(recordID), file = sys.stderr)
  191. yield WARCBlockChunk(warcContent)
  192. else:
  193. yield WARCBlockChunk(warcContent)
  194. yield EndOfRecord()
  195. class ProcessMode:
  196. @classmethod
  197. def split_args(cls, args):
  198. '''Split args into arguments to be passed into __init__ and filenames'''
  199. return (), args
  200. def process_event(self, event):
  201. raise NotImplementedError
  202. class Digest:
  203. def __init__(self, digest):
  204. self._digest = digest
  205. def format(self, digest = None):
  206. raise NotImplementedError
  207. def equals(self, digest):
  208. return self._digest == digest
  209. class Base32Digest(Digest):
  210. def format(self, digest = None):
  211. return base64.b32encode(digest if digest else self._digest)
  212. class HexDigest(Digest):
  213. def format(self, digest = None):
  214. return (digest if digest else self._digest).hex()
  215. class VerifyMode(ProcessMode):
  216. def __init__(self):
  217. self._blockDigester = None
  218. self._recordedBlockDigest = None
  219. self._payloadDigester = None
  220. self._brokenPayloadDigester = None
  221. self._recordedPayloadDigest = None
  222. self._printedBrokenPayloadWarning = False
  223. def parse_digest(self, digest):
  224. if not digest.startswith(b'sha1:'):
  225. print('Warning: don\'t understand hash format: {!r}'.format(digest), file = sys.stderr)
  226. return None
  227. if len(digest) == 37 and digest.rstrip(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567') == b'sha1:': # 5 for 'sha1:' + 32 for base-32 hash
  228. return Base32Digest(base64.b32decode(digest[5:]))
  229. if len(digest) == 45 and digest.rstrip(b'0123456789abcdef') == b'sha1:':
  230. return HexDigest(bytes.fromhex(digest[5:].decode('ascii')))
  231. return None
  232. def process_event(self, event):
  233. if type(event) is NewFile:
  234. self._printedBrokenPayloadWarning = False
  235. elif type(event) is BeginOfRecord:
  236. if any(x[0] == b'WARC-Block-Digest' for x in event.warcHeaders):
  237. self._blockDigester = hashlib.sha1()
  238. self._recordedBlockDigest = self.parse_digest(next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Block-Digest'))
  239. else:
  240. self._blockDigester = None
  241. self._recordedBlockDigest = None
  242. if any(x[0] == b'WARC-Payload-Digest' for x in event.warcHeaders):
  243. self._payloadDigester = hashlib.sha1()
  244. self._brokenPayloadDigester = hashlib.sha1()
  245. self._recordedPayloadDigest = self.parse_digest(next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Payload-Digest'))
  246. else:
  247. self._payloadDigester = None
  248. self._brokenPayloadDigester = None
  249. self._recordedPayloadDigest = None
  250. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID')
  251. self._recordType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  252. elif type(event) is WARCBlockChunk:
  253. if self._blockDigester:
  254. self._blockDigester.update(event.data)
  255. elif type(event) is HTTPBodyChunk:
  256. if self._payloadDigester:
  257. self._payloadDigester.update(event.data)
  258. elif type(event) is RawHTTPBodyChunk:
  259. if self._brokenPayloadDigester:
  260. self._brokenPayloadDigester.update(event.data)
  261. elif type(event) is EndOfRecord:
  262. if self._blockDigester and self._recordedBlockDigest:
  263. if not self._recordedBlockDigest.equals(self._blockDigester.digest()):
  264. print('Block digest mismatch for record {}: recorded {} v calculated {}'.format(self._recordID, self._recordedBlockDigest.format(), self._recordedBlockDigest.format(self._blockDigester.digest())), file = sys.stderr)
  265. if self._payloadDigester and self._recordType in (b'request', b'response'): #TODO: Support revisit
  266. if not self._recordedPayloadDigest.equals(self._payloadDigester.digest()):
  267. if self._recordedPayloadDigest.equals(self._brokenPayloadDigester.digest()):
  268. if not self._printedBrokenPayloadWarning:
  269. print('Warning: WARC uses incorrect payload digests without stripping the transfer encoding', file = sys.stderr)
  270. self._printedBrokenPayloadWarning = True
  271. else:
  272. 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)
  273. class DumpResponsesMode(ProcessMode):
  274. @classmethod
  275. def split_args(cls, args):
  276. if args[0] == '-m' or args[0] == '--meta':
  277. return (True,), args[1:]
  278. return (False,), args
  279. def __init__(self, withMeta):
  280. self._printEOR = False
  281. self._isResponse = False
  282. self._withMeta = withMeta
  283. if withMeta:
  284. self._recordID = None
  285. self._targetURI = None
  286. self._buffer = b''
  287. def _write(self, data):
  288. if not self._withMeta:
  289. sys.stdout.buffer.write(data)
  290. return
  291. buf = self._buffer + data
  292. lines = buf.split(b'\n')
  293. 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
  294. for line in lines:
  295. sys.stdout.buffer.write(':'.join((self._filename, '-1', self._recordID, '<' + self._targetURI + '>', '')).encode('utf-8'))
  296. sys.stdout.buffer.write(line)
  297. sys.stdout.buffer.write(b'\n')
  298. def process_event(self, event):
  299. if type(event) is NewFile:
  300. self._filename = event.filename
  301. if ':' in self._filename:
  302. self._filename = '<' + self._filename + '>'
  303. elif type(event) is BeginOfRecord:
  304. warcContentType = next(x[1] for x in event.warcHeaders if x[0] == b'Content-Type')
  305. warcType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  306. self._isResponse = warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response'
  307. self._printEOR = False
  308. if self._withMeta:
  309. # Both of these are URIs, and per RFC 3986, those can only contain ASCII characters.
  310. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID').decode('ascii')
  311. self._targetURI = next((x[1] for x in event.warcHeaders if x[0] == b'WARC-Target-URI'), b'').decode('ascii')
  312. self._buffer = b''
  313. elif type(event) is HTTPBodyChunk:
  314. if self._isResponse:
  315. self._printEOR = True
  316. self._write(event.data)
  317. elif type(event) is EndOfRecord:
  318. if self._printEOR:
  319. self._write(b'\r\n')
  320. class COLOURS:
  321. RESET = b'\x1b[0m'
  322. GREEN = b'\x1b[0;32m'
  323. LIGHTGREEN = b'\x1b[1;32m'
  324. PURPLE = b'\x1b[0;35m'
  325. LIGHTPURPLE = b'\x1b[1;35m'
  326. RED = b'\x1b[0;31m'
  327. INVERTED = b'\x1b[7m'
  328. class ColourMode(ProcessMode):
  329. def __init__(self):
  330. self._hadHttpStatusLine = False
  331. def _replace_esc(self, data):
  332. return data.replace(b'\x1b', COLOURS.INVERTED + b'ESC' + COLOURS.RESET)
  333. def _print_line(self, line, colour, withLF = True, colourOnlyBeforeColon = False):
  334. if colourOnlyBeforeColon:
  335. if b':' in line:
  336. offset = line.index(b':')
  337. else:
  338. offset = 0
  339. else:
  340. offset = len(line)
  341. if offset > 0:
  342. sys.stdout.buffer.write(colour)
  343. sys.stdout.buffer.write(self._replace_esc(line[:offset]))
  344. sys.stdout.buffer.write(COLOURS.RESET)
  345. sys.stdout.buffer.write(line[offset:])
  346. if withLF:
  347. sys.stdout.buffer.write(b'\n')
  348. def _print_data(self, data, colour, colourOnlyBeforeColon):
  349. later = False
  350. for line in data.split(b'\r\n'):
  351. if later:
  352. sys.stdout.buffer.write(b'\n')
  353. self._print_line(line, colour, withLF = False, colourOnlyBeforeColon = colourOnlyBeforeColon)
  354. later = True
  355. def process_event(self, event):
  356. if type(event) is BeginOfRecord:
  357. firstNewline = event.rawData.index(b'\r\n')
  358. self._print_line(event.rawData[:firstNewline], COLOURS.LIGHTGREEN)
  359. self._print_data(event.rawData[firstNewline + 2:], COLOURS.GREEN, True)
  360. sys.stdout.buffer.write(b'\n\n') # separator between header and block
  361. self._hadHttpStatusLine = False
  362. elif type(event) is WARCBlockChunk:
  363. if event.isHttpHeader is True:
  364. if not self._hadHttpStatusLine:
  365. firstNewline = event.data.index(b'\r\n')
  366. self._print_line(event.data[:firstNewline], COLOURS.LIGHTPURPLE)
  367. offset = firstNewline + 2
  368. self._hadHttpStatusLine = True
  369. else:
  370. offset = 0
  371. self._print_data(event.data[offset:], COLOURS.PURPLE, True)
  372. elif event.isHttpHeader is False:
  373. self._print_data(event.data, COLOURS.RED, False)
  374. elif event.isHttpHeader is None:
  375. sys.stdout.buffer.write(self._replace_esc(event.data))
  376. elif type(event) is EndOfRecord:
  377. sys.stdout.buffer.write(b'\n\n')
  378. class ScrapeMode(ProcessMode):
  379. @classmethod
  380. def split_args(cls, args):
  381. if args[0] == '-u' or args[0] == '--urls':
  382. return (True,), args[1:]
  383. return (False,), args
  384. def __init__(self, urlsOnly):
  385. self._urlsOnly = urlsOnly
  386. assert wpull is not None, 'Scrape mode requires wpull and lxml'
  387. htmlParser = wpull.document.htmlparse.lxml_.HTMLParser()
  388. elementWalker = wpull.scraper.html.ElementWalker()
  389. scrapers = []
  390. scrapers.append(wpull.scraper.html.HTMLScraper(htmlParser, elementWalker))
  391. scrapers.append(wpull.scraper.css.CSSScraper())
  392. elementWalker.css_scraper = scrapers[-1]
  393. scrapers.append(wpull.scraper.javascript.JavaScriptScraper())
  394. elementWalker.javascript_scraper = scrapers[-1]
  395. scrapers.append(wpull.scraper.sitemap.SitemapScraper(htmlParser))
  396. self._scraper = wpull.scraper.base.DemuxDocumentScraper(scrapers)
  397. self._isResponse = None
  398. self._body = None
  399. self._recordURI = None
  400. self._statusCode = None
  401. self._statusReason = None
  402. if not self._urlsOnly:
  403. self._filename = None
  404. self._recordID = None
  405. def process_event(self, event):
  406. if type(event) is NewFile and not self._urlsOnly:
  407. self._filename = event.filename
  408. elif type(event) is BeginOfRecord:
  409. warcContentType = next(x[1] for x in event.warcHeaders if x[0] == b'Content-Type')
  410. warcType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  411. self._isResponse = warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response'
  412. if self._isResponse:
  413. self._body = wpull.body.Body(file = tempfile.SpooledTemporaryFile(max_size = 10485760)) # Up to 10 MiB in memory
  414. self._printEOR = False
  415. if not self._urlsOnly:
  416. # Both of these are URIs, and per RFC 3986, those can only contain ASCII characters.
  417. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID').decode('ascii')
  418. self._recordURI = next((x[1] for x in event.warcHeaders if x[0] == b'WARC-Target-URI'), b'').decode('ascii')
  419. elif type(event) is HTTPHeaders and self._isResponse:
  420. assert len(event.headers[0]) == 1 and event.headers[0][0].startswith(b'HTTP/'), 'malformed HTTP response'
  421. _, statusCode, reason = event.headers[0][0].decode('ascii').split(' ', 2)
  422. self._statusCode = int(statusCode)
  423. self._statusReason = reason
  424. elif type(event) is HTTPBodyChunk and self._isResponse:
  425. self._body.write(event.data)
  426. elif type(event) is EndOfRecord and self._isResponse:
  427. request = wpull_protocol_http_request.Request(self._recordURI)
  428. response = wpull_protocol_http_request.Response(self._statusCode, self._statusReason)
  429. response.body = self._body
  430. response.body.seek(0)
  431. for scraper, scrapeResult in self._scraper.scrape_info(request, response).items():
  432. if not scrapeResult:
  433. continue
  434. for linkContext in scrapeResult.link_contexts:
  435. if self._urlsOnly:
  436. print(linkContext.link)
  437. continue
  438. o = {
  439. 'filename': self._filename,
  440. 'recordOffset': None,
  441. 'recordID': self._recordID,
  442. 'recordURI': self._recordURI,
  443. 'linkType': linkContext.link_type.value if isinstance(linkContext.link_type, enum.Enum) else linkContext.link_type,
  444. 'inline': bool(linkContext.inline), # Needs manual casting; https://github.com/ArchiveTeam/wpull/issues/458
  445. 'linked': bool(linkContext.linked),
  446. 'url': linkContext.link,
  447. }
  448. print(json.dumps(o))
  449. def main():
  450. processorMap = {'verify': VerifyMode, 'dump-responses': DumpResponsesMode, 'colour': ColourMode, 'scrape': ScrapeMode}
  451. assert len(sys.argv) - 1 >= 2
  452. mode = sys.argv[1]
  453. assert mode in processorMap
  454. processorArgs, files = processorMap[mode].split_args(sys.argv[2:])
  455. assert files
  456. processor = processorMap[mode](*processorArgs)
  457. try:
  458. for f in files:
  459. if f.endswith('.warc.gz') or f.endswith('.warc.zst'):
  460. 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)
  461. print('Info: processing {}'.format(f), file = sys.stderr)
  462. processor.process_event(NewFile(f))
  463. if f == '-':
  464. f = sys.stdin.buffer
  465. for event in iter_warc(f):
  466. processor.process_event(event)
  467. except BrokenPipeError:
  468. return
  469. if __name__ == '__main__':
  470. main()