aboutsummaryrefslogtreecommitdiffstats
path: root/netlib/http/semantics.py
blob: 63b6beb9972772b4bc3d185843f569285f00520d (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
from __future__ import (absolute_import, print_function, division)
import binascii
import collections
import string
import sys
import urlparse

from .. import utils, odict

class Request(object):

    def __init__(
        self,
        form_in,
        method,
        scheme,
        host,
        port,
        path,
        httpversion,
        headers,
        body,
        timestamp_start=None,
        timestamp_end=None,
    ):
        assert isinstance(headers, odict.ODictCaseless) or not headers

        self.form_in = form_in
        self.method = method
        self.scheme = scheme
        self.host = host
        self.port = port
        self.path = path
        self.httpversion = httpversion
        self.headers = headers
        self.body = body
        self.timestamp_start = timestamp_start
        self.timestamp_end = timestamp_end

    def __eq__(self, other):
        try:
            self_d = [self.__dict__[k] for k in self.__dict__ if k not in ('timestamp_start', 'timestamp_end')]
            other_d = [other.__dict__[k] for k in other.__dict__ if k not in ('timestamp_start', 'timestamp_end')]
            return self_d == other_d
        except:
            return False

    def __repr__(self):
        return "Request(%s - %s, %s)" % (self.method, self.host, self.path)

    @property
    def content(self):
        # TODO: remove deprecated getter
        return self.body

    @content.setter
    def content(self, content):
        # TODO: remove deprecated setter
        self.body = content


class EmptyRequest(Request):
    def __init__(self):
        super(EmptyRequest, self).__init__(
            form_in="",
            method="",
            scheme="",
            host="",
            port="",
            path="",
            httpversion=(0, 0),
            headers=odict.ODictCaseless(),
            body="",
            )


class Response(object):

    def __init__(
        self,
        httpversion,
        status_code,
        msg,
        headers,
        body,
        sslinfo=None,
        timestamp_start=None,
        timestamp_end=None,
    ):
        assert isinstance(headers, odict.ODictCaseless) or not headers

        self.httpversion = httpversion
        self.status_code = status_code
        self.msg = msg
        self.headers = headers
        self.body = body
        self.sslinfo = sslinfo
        self.timestamp_start = timestamp_start
        self.timestamp_end = timestamp_end

    def __eq__(self, other):
        try:
            self_d = [self.__dict__[k] for k in self.__dict__ if k not in ('timestamp_start', 'timestamp_end')]
            other_d = [other.__dict__[k] for k in other.__dict__ if k not in ('timestamp_start', 'timestamp_end')]
            return self_d == other_d
        except:
            return False

    def __repr__(self):
        return "Response(%s - %s)" % (self.status_code, self.msg)

    @property
    def content(self):
        # TODO: remove deprecated getter
        return self.body

    @content.setter
    def content(self, content):
        # TODO: remove deprecated setter
        self.body = content

    @property
    def code(self):
        # TODO: remove deprecated getter
        return self.status_code

    @code.setter
    def code(self, code):
        # TODO: remove deprecated setter
        self.status_code = code



def is_valid_port(port):
    if not 0 <= port <= 65535:
        return False
    return True


def is_valid_host(host):
    try:
        host.decode("idna")
    except ValueError:
        return False
    if "\0" in host:
        return None
    return True


def parse_url(url):
    """
        Returns a (scheme, host, port, path) tuple, or None on error.

        Checks that:
            port is an integer 0-65535
            host is a valid IDNA-encoded hostname with no null-bytes
            path is valid ASCII
    """
    try:
        scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
    except ValueError:
        return None
    if not scheme:
        return None
    if '@' in netloc:
        # FIXME: Consider what to do with the discarded credentials here Most
        # probably we should extend the signature to return these as a separate
        # value.
        _, netloc = string.rsplit(netloc, '@', maxsplit=1)
    if ':' in netloc:
        host, port = string.rsplit(netloc, ':', maxsplit=1)
        try:
            port = int(port)
        except ValueError:
            return None
    else:
        host = netloc
        if scheme == "https":
            port = 443
        else:
            port = 80
    path = urlparse.urlunparse(('', '', path, params, query, fragment))
    if not path.startswith("/"):
        path = "/" + path
    if not is_valid_host(host):
        return None
    if not utils.isascii(path):
        return None
    if not is_valid_port(port):
        return None
    return scheme, host, port, path


def get_header_tokens(headers, key):
    """
        Retrieve all tokens for a header key. A number of different headers
        follow a pattern where each header line can containe comma-separated
        tokens, and headers can be set multiple times.
    """
    toks = []
    for i in headers[key]:
        for j in i.split(","):
            toks.append(j.strip())
    return toks