コード例 #1
0
ファイル: CgiRequest.py プロジェクト: bzhpwr/Exports
 def __init__(self, **kwargs):
     Request.__init__(self, **kwargs)
     self.headers       = []
     self.headers_sent  = False
     self.the_get_data  = self.__read_get_data()
     self.the_post_data = self.__read_post_data()
     self.the_cookies   = self.__read_cookies()
コード例 #2
0
ファイル: ModPythonRequest.py プロジェクト: bzhpwr/Exports
 def __init__(self, request, **kwargs):
     from mod_python      import apache, Cookie
     from mod_python.util import FieldStorage
     Request.__init__(self, **kwargs)
     self.cookie_mod    = Cookie
     self.request       = request
     self.env           = apache.build_cgi_env(request)
     self.the_get_data  = self.__read_get_data()
     self.the_post_data = self.__read_post_data()
     self.the_cookies   = self.__read_cookies()
コード例 #3
0
    def __init__(self, bucket, request=None):
        # Copies the context
        context = request.getContext() if request else [{}]
        Request.__init__(self, *context)

        self._running = False
        self._name = None
        self._size = 0

        #: bucket used for rate limiting
        self.bucket = bucket
コード例 #4
0
ファイル: Download.py プロジェクト: ASCIIteapot/pyload
    def __init__(self, bucket, request=None):
        # Copies the context
        context = request.getContext() if request else [{}]
        Request.__init__(self, *context)

        self._running = False
        self._name = None
        self._size = 0

        #: bucket used for rate limiting
        self.bucket = bucket
コード例 #5
0
    def __init__(self, requestDict=None):
        Request.__init__(self)
        self._stack = []
        if requestDict:
            # Dictionaries come in from interfaces like WSGI
            if requestDict['format'] != 'CGI':
                raise ValueError(
                    'Request dict for HTTPRequest must have CGI format')
            self._time = requestDict['time']
            self._environ = requestDict['environ']
            self._input = requestDict['input']
            self._requestID = requestDict['requestID']
            # Protect the loading of fields with an exception handler,
            # because bad headers sometimes can break the field storage
            # (see also https://bugs.python.org/issue27777).
            try:
                self._fields = FieldStorage.FieldStorage(
                    self._input,
                    environ=self._environ,
                    keep_blank_values=True,
                    strict_parsing=False)
            except Exception:
                self._fields = cgi.FieldStorage(keep_blank_values=True)
                traceback.print_exc(file=sys.stderr)
            self._cookies = Cookie()
            if 'HTTP_COOKIE' in self._environ:
                # If there are duplicate cookies, always use the first one
                # because it is the most relevant one according to RFC 2965
                # (workaround for https://bugs.python.org/issue1375011).
                # noinspection PyTypeChecker
                cookies = dict(
                    cookie.split('=', 1) for cookie in reversed(
                        self._environ['HTTP_COOKIE'].split('; ')))
                # Protect the loading of cookies with an exception handler,
                # because MSIE cookies sometimes can break the cookie module.
                try:
                    self._cookies.load(cookies)
                except Exception:
                    traceback.print_exc(file=sys.stderr)
        else:
            # If there's no dictionary, we pretend we're a CGI script
            # and see what happens...
            self._time = time()
            self._environ = os.environ.copy()
            self._input = None
            self._fields = cgi.FieldStorage(keep_blank_values=True)
            self._cookies = Cookie()

        env = self._environ

        # Debugging
        if debug:
            with open('env.text', 'a') as f:
                f.write('>> env for request:\n')
                for key in sorted(env):
                    f.write(f'{key}: {env[key]!r}\n')
                f.write('\n')

        # Get servlet path and query string
        self._servletPath = env.get('SCRIPT_NAME', '')
        self._pathInfo = env.get('PATH_INFO', '')
        self._extraURLPath = ''  # will be determined later
        self._queryString = env.get('QUERY_STRING', '')
        if 'REQUEST_URI' in env:
            self._uri = env['REQUEST_URI']
            # correct servletPath if there was a redirection
            if not (self._uri + '/').startswith(self._servletPath + '/'):
                i = self._uri.find(self._pathInfo)
                self._servletPath = self._uri[:i] if i > 0 else ''
        else:
            # REQUEST_URI isn't actually part of the CGI standard and some
            # web servers like IIS don't set it (as of 8/22/2000).
            if 'SCRIPT_URL' in env:
                self._uri = env['SCRIPT_URL']
                # correct servletPath if there was a redirection
                if not (self._uri + '/').startswith(self._servletPath + '/'):
                    i = self._uri.find(self._pathInfo)
                    self._servletPath = self._uri[:i] if i > 0 else ''
            else:
                self._uri = self._servletPath + self._pathInfo
            if self._queryString:
                self._uri += '?' + self._queryString

        # We use the cgi module to get the fields,
        # but then change them into an ordinary dictionary of values:
        fieldStorage, fields = self._fields, {}
        try:
            # Avoid accessing fieldStorage as dict; that would be very slow
            # as it always iterates over all items to find a certain key.
            # Instead, iterate directly over the items of the internal list.
            fieldItems = fieldStorage.list
        except AttributeError:
            # This can happen if we do not have a a regular POST
            # from an HTML form, but, for example, an XML-RPC request.
            fieldItems = None
            if debug:
                print("Cannot get fieldStorage list.")
        if fieldItems:
            for item in fieldItems:
                if item.filename:
                    if debug:
                        print("Uploaded file found:", item.filename)
                    fields.setdefault(item.name, []).append(item)
                else:
                    fields.setdefault(item.name, []).append(item.value)
            for key, value in fields.items():
                if len(value) == 1:
                    fields[key] = value[0]
        self._fieldStorage, self._fields = fieldStorage, fields

        # We use Tim O'Malley's Cookie class to get the cookies,
        # but then change them into an ordinary dictionary of values
        self._cookies = dict(
            (key, self._cookies[key].value) for key in self._cookies)

        self._contextName = None
        self._serverSidePath = self._serverSideContextPath = None
        self._serverRootPath = ''
        self._sessionExpired = False

        self._pathInfo = self.pathInfo()

        if debug:
            print("Done setting up request, found fields:", ', '.join(fields))
