File: parametrized.py

package info (click to toggle)
python-flanker 0.9.15-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 17,976 kB
  • sloc: python: 9,308; makefile: 4
file content (326 lines) | stat: -rw-r--r-- 8,312 bytes parent folder | download
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
"""Module that is responsible for parsing parameterized header values
encoded in accordance to rfc2231 (new style) or rfc1342 (old style)
"""
from collections import deque
from itertools import groupby

import regex as re
import six
from six.moves import urllib_parse

from flanker.mime.message import charsets
from flanker.mime.message.headers import encodedword

_PARAM_STYLE_OLD = 'old'
_PARAM_STYLE_NEW = 'new'


def decode(header):
    """Accepts parameterized header value (encoded in accordance to
     rfc2231 (new style) or rfc1342 (old style)
     and returns tuple:
         value, {'key': u'val'}
     returns None in case of any failure
    """
    if six.PY3 and isinstance(header, six.binary_type):
        header = header.decode('utf-8')

    value, rest = split(encodedword.unfold(header))
    if value is None:
        return None, {}

    return value, decode_parameters(rest)


def is_parametrized(name, value):
    return name in ('Content-Type',
                    'Content-Disposition',
                    'Content-Transfer-Encoding')


def fix_content_type(value, default=None):
    """Content-Type value may be badly broken"""
    if not value:
        return default or ('text', 'plain')
    values = value.lower().split('/')
    if len(values) >= 2:
        return values[:2]
    elif len(values) == 1:
        if values[0] == 'text':
            return 'text', 'plain'
        elif values[0] == 'html':
            return 'text', 'html'
        return 'application', 'octet-stream'


def split(header):
    """Splits value part and parameters part,
    e.g.
         split("MULTIPART/MIXED;boundary=hal_9000")
    becomes:
         ["multipart/mixed", "boundary=hal_9000"]
    """
    match = _RE_HEADER_VALUE.match(header)
    if not match:
        return (None, None)
    return match.group(1).lower(), header[match.end():]


def decode_parameters(string):
    """Parameters can be splitted into several parts, e.g.

    title*0*=us-ascii'en'This%20is%20even%20more%20
    title*1*=%2A%2A%2Afun%2A%2A%2A%20
    title*2="isn't it!"

    decode them to the dictionary with keys and values"""
    parameters = collect_parameters(string)
    groups = {}
    for k, parts in groupby(parameters, get_key):
        groups[k] = concatenate(list(parts))
    return groups


def collect_parameters(rest):
    """Scans the string and collects parts
    that look like parameter, returns deque of strings
    """
    parameters = deque()
    p, rest = match_parameter(rest)
    while p:
        parameters.append(p)
        p, rest = match_parameter(rest)
    return parameters


def concatenate(parts):
    """ Concatenates splitted parts of a parameter in a single parameter,
    e.g.
         URL*0="ftp://";
         URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"

    becomes:

         URL="ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"
    """
    part = parts[0]
    if is_old_style(part):
        # old-style parameters do not support any continuations
        return encodedword.mime_to_unicode(get_value(part))

    return ''.join(decode_new_style(p) for p in partition(parts))


def match_parameter(rest):
    for match in (match_old, match_new):
        p, rest = match(rest)
        if p:
            return p, rest

    return None, rest


def match_old(rest):
    match = _RE_OLD_STYLE_PARAM.match(rest)
    if match:
        name = match.group('name')
        value = match.group('value')
        return parameter(_PARAM_STYLE_OLD, name, value), rest[match.end():]

    return None, rest


def match_new(rest):
    match = _RE_NEW_STYLE_PARAM.match(rest)
    if match:
        name = parse_parameter_name(match.group('name'))
        value = match.group('value')
        return parameter(_PARAM_STYLE_NEW, name, value), rest[match.end():]

    return None, rest


def reverse(string):
    """Native reverse of a string looks a little bit cryptic,
    just a readable wrapper"""
    return string[::-1]


def parse_parameter_name(key):
    """New style parameter names can be splitted into parts,
    e.g.

    title*0* means that it's the first part that is encoded
    title*1* means that it's the second part that is encoded
    title*2 means that it is the third part that is unencoded
    title means single unencoded
    title* means single encoded part

    I found it easier to match against a reversed string,
    as regexp is simpler
    """
    m = _RE_REVERSE_CONTINUATION.match(reverse(key))
    key = reverse(m.group('key'))
    part = reverse(m.group('part')) if m.group('part') else None
    encoded = m.group('encoded')
    return key, part, encoded


