summaryrefslogtreecommitdiffstats
path: root/htformtool.py
blob: 218daa768153d3fa60d964ba944998cd2ef68969 (plain) (blame)
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
#!/usr/bin/env python3

import requests
from bs4 import BeautifulSoup
import click

from enum import Enum

VERSION = '0.1.0'

sess = requests.Session()
base_headers = {
        # request (x)html form
        'Accept': 'text/html,application/xhtml+xml',
        'User-Agent': 'htformtool/{version}'.format(version=VERSION),
        }
# 
post_headers = {
        # request confirmation code
        'Accept': 'text/plain',
        }

def hide_ua(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return
    base_headers['User-Agent'] = None

def split_on_ascii_whitespace(inp):
    start_position = 0
    end_position = 0
    tokens = []
    while start_position < len(inp) and inp[start_position] in '\x09\x0A\x0C\x0D\x20':
        start_position = start_position + 1
    while start_position < len(inp):
        end_position = start_position
        while end_position < len(inp) and inp[end_position] not in '\x09\x0A\x0C\x0D\x20':
            end_position = end_position + 1
        tokens.append(inp[start_position:end_position])
        start_position = end_position
        while start_position < len(inp) and inp[start_position] in '\x09\x0A\x0C\x0D\x20':
            start_position = start_position + 1
    return tokens

def ascii_lowercase(s):
    import string
    return s.translate(str.maketrans(string.ascii_uppercase, string.ascii_lowercase))

def get_encoding(label):
    # fuck
    if ascii_lowercase(label) not in ('unicode-1-1-utf-8', 'utf-8', 'utf8'):
        raise NotImplementedError
    import codecs
    return codecs.lookup('utf-8')

import re
newline_normalize = re.compile('\x0D(?!\x0A)|(?<!\x0D)\x0A')

def append_an_entry(l, name, value, no_line_break_normalization=False):
    # TODO might not be *strictly* correct
    name = newline_normalize.sub('\r\n', name)
    try:
        if not no_line_break_normalization:
            value = newline_normalize.sub('\r\n', value)
    except ValueError:
        pass
    l.append((name, value))

class FieldState(Enum):
    # normal <input> types
    HIDDEN = 'hidden'
    TEXT = 'text'
    SEARCH = 'search'
    TELEPHONE = 'tel'
    URL = 'url'
    EMAIL = 'email'
    PASSWORD = 'password'
    DATE = 'date'
    MONTH = 'month'
    WEEK = 'week'
    TIME = 'time'
    LOCAL_DATE_AND_TIME = 'datetime-local'
    NUMBER = 'number'
    RANGE = 'range'
    COLOR = 'color'
    CHECKBOX = 'checkbox'
    RADIO = 'radio'
    FILE = 'file'
    SUBMIT = 'submit'
    IMAGE = 'image'
    RESET = 'reset'
    BUTTON = 'button'

    # custom, htformtool-specific <input> types
    CREDENTIALS = 'credentials'

    # non-<input> types
    TEXTAREA = 'textarea'
    SELECT = 'select'

    # <button> types
    BSUBMIT = 'bsubmit'
    BRESET = 'breset'
    BBUTTON = 'bbutton'

    def is_button(self, submitter=None):
        if self in (FieldState.BSUBMIT, FieldState.IMAGE, FieldState.SUBMIT):
            return submitter is None or submitter == True
        if self in (FieldState.BRESET, FieldState.BBUTTON, FieldState.RESET, FieldState.BUTTON):
            return submitter is None or submitter == False
        return False

    def blocks_implicit_submission(self):
        return self in (FieldState.TEXT, FieldState.SEARCH, FieldState.URL, FieldState.TELEPHONE,
                FieldState.EMAIL, FieldState.PASSWORD, FieldState.DATE, FieldState.MONTH,
                FieldState.WEEK, FieldState.TIME, FieldState.LOCAL_DATE_AND_TIME, FieldState.NUMBER)

class ConstraintError(ValueError):
    pass

class FormData:
    """
    Represents the data to be submitted by the form.
    """

    def __init__(self, encoding, entry_list, action, enctype, method, target):
        self.encoding = encoding
        """The codec object that should be used to encode the form for sending"""
        self.entry_list = entry_list
        """The entry list"""
        self.action = action
        """The form's raw action (URL) (not parsed)"""
        self.enctype = enctype
        """The form's enctype"""
        self.method = method
        """The form's method (not sanitized)"""
        self.target = target
        """The form's target (not sanitized)"""

class Form:
    def __init__(self, form):
        self.form = form
        # these have the same length
        self.elements = []
        self.fields = []

    def submit(self, document_encoding, submitter=None):
        """
        Submits the form implicitly, or with the given submitter.

        Raises ValueError if the given submitter isn't a valid submitter.

        Raises ConstraintError if this field's no-validate state is false and one or more of the form's fields is invalid. (note: ConstraintError is a subtype of ValueError)

        Returns a FormData object, or None if implicit submission is not allowed.
        """
        if submitter is not None:
            if not submitter in self.fields:
                raise ValueError
            if not submitter.is_button(submitter=True):
                raise ValueError
            if not submitter.no_validate():
                for field in self.fields:
                    field.check_value()
        elif not self.form.get('novalidate'):
            blocks_implicit_submission = 0
            for field in self.fields:
                field.check_value()
                if submitter is None:
                    if field.is_button(submitter=True):
                        blocks_implicit_submission = 0
                        submitter = field
                    elif field._blocks_implicit_submission():
                        blocks_implicit_submission += 1
            if blocks_implicit_submission > 1:
                return None

        encoding = document_encoding
        if self.form.get('accept-charset') is not None:
            candidate_enc_labels = split_on_ascii_whitespace(self.form['accept-charset'])
            candidate_enc = []
            for token in candidate_enc_labels:
                enc = get_encoding(token)
                if enc is not None:
                    candidate_enc.append(enc)
            if not candidate_enc:
                encoding = get_encoding('utf-8')
            else:
                encoding = candidate_enc[0]

        controls = self.fields
        entry_list = []
        for field in controls:
            if field.is_button() and field is not submitter:
                continue
            if field.is_checkable() and not field.is_checked():
                continue
            if field.is_image_button():
                name = field.field['name'] + '.' if field.field.get('name') else ''
                namex = name + 'x'
                namey = name + 'y'
                append_an_entry(entry_list, namex, 0)
                append_an_entry(entry_list, namey, 0)
                continue
            name = field.field['name']
            if field.is_select():
                for option in field.get_options():
                    raise NotImplementedError
            elif field.is_checkable():
                append_an_entry(entry_list, name, field.get_value())
            elif field.is_file():
                raise NotImplementedError
            elif field.is_hidden() and name == '_charset_':
                raise NotImplementedError
            elif field.is_textarea():
                raise NotImplementedError
            else:
                append_an_entry(name, field.get_value())
            if field.has_valid_dirname():
                dirname = field.field['dirname']
                raise NotImplementedError

        action = None
        if submitter is not None and submitter.field.get('formaction') is not None:
            action = submitter.field['formaction']
        if action is None and self.form.get('action'):
            action = self.form['action']
        if action is None:
            action = ''

        enctype = None
        if submitter is not None and submitter.field.get('formenctype') is not None:
            enctype = submitter.field['formenctype']
        if enctype is None and self.form.get('enctype'):
            enctype = self.form['enctype']
        enctype = ascii_lowercase(enctype)
        if enctype not in ('application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'):
            enctype = 'application/x-www-form-urlencoded'

        method = None
        if submitter is not None and submitter.field.get('formmethod') is not None:
            method = submitter.field['formmethod']
        if method is None and self.form.get('method'):
            method = self.form['method']
        method = ascii_lowercase(method)
        if method not in ('get', 'post', 'dialog'):
            method = 'get'

        # WARNING: NOT SANITIZED
        target = None
        if submitter is not None and submitter.field.get('formtarget') is not None:
            target = submitter.field['formtarget']
        else:
            if self.form.get('target') is not None:
                target = self.form['target']
            elif self.form.find_parent('[document]').base is not None and self.form.find_parent('[document]').base.get('target') is not None:
                target = self.form.find_parent('[document]').base['target'] 
            else:
                target = ''

        return FormData(encoding, entry_list, action, enctype, method, target)

class FormField:
    def __in