def __init__(self, environ): """Initialize the current request object. Arguments: environ (dict): Dictionary of environment variables. """ self.environ = environ self.method = environ.get('REQUEST_METHOD', 'GET') self.path = environ.get('PATH_INFO', '/') if not self.path: self.path = '/' self.query = MultiDict() self.form = MultiDict() self.cookies = MultiDict() if 'QUERY_STRING' in environ: for k, v in urllib.parse.parse_qsl(environ['QUERY_STRING']): self.query[k] = v if 'wsgi.input' in environ: fs = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ) for k in fs: for v in fs.getlist(k): self.form[k] = v if 'HTTP_COOKIE' in environ: cookies = http.cookies.SimpleCookie(environ['HTTP_COOKIE']) for c in cookies.values(): self.cookies[c.key] = c.value
def formatcookies(cookies): htmlstr = io.StringIO() for cookie in cookies.values(): unescapedcookiestr = cookie.OutputString() escapedcookiestr = html.escape(unescapedcookiestr) htmlstr.write(f'<li>{escapedcookiestr}</li>') return htmlstr.getvalue()
def loadCookies(self, sCookies, sDomain): cookies = http.cookies.SimpleCookie(sCookies) msg = http.client.HTTPMessage() for morsel in cookies.values(): msg['set-cookie'] = morsel.output(header='').strip() res = self.dummyRes(msg) req = urllib.request.Request(sDomain) self.extract_cookies(res, req) log.debug('load cookies from string input: {}'.format(self))
def do_GET(self): """Override this to enable redirecting paths that end in -redirect or rewrite in presence of ?file=""" cookies = http.cookies.SimpleCookie(self.headers['Cookie']) if 'int' in cookies: cookies['int'] = int(cookies['int'].value) + 1 for cookie in cookies.values(): self.headers_to_send.append(('Set-Cookie', cookie.OutputString(None))) if self.path.endswith('-redirect'): self.send_response(302) self.send_header('Location', self.path[:-len('-redirect')]) self.end_headers() elif 'setheaders' in self.path: # For paths that end with '-setheaders', we fish out the headers from the query # params and set them. url = urllib.parse.urlparse(self.path) params = urllib.parse.parse_qs(url.query) for key, values in params.items(): for value in values: self.headers_to_send.append((key, value)) # Now we need to chop off the '-setheaders' part. self.path = url.path[:-len('-setheaders')] super().do_GET() elif 'headers' in self.path: # For paths that end with '-headers', we check if the request actually # contains the header with the specified value. The expected header key # and value are in the query params. url = urllib.parse.urlparse(self.path) params = urllib.parse.parse_qs(url.query) for key in params: if self.headers[key] != params[key][0]: self.send_error(404) # Now we need to chop off the '-headers' part. self.path = url.path[:-len('-headers')] super().do_GET() else: # keep special ?file= to redirect the query if '?file=' in self.path: # Eclipse frameworks: # Redirect the checksum to the old path to keep different filenames # on the mock server. if '/downloads/sums.php?file=' in self.path: self.path += '.sha512' self.path = self.path.split('?file=', 1)[1] self.path = self.path.replace('&', '?', 1) # Replace the first & with ? to make it valid. if RequestHandler.ftp_redir: self.send_response(302) # We need to remove the query parameters, so we actually parse the URL. parsed_url = urllib.parse.urlparse(self.path) new_loc = 'ftp://' + RequestHandler.hostname + parsed_url.path self.send_header('Location', new_loc) self.end_headers() return super().do_GET()
def update_cookies(self, values, time_received=None): cookies = http.cookies.SimpleCookie() if isinstance(time_received, (list, tuple)): time_received = time_received[0] if time_received else None if isinstance(time_received, str): time_received = parsedate_tz(time_received) if time_received: time_received = mktime_tz(time_received) if time_received is None: time_received = time.time() for value in values: cookies.load(value) for cookie in cookies.values(): cookie.time_received = time_received self._cookies.update(cookies) self.log.debug('Updated cookie headers: %s' % values)
def do_checkout(self): cookies = http.cookies.SimpleCookie(self.headers.get('Cookie')) print(cookies) assert self.headers['Content-Type'] == 'application/x-www-form-urlencoded' length = int(self.headers['content-length']) data_lists = parse_qs( self.rfile.read(length), # Strict options: keep_blank_values=True, strict_parsing=True, errors='strict', ) # Flatten the listed values. data_flat = {k.decode("utf-8"): v.decode("utf-8") for (k, [v]) in data_lists.items()} cartdata=data_flat.get('cartdetail') base64_bytes = cartdata.encode('ascii') message_bytes = base64.b64decode(base64_bytes) message = json.loads(message_bytes.decode('ascii')) clientid = data_flat.get('clientid') creditcard = data_flat.get('number') creditdate = data_flat.get('expired').split("-") ccv = data_flat.get('cvv') mycursor.execute("SELECT * FROM product") myresult = mycursor.fetchall() nocheck= False datecheck=False if 12 < len(creditcard) < 17 : first2 = creditcard[0:2] first4 = creditcard[0:4] vendor = None if creditcard[0] == "4" : vendor = "Visa" if creditcard[0] == "5" and "0" < creditcard[1] < "6": vendor = "MasterCard" if first2 in ("36", "38"): vendor = "Diners Club" if first4 == "6011" or first2 == "65": vendor = "Discover" if first2 == "35": vendor = "JCB" if first2 in ("34", "37"): vendor = "American Express" if vendor is not None: nocheck =True now = datetime.datetime.now() if int(now.year)<=int(creditdate[0]) and int(now.month)<=int(creditdate[1]): datecheck=True enoughcheck = False if nocheck and datecheck: for x in message: for y in myresult: if int(x[0]) in y: if x[2]<=y[3]: sql="UPDATE product SET quantity="+str(y[3]-x[2])+" WHERE product_id = "+str(x[0])+";" mycursor.execute(sql) mydb.commit() enoughcheck=True else: enoughcheck=False if enoughcheck: self.send_response(302) for morsel in cookies.values(): self.send_header("Set-Cookie", morsel.OutputString()) self.send_header('Location','http://localhost:2222/done') self.end_headers() else: self.send_response(302) self.send_header('Location','http://localhost:2222/notenough') self.end_headers() else: self.send_response(302) self.send_header('Location','http://localhost:2222/carderror') self.end_headers()