コード例 #6
0
ファイル: HTTPRequest.py プロジェクト: Cito/w4py-olde-docs
    def __init__(self, requestDict=None):
        Request.__init__(self)
        self._stack = []
        if requestDict:
            # Dictionaries come in from web server adapters like the CGIAdapter
            assert requestDict['format'] == 'CGI'
            self._time = requestDict['time']
            self._environ = requestDict['environ']
            self._input = requestDict['input']
            self._requestID = requestDict['requestID']
            self._fields = FieldStorage.FieldStorage(
                self._input, environ=self._environ,
                keep_blank_values=True, strict_parsing=False)
            self._cookies = Cookie()
            if 'HTTP_COOKIE' in self._environ:
                # Protect the loading of cookies with an exception handler,
                # because MSIE cookies sometimes can break the cookie module.
                try:
                    self._cookies.load(self._environ['HTTP_COOKIE'])
                except Exception:
                    traceback.print_exc(file=sys.stderr)
        else:
            # If there's no dictionary, we pretend we're a CGI script
            # and see what happens...
            self._time = time()
            self._environ = os.environ.copy()
            self._input = None
            self._fields = cgi.FieldStorage(keep_blank_values=True)
            self._cookies = Cookie()

        env = self._environ

        # Debugging
        if debug:
            f = open('env.text', 'a')
            save = sys.stdout
            sys.stdout = f
            print '>> env for request:'
            for key in sorted(env):
                print '%s: %s' % (repr(key), repr(env[key]))
            print
            sys.stdout = save
            f.close()

        # Get adapter, servlet path and query string
        self._absolutepath = 'WK_ABSOLUTE' in env # set by adapter
        if self._absolutepath:
            # this is set when the servlet is a webserver file that shall
            # be handled without context (e.g. when the psp-handler is used)
            self._servletPath = '' # make it look like the normal handler
            self._extraURLPath = env.get('PATH_INFO', '')
            self._pathInfo = env.get('SCRIPT_NAME', '') + self._extraURLPath
            self._fsPath = self.fsPath()
        else:
            self._servletPath = env.get('SCRIPT_NAME', '')
            self._pathInfo = env.get('PATH_INFO', '')
            self._extraURLPath = '' # will be determined later
        self._queryString = env.get('QUERY_STRING', '')
        if 'REQUEST_URI' in env:
            self._uri = env['REQUEST_URI']
            # correct servletPath if there was a redirection
            if not (self._uri + '/').startswith(self._servletPath + '/'):
                i = self._uri.find(self._pathInfo)
                self._servletPath = i > 0 and self._uri[:i] or ''
        else:
            # REQUEST_URI isn't actually part of the CGI standard and some
            # web servers like IIS don't set it (as of 8/22/2000).
            if 'SCRIPT_URL' in env:
                self._uri = self._environ['SCRIPT_URL']
                # correct servletPath if there was a redirection
                if not (self._uri + '/').startswith(self._servletPath + '/'):
                    i = self._uri.find(self._pathInfo)
                    self._servletPath = i > 0 and self._uri[:i] or ''
            else:
                self._uri = self._servletPath + self._pathInfo
            if self._queryString:
                self._uri += '?' + self._queryString

        # We use the cgi module to get the fields,
        # but then change them into an ordinary dictionary of values:
        fieldStorage, fields = self._fields, {}
        try:
            # Avoid accessing fieldStorage as dict; that would be very slow
            # as it always iterates over all items to find a certain key.
            # Instead, iterate directly over the items of the internal list.
            fieldItems = fieldStorage.list
        except AttributeError:
            # This can happen if we do not have a a regular POST
            # from an HTML form, but, for example, an XML-RPC request.
            fieldItems = None
            if debug:
                print "Cannot get fieldstorage list."
        if fieldItems:
            for item in fieldItems:
                if item.filename:
                    if debug:
                        print "Uploaded file found:", item.filename
                    fields.setdefault(item.name, []).append(item)
                else:
                    fields.setdefault(item.name, []).append(item.value)
            for key, value in fields.iteritems():
                if len(value) == 1:
                    fields[key] = value[0]
        self._fieldStorage, self._fields = fieldStorage, fields

        # We use Tim O'Malley's Cookie class to get the cookies,
        # but then change them into an ordinary dictionary of values
        self._cookies = dict(
            (key, self._cookies[key].value) for key in self._cookies)

        self._contextName = None
        self._serverSidePath = self._serverSideContextPath = None
        self._serverRootPath = ''
        self._sessionExpired = False

        self._pathInfo = self.pathInfo()

        if debug:
            print "Done setting up request, found keys %r" % fields.keys()
