HTTPRequest.py 60.1 KB
Newer Older
Jim Fulton's avatar
Jim Fulton committed
1
##############################################################################
matt@zope.com's avatar
matt@zope.com committed
2 3
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
4
#
matt@zope.com's avatar
matt@zope.com committed
5 6 7 8 9 10
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
11
#
Jim Fulton's avatar
Jim Fulton committed
12 13
##############################################################################

14
__version__='$Revision: 1.88 $'[11:-2]
15

16
import re, sys, os,  urllib, time, random, cgi, codecs
17
from types import StringType, UnicodeType
Jim Fulton's avatar
Jim Fulton committed
18 19
from BaseRequest import BaseRequest
from HTTPResponse import HTTPResponse
20
from cgi import FieldStorage, escape
21
from urllib import quote, unquote, splittype, splitport
Martijn Pieters's avatar
Martijn Pieters committed
22
from copy import deepcopy
23
from Converters import get_converter
Martijn Pieters's avatar
Martijn Pieters committed
24
from TaintedString import TaintedString
Jim Fulton's avatar
Jim Fulton committed
25
from maybe_lock import allocate_lock
Jim Fulton's avatar
Jim Fulton committed
26
xmlrpc=None # Placeholder for module that we'll import if we have to.
Jim Fulton's avatar
Jim Fulton committed
27 28

isCGI_NAME = {
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
        '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,
Jim Fulton's avatar
Jim Fulton committed
45 46 47 48 49 50 51 52
        'CONTENT_LENGTH' : 1,
        'SERVER_URL': 1,
        }.has_key

hide_key={'HTTP_AUTHORIZATION':1,
          'HTTP_CGI_AUTHORIZATION': 1,
          }.has_key

53 54
default_port={'http': '80', 'https': '443'}

55 56 57
tainting_env = str(os.environ.get('ZOPE_DTML_REQUEST_AUTOQUOTE', '')).lower()
TAINTING_ENABLED  = tainting_env not in ('disabled', '0', 'no')

Jim Fulton's avatar
Jim Fulton committed
58 59 60 61
_marker=[]
class HTTPRequest(BaseRequest):
    """\
    Model HTTP request data.
62

Jim Fulton's avatar
Jim Fulton committed
63 64 65 66 67 68 69 70
    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
71
    are divided into five categories:
Jim Fulton's avatar
Jim Fulton committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

      - Environment variables

        These variables include input headers, server data, and other
        request-related data.  The variable names are as <a
        href="http://hoohoo.ncsa.uiuc.edu/cgi/env.html">specified</a>
        in the <a
        href="http://hoohoo.ncsa.uiuc.edu/cgi/interface.html">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.

91 92 93 94 95 96
      - Lazy Data

        These are callables which are deferred until explicitly
        referenced, at which point they are resolved and stored as
        application data.

Jim Fulton's avatar
Jim Fulton committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
      - 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
Jim Fulton's avatar
Jim Fulton committed
112
    args=()
113
    _file=None
114
    _urls = ()
115

Jim Fulton's avatar
Jim Fulton committed
116
    retry_max_count=3
117 118
    def supports_retry(self):
        if self.retry_count < self.retry_max_count:
119
            time.sleep(random.uniform(0, 2**(self.retry_count)))
120
            return 1
Jim Fulton's avatar
Jim Fulton committed
121 122

    def retry(self):
123
        self.retry_count=self.retry_count+1
124
        self.stdin.seek(0)
Jim Fulton's avatar
Jim Fulton committed
125 126 127 128
        r=self.__class__(stdin=self.stdin,
                         environ=self._orig_env,
                         response=self.response.retry()
                         )
129
        r.retry_count=self.retry_count
Jim Fulton's avatar
Jim Fulton committed
130 131
        return r

132 133 134 135 136 137
    def close(self):
        # 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.close(self)
138

139 140 141 142 143 144 145 146 147 148 149
    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
        oldprotocol, oldhost = splittype(server_url)
        oldhostname, oldport = splitport(oldhost[2:])
        if protocol is None: protocol = oldprotocol
        if hostname is None: hostname = oldhostname
        if port is None: port = oldport
150

151 152 153 154 155 156 157 158 159 160 161
        if (port is None or default_port[protocol] == port):
            host = hostname
        else:
            host = hostname + ':' + port
        server_url = other['SERVER_URL'] = '%s://%s' % (protocol, host)
        self._resetURLS()
        return server_url

    def setVirtualRoot(self, path, hard=0):
        """ Treat the current publishing object as a VirtualRoot """
        other = self.other
162 163
        if isinstance(path, StringType) or isinstance(path, UnicodeType):
            path = path.split('/')
164
        self._script[:] = map(quote, filter(None, path))
165 166 167 168 169 170 171
        del self._steps[:]
        parents = other['PARENTS']
        if hard:
            del parents[:-1]
        other['VirtualRootPhysicalPath'] = parents[-1].getPhysicalPath()
        self._resetURLS()

172 173 174
    def physicalPathToVirtualPath(self, path):
        """ Remove the path to the VirtualRoot from a physical path """
        if type(path) is type(''):
175
            path = path.split( '/')
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        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 + map(quote, self.physicalPathToVirtualPath(path))
        if relative:
            path.insert(0, '')
        else:
            path.insert(0, self['SERVER_URL'])
192
        return '/'.join(path)
193

194 195 196 197 198 199
    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
        bad_server_url = 0
200
        path = filter(None, URL.split( '/'))
201

202
        if URL.find( '://') >= 0:
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
            path = path[2:]

        # Check the path against BASEPATH1
        vhbase = self._script
        vhbl = len(vhbase)
        bad_basepath = 0
        if path[:vhbl] == vhbase:
            path = path[vhbl:]
        else:
            raise ValueError, (
                'Url does not match virtual hosting context'
                )
        vrpp = other.get('VirtualRootPhysicalPath', ('',))
        return list(vrpp) + map(unquote, path)

218 219
    def _resetURLS(self):
        other = self.other
220 221
        other['URL'] = '/'.join([other['SERVER_URL']] + self._script +
                            self._steps)
222 223
        for x in self._urls:
            del self.other[x]
224
        self._urls = ()
225

226 227 228 229 230
    def getClientAddr(self):
        """ The IP address of the client.
        """
        return self._client_addr

231
    def __init__(self, stdin, environ, response, clean=0):
Jim Fulton's avatar
Jim Fulton committed
232
        self._orig_env=environ
Jim Fulton's avatar
Jim Fulton committed
233 234 235 236 237
        # 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)
238 239 240 241 242

        if environ.has_key('HTTP_AUTHORIZATION'):
            self._auth=environ['HTTP_AUTHORIZATION']
            response._auth=1
            del environ['HTTP_AUTHORIZATION']
243

244 245
        self.stdin=stdin
        self.environ=environ
Jim Fulton's avatar
Jim Fulton committed
246 247
        have_env=environ.has_key
        get_env=environ.get
248
        self.response=response
Jim Fulton's avatar
Jim Fulton committed
249 250
        other=self.other={'RESPONSE': response}
        self.form={}
Martijn Pieters's avatar
Martijn Pieters committed
251
        self.taintedform={}
Jim Fulton's avatar
Jim Fulton committed
252
        self.steps=[]
253
        self._steps=[]
254
        self._lazies={}
Jim Fulton's avatar
Jim Fulton committed
255

256 257 258 259 260 261 262 263 264 265

        if environ.has_key('REMOTE_ADDR'):
            self._client_addr = environ['REMOTE_ADDR']
            if environ.has_key('HTTP_X_FORWARDED_FOR') 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
                self._client_addr = environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip()
        else:
            self._client_addr = ''

Jim Fulton's avatar
Jim Fulton committed
266 267 268
        ################################################################
        # Get base info first. This isn't likely to cause
        # errors and might be useful to error handlers.
269
        b=script=get_env('SCRIPT_NAME','').strip()
270 271

        # _script and the other _names are meant for URL construction
272
        self._script = map(quote, filter(None, script.split( '/')))
273

Jim Fulton's avatar
Jim Fulton committed
274
        while b and b[-1]=='/': b=b[:-1]
275
        p = b.rfind('/')
Jim Fulton's avatar
Jim Fulton committed
276 277 278 279 280 281
        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:
282
            other['SERVER_URL'] = server_url = server_url.strip()
Jim Fulton's avatar
Jim Fulton committed
283
        else:
284 285 286
            if have_env('HTTPS') and (
                environ['HTTPS'] == "on" or environ['HTTPS'] == "ON"):
                protocol = 'https'
287
            elif (have_env('SERVER_PORT_SECURE') and
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
                environ['SERVER_PORT_SECURE'] == "1"):
                protocol = 'https'
            else: protocol = 'http'

            if have_env('HTTP_HOST'):
                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 environ.has_key('SERVER_PORT'):
                #     s_port=environ['SERVER_PORT']
                #     if s_port not in ('80', '443'):
                #         port=s_port

            else:
                hostname = environ['SERVER_NAME'].strip()
                port = environ['SERVER_PORT']
            self.setServerURL(protocol=protocol, hostname=hostname, port=port)
            server_url = other['SERVER_URL']
312

Jim Fulton's avatar
Jim Fulton committed
313
        if server_url[-1:]=='/': server_url=server_url[:-1]
314

Jim Fulton's avatar
Jim Fulton committed
315 316 317 318 319 320 321 322 323 324 325 326
        if b: self.base="%s/%s" % (server_url,b)
        else: self.base=server_url
        while script[:1]=='/': script=script[1:]
        if script: script="%s/%s" % (server_url,script)
        else:      script=server_url
        other['URL']=self.script=script

        ################################################################
        # 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={}
Martijn Pieters's avatar
Martijn Pieters committed
327
        taintedcookies={}
Jim Fulton's avatar
Jim Fulton committed
328 329 330
        k=get_env('HTTP_COOKIE','')
        if k:
            parse_cookie(k, cookies)
Martijn Pieters's avatar
Martijn Pieters committed
331 332 333 334 335 336 337 338 339 340
            for k, v in cookies.items():
                istainted = 0
                if '<' in k:
                    k = TaintedString(k)
                    istainted = 1
                if '<' in v:
                    v = TaintedString(v)
                    istainted = 1
                if istainted:
                    taintedcookies[k] = v
Jim Fulton's avatar
Jim Fulton committed
341
        self.cookies=cookies
Martijn Pieters's avatar
Martijn Pieters committed
342
        self.taintedcookies = taintedcookies
343

344 345 346 347 348 349 350 351 352 353 354 355 356
    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,
357
        search_type=re.compile('(:[a-zA-Z][-a-zA-Z0-9_]+|\\.[xy])$').search,
358 359 360
        ):
        """Process request inputs