def decode_new_style(parameter):
    """Decodes parameter values, quoted or percent encoded, to unicode"""
    if is_quoted(parameter):
        return unquote(parameter)
    if is_encoded(parameter):
        return decode_charset(parameter)
    return get_value(parameter)


def partition(parts):
    """Partitions the parts in accordance to the algo here:
    http://tools.ietf.org/html/rfc2231#section-4.1
    """
    encoded = deque()
    for part in parts:
        if is_encoded(part):
            encoded.append(part)
            continue
        if encoded:
            yield join_parameters(encoded)
            encoded = deque()
        yield part
    if encoded:
        yield join_parameters(encoded)


def decode_charset(parameter):
    """Decodes things like:
    "us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20"
    to unicode """

    v = get_value(parameter)
    parts = v.split("'", 2)
    if len(parts) != 3:
        return v
    charset, language, val = parts
    val = urllib_parse.unquote(val)
    return charsets.convert_to_unicode(charset, val)


def unquote(parameter):
    """Simply removes quotes"""
    return get_value(parameter).strip('"')


def parameter(ptype, key, value):
    """Parameter is stored as a tuple,
    and below are conventional
    """
    return (ptype, key, value)


def is_quoted(part):
    return get_value(part)[0] == '"'


def is_new_style(parameter):
    return parameter[0] == _PARAM_STYLE_NEW


def is_old_style(parameter):
    return parameter[0] == _PARAM_STYLE_OLD


def is_encoded(part):
    return part[1][2] == '*'


def get_key(parameter):
    if is_old_style(parameter):
        return parameter[1].lower()
    else:
        return parameter[1][0].lower()


def get_value(parameter):
    return parameter[2]


def join_parameters(parts):
    joined = "".join(get_value(p) for p in parts)
    for p in parts:
        return parameter(p[0], p[1], joined)


# used to split header value and parameters
_RE_HEADER_VALUE = re.compile(r'''
       # don't care about the spaces
       ^[\ \t]*
       #main type and sub type or any other value
       ([^\ \t;]+)
       # grab the trailing spaces, colons
       [\ \t;]*''', re.IGNORECASE | re.VERBOSE)


_RE_OLD_STYLE_PARAM = re.compile(r'''
     # according to rfc1342, param value can be encoded-word
     # and it's actually very popular, so detect this parameter first
     ^
     # skip spaces
     [\ \t]*
     # parameter name
     (?P<name>
         [^\x00-\x1f\s\(\)<>@,;:\\"/\[\]\?=]+
     )
     # skip spaces
     [\ \t]*
     =
     # skip spaces
     [\ \t]*
     #optional quoting sign
     "?
     # skip spaces
     [\ \t]*
     # and a glorious encoded-word sequence
     (?P<value>
       =\?
       .* # non-greedy to match the end sequence chars
       \?=
     )
     # ends with optional quoting sign that we ignore
     "?
''', re.IGNORECASE | re.VERBOSE)

_RE_NEW_STYLE_PARAM = re.compile(r'''
     # Here we grab anything that looks like a parameter
     ^
     # skip spaces
     [\ \t]*
     # parameter name
     (?P<name>
         [^\x00-\x1f\s\(\)<>@,;:\\"/\[\]\?=]+
     )
     # skip spaces
     [\ \t]*
     =
     # skip spaces
     [\ \t]*
     (?P<value>
       (?:
         "(?:
             # so this works for unicode too
             [^\x00-\x10\x12-\x19\x22\x5c\x7f]
             |
             (?:\\[\x21-\x7e\t\ ])
          )+"
       )
     |
     # any (US-ASCII) CHAR except SPACE, CTLs, or tspecials
     [^\x00-\x1f\s\(\)<>@,;:\\"/\[\]\?=]+
     )
     # skip spaces
     [\ \t]*
     ;?
''', re.IGNORECASE | re.VERBOSE)

_RE_REVERSE_CONTINUATION = re.compile(
    r'^(?P<encoded>\*)?(?P<part>\d+\*)?(?P<key>.*)')