コード例 #7
0
ファイル: HTTPRequest.py プロジェクト: techeye220/w4py
    def __init__(self, requestDict=None):
        Request.__init__(self)
        self._stack = []
        if requestDict:
            # Dictionaries come in from web server adapters like the CGIAdapter
            assert requestDict['format'] == 'CGI'
            self._time = requestDict['time']
            self._environ = requestDict['environ']
            self._input = requestDict['input']
            self._requestID = requestDict['requestID']
            self._fields = FieldStorage.FieldStorage(self._input,
                                                     environ=self._environ,
                                                     keep_blank_values=True,
                                                     strict_parsing=False)
            self._cookies = Cookie()
            if 'HTTP_COOKIE' in self._environ:
                # Protect the loading of cookies with an exception handler,
                # because MSIE cookies sometimes can break the cookie module.
                try:
                    self._cookies.load(self._environ['HTTP_COOKIE'])
                except Exception:
                    traceback.print_exc(file=sys.stderr)
        else:
            # If there's no dictionary, we pretend we're a CGI script
            # and see what happens...
            self._time = time()
            self._environ = os.environ.copy()
            self._input = None
            self._fields = cgi.FieldStorage(keep_blank_values=True)
            self._cookies = Cookie()

        env = self._environ

        # Debugging
        if debug:
            with open('env.text', 'a') as f:
                save = sys.stdout
                sys.stdout = f
                print '>> env for request:'
                for key in sorted(env):
                    print '%s: %s' % (repr(key), repr(env[key]))
                print
                sys.stdout = save

        # Get adapter, servlet path and query string
        self._absolutepath = 'WK_ABSOLUTE' in env  # set by adapter
        if self._absolutepath:
            # this is set when the servlet is a webserver file that shall
            # be handled without context (e.g. when the psp-handler is used)
            self._servletPath = ''  # make it look like the normal handler
            self._extraURLPath = env.get('PATH_INFO', '')
            self._pathInfo = env.get('SCRIPT_NAME', '') + self._extraURLPath
            self._fsPath = self.fsPath()
        else:
            self._servletPath = env.get('SCRIPT_NAME', '')
            self._pathInfo = env.get('PATH_INFO', '')
            self._extraURLPath = ''  # will be determined later
        self._queryString = env.get('QUERY_STRING', '')
        if 'REQUEST_URI' in env:
            self._uri = env['REQUEST_URI']
            # correct servletPath if there was a redirection
            if not (self._uri + '/').startswith(self._servletPath + '/'):
                i = self._uri.find(self._pathInfo)
                self._servletPath = self._uri[:i] if i > 0 else ''
        else:
            # REQUEST_URI isn't actually part of the CGI standard and some
            # web servers like IIS don't set it (as of 8/22/2000).
            if 'SCRIPT_URL' in env:
                self._uri = self._environ['SCRIPT_URL']
                # correct servletPath if there was a redirection
                if not (self._uri + '/').startswith(self._servletPath + '/'):
                    i = self._uri.find(self._pathInfo)
                    self._servletPath = self._uri[:i] if i > 0 else ''
            else:
                self._uri = self._servletPath + self._pathInfo
            if self._queryString:
                self._uri += '?' + self._queryString

        # We use the cgi module to get the fields,
        # but then change them into an ordinary dictionary of values:
        fieldStorage, fields = self._fields, {}
        try:
            # Avoid accessing fieldStorage as dict; that would be very slow
            # as it always iterates over all items to find a certain key.
            # Instead, iterate directly over the items of the internal list.
            fieldItems = fieldStorage.list
        except AttributeError:
            # This can happen if we do not have a a regular POST
            # from an HTML form, but, for example, an XML-RPC request.
            fieldItems = None
            if debug:
                print "Cannot get fieldstorage list."
        if fieldItems:
            for item in fieldItems:
                if item.filename:
                    if debug:
                        print "Uploaded file found:", item.filename
                    fields.setdefault(item.name, []).append(item)
                else:
                    fields.setdefault(item.name, []).append(item.value)
            for key, value in fields.iteritems():
                if len(value) == 1:
                    fields[key] = value[0]
        self._fieldStorage, self._fields = fieldStorage, fields

        # We use Tim O'Malley's Cookie class to get the cookies,
        # but then change them into an ordinary dictionary of values
        self._cookies = dict(
            (key, self._cookies[key].value) for key in self._cookies)

        self._contextName = None
        self._serverSidePath = self._serverSideContextPath = None
        self._serverRootPath = ''
        self._sessionExpired = False

        self._pathInfo = self.pathInfo()

        if debug:
            print "Done setting up request, found keys %r" % fields.keys()