Jim Fulton's avatar
Jim Fulton committed
361 362
        We need to delay input parsing so that it is done under
        publisher control for error handling purposes.
363 364 365
        """
        response=self.response
        environ=self.environ
Jim Fulton's avatar
Jim Fulton committed
366
        method=environ.get('REQUEST_METHOD','GET')
367

368
        if method != 'GET': fp=self.stdin
Jim Fulton's avatar
Jim Fulton committed
369
        else:               fp=None
Jim Fulton's avatar
Jim Fulton committed
370

Jim Fulton's avatar
Jim Fulton committed
371
        form=self.form
372
        other=self.other
Martijn Pieters's avatar
Martijn Pieters committed
373
        taintedform=self.taintedform
Jim Fulton's avatar
Jim Fulton committed
374

Jim Fulton's avatar
Jim Fulton committed
375 376 377
        meth=None
        fs=FieldStorage(fp=fp,environ=environ,keep_blank_values=1)
        if not hasattr(fs,'list') or fs.list is None:
Jim Fulton's avatar
Jim Fulton committed
378 379 380 381 382 383 384 385
            # Hm, maybe it's an XML-RPC
            if (fs.headers.has_key('content-type') and
                fs.headers['content-type'] == 'text/xml' and
                method == 'POST'):
                # Ye haaa, XML-RPC!
                global xmlrpc
                if xmlrpc is None: import xmlrpc
                meth, self.args = xmlrpc.parse_input(fs.value)
Jim Fulton's avatar
Jim Fulton committed
386 387
                response=xmlrpc.response(response)
                other['RESPONSE']=self.response=response
388
                self.maybe_webdav_client = 0
Jim Fulton's avatar
Jim Fulton committed
389
            else:
390
                self._file=fs.file
Jim Fulton's avatar
Jim Fulton committed
391 392 393 394 395
        else:
            fslist=fs.list
            tuple_items={}
            lt=type([])
            CGI_name=isCGI_NAME
396
            defaults={}
Martijn Pieters's avatar
Martijn Pieters committed
397
            tainteddefaults={}
398
            converter=seqf=None
399

Jim Fulton's avatar
Jim Fulton committed
400
            for item in fslist:
401

Martijn Pieters's avatar
Martijn Pieters committed
402
                isFileUpload = 0
403
                key=item.name
Jim Fulton's avatar
Jim Fulton committed
404 405 406
                if (hasattr(item,'file') and hasattr(item,'filename')
                    and hasattr(item,'headers')):
                    if (item.file and
407 408 409 410
                        (item.filename is not None
                         # RFC 1867 says that all fields get a content-type.
                         # or 'content-type' in map(lower, item.headers.keys())
                         )):
Jim Fulton's avatar
Jim Fulton committed
411
                        item=FileUpload(item)
Martijn Pieters's avatar
Martijn Pieters committed
412
                        isFileUpload = 1
Jim Fulton's avatar
Jim Fulton committed
413 414 415
                    else:
                        item=item.value

416
                flags=0
417
                character_encoding = ''
Martijn Pieters's avatar
Martijn Pieters committed
418 419 420
                # Variables for potentially unsafe values.
                tainted = None
                converter_type = None
421 422 423

                # Loop through the different types and set
                # the appropriate flags
424 425 426 427

                # 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
428
                # a re search.
429

430

431
                l=key.rfind(':')
432
                if l >= 0:
433 434 435 436
                    mo = search_type(key,l)
                    if mo: l=mo.start(0)
                    else:  l=-1

437 438 439 440
                    while l >= 0:
                        type_name=key[l+1:]
                        key=key[:l]
                        c=get_converter(type_name, None)
441 442

                        if c is not None:
443
                            converter=c
Martijn Pieters's avatar
Martijn Pieters committed
444
                            converter_type = type_name
445 446 447 448 449 450 451 452
                            flags=flags|CONVERTED
                        elif type_name == 'list':
                            seqf=list
                            flags=flags|SEQUENCE
                        elif type_name == 'tuple':
                            seqf=tuple
                            tuple_items[key]=1
                            flags=flags|SEQUENCE
453
                        elif (type_name == 'method' or type_name == 'action'):
454 455
                            if l: meth=key
                            else: meth=item
456 457
                        elif (type_name == 'default_method' or type_name == \
                              'default_action'):
458 459 460 461 462 463 464 465 466 467 468
                            if not meth:
                                if l: 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
469 470
                        elif has_codec(type_name):
                            character_encoding = type_name
471

472
                        l=key.rfind(':')
473
                        if l < 0: break
474 475 476 477 478
                        mo=search_type(key,l)
                        if mo: l = mo.start(0)
                        else:  l = -1


479

Jim Fulton's avatar
Jim Fulton committed
480 481 482
                # Filter out special names from form:
                if CGI_name(key) or key[:5]=='HTTP_': continue

Martijn Pieters's avatar
Martijn Pieters committed
483 484 485 486 487
                # If the key is tainted, mark it so as well.
                tainted_key = key
                if '<' in key:
                    tainted_key = TaintedString(key)

488 489
                if flags:

490
                    # skip over empty fields
491 492 493 494
                    if flags&EMPTY: continue

                    #Split the key and its attribute
                    if flags&REC:
495 496
                        key=key.split(".")
                        key, attr=".".join(key[:-1]), key[-1]
Martijn Pieters's avatar
Martijn Pieters committed
497 498 499 500 501 502 503 504 505 506 507

                        # Update the tainted_key if necessary
                        tainted_key = key
                        if '<' in key:
                            tainted_key = TaintedString(key)

                        # Attributes cannot hold a <.
                        if '<' in attr:
                            raise ValueError(
                                "%s is not a valid record attribute name" %
                                escape(attr))
508

509 510 511
                    # defer conversion
                    if flags&CONVERTED:
                        try:
512 513 514 515 516 517 518 519 520 521 522
                            if character_encoding:
                                # We have a string with a specified character encoding.
                                # This gets passed to the converter either as unicode, if it can
                                # handle it, or crunched back down to latin-1 if it can not.
                                item = unicode(item,character_encoding)
                                if hasattr(converter,'convert_unicode'):
                                    item = converter.convert_unicode(item)
                                else:
                                    item = converter(item.encode('latin1'))
                            else:
                                item=converter(item)
Martijn Pieters's avatar
Martijn Pieters committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

                            # Flag potentially unsafe values
                            if converter_type in ('string', 'required', 'text',
                                                  'ustring', 'utext'):
                                if not isFileUpload and '<' in item:
                                    tainted = TaintedString(item)
                            elif converter_type in ('tokens', 'lines',
                                                    'utokens', 'ulines'):
                                is_tainted = 0
                                tainted = item[:]
                                for i in range(len(tainted)):
                                    if '<' in tainted[i]:
                                        is_tainted = 1
                                        tainted[i] = TaintedString(tainted[i])
                                if not is_tainted:
                                    tainted = None
539

540 541 542 543 544 545 546
                        except:
                            if (not item and not (flags&DEFAULT) and
                                defaults.has_key(key)):
                                item = defaults[key]
                                if flags&RECORD:
                                    item=getattr(item,attr)
                                if flags&RECORDS:
547
                                    item = getattr(item[-1], attr)
Martijn Pieters's avatar
Martijn Pieters committed
548 549 550 551 552 553
                                if tainteddefaults.has_key(tainted_key):
                                    tainted = tainteddefaults[tainted_key]
                                    if flags&RECORD:
                                        tainted = getattr(tainted, attr)
                                    if flags&RECORDS:
                                        tainted = getattr(tainted[-1], attr)
554
                            else:
555 556
                                raise

Martijn Pieters's avatar
Martijn Pieters committed
557 558 559 560 561 562 563 564 565
                    elif not isFileUpload and '<' in item:
                        # Flag potentially unsafe values
                        tainted = TaintedString(item)

                    # If the key is tainted, we need to store stuff in the
                    # tainted dict as well, even if the value is safe.
                    if '<' in tainted_key and tainted is None:
                        tainted = item

566 567
                    #Determine which dictionary to use
                    if flags&DEFAULT:
568
                        mapping_object = defaults
Martijn Pieters's avatar
Martijn Pieters committed
569
                        tainted_mapping = tainteddefaults
570
                    else:
571
                        mapping_object = form
Martijn Pieters's avatar
Martijn Pieters committed
572
                        tainted_mapping = taintedform
573 574 575

                    #Insert in dictionary
                    if mapping_object.has_key(key):
576 577
                        if flags&RECORDS:
                            #Get the list and the last record
578
                            #in the list. reclist is mutable.
579 580
                            reclist = mapping_object[key]
                            x = reclist[-1]
Martijn Pieters's avatar
Martijn Pieters committed
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

                            if tainted:
                                # Store a tainted copy as well
                                if not tainted_mapping.has_key(tainted_key):
                                    tainted_mapping[tainted_key] = deepcopy(
                                        reclist)
                                treclist = tainted_mapping[tainted_key]
                                lastrecord = treclist[-1]

                                if not hasattr(lastrecord, attr):
                                    if flags&SEQUENCE: tainted = [tainted]
                                    setattr(lastrecord, attr, tainted)
                                else:
                                    if flags&SEQUENCE:
                                        getattr(lastrecord,
                                            attr).append(tainted)
                                    else:
                                        newrec = record()
                                        setattr(newrec, attr, tainted)
                                        treclist.append(newrec)

                            elif tainted_mapping.has_key(tainted_key):
                                # If we already put a tainted value into this
                                # recordset, we need to make sure the whole
                                # recordset is built.
                                treclist = tainted_mapping[tainted_key]
                                lastrecord = treclist[-1]
                                copyitem = item

                                if not hasattr(lastrecord, attr):
                                    if flags&SEQUENCE: copyitem = [copyitem]
                                    setattr(lastrecord, attr, copyitem)
                                else:
                                    if flags&SEQUENCE:
                                        getattr(lastrecord,
                                            attr).append(copyitem)
                                    else:
                                        newrec = record()
                                        setattr(newrec, attr, copyitem)
                                        treclist.append(newrec)
621

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
                            if not hasattr(x,attr):
                                #If the attribute does not
                                #exist, setit
                                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)
640
                                    mapping_object[key].append(n)
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
                        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
656
                                setattr(b,attr,item)
Martijn Pieters's avatar
Martijn Pieters committed
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

                            # Store a tainted copy as well if necessary
                            if tainted:
                                if not tainted_mapping.has_key(tainted_key):
                                    tainted_mapping[tainted_key] = deepcopy(
                                        mapping_object[key])
                                b = tainted_mapping[tainted_key]
                                if flags&SEQUENCE:
                                    seq = getattr(b, attr, [])
                                    seq.append(tainted)
                                    setattr(b, attr, seq)
                                else:
                                    setattr(b, attr, tainted)

                            elif tainted_mapping.has_key(tainted_key):
                                # If we already put a tainted value into this
                                # record, we need to make sure the whole record
                                # is built.
                                b = tainted_mapping[tainted_key]
                                if flags&SEQUENCE:
                                    seq = getattr(b, attr, [])
                                    seq.append(item)
                                    setattr(b, attr, seq)
                                else:
                                    setattr(b, attr, item)

683 684 685
                        else:
                            # it is not a record or list of records
                            found=mapping_object[key]
Martijn Pieters's avatar
Martijn Pieters committed
686 687 688 689 690 691 692 693 694 695

                            if tainted:
                                # Store a tainted version if necessary
                                if not tainted_mapping.has_key(tainted_key):
                                    copied = deepcopy(found)
                                    if isinstance(copied, lt):
                                        tainted_mapping[tainted_key] = copied
                                    else:
                                        tainted_mapping[tainted_key] = [copied]
                                tainted_mapping[tainted_key].append(tainted)
696

Martijn Pieters's avatar
Martijn Pieters committed
697 698 699 700 701 702 703 704 705 706 707
                            elif tainted_mapping.has_key(tainted_key):
                                # We may already have encountered a tainted
                                # value for this key, and the tainted_mapping
                                # needs to hold all the values.
                                tfound = tainted_mapping[tainted_key]
                                if isinstance(tfound, lt):
                                    tainted_mapping[tainted_key].append(item)
                                else:
                                    tainted_mapping[tainted_key] = [tfound,
                                                                    item]

708 709 710 711 712
                            if type(found) is lt:
                                found.append(item)
                            else:
                                found=[found,item]
                                mapping_object[key]=found
713
                    else:
714 715 716 717 718 719 720 721
                        # 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]
Martijn Pieters's avatar
Martijn Pieters committed
722 723 724 725 726 727 728 729

                            if tainted:
                                # Store a tainted copy if necessary
                                a = record()
                                if flags&SEQUENCE: tainted = [tainted]
                                setattr(a, attr, tainted)
                                tainted_mapping[tainted_key] = [a]

730 731 732 733 734 735
                        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)
Martijn Pieters's avatar
Martijn Pieters committed
736 737 738 739 740 741

                            if tainted:
                                # Store a tainted copy if necessary
                                if flags&SEQUENCE: tainted = [tainted]
                                r = tainted_mapping[tainted_key] = record()
                                setattr(r, attr, tainted)
742 743 744 745
                        else:
                            # it is not a record or list of records
                            if flags&SEQUENCE: item=[item]
                            mapping_object[key]=item
746

Martijn Pieters's avatar
Martijn Pieters committed
747 748 749 750 751
                            if tainted:
                                # Store a tainted copy if necessary
                                if flags&SEQUENCE: tainted = [tainted]
                                tainted_mapping[tainted_key] = tainted

752
                else:
753 754
                    # This branch is for case when no type was specified.
                    mapping_object = form
755

Martijn Pieters's avatar
Martijn Pieters committed
756 757 758 759 760
                    if not isFileUpload and '<' in item:
                        tainted = TaintedString(item)
                    elif '<' in key:
                        tainted = item

761 762 763 764
                    #Insert in dictionary
                    if mapping_object.has_key(key):
                        # it is not a record or list of records
                        found=mapping_object[key]
Martijn Pieters's avatar
Martijn Pieters committed
765 766 767 768 769 770 771 772 773

                        if tainted:
                            # Store a tainted version if necessary
                            if not taintedform.has_key(tainted_key):
                                copied = deepcopy(found)
                                if isinstance(copied, lt):
                                    taintedform[tainted_key] = copied
                                else:
                                    taintedform[tainted_key] = [copied]
774 775 776
                            elif not isinstance(taintedform[tainted_key], lt):
                                taintedform[tainted_key] = [
                                    taintedform[tainted_key]]
Martijn Pieters's avatar
Martijn Pieters committed
777
                            taintedform[tainted_key].append(tainted)
778

Martijn Pieters's avatar
Martijn Pieters committed
779 780 781 782 783 784 785 786 787 788
                        elif taintedform.has_key(tainted_key):
                            # We may already have encountered a tainted value
                            # for this key, and the taintedform needs to hold
                            # all the values.
                            tfound = taintedform[tainted_key]
                            if isinstance(tfound, lt):
                                taintedform[tainted_key].append(item)
                            else:
                                taintedform[tainted_key] = [tfound, item]

789 790 791 792 793 794 795
                        if type(found) is lt:
                            found.append(item)
                        else:
                            found=[found,item]
                            mapping_object[key]=found
                    else:
                        mapping_object[key]=item
Martijn Pieters's avatar
Martijn Pieters committed
796 797
                        if tainted:
                            taintedform[tainted_key] = tainted
798

799
            #insert defaults into form dictionary
800
            if defaults:
801
                for key, value in defaults.items():
Martijn Pieters's avatar
Martijn Pieters committed
802 803
                    tainted_key = key
                    if '<' in key: tainted_key = TaintedString(key)
804

805
                    if not form.has_key(key):
806 807
                        # if the form does not have the key,
                        # set the default
808
                        form[key]=value
Martijn Pieters's avatar
Martijn Pieters committed
809 810 811

                        if tainteddefaults.has_key(tainted_key):
                            taintedform[tainted_key] = \
812
                                tainteddefaults[tainted_key]
813
                    else:
814
                        #The form has the key
Martijn Pieters's avatar
Martijn Pieters committed
815
                        tdefault = tainteddefaults.get(tainted_key, value)
816
                        if isinstance(value, record):
817 818
                            # if the key is mapped to a record, get the
                            # record
819
                            r = form[key]
Martijn Pieters's avatar
Martijn Pieters committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842

                            # First deal with tainted defaults.
                            if taintedform.has_key(tainted_key):
                                tainted = taintedform[tainted_key]
                                for k, v in tdefault.__dict__.items():
                                    if not hasattr(tainted, k):
                                        setattr(tainted, k, v)

                            elif tainteddefaults.has_key(tainted_key):
                                # Find out if any of the tainted default
                                # attributes needs to be copied over.
                                missesdefault = 0
                                for k, v in tdefault.__dict__.items():
                                    if not hasattr(r, k):
                                        missesdefault = 1
                                        break
                                if missesdefault:
                                    tainted = deepcopy(r)
                                    for k, v in tdefault.__dict__.items():
                                        if not hasattr(tainted, k):
                                            setattr(tainted, k, v)
                                    taintedform[tainted_key] = tainted

843 844
                            for k, v in value.__dict__.items():
                                # loop through the attributes and value
845 846 847 848 849
                                # 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)
850 851
                            form[key] = r

852 853 854 855 856
                        elif isinstance(value, lt):
                            # the default value is a list
                            l = form[key]
                            if not isinstance(l, lt):
                                l = [l]
Martijn Pieters's avatar
Martijn Pieters committed
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

                            # First deal with tainted copies
                            if taintedform.has_key(tainted_key):
                                tainted = taintedform[tainted_key]
                                if not isinstance(tainted, lt):
                                    tainted = [tainted]
                                for defitem in tdefault:
                                    if isinstance(defitem, record):
                                        for k, v in defitem.__dict__.items():
                                            for origitem in tainted:
                                                if not hasattr(origitem, k):
                                                    setattr(origitem, k, v)
                                    else:
                                        if not defitem in tainted:
                                            tainted.append(defitem)
                                taintedform[tainted_key] = tainted

                            elif tainteddefaults.has_key(tainted_key):
                                missesdefault = 0
                                for defitem in tdefault:
                                    if isinstance(defitem, record):
                                        try:
                                            for k, v in \
                                                defitem.__dict__.items():
                                                for origitem in l:
                                                    if not hasattr(origitem, k):
                                                        missesdefault = 1
                                                        raise "Break"
                                        except "Break":
                                            break
                                    else:
                                        if not defitem in l:
                                            missesdefault = 1
                                            break
                                if missesdefault:
                                    tainted = deepcopy(l)
                                    for defitem in tdefault:
                                        if isinstance(defitem, record):
                                            for k, v in defitem.__dict__.items():
                                                for origitem in tainted:
                                                    if not hasattr(origitem, k):
                                                        setattr(origitem, k, v)
                                        else:
                                            if not defitem in tainted:
                                                tainted.append(defitem)
                                    taintedform[tainted_key] = tainted

904
                            for x in value:
Martijn Pieters's avatar
Martijn Pieters committed
905
                                # for each x in the list
906
                                if isinstance(x, record):
907 908
                                    # if the x is a record
                                    for k, v in x.__dict__.items():
909

910 911 912
                                        # loop through each
                                        # attribute and value in
                                        # the record
913

914
                                        for y in l:
915

916 917 918 919 920 921
                                            # loop through each
                                            # record in the form
                                            # list if it doesn't
                                            # have the attributes
                                            # in the default
                                            # dictionary, set them
922

923 924 925 926
                                            if not hasattr(y, k):
                                                setattr(y, k, v)
                                else:
                                    # x is not a record
927 928 929
                                    if not x in l:
                                        l.append(x)
                            form[key] = l
930
                        else:
931 932
                            # The form has the key, the key is not mapped
                            # to a record or sequence so do nothing
Jim Fulton's avatar
Jim Fulton committed
933
                            pass
934

935
            # Convert to tuples
936 937
            if tuple_items:
                for key in tuple_items.keys():
938 939 940 941
                    # Split the key and get the attr
                    k=key.split( ".")
                    k,attr='.'.join(k[:-1]), k[-1]
                    a = attr
942
                    new = ''
943 944 945 946 947 948 949
                    # remove any type_names in the attr
                    while not a=='':
                        a=a.split( ":")
                        a,new=':'.join(a[:-1]), a[-1]
                    attr = new
                    if form.has_key(k):
                        # If the form has the split key get its value
Martijn Pieters's avatar
Martijn Pieters committed
950 951
                        tainted_split_key = k
                        if '<' in k: tainted_split_key = TaintedString(k)
952
                        item =form[k]
953
                        if isinstance(item, record):
954 955 956 957 958 959 960 961 962 963 964
                            # 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):
965 966 967
                                    # If the record has the attribute
                                    # convert it to a tuple and set it
                                    value=tuple(getattr(x,attr))
968
                                    setattr(x,attr,value)
Martijn Pieters's avatar
Martijn Pieters committed
969 970 971 972 973 974 975 976 977 978 979 980 981

                        # Do the same for the tainted counterpart
                        if taintedform.has_key(tainted_split_key):
                            tainted = taintedform[tainted_split_key]
                            if isinstance(item, record):
                                seq = tuple(getattr(tainted, attr))
                                setattr(tainted, attr, seq)
                            else:
                                for trec in tainted:
                                    if hasattr(trec, attr):
                                        seq = getattr(trec, attr)
                                        seq = tuple(seq)
                                        setattr(trec, attr, seq)
982
                    else:
983
                        # the form does not have the split key
Martijn Pieters's avatar
Martijn Pieters committed
984 985
                        tainted_key = key
                        if '<' in key: tainted_key = TaintedString(key)
986 987 988
                        if form.has_key(key):
                            # if it has the original key, get the item
                            # convert it to a tuple
989
                            item=form[key]
990 991
                            item=tuple(form[key])
                            form[key]=item
Martijn Pieters's avatar
Martijn Pieters committed
992 993 994 995

                        if taintedform.has_key(tainted_key):
                            tainted = tuple(taintedform[tainted_key])
                            taintedform[tainted_key] = tainted
996

Jim Fulton's avatar
Jim Fulton committed
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
        if meth:
            if environ.has_key('PATH_INFO'):
                path=environ['PATH_INFO']
                while path[-1:]=='/': path=path[:-1]
            else: path=''
            other['PATH_INFO']=path="%s/%s" % (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 dont
        # match that of the current request), a ValueError will
        # be raised.
1015
        if url.find(self.script) != 0:
Jim Fulton's avatar
Jim Fulton committed
1016 1017 1018 1019 1020 1021 1022 1023
            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
1024

1025 1026 1027 1028 1029
        # 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).
Jim Fulton's avatar
Jim Fulton committed
1030
        try: object=req.traverse(path)
1031
        except: rsp.exception()
1032
        if object is None:
1033
            req.close()
's avatar
committed
1034
            raise rsp.errmsg, sys.exc_info()[1]
1035 1036 1037 1038 1039 1040

        # 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.
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
        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.close()
        return object
1053

Jim Fulton's avatar
Jim Fulton committed
1054 1055

    def clone(self):
1056
        # Return a clone of the current request object
Jim Fulton's avatar
Jim Fulton committed
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
        # that may be used to perform object traversal.
        environ=self.environ.copy()
        environ['REQUEST_METHOD']='GET'
        if self._auth: environ['HTTP_AUTHORIZATION']=self._auth
        clone=HTTPRequest(None, environ, HTTPResponse(), clean=1)
        clone['PARENTS']=[self['PARENTS'][-1]]
        return clone

    def get_header(self, name, default=None):
        """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
