summaryrefslogtreecommitdiff
path: root/crocoite/warc.py
blob: 3fd65e456048729595af44f9a71be1fb66997c2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# Copyright (c) 2017 crocoite contributors
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""
Classes writing data to WARC files
"""

import logging
import json
from http.server import BaseHTTPRequestHandler
from io import BytesIO
from warcio.statusandheaders import StatusAndHeaders
from urllib.parse import urlsplit
from logging.handlers import BufferingHandler
from datetime import datetime
from threading import Thread
from queue import Queue

from warcio.timeutils import datetime_to_iso_date
from warcio.warcwriter import WARCWriter

from .browser import AccountingSiteLoader
from .util import packageUrl
from .controller import defaultSettings

class SerializingWARCWriter (WARCWriter):
    """
    Serializing WARC writer using separate writer thread and queue for
    non-blocking operation

    Needs an explicit .flush() before deletion.
    """

    def __init__ (self, filebuf, *args, **kwargs):
        WARCWriter.__init__ (self, filebuf, *args, **kwargs)
        self.queue = Queue ()
        self.thread = Thread (target=self._run_writer)
        self.thread.start ()

    def flush (self):
        self.queue.put (None)
        self.thread.join ()
        self.queue = None
        self.thread = None

    def _run_writer (self):
        while True:
            item = self.queue.get ()
            if not item:
                break
            out, record = item
            WARCWriter._write_warc_record (self, out, record)

    def _write_warc_record (self, out, record):
        self.queue.put ((out, record))

class WARCLogHandler (BufferingHandler):
    """
    Buffered log handler, flushing to warcio
    """

    contentType = 'text/plain; charset=utf-8'

    def __init__ (self, capacity, warcfile):
        BufferingHandler.__init__ (self, capacity)
        self.warcfile = warcfile

    def flush (self):
        self.acquire ()
        try:
            if self.buffer:
                buf = ''
                for record in self.buffer:
                    buf += self.format (record)
                    buf += '\n'
                # XXX: record type?
                record = self.warcfile.create_warc_record (
                        packageUrl ('log'), 'metadata',
                        payload=BytesIO (buf.encode ('utf8')),
                        warc_headers_dict={'Content-Type': self.contentType})
                self.warcfile.write_record(record)
                self.buffer = []
        finally:
            self.release ()

class WarcLoader (AccountingSiteLoader):
    def __init__ (self, browser, url, writer,
            logger=logging.getLogger(__name__),
            logBuffer=defaultSettings.logBuffer,
            maxBodySize=defaultSettings.maxBodySize):
        super ().__init__ (browser, url, logger)
        self.writer = writer
        self.maxBodySize = maxBodySize
        self.warcLogger = WARCLogHandler (logBuffer, writer)
        self.logger.addHandler (self.warcLogger)

    def __exit__ (self, exc_type, exc_value, traceback):
        self.logger.removeHandler (self.warcLogger)
        self.warcLogger.flush ()
        return super ().__exit__ (exc_type, exc_value, traceback)

    @staticmethod
    def getStatusText (response):
        text = response.get ('statusText')
        if text:
            return text
        text = BaseHTTPRequestHandler.responses.get (response['status'])
        if text:
            return text[0]
        return 'No status text available'

    def _writeRequest (self, item):
        writer = self.writer

        req = item.request
        resp = item.response
        url = urlsplit (resp['url'])

        path = url.path
        if url.query:
            path += '?' + url.query
        httpHeaders = StatusAndHeaders('{} {} HTTP/1.1'.format (req['method'], path),
                item.requestHeaders, protocol='HTTP/1.1', is_http_request=True)
        initiator = item.initiator
        warcHeaders = {
                'X-Chrome-Initiator': json.dumps (initiator),
                'WARC-Date': datetime_to_iso_date (datetime.utcfromtimestamp (item.chromeRequest['wallTime'])),
                }
        payload, payloadBase64Encoded = item.requestBody
        if payload:
            payload = BytesIO (payload)
            warcHeaders['X-Chrome-Base64Body'] = str (payloadBase64Encoded)
        record = writer.create_warc_record(req['url'], 'request',
                payload=payload, http_headers=httpHeaders,
                warc_headers_dict=warcHeaders)
        writer.write_record(record)

        return record.rec_headers['WARC-Record-ID']

    def _getBody (self, item, redirect):
        reqId = item.id
        resp = item.response

        rawBody = b''
        base64Encoded = False
        if redirect:
            # redirects reuse the same request, thus we cannot safely retrieve
            # the body (i.e getResponseBody may return the new location’s
            # body). This is fine.
            pass
        elif item.encodedDataLength > self.maxBodySize:
            # check body size first, since we’re loading everything into memory
            raise ValueError ('body for {} too large {} vs {}'.format (reqId,
                    item.encodedDataLength, self.maxBodySize))
        else:
            rawBody, base64Encoded = item.body
        return rawBody, base64Encoded

    def _writeResponse (self, item, redirect, concurrentTo, rawBody, base64Encoded):
        writer = self.writer
        reqId = item.id
        resp = item.response

        # now the response
        warcHeaders = {
                'WARC-Concurrent-To': concurrentTo,
                'WARC-IP-Address': resp.get ('remoteIPAddress', ''),
                'X-Chrome-Protocol': resp.get ('protocol', ''),
                'X-Chrome-FromDiskCache': str (resp.get ('fromDiskCache')),
                'X-Chrome-ConnectionReused': str (resp.get ('connectionReused')),
                'X-Chrome-Base64Body': str (base64Encoded),
                'WARC-Date': datetime_to_iso_date (datetime.utcfromtimestamp (
                        item.chromeRequest['wallTime']+
                        (item.chromeResponse['timestamp']-item.chromeRequest['timestamp']))),
                }

        httpHeaders = StatusAndHeaders('{} {}'.format (resp['status'],
                self.getStatusText (resp)), item.responseHeaders,
                protocol='HTTP/1.1')

        # Content is saved decompressed and decoded, remove these headers
        blacklistedHeaders = {'transfer-encoding', 'content-encoding'}
        for h in blacklistedHeaders:
            httpHeaders.remove_header (h)

        # chrome sends nothing but utf8 encoded text. Fortunately HTTP
        # headers take precedence over the document’s <meta>, thus we can
        # easily override those.
        contentType = resp.get ('mimeType')
        if contentType:
            if not base64Encoded:
                contentType += '; charset=utf-8'
            httpHeaders.replace_header ('content-type', contentType)

        httpHeaders.replace_header ('content-length', '{:d}'.format (len (rawBody)))

        record = writer.create_warc_record(resp['url'], 'response',
                warc_headers_dict=warcHeaders, payload=BytesIO (rawBody),
                http_headers=httpHeaders)
        writer.write_record(record)

    def loadingFinished (self, item, redirect=False):
        super ().loadingFinished (item, redirect)

        writer = self.writer

        req = item.request
        reqId = item.id
        resp = item.response
        url = urlsplit (resp['url'])

        try:
            # write neither request nor response if we cannot retrieve the body
            rawBody, base64Encoded = self._getBody (item, redirect)
            concurrentTo = self._writeRequest (item)
            self._writeResponse (item, redirect, concurrentTo, rawBody, base64Encoded)
        except ValueError as e:
            self.logger.error (e.args[0])