warc.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # Copyright (c) 2017 crocoite contributors
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. # THE SOFTWARE.
  20. """
  21. Classes writing data to WARC files
  22. """
  23. import json, threading
  24. from io import BytesIO
  25. from datetime import datetime
  26. from http.server import BaseHTTPRequestHandler
  27. from warcio.timeutils import datetime_to_iso_date
  28. from warcio.warcwriter import WARCWriter
  29. from warcio.statusandheaders import StatusAndHeaders
  30. from yarl import URL
  31. from .util import StrJsonEncoder
  32. from .controller import EventHandler, ControllerStart
  33. from .behavior import Script, DomSnapshotEvent, ScreenshotEvent
  34. from .browser import RequestResponsePair, UnicodeBody
  35. # the official mimetype for json, according to https://tools.ietf.org/html/rfc8259
  36. jsonMime = 'application/json'
  37. # mime for javascript, according to https://tools.ietf.org/html/rfc4329#section-7.2
  38. jsMime = 'application/javascript'
  39. def makeContentType (mime, charset=None):
  40. """ Create value of Content-Type WARC header with optional charset """
  41. s = [mime]
  42. if charset:
  43. s.extend (['; charset=', charset])
  44. return ''.join (s)
  45. class WarcHandler (EventHandler):
  46. __slots__ = ('logger', 'writer', 'documentRecords', 'log',
  47. 'maxLogSize', 'logEncoding', 'warcinfoRecordId')
  48. def __init__ (self, fd, logger):
  49. self.logger = logger
  50. self.writer = WARCWriter (fd, gzip=True)
  51. self.logEncoding = 'utf-8'
  52. self.log = BytesIO ()
  53. # max log buffer size (bytes)
  54. self.maxLogSize = 500*1024
  55. # maps document urls to WARC record ids, required for DomSnapshotEvent
  56. # and ScreenshotEvent
  57. self.documentRecords = {}
  58. # record id of warcinfo record
  59. self.warcinfoRecordId = None
  60. def __enter__ (self):
  61. return self
  62. def __exit__(self, exc_type, exc_value, traceback):
  63. self._flushLogEntries ()
  64. def writeRecord (self, url, kind, payload, warc_headers_dict=None, http_headers=None):
  65. """
  66. Thin wrapper around writer.create_warc_record and writer.write_record.
  67. Adds default WARC headers.
  68. """
  69. assert url is None or isinstance (url, URL)
  70. d = {}
  71. if self.warcinfoRecordId:
  72. d['WARC-Warcinfo-ID'] = self.warcinfoRecordId
  73. d.update (warc_headers_dict)
  74. warc_headers_dict = d
  75. record = self.writer.create_warc_record (str (url) if url else '',
  76. kind,
  77. payload=payload,
  78. warc_headers_dict=warc_headers_dict,
  79. http_headers=http_headers)
  80. self.writer.write_record (record)
  81. return record
  82. def _writeRequest (self, item):
  83. logger = self.logger.bind (reqId=item.id)
  84. req = item.request
  85. url = item.url
  86. path = url.relative().with_fragment(None)
  87. httpHeaders = StatusAndHeaders(f'{req.method} {path} HTTP/1.1',
  88. req.headers, protocol='HTTP/1.1', is_http_request=True)
  89. warcHeaders = {
  90. # required to correlate request with log entries
  91. 'X-Chrome-Request-ID': item.id,
  92. 'WARC-Date': datetime_to_iso_date (req.timestamp),
  93. }
  94. body = item.request.body
  95. if item.request.hasPostData and body is None:
  96. # oops, don’t know what went wrong here
  97. logger.error ('requestBody missing',
  98. uuid='ee9adc58-e723-4595-9feb-312a67ead6a0')
  99. warcHeaders['WARC-Truncated'] = 'unspecified'
  100. else:
  101. body = BytesIO (body)
  102. record = self.writeRecord (url, 'request',
  103. payload=body, http_headers=httpHeaders,
  104. warc_headers_dict=warcHeaders)
  105. return record.rec_headers['WARC-Record-ID']
  106. def _writeResponse (self, item, concurrentTo):
  107. # fetch the body
  108. reqId = item.id
  109. # now the response
  110. resp = item.response
  111. warcHeaders = {
  112. 'WARC-Concurrent-To': concurrentTo,
  113. # required to correlate request with log entries
  114. 'X-Chrome-Request-ID': item.id,
  115. 'WARC-Date': datetime_to_iso_date (resp.timestamp),
  116. }
  117. # conditional WARC headers
  118. if item.remoteIpAddress:
  119. warcHeaders['WARC-IP-Address'] = item.remoteIpAddress
  120. # HTTP headers
  121. statusText = resp.statusText or \
  122. BaseHTTPRequestHandler.responses.get (
  123. resp.status, ('No status text available', ))[0]
  124. httpHeaders = StatusAndHeaders(f'{resp.status} {statusText}',
  125. resp.headers, protocol='HTTP/1.1')
  126. # Content is saved decompressed and decoded, remove these headers
  127. blacklistedHeaders = {'transfer-encoding', 'content-encoding'}
  128. for h in blacklistedHeaders:
  129. httpHeaders.remove_header (h)
  130. # chrome sends nothing but utf8 encoded text. Fortunately HTTP
  131. # headers take precedence over the document’s <meta>, thus we can
  132. # easily override those.
  133. if resp.mimeType:
  134. charset = 'utf-8' if isinstance (resp.body, UnicodeBody) else None
  135. contentType = makeContentType (resp.mimeType, charset=charset)
  136. httpHeaders.replace_header ('Content-Type', contentType)
  137. # response body
  138. body = resp.body
  139. if body is None:
  140. warcHeaders['WARC-Truncated'] = 'unspecified'
  141. else:
  142. httpHeaders.replace_header ('Content-Length', str (len (body)))
  143. body = BytesIO (body)
  144. record = self.writeRecord (item.url, 'response',
  145. warc_headers_dict=warcHeaders, payload=body,
  146. http_headers=httpHeaders)
  147. if item.resourceType == 'Document':
  148. self.documentRecords[item.url] = record.rec_headers.get_header ('WARC-Record-ID')
  149. def _writeScript (self, item):
  150. writer = self.writer
  151. encoding = 'utf-8'
  152. # XXX: yes, we’re leaking information about the user here, but this is
  153. # the one and only source URL of the scripts.
  154. uri = URL(f'file://{item.abspath}') if item.path else None
  155. self.writeRecord (uri, 'resource',
  156. payload=BytesIO (str (item).encode (encoding)),
  157. warc_headers_dict={
  158. 'Content-Type': makeContentType (jsMime, encoding),
  159. 'X-Crocoite-Type': 'script',
  160. })
  161. def _writeItem (self, item):
  162. assert item.request
  163. concurrentTo = self._writeRequest (item)
  164. # items that failed loading don’t have a response
  165. if item.response:
  166. self._writeResponse (item, concurrentTo)
  167. def _addRefersTo (self, headers, url):
  168. refersTo = self.documentRecords.get (url)
  169. if refersTo:
  170. headers['WARC-Refers-To'] = refersTo
  171. else:
  172. self.logger.error (f'No document record found for {url}')
  173. return headers
  174. def _writeDomSnapshot (self, item):
  175. writer = self.writer
  176. warcHeaders = {
  177. 'X-Crocoite-Type': 'dom-snapshot',
  178. 'X-Chrome-Viewport': item.viewport,
  179. 'Content-Type': makeContentType ('text/html', 'utf-8')
  180. }
  181. self._addRefersTo (warcHeaders, item.url)
  182. self.writeRecord (item.url, 'conversion',
  183. payload=BytesIO (item.document),
  184. warc_headers_dict=warcHeaders)
  185. def _writeScreenshot (self, item):
  186. writer = self.writer
  187. warcHeaders = {
  188. 'Content-Type': makeContentType ('image/png'),
  189. 'X-Crocoite-Screenshot-Y-Offset': str (item.yoff),
  190. 'X-Crocoite-Type': 'screenshot',
  191. }
  192. self._addRefersTo (warcHeaders, item.url)
  193. self.writeRecord (item.url, 'conversion',
  194. payload=BytesIO (item.data), warc_headers_dict=warcHeaders)
  195. def _writeControllerStart (self, item, encoding='utf-8'):
  196. payload = BytesIO (json.dumps (item.payload, indent=2, cls=StrJsonEncoder).encode (encoding))
  197. writer = self.writer
  198. warcinfo = self.writeRecord (None, 'warcinfo',
  199. warc_headers_dict={'Content-Type': makeContentType (jsonMime, encoding)},
  200. payload=payload)
  201. self.warcinfoRecordId = warcinfo.rec_headers['WARC-Record-ID']
  202. def _flushLogEntries (self):
  203. if self.log.tell () > 0:
  204. writer = self.writer
  205. self.log.seek (0)
  206. warcHeaders = {
  207. 'Content-Type': makeContentType (jsonMime, self.logEncoding),
  208. 'X-Crocoite-Type': 'log',
  209. }
  210. self.writeRecord (None, 'metadata', payload=self.log,
  211. warc_headers_dict=warcHeaders)
  212. self.log = BytesIO ()
  213. def _writeLog (self, item):
  214. """ Handle log entries, called by .logger.WarcHandlerConsumer only """
  215. self.log.write (item.encode (self.logEncoding))
  216. self.log.write (b'\n')
  217. if self.log.tell () > self.maxLogSize:
  218. self._flushLogEntries ()
  219. route = {Script: _writeScript,
  220. RequestResponsePair: _writeItem,
  221. DomSnapshotEvent: _writeDomSnapshot,
  222. ScreenshotEvent: _writeScreenshot,
  223. ControllerStart: _writeControllerStart,
  224. }
  225. async def push (self, item):
  226. for k, v in self.route.items ():
  227. if isinstance (item, k):
  228. v (self, item)
  229. break