1073
        name=('_'.join(name.split("-"))).upper()
Jim Fulton's avatar
Jim Fulton committed
1074 1075 1076 1077 1078 1079 1080
        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)

Martijn Pieters's avatar
Martijn Pieters committed
1081
    def get(self, key, default=None, returnTaints=0,
1082 1083 1084
            URLmatch=re.compile('URL(PATH)?([0-9]+)$').match,
            BASEmatch=re.compile('BASE(PATH)?([0-9]+)$').match,
            ):
Jim Fulton's avatar
Jim Fulton committed
1085 1086 1087 1088 1089
        """Get a variable value

        Return a value for the required variable name.
        The value will be looked up from one of the request data
        categories. The search order is environment variables,
1090 1091
        other variables, form data, and then cookies.

Jim Fulton's avatar
Jim Fulton committed
1092 1093 1094 1095 1096 1097
        """ #"
        other=self.other
        if other.has_key(key):
            if key=='REQUEST': return self
            return other[key]

's avatar
committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        if key[:1]=='U':
            match = URLmatch(key)
            if match is not None:
                pathonly, n = match.groups()
                path = self._script + self._steps
                n = len(path) - int(n)
                if n < 0:
                    raise KeyError, key
                if pathonly:
                    path = [''] + path[:n]
                else:
                    path = [other['SERVER_URL']] + path[:n]
