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.
 
 
 

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