コード例 #8
0
ファイル: HTTPRequest.py プロジェクト: akkmzack/RIOS-8.5
	def __init__(self, dict=None):
		Request.__init__(self)
		self._stack = []
		if dict:
			# Dictionaries come in from web server adapters like the CGIAdapter
			assert dict['format'] == 'CGI'
			self._time = dict['time']
			self._environ = dict['environ']
			self._input = dict['input']
			self._requestID = dict['requestID']
			self._fields = FieldStorage.FieldStorage(
				self._input, environ=self._environ,
				keep_blank_values=True, strict_parsing=False)
			self._fields.parse_qs()
			self._cookies = Cookie()
			if self._environ.has_key('HTTP_COOKIE'):
				# Protect the loading of cookies with an exception handler,
				# because MSIE cookies sometimes can break the cookie module.
				try:
					self._cookies.load(self._environ['HTTP_COOKIE'])
				except Exception:
					traceback.print_exc(file=sys.stderr)
		else:
			# If there's no dictionary, we pretend we're a CGI script
			# and see what happens...
			self._time = time.time()
			self._environ = os.environ.copy()
			self._input = None
			self._fields = cgi.FieldStorage(keep_blank_values=True)
			self._cookies = Cookie()

		env = self._environ

		# Debugging
		if debug:
			f = open('env.text', 'a')
			save = sys.stdout
			sys.stdout = f
			print '>> env for request:'
			keys = env.keys()
			keys.sort()
			for key in keys:
				print '%s: %s' % (repr(key), repr(env[key]))
			print
			sys.stdout = save
			f.close()

		# Get adapter, servlet path and query string
		self._servletPath = env.get('SCRIPT_NAME', '')
		self._pathInfo = env.get('PATH_INFO', '')
		self._queryString = env.get('QUERY_STRING', '')
		if env.has_key('REQUEST_URI'):
			self._uri = env['REQUEST_URI']
			# correct servletPath if there was a redirection
			if not (self._uri + '/').startswith(self._servletPath + '/'):
				i = self._uri.find(self._pathInfo)
				self._servletPath = i >= 0 and self._uri[:i] or '/'
		else:
			# REQUEST_URI isn't actually part of the CGI standard and some
			# web servers like IIS don't set it (as of 8/22/2000).
			if env.has_key('SCRIPT_URL'):
				self._uri = self._environ['SCRIPT_URL']
				# correct servletPath if there was a redirection
				if not (self._uri + '/').startswith(self._servletPath + '/'):
					i = self._uri.find(self._pathInfo)
					self._servletPath = i >= 0 and self._uri[:i] or '/'
			else:
				self._uri = self._servletPath + self._pathInfo
			if self._queryString:
				self._uri += '?' + self._queryString
		self._absolutepath = env.has_key('WK_ABSOLUTE') # set by adapter
		if self._absolutepath:
			self._fsPath = self.fsPath()

		# We use the cgi module to get the fields,
		# but then change them into an ordinary dictionary of values:
		try:
			keys = self._fields.keys()
		except TypeError:
			# This can happen if, for example, the request is an XML-RPC request,
			# not a regular POST from an HTML form. In that case we just create
			# an empty set of fields.
			keys = []
		dict = {}
		for key in keys:
			value = self._fields[key]
			if type(value) is not ListType:
				if value.filename:
					if debug:
						print "Uploaded File Found"
				else: # i.e., if we don't have a list,
					# we have one of those cgi.MiniFieldStorage objects.
					value = value.value # get it's value.
			else:
				value = map(lambda miniFieldStorage: miniFieldStorage.value,
					value) # extract those value's
			dict[key] = value

		self._fieldStorage = self._fields
		self._fields = dict

		# We use Tim O'Malley's Cookie class to get the cookies,
		# but then change them into an ordinary dictionary of values
		dict = {}
		for key in self._cookies.keys():
			dict[key] = self._cookies[key].value
		self._cookies = dict

		self._contextName = None
		self._serverSidePath = self._serverSideContextPath = None
		self._serverRootPath = self._extraURLPath = ''
		self._sessionExpired = False

		self._pathInfo = self.pathInfo()

		if debug:
			print "Done setting up request, found keys %r" % self._fields.keys()