1110 1111 1112 1113
                if other.has_key('PUBLISHED'):
                    # Don't cache URLs until publishing traversal is done.
                    other[key] = URL = '/'.join(path)
                    self._urls = self._urls + (key,)
1114
                return URL
Jim Fulton's avatar
Jim Fulton committed
1115 1116 1117 1118 1119 1120 1121 1122 1123

        if isCGI_NAME(key) or key[:5] == 'HTTP_':
            environ=self.environ
            if environ.has_key(key) and (not hide_key(key)):
                return environ[key]
            return ''

        if key=='REQUEST': return self

1124
        if key[:1]=='B':
's avatar
committed
1125 1126 1127
            match = BASEmatch(key)
            if match is not None:
                pathonly, n = match.groups()
1128
                path = self._steps
's avatar
committed
1129
                n = int(n)
1130
                if n:
1131 1132
                    n = n - 1
                    if len(path) < n:
1133 1134
                        raise KeyError, key

1135
                    v = self._script + path[:n]
1136
                else:
1137
                    v = self._script[:-1]
's avatar
committed
1138 1139 1140 1141
                if pathonly:
                    v.insert(0, '')
                else:
                    v.insert(0, other['SERVER_URL'])
1142 1143 1144 1145
                if other.has_key('PUBLISHED'):
                    # Don't cache URLs until publishing traversal is done.
                    other[key] = URL = '/'.join(v)
                    self._urls = self._urls + (key,)
