Source

vlastic / vlastic / http.py

Full commit
  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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
"""The abstractions for HTTP concepts.

Defines Message, Request and Response classes. It abstracts HTTP concepts for
web application.

"""


import re

__all__ = ["Message", "RequestPath", "Request", "Response", "ErrorResponse",
           "NotFoundError", "MethodNotAllowedError", "NotAcceptableError",
           "NegotiativeHeader", "NegotiativeLanguageHeader"]


class Message:
    """HTTP messages [1] abstract class for HTTP requests [2] and
    responses [3].

    [1] http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4
    [2] http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5
    [3] http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6

    """

    MESSAGE_PATTERN = re.compile(br"""^
        (?P<start_line> .+? ) \r\n
        (?P<headers>
            (?P<field>
                (?P<name> [^:]+? ) : [ \t\f\v]*
                (?P<value> .+? ) [ \t\f\v]*? \r\n
            )*
        ) \r\n
        (?P<body> .* )
    $""", re.VERBOSE)

    HEADER_PATTERN = re.compile(br"""
        (?P<field>
            (?P<name> [^:]+? ) : [ \t\f\v]*
            (?P<value> .+? ) [ \t\f\v]*? \r\n
        )
    """, re.VERBOSE)

    @staticmethod
    def _message_iterator(full_message):
        """Returns an iterator which split given full_message (sequence of
        bytes) by CRLF before its body. A start-line and each header become
        a element of the sequence, and the following body is leaved.

            >>> it = Message._message_iterator([
            ...     b"POST / ", b"HTTP/1.1\r",
            ...     b"\nHost: d", b"ahlia.kr",
            ...     b"\r\n\r\nabc", b"=def"
            ... ])
            >>> list(it)
            [b'POST / HTTP/1.1\r\n', b'Host: dahlia.kr\r\n', b'\r\n',
             b'abc=def']

        """
        buffer = b""
        for part in full_message:
            if buffer is None:
                yield part
            else:
                buffer += part
                try:
                    offset = buffer.index(b"\r\n\r\n") + 4
                    yield buffer[:offset - 2]
                    yield b"\r\n"
                    yield buffer[offset:]
                    buffer = None
                except ValueError:
                    try:
                        offset = buffer.index(b"\r\n") + 2
                        yield buffer[:offset]
                        buffer = buffer[offset:]
                    except ValueError:
                        continue
        if buffer is not None:
            yield buffer

    def __init__(self, *args, **kwargs):
        """Initializes a message. It accepts a start-line string, header
        fields [(name, value), ...] sequence (or dict) and body string as
        three arguments or full HTTP message string as an only argument.

        Start-line and headers accept str or bytes both. All bytes become
        decoded to bytes. Body accept bytes or an other iterable sequence
        of bytes.

        """
        from sys import getdefaultencoding
        def full_message(full_message, encoding=None):
            if encoding is not None and not isinstance(encoding, str):
                raise TypeError("encoding must be str")
            self.encoding = encoding
            if isinstance(full_message, str):
                if not encoding:
                    encoding = getdefaultencoding()
                full_message = full_message.encode(encoding)
            if not isinstance(full_message, bytes):
                msg = self._message_iterator(full_message)
                for line in msg:
                    if line == b"\r\n":
                        break
                    elif hasattr(self, "start_line"):
                        m = self.HEADER_PATTERN.match(line)
                        self.headers.append((m.group("name"), m.group("value")))
                    else:
                        self.start_line = line[:-2] # strip trailling CRLF
                        self.headers = []
                self.body = msg
                return
            match = self.MESSAGE_PATTERN.match(full_message)
            self.start_line = match.group("start_line")
            self.body = (match.group("body"),)
            self.headers = [
                (m.group("name"), m.group("value"))
                for m in self.HEADER_PATTERN.finditer(match.group("headers"))
            ]
        def each(start_line, headers, body=b"", encoding=None):
            self.encoding = encoding or getdefaultencoding()
            if not isinstance(start_line, bytes):
                start_line = b" ".join(
                    prt if isinstance(prt, bytes)
                        else str(prt).encode(self.encoding)
                    for prt in start_line
                )
            self.start_line = start_line
            headers = (headers.items() if isinstance(headers, dict)
                                       else headers)
            def encode(s):
                return s.encode(self.encoding) if isinstance(s, str) else s
            self.headers = list((encode(name), encode(content))
                                for name, content in headers)
            self.body = (body,) if isinstance(body, bytes) else body
        try:
            full_message(*args, **kwargs)
        except TypeError:
            each(*args, **kwargs)
        self.encoding = self.encoding or getdefaultencoding()

    def _case_insensitive_re(self, name):
        if not isinstance(name, (bytes, str)):
            name_type = type(name).__name__
            raise TypeError("expected bytes or a str, but %s given" % name_type)
        if isinstance(name, str):
            name = name.encode(self.encoding)
        return re.compile(b"^" + re.escape(name) + b"$", re.IGNORECASE)

    def __contains__(self, name):
        """Returns True if it contains the header. Case-insensitive."""
        pattern = self._case_insensitive_re(name)
        return any(pattern.match(key) for key, _ in self.headers)

    def __getitem__(self, name):
        """Get a header value by the name.

            >>> msg = Message("...", [(b"Content-Length", b"123")], b"")
            >>> msg[b"Content-Length"]
            b"123"

        The header name is case-insensitive.

            >>> msg[b"CONTENT-length"]
            b"123"

        It returns a value by str if the given name is str.

            >>> msg["content-length"]
            "123"

        Raises KeyError when the header is not there.

            >>> msg["Connection"]
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            KeyError: there is no header 'Connection'

        """
        pattern = self._case_insensitive_re(name)
        for field, value in self.headers:
            if pattern.match(field):
                return value.decode(self.encoding) \
                    if isinstance(name, str) \
                    else value
        raise KeyError("there is no header %r" % name)

    def __setitem__(self, name, value):
        """Set a header. It accepts a str or bytes for a name and a value."""
        pattern = self._case_insensitive_re(name)
        if isinstance(name, str):
            name = name.encode(self.encoding)
        if isinstance(value, str):
            value = value.encode(self.encoding)
        elif not isinstance(value, bytes):
            raise TypeError("value must be a str or bytes")
        for i, (field, _) in enumerate(self.headers):
            if pattern.match(field):
                self.headers[i] = (name, value)
                return
        self.headers.append((name, value))

    def __str__(self):
        """Returns the full message string."""
        return bytes(self).decode(self.encoding)

    def __bytes__(self):
        """Returns the full message as bytes.

        It has a side effect about iteration status of the body iterator.

        """
        return self.start_line + b"\r\n" + \
               b"\r\n".join(n + b": " + v for n, v in self.headers) + \
               b"\r\n\r\n" + b"".join(self.body)

    def __repr__(self):
        """Returns a reprsentation string."""
        return ("" if __name__ == "__main__" else __name__ + ".") \
             + "%s(%r, ...)" % (type(self).__name__, self.start_line)