コード例 #9
0
    def __init__(self, dict={}):
        ##		import pprint
        ##		pprint.pprint(dict)
        Request.__init__(self)
        self._parents = []
        if dict:
            # Dictionaries come in from web server adapters like the CGIAdapter
            assert dict['format'] == 'CGI'
            self._time = dict['time']
            self._environ = dict['environ']
            self._input = dict['input']
            self._fields = FieldStorage.FieldStorage(self._input,
                                                     environ=self._environ,
                                                     keep_blank_values=1,
                                                     strict_parsing=0)
            self._fields.parse_qs()
            self._cookies = Cookie()
            if self._environ.has_key('HTTP_COOKIE'):
                # Protect the loading of cookies with an exception handler, because some cookies
                # from IE are known to break the cookie module.
                try:
                    self._cookies.load(self._environ['HTTP_COOKIE'])
                except:
                    traceback.print_exc(file=sys.stderr)
        else:
            # If there's no dictionary, we pretend we're a CGI script and see what happens...
            import time
            self._time = time.time()
            self._environ = os.environ.copy()
            self._input = None
            self._fields = cgi.FieldStorage(keep_blank_values=1)
            self._cookies = Cookie()

        # Debugging
        if 0:
            f = open('env.text', 'a')
            save = sys.stdout
            sys.stdout = f
            print '>> env for request:'
            keys = self._environ.keys()
            keys.sort()
            for key in keys:
                print '%s: %s' % (repr(key), repr(self._environ[key]))
            print
            sys.stdout = save
            f.close()

        # Fix up environ if it doesn't look right.

        # Fix #1: No PATH_INFO
        # This can happen when there is no extra path info past the adapter.
        # e.g., http://localhost/WebKit.cgi
        if not self._environ.has_key('PATH_INFO'):
            self._environ['PATH_INFO'] = ''

        # Fix #2: No REQUEST_URI
        # REQUEST_URI isn't actually part of the CGI standard and some
        # web servers like IIS don't set it (as of 8/22/2000).
        if not self._environ.has_key('REQUEST_URI'):
            self._environ['REQUEST_URI'] = requestURI(self._environ)

        self._adapterName = self._environ.get('SCRIPT_NAME', '')

        # We use the cgi module to get the fields, but then change them into an ordinary dictionary of values
        try:
            keys = self._fields.keys()
        except TypeError:
            # This can happen if, for example, the request is an XML-RPC request, not
            # a regular POST from an HTML form.  In that case we just create an empty
            # set of fields.
            keys = []
        dict = {}

        for key in keys:
            value = self._fields[key]
            if type(value) is not ListType:
                if value.filename:
                    if debug: print "Uploaded File Found"
                else:
                    value = value.value  # i.e., if we don't have a list, we have one of those cgi.MiniFieldStorage objects. Get it's value.
            else:
                value = map(lambda miniFieldStorage: miniFieldStorage.value,
                            value)  # extract those .value's

            dict[key] = value
        self._fieldStorage = self._fields
        self._fields = dict
        self._pathInfo = None

        # We use Tim O'Malley's Cookie class to get the cookies, but then change them into an ordinary dictionary of values
        dict = {}
        for key in self._cookies.keys():
            dict[key] = self._cookies[key].value
        self._cookies = dict

        self._transaction = None
        self._serverRootPath = ""
        self._extraURLPath = ""

        # try to get automatic path session
        # if UseAutomaticPathSessions is enabled in Application.config
        # Application.py redirects the browser to a url with SID in path
        # http://gandalf/a/_SID_=2001080221301877755/Examples/
        # _SID_ is extracted and removed from path
        self._pathSession = None
        if self._environ['PATH_INFO'][1:6] == '_SID_':
            self._pathSession = self._environ['PATH_INFO'][7:].split('/', 1)[0]
            self._cookies['_SID_'] = self._pathSession
            sidstring = '_SID_=' + self._pathSession + '/'
            self._environ['REQUEST_URI'] = self._environ[
                'REQUEST_URI'].replace(sidstring, '')
            self._environ['PATH_INFO'] = self._environ['PATH_INFO'].replace(
                sidstring, '')
            if self._environ.has_key('PATH_TRANSLATED'):
                self._environ['PATH_TRANSLATED'] = self._environ[
                    'PATH_TRANSLATED'].replace(sidstring, '')
            assert (not self._environ.has_key('WK_URI'))  # obsolete?

        self._sessionExpired = 0

        # Save the original urlPath.
        self._originalURLPath = self.urlPath()

        if debug:
            print "Done setting up request, found keys %s" % repr(
                self._fields.keys())