's avatar
committed
1146
                return URL
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

            if key=='BODY' and self._file is not None:
                p=self._file.tell()
                self._file.seek(0)
                v=self._file.read()
                self._file.seek(p)
                self.other[key]=v
                return v

            if key=='BODYFILE' and self._file is not None:
                v=self._file
                self.other[key]=v
                return v
Jim Fulton's avatar
Jim Fulton committed
1160

1161
        v=self.common.get(key, _marker)
Jim Fulton's avatar
Jim Fulton committed
1162 1163
        if v is not _marker: return v

1164 1165 1166 1167 1168 1169 1170 1171
        if self._lazies:
            v = self._lazies.get(key, _marker)
            if v is not _marker:
                if callable(v): v = v()
                self[key] = v                   # Promote lazy value
                del self._lazies[key]
                return v

Martijn Pieters's avatar
Martijn Pieters committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
        # Return tainted data first (marked as suspect)
        if returnTaints:
            v = self.taintedform.get(key, _marker)
            if v is not _marker:
                other[key] = v
                return v

        # Untrusted data *after* trusted data
        v = self.form.get(key, _marker)
        if v is not _marker:
            other[key] = v
            return v

        # Return tainted data first (marked as suspect)
        if returnTaints:
            v = self.taintedcookies.get(key, _marker)
            if v is not _marker:
                other[key] = v
                return v

        # Untrusted data *after* trusted data
        v = self.cookies.get(key, _marker)
        if v is not _marker:
            other[key] = v
            return v