class RequestPath:
    """Path for HTTP requests."""

    def __init__(self, path):
        if path == "/":
            list = []
        else:
            # /path//entry/1 -> ["path", "entry", "1"]
            list = re.split(r"/+", path)[1:]
        self.path_list = list
        self.offset = 0

    def __iter__(self):
        return self

    def __next__(self):
        offset = self.offset
        if len(self.path_list) == offset:
            raise StopIteration
        self.offset += 1
        return self.path_list[offset]

    def __str__ (self):
        return str("/" + "/".join(self.path_list))

    def front_segments(self):
        """Components front of the current component. If the full path is
        /blog/post/entry/1 and the current component is "entry", then the
        front components are ["blog", "post"].

        """
        return self.path_list[0:self.offset]

    def current_segment(self):
        return self.path_list[self.offset]


class Request(Message):
    """HTTP requests [1] class.

    [1] http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5

    """

    def __init__(self, *args, **kwargs):
        Message.__init__(self, *args, **kwargs)
        self.method, full_path, self.http_version = \
            self.start_line.decode().split()
        self.path = RequestPath(full_path)

    @property
    def accept(self):
        """Returns a NegotiativeHeader instance of 'Accept' header.

        If 'Accept' header does not exist, it returns None.

        """
        try:
            return NegotiativeHeader(self[b"Accept"], self.encoding)
        except KeyError:
            pass


