-
Notifications
You must be signed in to change notification settings - Fork 101
/
HTTPRequest.py
1719 lines (1476 loc) · 61.6 KB
/
HTTPRequest.py
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
#
# Copyright (c) 2002-2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" HTTP request management.
"""
import codecs
import html
import os
import random
import re
import time
from types import SimpleNamespace
from urllib.parse import parse_qsl
from urllib.parse import unquote
from urllib.parse import urlparse
from AccessControl.tainted import should_be_tainted as base_should_be_tainted
from AccessControl.tainted import taint_string
from multipart import Headers
from multipart import MultipartParser
from multipart import parse_options_header
from zExceptions import BadRequest
from zope.component import queryUtility
from zope.i18n.interfaces import IUserPreferredLanguages
from zope.i18n.locales import LoadLocaleError
from zope.i18n.locales import locales
from zope.interface import directlyProvidedBy
from zope.interface import directlyProvides
from zope.interface import implementer
from zope.publisher.base import DebugFlags
from zope.publisher.http import splitport
from zope.publisher.interfaces.browser import IBrowserRequest
from ZPublisher import xmlrpc
from ZPublisher.BaseRequest import BaseRequest
from ZPublisher.BaseRequest import quote
from ZPublisher.Converters import get_converter
from ZPublisher.interfaces import IXmlrpcChecker
from ZPublisher.utils import basic_auth_decode
from .cookie import getCookieValuePolicy
# DOS attack protection -- limiting the amount of memory for forms
# probably should become configurable
FORM_MEMORY_LIMIT = 2 ** 20 # memory limit for forms
FORM_DISK_LIMIT = 2 ** 30 # disk limit for forms
FORM_MEMFILE_LIMIT = 4000 # limit for `BytesIO` -> temporary file switch
# This may get overwritten during configuration
default_encoding = 'utf-8'
isCGI_NAMEs = {
'SERVER_SOFTWARE': 1,
'SERVER_NAME': 1,
'GATEWAY_INTERFACE': 1,
'SERVER_PROTOCOL': 1,
'SERVER_PORT': 1,
'REQUEST_METHOD': 1,
'PATH_INFO': 1,
'PATH_TRANSLATED': 1,
'SCRIPT_NAME': 1,
'QUERY_STRING': 1,
'REMOTE_HOST': 1,
'REMOTE_ADDR': 1,
'AUTH_TYPE': 1,
'REMOTE_USER': 1,
'REMOTE_IDENT': 1,
'CONTENT_TYPE': 1,
'CONTENT_LENGTH': 1,
'SERVER_URL': 1,
}
isCGI_NAME = isCGI_NAMEs.__contains__
hide_key = {'HTTP_AUTHORIZATION': 1, 'HTTP_CGI_AUTHORIZATION': 1}
default_port = {'http': 80, 'https': 443}
tainting_env = str(os.environ.get('ZOPE_DTML_REQUEST_AUTOQUOTE', '')).lower()
TAINTING_ENABLED = tainting_env not in ('disabled', '0', 'no')
search_type = re.compile(r'(:[a-zA-Z][-a-zA-Z0-9_]+|\.[xy])$').search
_marker = []
# The trusted_proxies configuration setting contains a sequence
# of front-end proxies that are trusted to supply an accurate
# X_FORWARDED_FOR header. If REMOTE_ADDR is one of the values in this list
# and it has set an X_FORWARDED_FOR header, ZPublisher copies REMOTE_ADDR
# into X_FORWARDED_BY, and the last element of the X_FORWARDED_FOR list
# into REMOTE_ADDR. X_FORWARDED_FOR is left unchanged.
# The ZConfig machinery may sets this attribute on initialization
# if any trusted-proxies are defined in the configuration file.
trusted_proxies = []
class NestedLoopExit(Exception):
pass
@implementer(IBrowserRequest)
class HTTPRequest(BaseRequest):
""" Model HTTP request data.
This object provides access to request data. This includes, the
input headers, form data, server data, and cookies.
Request objects are created by the object publisher and will be
passed to published objects through the argument name, REQUEST.
The request object is a mapping object that represents a
collection of variable to value mappings. In addition, variables
are divided into five categories:
- Environment variables
These variables include input headers, server data, and other
request-related data. The variable names are as specified
in the <a href="https://tools.ietf.org/html/rfc3875">CGI
specification</a>
- Form data
These are data extracted from either a URL-encoded query
string or body, if present.
- Cookies
These are the cookie data, if present.
- Lazy Data
These are callables which are deferred until explicitly
referenced, at which point they are resolved and stored as
application data.
- Other
Data that may be set by an application object.
The form attribute of a request is actually a Field Storage
object. When file uploads are used, this provides a richer and
more complex interface than is provided by accessing form data as
items of the request. See the FieldStorage class documentation
for more details.
The request object may be used as a mapping object, in which case
values will be looked up in the order: environment variables,
other variables, form data, and then cookies.
"""
_hacked_path = None
args = ()
_urls = ()
_file = None
charset = default_encoding
retry_max_count = 0
def supports_retry(self):
return self.retry_count < self.retry_max_count
def delay_retry(self):
# Insert a delay before retrying. Moved here from supports_retry.
time.sleep(random.uniform(0, 2 ** (self.retry_count)))
def retry(self):
self.retry_count = self.retry_count + 1
self.stdin.seek(0)
r = self.__class__(stdin=self.stdin,
environ=self._orig_env,
response=self.response.retry())
r.retry_count = self.retry_count
return r
def clear(self):
# Clear all references to the input stream, possibly
# removing tempfiles.
self.stdin = None
self._file = None
self._fs = None
self.form.clear()
# we want to clear the lazy dict here because BaseRequests don't have
# one. Without this, there's the possibility of memory leaking
# after every request.
self._lazies = {}
BaseRequest.clear(self)
def setServerURL(self, protocol=None, hostname=None, port=None):
""" Set the parts of generated URLs. """
other = self.other
server_url = other.get('SERVER_URL', '')
if protocol is None and hostname is None and port is None:
return server_url
old_url = urlparse(server_url)
if protocol is None:
protocol = old_url.scheme
if hostname is None:
hostname = old_url.hostname
if port is None:
port = old_url.port
if (port is None or default_port[protocol] == port):
host = hostname
else:
host = f'{hostname}:{port}'
server_url = other['SERVER_URL'] = f'{protocol}://{host}'
self._resetURLS()
return server_url
def setVirtualRoot(self, path, hard=0):
""" Treat the current publishing object as a VirtualRoot """
other = self.other
if isinstance(path, str):
path = path.split('/')
self._script[:] = list(map(quote, [_p for _p in path if _p]))
del self._steps[:]
parents = other['PARENTS']
if hard:
del parents[:-1]
other['VirtualRootPhysicalPath'] = parents[-1].getPhysicalPath()
self._resetURLS()
def getVirtualRoot(self):
""" Return a slash-separated virtual root.
If it is same as the physical root, return ''.
"""
return '/'.join([''] + self._script)
def physicalPathToVirtualPath(self, path):
""" Remove the path to the VirtualRoot from a physical path """
if isinstance(path, str):
path = path.split('/')
rpp = self.other.get('VirtualRootPhysicalPath', ('',))
i = 0
for name in rpp[:len(path)]:
if path[i] == name:
i = i + 1
else:
break
return path[i:]
def physicalPathToURL(self, path, relative=0):
""" Convert a physical path into a URL in the current context """
path = self._script + list(
map(quote, self.physicalPathToVirtualPath(path)))
if relative:
path.insert(0, '')
else:
path.insert(0, self['SERVER_URL'])
return '/'.join(path)
def physicalPathFromURL(self, URL):
""" Convert a URL into a physical path in the current context.
If the URL makes no sense in light of the current virtual
hosting context, a ValueError is raised."""
other = self.other
path = [_p for _p in URL.split('/') if _p]
if URL.find('://') >= 0:
path = path[2:]
# Check the path against BASEPATH1
vhbase = self._script
vhbl = len(vhbase)
if path[:vhbl] == vhbase:
path = path[vhbl:]
else:
raise ValueError('Url does not match virtual hosting context')
vrpp = other.get('VirtualRootPhysicalPath', ('',))
return list(vrpp) + list(map(unquote, path))
def _resetURLS(self):
other = self.other
other['URL'] = '/'.join(
[other['SERVER_URL']] + self._script + self._steps)
for x in self._urls:
del self.other[x]
self._urls = ()
def getClientAddr(self):
""" The IP address of the client.
"""
return self._client_addr
def setupLocale(self):
envadapter = IUserPreferredLanguages(self, None)
if envadapter is None:
self._locale = None
return
langs = envadapter.getPreferredLanguages()
for httplang in langs:
parts = (httplang.split('-') + [None, None])[:3]
try:
self._locale = locales.getLocale(*parts)
return
except LoadLocaleError:
# Just try the next combination
pass
else:
# No combination gave us an existing locale, so use the default,
# which is guaranteed to exist
self._locale = locales.getLocale(None, None, None)
def __init__(self, stdin, environ, response, clean=0):
self.__doc__ = None # Make HTTPRequest objects unpublishable
self._orig_env = environ
# Avoid the overhead of scrubbing the environment in the
# case of request cloning for traversal purposes. If the
# clean flag is set, we know we can use the passed in
# environ dict directly.
if not clean:
environ = sane_environment(environ)
if 'HTTP_AUTHORIZATION' in environ:
self._auth = environ['HTTP_AUTHORIZATION']
response._auth = 1
del environ['HTTP_AUTHORIZATION']
self.stdin = stdin
self.environ = environ
get_env = environ.get
self.response = response
other = self.other = {'RESPONSE': response}
self.form = {}
self.taintedform = {}
self.steps = []
self._steps = []
self._lazies = {}
self._debug = DebugFlags()
# We don't set up the locale initially but just on first access
self._locale = _marker
if 'REMOTE_ADDR' in environ:
self._client_addr = environ['REMOTE_ADDR']
if 'HTTP_X_FORWARDED_FOR' in environ and \
self._client_addr in trusted_proxies:
# REMOTE_ADDR is one of our trusted local proxies.
# Not really very remote at all. The proxy can tell us the
# IP of the real remote client in the forwarded-for header
# Skip the proxy-address itself though
forwarded_for = [
e.strip()
for e in environ['HTTP_X_FORWARDED_FOR'].split(',')]
forwarded_for.reverse()
for entry in forwarded_for:
if entry not in trusted_proxies:
self._client_addr = entry
break
else:
self._client_addr = ''
################################################################
# Get base info first. This isn't likely to cause
# errors and might be useful to error handlers.
b = script = get_env('SCRIPT_NAME', '').strip()
# _script and the other _names are meant for URL construction
self._script = list(map(quote, [_s for _s in script.split('/') if _s]))
while b and b[-1] == '/':
b = b[:-1]
p = b.rfind('/')
if p >= 0:
b = b[:p + 1]
else:
b = ''
while b and b[0] == '/':
b = b[1:]
server_url = get_env('SERVER_URL', None)
if server_url is not None:
other['SERVER_URL'] = server_url = server_url.strip()
else:
https_environ = environ.get('HTTPS', False)
if https_environ and https_environ in ('on', 'ON', '1'):
protocol = 'https'
elif environ.get('SERVER_PORT_SECURE', None) == 1:
protocol = 'https'
elif (environ.get('REQUEST_SCHEME', '') or '').lower() == 'https':
protocol = 'https'
elif environ.get('wsgi.url_scheme') == 'https':
protocol = 'https'
else:
protocol = 'http'
if 'HTTP_HOST' in environ:
host = environ['HTTP_HOST'].strip()
hostname, port = splitport(host)
# NOTE: some (DAV) clients manage to forget the port. This
# can be fixed with the commented code below - the problem
# is that it causes problems for virtual hosting. I've left
# the commented code here in case we care enough to come
# back and do anything with it later.
#
# if port is None and 'SERVER_PORT' in environ:
# s_port = environ['SERVER_PORT']
# if s_port not in ('80', '443'):
# port = s_port
else:
hostname = environ['SERVER_NAME'].strip()
port = int(environ['SERVER_PORT'])
self.setServerURL(protocol=protocol, hostname=hostname, port=port)
server_url = other['SERVER_URL']
if server_url[-1:] == '/':
server_url = server_url[:-1]
if b:
self.base = f"{server_url}/{b}"
else:
self.base = server_url
while script[:1] == '/':
script = script[1:]
if script:
script = f"{server_url}/{script}"
else:
script = server_url
other['URL'] = self.script = script
other['method'] = environ.get('REQUEST_METHOD', 'GET').upper()
# Make WEBDAV_SOURCE_PORT reachable with a simple REQUEST.get
# to stay backwards-compatible
if environ.get('WEBDAV_SOURCE_PORT'):
other['WEBDAV_SOURCE_PORT'] = environ.get('WEBDAV_SOURCE_PORT')
################################################################
# Cookie values should *not* be appended to existing form
# vars with the same name - they are more like default values
# for names not otherwise specified in the form.
cookies = {}
k = get_env('HTTP_COOKIE', '')
if k:
parse_cookie(k, cookies)
self.cookies = cookies
self.taintedcookies = taint(cookies)
def processInputs(
self,
# "static" variables that we want to be local for speed
SEQUENCE=1,
DEFAULT=2,
RECORD=4,
RECORDS=8,
REC=12, # RECORD | RECORDS
EMPTY=16,
CONVERTED=32,
hasattr=hasattr,
getattr=getattr,
setattr=setattr):
"""Process request inputs
See the `Zope Developer Guide Object Publishing chapter
<https://zope.readthedocs.io/en/latest/zdgbook/ObjectPublishing.html>`_
for a detailed explanation in the section `Marshalling Arguments from
the Request`.
We need to delay input parsing so that it is done under
publisher control for error handling purposes.
"""
response = self.response
environ = self.environ
method = environ.get('REQUEST_METHOD', 'GET')
if method != 'GET':
fp = self.stdin
else:
fp = None
form = self.form
other = self.other
# If 'QUERY_STRING' is not present in environ
# FieldStorage will try to get it from sys.argv[1]
# which is not what we need.
if 'QUERY_STRING' not in environ:
environ['QUERY_STRING'] = ''
meth = None
self._fs = fs = ZopeFieldStorage(fp, environ)
self._file = fs.file
if 'HTTP_SOAPACTION' in environ:
# Stash XML request for interpretation by a SOAP-aware view
other['SOAPXML'] = fs.value
if 'CONTENT_TYPE' not in environ:
environ['CONTENT_TYPE'] = 'application/soap+xml'
if fs.list:
fslist = fs.list
tuple_items = {}
defaults = {}
converter = None
for item in fslist: # form data
# Note:
# we want to support 2 use cases
# 1. the form data has been created by the browser
# 2. the form data is free standing
# A browser internally works with character data,
# which it encodes for transmission to the server --
# usually with `self.charset`. Therefore, we
# usually expect the form data to represent data
# in this charset.
# We make this same assumption also for free standing
# form data, i.e. we expect the form creator to know
# the server's charset. However, sometimes data cannot
# be represented in this charset (e.g. arbitrary binary
# data). To cover this case, we decode data
# with the `surrogateescape` error handler (see PEP 383).
# It allows to retrieve the original byte sequence.
# With an encoding modifier, the form creator
# can specify the correct encoding used by a form field value.
# Note: we always expect the form field name
# to be representable with `self.charset`. As those
# names are expected to be `ASCII`, this should be no
# big restriction.
# Note: the use of `surrogateescape` can lead to delayed
# problems when surrogates reach the application because
# they cannot be encoded with a standard error handler.
# We might want to prevent this.
key = item.name
if key is None:
continue
character_encoding = ""
key = item.name.encode("latin-1").decode(
item.name_charset or self.charset)
if hasattr(item, 'file') and \
hasattr(item, 'filename') and \
hasattr(item, 'headers'):
item = FileUpload(item, self.charset)
else:
character_encoding = item.value_charset or self.charset
item = item.value.decode(
character_encoding, "surrogateescape")
# from here on, `item` contains the field value
# either as `FileUpload` or `str` with
# `character_encoding` as encoding,
# `key` the field name (`str`)
flags = 0
# Loop through the different types and set
# the appropriate flags
# We'll search from the back to the front.
# We'll do the search in two steps. First, we'll
# do a string search, and then we'll check it with
# a re search.
delim = key.rfind(':')
if delim >= 0:
mo = search_type(key, delim)
if mo:
delim = mo.start(0)
else:
delim = -1
while delim >= 0:
type_name = key[delim + 1:]
key = key[:delim]
c = get_converter(type_name, None)
if c is not None:
converter = c
flags = flags | CONVERTED
elif type_name == 'list':
flags = flags | SEQUENCE
elif type_name == 'tuple':
tuple_items[key] = 1
flags = flags | SEQUENCE
elif type_name == 'method' or type_name == 'action':
if delim:
meth = key
else:
meth = item
elif (type_name == 'default_method'
or type_name == 'default_action'):
if not meth:
if delim:
meth = key
else:
meth = item
elif type_name == 'default':
flags = flags | DEFAULT
elif type_name == 'record':
flags = flags | RECORD
elif type_name == 'records':
flags = flags | RECORDS
elif type_name == 'ignore_empty':
if not item:
flags = flags | EMPTY
elif has_codec(type_name):
# recode:
assert not isinstance(item, FileUpload), \
"cannot recode files"
item = item.encode(
character_encoding, "surrogateescape")
character_encoding = type_name
# we do not use `surrogateescape` as
# we immediately want to determine
# an incompatible encoding modifier
item = item.decode(character_encoding)
delim = key.rfind(':')
if delim < 0:
break
mo = search_type(key, delim)
if mo:
delim = mo.start(0)
else:
delim = -1
# Filter out special names from form:
if key in isCGI_NAMEs or key.startswith('HTTP_'):
continue
if flags:
# skip over empty fields
if flags & EMPTY:
continue
# Split the key and its attribute
if flags & REC:
key = key.split(".")
key, attr = ".".join(key[:-1]), key[-1]
# defer conversion
if flags & CONVERTED:
try:
if character_encoding and \
getattr(converter, "binary", False):
item = item.encode(character_encoding,
"surrogateescape")
item = converter(item)
except Exception:
if not item and \
not (flags & DEFAULT) and \
key in defaults:
item = defaults[key]
if flags & RECORD:
item = getattr(item, attr)
if flags & RECORDS:
item = getattr(item[-1], attr)
else:
raise
# Determine which dictionary to use
if flags & DEFAULT:
mapping_object = defaults
else:
mapping_object = form
# Insert in dictionary
if key in mapping_object:
if flags & RECORDS:
# Get the list and the last record
# in the list. reclist is mutable.
reclist = mapping_object[key]
x = reclist[-1]
if not hasattr(x, attr):
# If the attribute does not
# exist, set it
if flags & SEQUENCE:
item = [item]
setattr(x, attr, item)
else:
if flags & SEQUENCE:
# If the attribute is a
# sequence, append the item
# to the existing attribute
y = getattr(x, attr)
y.append(item)
setattr(x, attr, y)
else:
# Create a new record and add
# it to the list
n = record()
setattr(n, attr, item)
mapping_object[key].append(n)
elif flags & RECORD:
b = mapping_object[key]
if flags & SEQUENCE:
item = [item]
if not hasattr(b, attr):
# if it does not have the
# attribute, set it
setattr(b, attr, item)
else:
# it has the attribute so
# append the item to it
setattr(b, attr, getattr(b, attr) + item)
else:
# it is not a sequence so
# set the attribute
setattr(b, attr, item)
else:
# it is not a record or list of records
found = mapping_object[key]
if isinstance(found, list):
found.append(item)
else:
found = [found, item]
mapping_object[key] = found
else:
# The dictionary does not have the key
if flags & RECORDS:
# Create a new record, set its attribute
# and put it in the dictionary as a list
a = record()
if flags & SEQUENCE:
item = [item]
setattr(a, attr, item)
mapping_object[key] = [a]
elif flags & RECORD:
# Create a new record, set its attribute
# and put it in the dictionary
if flags & SEQUENCE:
item = [item]
r = mapping_object[key] = record()
setattr(r, attr, item)
else:
# it is not a record or list of records
if flags & SEQUENCE:
item = [item]
mapping_object[key] = item
else:
# This branch is for case when no type was specified.
mapping_object = form
# Insert in dictionary
if key in mapping_object:
# it is not a record or list of records
found = mapping_object[key]
if isinstance(found, list):
found.append(item)
else:
found = [found, item]
mapping_object[key] = found
else:
mapping_object[key] = item
# insert defaults into form dictionary
if defaults:
for key, value in defaults.items():
if key not in form:
# if the form does not have the key,
# set the default
form[key] = value
else:
# The form has the key
if isinstance(value, record):
# if the key is mapped to a record, get the
# record
r = form[key]
for k, v in value.__dict__.items():
# loop through the attributes and value
# in the default dictionary
if not hasattr(r, k):
# if the form dictionary doesn't have
# the attribute, set it to the default
setattr(r, k, v)
form[key] = r
elif isinstance(value, list):
# the default value is a list
val = form[key]
if not isinstance(val, list):
val = [val]
for x in value:
# for each x in the list
if isinstance(x, record):
# if the x is a record
for k, v in x.__dict__.items():
# loop through each
# attribute and value in
# the record
for y in val:
# loop through each
# record in the form
# list if it doesn't
# have the attributes
# in the default
# dictionary, set them
if not hasattr(y, k):
setattr(y, k, v)
else:
# x is not a record
if x not in val:
val.append(x)
form[key] = val
else:
# The form has the key, the key is not mapped
# to a record or sequence so do nothing
pass
# Convert to tuples
if tuple_items:
for key in tuple_items.keys():
# Split the key and get the attr
k = key.split(".")
k, attr = '.'.join(k[:-1]), k[-1]
a = attr
new = ''
# remove any type_names in the attr
while not a == '':
a = a.split(":")
a, new = ':'.join(a[:-1]), a[-1]
attr = new
if k in form:
# If the form has the split key get its value
item = form[k]
if isinstance(item, record):
# if the value is mapped to a record, check if it
# has the attribute, if it has it, convert it to
# a tuple and set it
if hasattr(item, attr):
value = tuple(getattr(item, attr))
setattr(item, attr, value)
else:
# It is mapped to a list of records
for x in item:
# loop through the records
if hasattr(x, attr):
# If the record has the attribute
# convert it to a tuple and set it
value = tuple(getattr(x, attr))
setattr(x, attr, value)
else:
# the form does not have the split key
if key in form:
# if it has the original key, get the item
# convert it to a tuple
item = form[key]
item = tuple(form[key])
form[key] = item
self.taintedform = taint(self.form)
if method == 'POST' \
and 'text/xml' in fs.headers.get('content-type', '') \
and use_builtin_xmlrpc(self):
# Ye haaa, XML-RPC!
if meth is not None:
raise BadRequest('method directive not supported for '
'xmlrpc request')
meth, self.args = xmlrpc.parse_input(fs.value)
response = xmlrpc.response(response)
other['RESPONSE'] = self.response = response
self.maybe_webdav_client = 0
if meth:
if 'PATH_INFO' in environ:
path = environ['PATH_INFO']
while path[-1:] == '/':
path = path[:-1]
else:
path = ''
other['PATH_INFO'] = f"{path}/{meth}"
self._hacked_path = 1
def resolve_url(self, url):
# Attempt to resolve a url into an object in the Zope
# namespace. The url must be a fully-qualified url. The
# method will return the requested object if it is found
# or raise the same HTTP error that would be raised in
# the case of a real web request. If the passed in url
# does not appear to describe an object in the system
# namespace (e.g. the host, port or script name don't
# match that of the current request), a ValueError will
# be raised.
if url.find(self.script) != 0:
raise ValueError('Different namespace.')
path = url[len(self.script):]
while path and path[0] == '/':
path = path[1:]
while path and path[-1] == '/':
path = path[:-1]
req = self.clone()
rsp = req.response
req['PATH_INFO'] = path
object = None
# Try to traverse to get an object. Note that we call
# the exception method on the response, but we don't
# want to actually abort the current transaction
# (which is usually the default when the exception
# method is called on the response).
try:
object = req.traverse(path)
except Exception as exc:
rsp.exception()
req.clear()
raise exc.__class__(rsp.errmsg)
# The traversal machinery may return a "default object"
# like an index_html document. This is not appropriate
# in the context of the resolve_url method so we need
# to ensure we are getting the actual object named by
# the given url, and not some kind of default object.
if hasattr(object, 'id'):
if callable(object.id):
name = object.id()
else:
name = object.id
elif hasattr(object, '__name__'):
name = object.__name__
else:
name = ''
if name != os.path.split(path)[-1]:
object = req.PARENTS[0]
req.clear()
return object
def clone(self):
# Return a clone of the current request object
# that may be used to perform object traversal.
environ = self.environ.copy()
environ['REQUEST_METHOD'] = 'GET'
if self._auth:
environ['HTTP_AUTHORIZATION'] = self._auth
if self.response is not None:
response = self.response.__class__()
else:
response = None
clone = self.__class__(None, environ, response, clean=1)
clone['PARENTS'] = [self['PARENTS'][-1]]
directlyProvides(clone, *directlyProvidedBy(self))
return clone
def getHeader(self, name, default=None, literal=False):
"""Return the named HTTP header, or an optional default
argument or None if the header is not found. Note that
both original and CGI-ified header names are recognized,
e.g. 'Content-Type', 'CONTENT_TYPE' and 'HTTP_CONTENT_TYPE'
should all return the Content-Type header, if available.
"""
environ = self.environ
if not literal:
name = name.replace('-', '_').upper()
val = environ.get(name, None)
if val is not None:
return val
if name[:5] != 'HTTP_':
name = 'HTTP_%s' % name
return environ.get(name, default)
get_header = getHeader # BBB
def get(self, key, default=None, returnTaints=0,
URLmatch=re.compile('URL(PATH)?([0-9]+)$').match,
BASEmatch=re.compile('BASE(PATH)?([0-9]+)$').match,
):
"""Get a variable value
Return a value for the variable key, or default if not found.
If key is "REQUEST", return the request.
Otherwise, the value will be looked up from one of the request data
categories. The search order is:
other (the target for explicitly set variables),
the special URL and BASE variables,
environment variables,
common variables (defined by the request class),
lazy variables (set with set_lazy),
form data and cookies.
If returnTaints has a true value, then the access to
form and cookie variables returns values with special
protection against embedded HTML fragments to counter
some cross site scripting attacks.
"""
if key == 'REQUEST':