1198
        return default
1199

Martijn Pieters's avatar
Martijn Pieters committed
1200 1201
    def __getitem__(self, key, default=_marker, returnTaints=0):
        v = self.get(key, default, returnTaints=returnTaints)
1202 1203 1204
        if v is _marker:
            raise KeyError, key
        return v
Jim Fulton's avatar
Jim Fulton committed
1205

Martijn Pieters's avatar
Martijn Pieters committed
1206 1207
    def __getattr__(self, key, default=_marker, returnTaints=0):
        v = self.get(key, default, returnTaints=returnTaints)
1208 1209 1210
        if v is _marker:
            raise AttributeError, key
        return v
1211

1212 1213 1214
    def set_lazy(self, key, callable):
        self._lazies[key] = callable

Martijn Pieters's avatar
Martijn Pieters committed
1215 1216
    def has_key(self, key, returnTaints=0):
        try: self.__getitem__(key, returnTaints=returnTaints)
1217 1218 1219
        except: return 0
        else: return 1

Martijn Pieters's avatar
Martijn Pieters committed
1220
    def keys(self, returnTaints=0):
Jim Fulton's avatar
Jim Fulton committed
1221 1222
        keys = {}
        keys.update(self.common)
1223
        keys.update(self._lazies)
Jim Fulton's avatar
Jim Fulton committed
1224 1225

        for key in self.environ.keys():