class Response(Message):
    """HTTP responses [1] class.
    
    [1] http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6

    """

    def __init__(self, *args, **kwargs):
        Message.__init__(self, *args, **kwargs)
        self.http_version, status_code, self.reason_phrase = \
            self.start_line.decode().split(None, 2)
        self.status_code = int(status_code)


class ErrorResponse(Response, Exception):
    """Error response class."""

    def __init__(self, status_code, reason_phrase, headers={}):
        start_line = (b"HTTP/1.1", status_code, reason_phrase)
        Response.__init__(self, start_line, headers)


class NotFoundError(ErrorResponse):
    """404 Not Found response class."""

    def __init__(self, headers={}):
        ErrorResponse.__init__(self, 404, b"Not Found", headers)


class MethodNotAllowedError(ErrorResponse):
    """405 Method Not Allowed response class."""

    def __init__(self, headers={}):
        ErrorResponse.__init__(self, 405, b"Method Not Allowed", headers)


class NotAcceptableError(ErrorResponse):
    """406 Not Acceptable response class."""

    def __init__(self, headers={}):
        ErrorResponse.__init__(self, 406, b"Not Acceptable", headers)


class NegotiativeHeader:
    """HTTP content negotiation [1] class. It used by Accept, Accept-Charset,
    Accept-Encoding, Accept-Ranges. [2]

    [1] http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html#sec12
    [2] http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14

    """

    PATTERN = re.compile(r"""
        \s*
        (?P<term> [^,;]+ )
        (?:
            \s* ; \s* q \s* = \s*
            (?P<q> \d+ (?: \. \d+)? )
        )?
        \s* (, | $)
    """, re.VERBOSE)

    def __init__(self, bytes_header, encoding=None):
        from sys import getdefaultencoding
        self.encoding = encoding or getdefaultencoding()
        self.bytes_header = bytes(bytes_header)
        self.header = [(m.group("term"), float(m.group("q") or 1))
                       for m in self.PATTERN.finditer(str(self))]

    def __bytes__(self):
        return self.bytes_header

    def __str__(self):
        return bytes(self).decode(self.encoding)

    def __repr__(self):
        L = []
        for key, qvalue in self.header:
            L.append("{0}; q={1:g}".format(key, qvalue))
        return ", ".join(L)

    def __contains__(self, item):
        return item in (key for key, _ in self.header)

    def __iter__(self):
        for key, qvalue in self.header:
            if key != "*" and qvalue != 0:
                yield key

    def _all_matches(self, header):
        return [(key, qvalue) for key, qvalue in self.header if key in header]

    def all_matches(self, header):
        return [key for key, _ in self._all_matches(header)]

    def first_match(self, header):
        having_header = self._all_matches(header)
        if len(having_header) == 0:
            return None
        key, _ = having_header[0]
        return key

    def best_match(self, header):
        all_matched = self._all_matches(header)
        if len(all_matched) == 0:
            return None
        best_matched = max(all_matched, key=lambda x: x[1])
        return best_matched[0]

    def best_matches(self, header):
        return [
            key
            for key, _ in sorted(
                self._all_matches(header), key=lambda x: x[1], reverse=True)
        ]


def CmpToKey(mycmp):
    """Convert a cmp= function into a key= function.
    Python 3.0 removes keyword argument 'cmp' in the method of
    `list.sort`and sorted. But Making complicated comparing function
    with'key' and 'reverse' keyword argument is very difficult.
    Specially when comparing function is required to be
    a closure or function object, it's impossible.

    http://code.activestate.com/recipes/576653/

    """
    class K:
        def __init__(self, obj):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K


class LanguageComparator:
    @staticmethod
    def unpack_lang_country(language):
        """'en-US' -> ('en', 'US'), 'en' -> ('en', '')"""
        lang_country = language.split("-")
        lang = lang_country[0]
        if len(lang_country) == 2:
            country = lang_country[1]
        else:
            country = ''
        return lang, country

    @staticmethod
    def lang_indexes(lang_list, lang):
        start = 0
        start = 0
        indexes = []
        while True:
            try:
                start = lang_list.index(lang, start)
                indexes.append(start)
                start += 1
            except ValueError:
                break
        return indexes

    @staticmethod
    def lang_country_index(lang_indexes, country_list, country):
        for idx in lang_indexes:
            if country_list[idx] == country:
                return idx
        return len(country_list)

    def __init__(self, sorted_client_lang):
        self.c_lang_list = []
        self.c_country_list = []
        for client in sorted_client_lang:
            self.c_lang_list.append(client[0])
            self.c_country_list.append(client[1])

    def __call__(self, a, b):
        """Compares server character languages."""
        a_lang, a_country = self.unpack_lang_country(a)
        b_lang, b_country = self.unpack_lang_country(b)
        a_lang_indexes = self.lang_indexes(self.c_lang_list, a_lang)
        b_lang_indexes = self.lang_indexes(self.c_lang_list, b_lang)
        if a_lang_indexes != [] and b_lang_indexes == []:
            result = -1
        elif a_lang_indexes == [] and b_lang_indexes != []:
            result = 1
        elif a_lang_indexes == [] and b_lang_indexes == []:
            result = 0
        else:
            a_matched_index = self.lang_country_index(
                a_lang_indexes, self.c_country_list, a_country)
            b_matched_index = self.lang_country_index(
                b_lang_indexes, self.c_country_list, b_country)
            result = a_matched_index - b_matched_index
            if result == 0 and a_matched_index == len(self.c_lang_list):
                a_matched_index = self.lang_country_index(
                    a_lang_indexes, self.c_country_list, '')
                b_matched_index = self.lang_country_index(
                    b_lang_indexes, self.c_country_list, '')
                result = a_matched_index - b_matched_index
                if result == 0:
                    result = a_lang_indexes[0] - b_lang_indexes[0]
        return result


class NegotiativeLanguageHeader:
    """HTTP Accept-Language negotiation [1] class.

    [1] http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

    """

    PATTERN = re.compile(r"""
        \s*
        (?P<lang> [^,;-]+ )
        (?:
            \-
            (?P<country> [^,;]+ )
        )?
        (?:
            \s* ; \s* q \s* = \s*
            (?P<q> \d+ (?: \. \d+)? )
        )?
        \s* (, | $)
    """, re.VERBOSE)

    def __init__(self, bytes_header, encoding=None):
        from sys import getdefaultencoding
        self.encoding = encoding or getdefaultencoding()
        self.bytes_header = bytes(bytes_header)
        self.header = []
        for m in self.PATTERN.finditer(str(self)):
            lang = m.group("lang")
            country = m.group("country") or ""
            q = float(m.group("q") or 1)
            self.header.append((lang, country, q))

    def __bytes__(self):
        return self.bytes_header

    def __str__(self):
        return bytes(self).decode(self.encoding)

    def __repr__(self):
        L = []
        for lang, country, q in self.header:
            L.append("{0}; q={1:g}".format(lang + (country and "-" + country), q))
        return ", ".join(L)

    def best_matches(self, server_lang):
        sorted_lang = sorted(self.header, key=lambda x: x[2], reverse=True)
        lang_cmp = LanguageComparator(sorted_lang)
        server_lang.sort(key=CmpToKey(lang_cmp))
        return server_lang