1226 1227
            if (isCGI_NAME(key) or key[:5] == 'HTTP_') and (not hide_key(key)):
                keys[key] = 1
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240

        n=0
        while 1:
            n=n+1
            key = "URL%s" % n
            if not self.has_key(key): break

        n=0
        while 1:
            n=n+1
            key = "BASE%s" % n
            if not self.has_key(key): break

Jim Fulton's avatar
Jim Fulton committed
1241
        keys.update(self.other)
Martijn Pieters's avatar
Martijn Pieters committed
1242 1243 1244 1245
        keys.update(self.cookies)
        if returnTaints: keys.update(self.taintedcookies)
        keys.update(self.form)
        if returnTaints: keys.update(self.taintedform)
Jim Fulton's avatar
Jim Fulton committed
1246

1247 1248 1249 1250
        keys=keys.keys()
        keys.sort()

        return keys
Jim Fulton's avatar
Jim Fulton committed
1251

1252 1253 1254 1255
    def __str__(self):
        result="<h3>form</h3><table>"
        row='<tr valign="top" align="left"><th>%s</th><td>%s</td></tr>'
        for k,v in self.form.items():
1256
            result=result + row % (escape(k), escape(repr(v)))
1257 1258
        result=result+"</table><h3>cookies</h3><table>"
        for k,v in self.cookies.items():
1259
            result=result + row % (escape(k), escape(repr(v)))
1260 1261 1262
        result=result+"</table><h3>lazy items</h3><table>"
        for k,v in self._lazies.items():
            result=result + row % (escape(k), escape(repr(v)))
1263 1264 1265
        result=result+"</table><h3>other</h3><table>"
        for k,v in self.other.items():
            if k in ('PARENTS','RESPONSE'): continue
1266
            result=result + row % (escape(k), escape(repr(v)))
1267

1268 1269
        for n in "0123456789":
            key = "URL%s"%n
1270
            try: result=result + row % (key, escape(self[key]))
1271 1272 1273
            except KeyError: pass
        for n in "0123456789":
            key = "BASE%s"%n
1274
            try: result=result + row % (key, escape(self[key]))
1275 1276 1277 1278 1279
            except KeyError: pass

        result=result+"</table><h3>environ</h3><table>"
        for k,v in self.environ.items():
            if not hide_key(k):
1280
                result=result + row % (escape(k), escape(repr(v)))
1281 1282
        return result+"</table>"

1283 1284
    def __repr__(self):
        return "<%s, URL=%s>" % (self.__class__.__name__, self['URL'])
1285

1286 1287 1288 1289 1290 1291 1292 1293
    def text(self):
        result="FORM\n\n"
        row='%-20s %s\n'
        for k,v in self.form.items():
            result=result + row % (k, repr(v))
        result=result+"\nCOOKIES\n\n"
        for k,v in self.cookies.items():
            result=result + row % (k, repr(v))
1294 1295 1296
        result=result+"\nLAZY ITEMS\n\n"
        for k,v in self._lazies.items():
            result=result + row % (k, repr(v))
1297 1298 1299 1300
        result=result+"\nOTHER\n\n"
        for k,v in self.other.items():
            if k in ('PARENTS','RESPONSE'): continue
            result=result + row % (k, repr(v))
1301

1302 1303
        for n in "0123456789":
            key = "URL%s"%n
1304
            try: result=result + row % (key, self[key])
1305 1306 1307
            except KeyError: pass
        for n in "0123456789":
            key = "BASE%s"%n
1308
            try: result=result + row % (key, self[key])
1309 1310 1311 1312 1313 1314 1315 1316
            except KeyError: pass

        result=result+"\nENVIRON\n\n"
        for k,v in self.environ.items():
            if not hide_key(k):
                result=result + row % (k, v)
        return result

Jim Fulton's avatar
Jim Fulton committed
1317 1318 1319 1320
    def _authUserPW(self):
        global base64
        auth=self._auth
        if auth:
1321
            if auth[:6].lower() == 'basic ':
Jim Fulton's avatar
Jim Fulton committed
1322
                if base64 is None: import base64
1323
                [name,password] = \
1324
                    base64.decodestring(auth.split()[-1]).split(':')
Jim Fulton's avatar
Jim Fulton committed
1325 1326
                return name, password

1327 1328
    def taintWrapper(self, enabled=TAINTING_ENABLED):
        return enabled and TaintRequestWrapper(self) or self
Martijn Pieters's avatar
Martijn Pieters committed
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352


class TaintRequestWrapper:
    def __init__(self, req):
        self._req = req

    def __getattr__(self, key):
        if key in ('get', '__getitem__', '__getattr__', 'has_key', 'keys'):
            return TaintMethodWrapper(getattr(self._req, key))
        if not key in self._req.keys():
            item = getattr(self._req, key, _marker)
            if item is not _marker:
                return item
        return self._req.__getattr__(key, returnTaints=1)


class TaintMethodWrapper:
    def __init__(self, method):
        self._method = method

    def __call__(self, *args, **kw):
        kw['returnTaints'] = 1
        return self._method(*args, **kw)

Jim Fulton's avatar
Jim Fulton committed
1353

1354 1355 1356
def has_codec(x):
    try:
        codecs.lookup(x)
1357
    except (LookupError, SystemError):
1358 1359 1360
        return 0
    else:
        return 1
Jim Fulton's avatar
Jim Fulton committed
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393


base64=None

def sane_environment(env):
    # return an environment mapping which has been cleaned of
    # funny business such as REDIRECT_ prefixes added by Apache
    # or HTTP_CGI_AUTHORIZATION hacks.
    dict={}
    for key, val in env.items():
        while key[:9]=='REDIRECT_':
            key=key[9:]
        dict[key]=val
    if dict.has_key('HTTP_CGI_AUTHORIZATION'):
        dict['HTTP_AUTHORIZATION']=dict['HTTP_CGI_AUTHORIZATION']
        try: del dict['HTTP_CGI_AUTHORIZATION']
        except: pass
    return dict


class FileUpload:
    '''\
    File upload objects

    File upload objects are used to represent file-uploaded data.

    File upload objects can be used just like files.

    In addition, they have a 'headers' attribute that is a dictionary
    containing the file-upload headers, and a 'filename' attribute
    containing the name of the uploaded file.
    '''

's avatar
committed
1394 1395 1396 1397
    # Allow access to attributes such as headers and filename so
    # that ZClass authors can use DTML to work with FileUploads.
    __allow_access_to_unprotected_subobjects__=1

Jim Fulton's avatar
Jim Fulton committed
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
    def __init__(self, aFieldStorage):

        file=aFieldStorage.file
        if hasattr(file, '__methods__'): methods=file.__methods__
        else: methods= ['close', 'fileno', 'flush', 'isatty',
                        'read', 'readline', 'readlines', 'seek',
                        'tell', 'truncate', 'write', 'writelines']

        d=self.__dict__
        for m in methods:
            if hasattr(file,m): d[m]=getattr(file,m)

        self.headers=aFieldStorage.headers
        self.filename=aFieldStorage.filename
1412 1413 1414 1415 1416

        # Add an assertion to the rfc822.Message object that implements
        # self.headers so that managed code can access them.
        try:    self.headers.__allow_access_to_unprotected_subobjects__ = 1
        except: pass
1417

1418
    def __nonzero__(self):
1419
        """FileUpload objects are considered false if their
1420 1421 1422
           filename is empty.
        """
        return not not self.filename
1423

Jim Fulton's avatar
Jim Fulton committed
1424 1425 1426 1427

parse_cookie_lock=allocate_lock()
def parse_cookie(text,
                 result=None,
1428 1429 1430 1431 1432
                 qparmre=re.compile(
                    '([\x00- ]*([^\x00- ;,="]+)="([^"]*)"([\x00- ]*[;,])?[\x00- ]*)'),
                 parmre=re.compile(
                    '([\x00- ]*([^\x00- ;,="]+)=([^\x00- ;,"]*)([\x00- ]*[;,])?[\x00- ]*)'),

Jim Fulton's avatar
Jim Fulton committed
1433 1434 1435 1436 1437 1438 1439 1440 1441
                 acquire=parse_cookie_lock.acquire,
                 release=parse_cookie_lock.release,
                 ):

    if result is None: result={}
    already_have=result.has_key

    acquire()
    try:
1442 1443 1444 1445

        mo_q = qparmre.match(text)

        if mo_q:
Jim Fulton's avatar
Jim Fulton committed
1446
            # Match quoted correct cookies
1447 1448 1449 1450 1451

            l     = len(mo_q.group(1))
            name  = mo_q.group(2)
            value = mo_q.group(3)

Jim Fulton's avatar
Jim Fulton committed
1452
        else:
1453 1454 1455 1456 1457 1458 1459 1460 1461
            # Match evil MSIE cookies ;)

            mo_p = parmre.match(text)

            if mo_p:
                l     = len(mo_p.group(1))
                name  = mo_p.group(2)
                value = mo_p.group(3)

1462 1463
            else:
                return result
1464

Jim Fulton's avatar
Jim Fulton committed
1465 1466
    finally: release()

1467
    if not already_have(name): result[name]=value
Jim Fulton's avatar
Jim Fulton committed
1468 1469

    return apply(parse_cookie,(text[l:],result))
1470 1471 1472

# add class
class record:
's avatar
committed
1473 1474 1475 1476

    # Allow access to record methods and values from DTML
    __allow_access_to_unprotected_subobjects__=1

1477 1478 1479
    def __getattr__(self, key, default=None):
        if key in ('get', 'keys', 'items', 'values', 'copy', 'has_key'):
            return getattr(self.__dict__, key)
1480
        raise AttributeError, key
1481 1482 1483

    def __getitem__(self, key):
        return self.__dict__[key]
1484

1485 1486 1487
    def __str__(self):
        L1 = self.__dict__.items()
        L1.sort()
1488
        return ", ".join(map(lambda item: "%s: %s" % item, L1))
1489

's avatar
committed
1490
    def __repr__(self):
1491
        #return repr( self.__dict__ )
's avatar
committed
1492 1493
        L1 = self.__dict__.items()
        L1.sort()
1494 1495
        return '{%s}' % ', '.join(
            map(lambda item: "'%s': %s" % (item[0], repr(item[1])), L1))
1496

Martijn Pieters's avatar
Martijn Pieters committed
1497 1498 1499 1500 1501 1502
    def __cmp__(self, other):
        return (cmp(type(self), type(other)) or
                cmp(self.__class__, other.__class__) or
                cmp(self.__dict__.items(), other.__dict__.items()))


1503 1504 1505 1506 1507 1508 1509 1510
# Flags
SEQUENCE=1
DEFAULT=2
RECORD=4
RECORDS=8
REC=RECORD|RECORDS
EMPTY=16
CONVERTED=32
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527


# The ZOPE_TRUSTED_PROXIES environment variable contains a colon separated 
# list 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.
# This function parses the environment variable into a module variable
# 
def trusted_proxies():
    proxies = os.environ.get('ZOPE_TRUSTED_PROXIES','')
    proxies = proxies.split(':')
    proxies = [p.strip() for p in proxies]
    return tuple(proxies)
trusted_proxies = trusted_proxies()