def do_POST(self): if self.path != '/connect': self.finish_up(404) return form = FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type']} ) them = form.getvalue('them') if them is None: self.finish_up(500) return # only connect people we have not recently connected # silently swallow requests for reconnections status_code = 200 if them not in self.previous: self.previous.append(them) status_code = send_connection_message(them) print("Emailed %s. MG code: %i", them, status_code) else: print("We recently emailed %s so skipping them.", them) self.finish_up(status_code)
def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/html')]) form = FieldStorage(fp=environ['wsgi.input'], environ=environ) input = form.getvalue('eingabe') auswahl = form.getvalue('auswahl') if input: filter= re.match('[0-9]+', input) if filter: eingabe = int(filter.group()) else: eingabe= 0 if auswahl == 'Rekursiv': try: ausgabe = fibboRecursive(eingabe) except: ausgabe = 0 eingabe = 'Zahl zu gross' else: try: ausgabe = fibboBinet(eingabe) except: ausgabe = 0 eingabe = 'Zahl zu gross' else: eingabe = ausgabe = '' return [html_template % (eingabe, ausgabe)]
def web_loader(environ, start_response): headers = [('Content-type', 'application/json; charset=UTF-8'), ("Access-Control-Allow-Origin", "*")] start_response('200 OK', headers) form = FieldStorage() pid = os.fork() if pid == 0: # new process os.system("philoload4 %s %s &" % (form.getvalue("dbname"), form.getvalue("files"))) exit() yield dumps({"success": True})
def add_score(params: cgi.FieldStorage, dest: pathlib.Path) -> dict: score = convert_results( dict(dateTime='{0:%d}.{0:%m}.{0:%Y} {0:%H}:{0:%M}:{0:%S}'.format( datetime.now()), username=re.sub('\W', '', params.getvalue('username')), gridSize=params.getvalue('gridSize'), shipCount=params.getvalue('shipCount'), playerOneScore=params.getvalue('playerOneScore'), playerTwoScore=params.getvalue('playerTwoScore'), gameTime=params.getvalue('gameTime'))) with dest.open('a') as out: csv.DictWriter(out, fieldnames=fields).writerow(score) return score
def main(q: cgi.FieldStorage, self_url): ORG = Organization(self_url, q) student_id = int(q.getvalue('student', 0)) Menu.response_ok() menu = Menu(ORG, self_url, student_id) if 'act' not in q: menu.show_menu(self_url, student_id) else: act_id = int(q.getvalue('act', Menu.EXIT_CODE)) if act_id == -1: # remove ORG.remove_man(q.getvalue('id')) return menu.start(act_id)
def main(q: cgi.FieldStorage, self_url): RSU = University(self_url, q) student_id = int(q.getvalue('student', 0)) Menu.response_ok() menu = Menu(RSU, self_url, student_id) if 'act' not in q: menu.show_menu(self_url, student_id) else: act_id = int(q.getvalue('act', Menu.EXIT_CODE)) if act_id == -1: # remove RSU.remove_man(q.getvalue('id')) return menu.start(act_id)
def repo_application(environ, start_response): """ The repositories WSGI application. If the incoming request's type is POST then it will be delegated to a protocol handler, otherwise the default template will be returned. """ response_body = [] response_headers = [] status = '200 OK' if environ['REQUEST_METHOD'] == 'POST': try: size = int(environ.get('CONTENT_LENGTH', 0)) except ValueError, e: size = 0 args = FieldStorage(fp=environ['wsgi.input'], environ=environ) jsonstr = args.getvalue('j') logger.info('POST from %s: %s' % (environ['REMOTE_ADDR'], jsonstr)) try: repository = Repository() handler = ProtocolHandler(repository, jsonstr) response_body = [handler.execute(environ)] except DatabaseException, e: logger.warning('database exception: %s' % str(e)) response_body = ['{"error":{"c":%d,"args":["errorstr":"%s"]}}' % (RepositoryErrorCode.DATABASE_ERROR, str(e))]
def __call__(self, environ, start_response): location = environ["PATH_INFO"] if environ["REQUEST_METHOD"] == "POST": try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): request_body_size = 0 request_body = BytesIO( environ['wsgi.input'].read(request_body_size)) sphinx_docu = FieldStorage(fp=request_body, environ=environ) if sphinx_docu.getvalue(":action") != "doc_upload": start_response('400 Bad Request', []) return [b""] stream = BytesIO(sphinx_docu.getvalue("content")) try: archive = zipfile.ZipFile(stream, "r") except zipfile.BadZipfile: start_response('400 File is not a zip file', []) return [b""] try: if archive.testzip(): start_response('400 Zip file is not sane', []) return [b""] except ValueError: start_response('400 Unexpected end of Zipfile', []) return [b""] location = path.join(self.home, sphinx_docu.getvalue("name")) real_location = path.realpath(location) if not real_location.startswith(path.realpath(self.home)): start_response('404 Forbidden', []) return [b""] if path.exists(location): shutil.rmtree(location) archive.extractall(location) start_response('200 OK', []) return [b""] else: if location == "/": index = self._index() response_header = [('Content-Type', 'text/html'), ('Content-Length', str(len(index)))] start_response('200 OK', response_header) return [index.encode("utf-8")] else: return self.static_app(environ, start_response)
def do_POST(self): self.send_response(200) self.end_headers() # Parse the form data posted form = FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) # debuglog('Client: ', self.address_string()) request = form.getvalue('request') url = form.getvalue('url') path = form.getvalue('path') rev = form.getvalue('rev') svnurl = form.getvalue('svnurl') debuglog('Handling POST:', None) debuglog('Request: ', request) debuglog('URL : ', url) debuglog('Path : ', path) debuglog('Rev : ', rev) debuglog('SVNURL : ', svnurl) if path != None: # annotate using file path self.send_response(200) self.end_headers() # restore original URL - "protected" ';' etc: url = url.replace("%3B", ";") msg = external_get_message(path, rev) msg += "\n" tmp_file = create_temp_file(msg, url) external_change_log(path, rev, tmp_file.name) delete_temp_file(tmp_file.name) elif svnurl != None: self.send_response(200) self.end_headers() # restore original URL - "protected" ';' etc: url = url.replace("%3B", ";") msg = external_get_message(svnurl, rev) msg += "\n" tmp_file = create_temp_file(msg, url) external_change_log(svnurl, rev, tmp_file.name) delete_temp_file(tmp_file.name)
def do_POST(self): self.send_response(200) self.end_headers() # Parse the form data posted form = FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) # debuglog('Client: ', self.address_string()) request = form.getvalue('request') url = form.getvalue('url') path = form.getvalue('path') rev = form.getvalue('rev') svnurl = form.getvalue('svnurl') debuglog('Handling POST:', None) debuglog('Request: ', request) debuglog('URL : ', url) debuglog('Path : ', path) debuglog('Rev : ', rev) debuglog('SVNURL : ', svnurl) if path != None: # annotate using file path self.send_response(200) self.end_headers() # restore original URL - "protected" ';' etc: url = url.replace("%3B", ";") msg = external_get_message(path, rev) msg += "\n" tmp_file = create_temp_file(msg, url) external_change_log(path, rev, tmp_file.name) delete_temp_file(tmp_file.name) elif svnurl != None: self.send_response(200) self.end_headers() # restore original URL - "protected" ';' etc: url = url.replace("%3B", ";") msg = external_get_message(svnurl, rev) msg += "\n" tmp_file = create_temp_file(msg, url) external_change_log(svnurl, rev, tmp_file.name) delete_temp_file(tmp_file.name)
def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/html')]) form = FieldStorage(fp=environ['wsgi.input'], environ=environ) name = form.getvalue('name') vorname = form.getvalue('vorname') try: gebDatum = re.match('[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]', str(form.getvalue('gebDatum'))).group() except AttributeError: gebDatum = 'TT-MM-JJJJ' gebOrt = form.getvalue('gebOrt') groesse = form.getvalue('groesse') augenfarbe = form.getvalue('augenfarbe') button = form.getvalue('enter') liste= [] liste.append(name) liste.append(vorname) liste.append(gebDatum) liste.append(gebOrt) liste.append(groesse) liste.append(augenfarbe) print liste if button == 'anzeigen': for info in liste: print info print type(info) if (info == 'None' or info == None or info == 'TT-MM-JJJJ'): html = [html_form_template % (name, vorname, gebOrt, groesse, gebDatum)] break else: html= [html_view_template % (name, vorname, gebOrt, groesse, gebDatum, augenfarbe, name, vorname, gebOrt, groesse, gebDatum, augenfarbe)] elif button == 'csv': csvDaten = csv.writer(open('personen.csv', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) csvDaten.writerow(liste) html = csv_view_template else: html = html_form_template % (name, vorname, gebOrt, groesse, gebDatum) return html
def extract_data_from_multipart_request(self, environ: dict) -> Any: try: form = FieldStorage(fp=environ["wsgi.input"], environ=environ, keep_blank_values=True) except (TypeError, ValueError): raise HttpBadRequestError("Malformed request data") try: operations = json.loads(form.getvalue("operations")) except (TypeError, ValueError): raise HttpBadRequestError( "Request 'operations' multipart field is not a valid JSON") try: files_map = json.loads(form.getvalue("map")) except (TypeError, ValueError): raise HttpBadRequestError( "Request 'map' multipart field is not a valid JSON") return combine_multipart_data(operations, files_map, form)
def __init__(self, environ): """ constructor """ self.q = {} if isinstance(environ, (dict, )) and not "REQUEST_METHOD" in environ: self.q = environ elif environ and "REQUEST_METHOD" in environ and environ[ "REQUEST_METHOD"] == "GET": request_body = environ['QUERY_STRING'] q = parse_qs(request_body) for key in q: self.q[key] = [escape(item) for item in q[key]] elif environ and "REQUEST_METHOD" in environ and environ[ "REQUEST_METHOD"] == "POST": env_copy = environ.copy() env_copy['QUERY_STRING'] = '' q = FieldStorage(fp=environ["wsgi.input"], environ=env_copy, keep_blank_values=True) for key in q: self.q[key] = q.getvalue(key) # print(key, "=", len(q.getvalue(key))) # load extra query string info: request_body = environ['QUERY_STRING'] q = parse_qs(request_body) for key in q: self.q[key] = [escape(item) for item in q[key]] if environ and "DOCUMENT_ROOT" in environ: self.q["DOCUMENT_ROOT"] = environ["DOCUMENT_ROOT"] environ["DOCUMENT_WWW"] = os.path.abspath( environ["DOCUMENT_ROOT"] + "/var/www") self.q["DOCUMENT_WWW"] = environ["DOCUMENT_WWW"] if environ and "HTTP_COOKIE" in environ: if isinstance(environ["HTTP_COOKIE"], (str, )): self.q["HTTP_COOKIE"] = mapify(environ["HTTP_COOKIE"], ";") else: self.q["HTTP_COOKIE"] = environ["HTTP_COOKIE"] if "encoded" in self.q and self.q["encoded"] in ("true", "1", 1): for key in q: if not key in ("encoded", "encrypted"): try: self.q[key] = base64.b64decode(self.q[key]) except: pass
def main(): # parse query string arguments = FieldStorage(keep_blank_values=True) json = arguments.getvalue('payload') content = loads(json) if 'commits' in content: repo = content['repository']['name'] if repo in VALID_UPDATE_REPOSITORIES: handle_repository_update(repo) process_commit_mails(content)
def main(): """ Script entry-point, reads from github.com request and processes the event. """ # parse query string arguments = FieldStorage(keep_blank_values=True) json = arguments.getvalue('payload') content = loads(json) if 'commits' in content: repo = content['repository']['name'] if repo in config['git']['repositories']: handle_irc_message(repo, content)
def do_POST(self): """Respond to a POST request""" form = FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) user = form.getvalue('user') hashedPass = form.getvalue('hashedPass') clientDB = ''#form.getvalue('clientDB') #form = dict(form) #print(form) #Check if the user is authorized and he has access to clientDb authUser = AuthUser() if True or authUser.checkAuth(user, authUser.hashPass(hashedPass), clientDB): action = form.getvalue('action') requestHandler = requestHandling() respData = requestHandler.handle(clientDB, action, form) respXML = self.buildXMLResponse(respData) else: respXML = "You're not authorized to call me !\ Register at speech.wumzi.info" #respXML = self.buildXMLResponse({'respWord' : user}) #And respond self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() self.wfile.write(respXML)
def handler(env, resp): path = env.get('PATH_INFO') route, args = self.get(path) env['args'] = args if env.get('REQUEST_METHOD') in ('GET', 'HEAD'): qs = parse_qs(env.get('QUERY_STRING', '')) for key, value in qs.iteritems(): env['args'][key] = value[0] elif env.get('REQUEST_METHOD') in ('POST', 'PUT'): fs = FieldStorage(env.get('wsgi.input'), environ=env, keep_blank_values=True) for key in fs: env['args'][key] = fs.getvalue(key, '') return route(env, resp)
def password_entry(environ, start_response): status = '200 OK' headers = [('Content-type', 'application/json; charset=UTF-8'),("Access-Control-Allow-Origin","*")] start_response(status,headers) form = FieldStorage() username = form.getvalue('username') password = form.getvalue('password') print >> sys.stderr, "PASSWORD", password path = environ["SCRIPT_FILENAME"].replace('scripts/password_entry.py', '') access, user_exists = check_login(path, username, password) if access: write_access = open("/tmp/philo4_access", "a") print >> write_access, environ["REMOTE_ADDR"] yield json.dumps('ok') else: yield json.dumps('not')
def password_entry(environ, start_response): status = '200 OK' headers = [('Content-type', 'application/json; charset=UTF-8'), ("Access-Control-Allow-Origin", "*")] start_response(status, headers) form = FieldStorage() username = form.getvalue('username') password = form.getvalue('password') print >> sys.stderr, "PASSWORD", password path = environ["SCRIPT_FILENAME"].replace('scripts/password_entry.py', '') access, user_exists = check_login(path, username, password) if access: write_access = open("/tmp/philo4_access", "a") print >> write_access, environ["REMOTE_ADDR"] yield json.dumps('ok') else: yield json.dumps('not')
def __call__(self, environ, start_response): self.requests += 1 self.params = parse_qs(environ['QUERY_STRING']) if environ.get('REQUEST_METHOD', 'GET').lower() == 'post': fs = FieldStorage(fp=environ['wsgi.input'], environ = environ, keep_blank_values = True) for k in fs.keys(): self.params[k] = [fs.getvalue(k, ''),] else: sys.stderr.write("Usando GET\n") self.path = environ.get('PATH_INFO', '').lstrip('/').rstrip('/') if not bool(self.path): self.path = "index" self.environ = environ self.start_response = start_response return self._dispatch()
def __parse_post_body(environ, ignore_get=False): post_data = {} # accept post json if environ["CONTENT_TYPE"].strip(';') == "application/json" and environ["REQUEST_METHOD"] == "POST": storage = environ['wsgi.input'].read() if storage: return json.loads(storage) storage = FieldStorage(environ['wsgi.input'], environ=environ, keep_blank_values=True) # accept get querystring if not ignore_get: for k in storage.keys(): post_data[k] = storage.getvalue(k) return post_data
def extract_fields(): form = FieldStorage() if Fields.zip in form.keys(): file_item = form[Fields.zip] if file_item.filename: if file_item.done == -1: raise Exception("File not fully downloaded.") else: product_name = get_str_value(form, Fields.product_name) product_version = get_str_value(form, Fields.product_version) comment = get_str_value(form, Fields.comment) zip_content = form.getvalue(Fields.zip) return fields_tuple(zip_content, file_item.filename, product_name, product_version, comment) else: raise Exception(Fields.zip + " field is not a file") else: raise Exception("No " + Fields.zip + " field")
def do_POST(self): p = urlparse(self.path) form = FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) print("POST", self.path) print(form) if p.path == '/action': actionid = form.getvalue("id", None) if actionid == "starttimelapse": c.starttimelapse() elif actionid == "startstreaming": c.startstreaming() elif actionid == "startfocusstreaming": c.startstreaming(zoom=3) elif actionid == "focusTL": c.startstreaming(zoom=3, x='l', y='t') elif actionid == "focusTC": c.startstreaming(zoom=3, x='c', y='t') elif actionid == "focusTR": c.startstreaming(zoom=3, x='r', y='t') elif actionid == "focusCL": c.startstreaming(zoom=3, x='l', y='c') elif actionid == "focusCC": c.startstreaming(zoom=3, x='c', y='c') elif actionid == "focusCR": c.startstreaming(zoom=3, x='r', y='c') elif actionid == "focusBL": c.startstreaming(zoom=3, x='l', y='b') elif actionid == "focusBC": c.startstreaming(zoom=3, x='c', y='b') elif actionid == "focusBR": c.startstreaming(zoom=3, x='r', y='b') elif actionid == "stop": c.stop() self.send_response(301) self.send_header('Location', '/index.html') self.end_headers()
def handle_post(self, request): """ Attempt to insert a new image! """ import base64, random from cgi import FieldStorage from tempfile import NamedTemporaryFile p = FieldStorage(fp=request.environ["wsgi.input"], environ=request.environ) tmp_image = NamedTemporaryFile() tmp_image.write(p.getvalue("image")) tmp_image.flush() # Attempt to open try: image = Image.open(tmp_image.name) except IOError: raise Redirect(request, location="/?error=UnknownType") image.thumbnail((1280, 1280)) counter = 0 while True: name = base64.urlsafe_b64encode(str(random.randint(0, 65536))) path = "%s/%s.jpg" % (self.img_path, name) if not os.path.exists(path): break else: counter += 1 if counter > 10: raise Redirect(request, location="/?error=OutOfNumbers") try: image.save(path) self.logger.info("Saved image %s" % name) except Exception: raise Redirect(request, location="/?error=ProbablySomethingBad") raise Redirect(request, location=name)
def GetCGIdata(): "CGI POST und GET Daten zur einfacheren Verarbeitung zusammen in ein Dict packen" CGIdata = {} if os.environ.has_key('QUERY_STRING'): # GET URL-Parameter parsen for i in os.environ['QUERY_STRING'].split("&"): i = i.split("=") if len(i) == 1: if i[0] != "": CGIdata[i[0]] = "" else: CGIdata[i[0]] = i[1] from cgi import FieldStorage FieldStorageData = FieldStorage() # POST Daten auswerten for i in FieldStorageData.keys(): CGIdata[i] = FieldStorageData.getvalue(i) return CGIdata
def sendMail(class_id): c1 = database.find_class(class_id) if c1 == None or session.get('auth') == None: return redirect("/") if request.method == "GET": return render_template("sendMail.html",client_id = client_id, username = session.get('username'), auth=session.get('auth'), class_one = c1, students = database.all_students_in_class(class_id)) elif request.method == "POST": button = request.form['button'] formData = FieldStorage() if 'checkbox' in formData and formData.getvalue('checkbox') == 'on': template = request.form['checkbox'] else: template = '' to = request.form.getlist("checks") body = request.form.get("body_name") subject = request.form.get("subject_name") teacher_name = session.get('username') for student in request.form.getlist("checks"): database.add_log(session.get('username'), student, subject, body) return redirect("/classes/" + class_id)
def parse(req, ): if 'multipart/form-data' not in (req.content_type or ''): return env = req.env env.setdefault('QUERY_STRING', '') # TODO: Add error handling, when the request is not formatted # correctly or does not contain the desired field... # TODO: Consider overriding make_file, so that you can # stream directly to the destination rather than # buffering using TemporaryFile (see http://goo.gl/Yo8h3P) form = FieldStorage(fp=req.stream, environ=env) for key in form: field = form[key] if not getattr(field, 'filename', False): field = form.getvalue(key) # TODO: put files in req.files instead when #493 get merged. req._params[key] = field
def GetCGIdata(): "CGI POST und GET Daten zur einfacheren Verarbeitung zusammen in ein Dict packen" CGIdata={} if os.environ.has_key('QUERY_STRING'): # GET URL-Parameter parsen for i in os.environ['QUERY_STRING'].split("&"): i=i.split("=") if len(i)==1: if i[0]!="": CGIdata[ i[0] ] = "" else: CGIdata[ i[0] ] = i[1] from cgi import FieldStorage FieldStorageData = FieldStorage() # POST Daten auswerten for i in FieldStorageData.keys(): CGIdata[i]=FieldStorageData.getvalue(i) return CGIdata
def avatar_form_handler(method, env): params = {} try: content_type = env.get("CONTENT_TYPE", "multipart/form-data") if not content_type.startswith("multipart/form-data"): raise exception.HTTPException(400, "Bad Request") form = FieldStorage(fp=env['wsgi.input'], environ=env) params["file"] = form["file"].file params["filename"] = form.getvalue("filename") return params except exception.HTTPException as e: raise e except Exception as e: raise exception.HTTPException(400, "Bad Request")
def do_POST(self): try: content = FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['content-type'], }) pdf = renderPDF(content.getvalue('data')) except Exception: self.send_response(400) self.end_headers() return self.send_response(200) self.end_headers() response = BytesIO() response.write(pdf) self.wfile.write(response.getvalue())
def main(): if getenv('CONTENT_TYPE') == 'application/x-www-form-urlencoded': from cgi import FieldStorage form = FieldStorage() msg = form.getvalue('msg') if msg == None: raise Exception("No message") else: msg = ''.join(stdin) client = create_connected_authed_client() send_line_iterable_w_send_delay(client, StringIO(msg), 1) if getenv('CONTENT_TYPE') == 'application/x-www-form-urlencoded': print "Status: 303" print "Location: /" else: print "Status: 204" print ''
def do_POST(self): form = FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD': 'POST'}) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", str(self.path), str(self.headers), form) saml_response = form.getvalue("SAMLResponse", None) if saml_response: with open("saml-response.txt", "w") as target: target.write(saml_response) self.wfile.write( b"<body><h3>Authentication details received, processing details. You may close this window at any time.</h3></body>" ) else: self.wfile.write( b"<body><h3>Unable to get authentication details</h3></body>")
def __call__(self,environ,start_response): self.response = start_response params = None if environ['REQUEST_METHOD'] == 'GET': params = dict(parse_qsl(environ['QUERY_STRING'])) elif environ['REQUEST_METHOD'] == 'POST': #fetchs form data from request body: form_data = FieldStorage( environ['wsgi.input'], headers={'content-type': environ['CONTENT_TYPE']}, environ={'REQUEST_METHOD': 'POST'}) params = {key:form_data.getvalue(str(key)) for key in form_data} url = environ['PATH_INFO'] controller = self.router.get(url,None) if controller: return controller(params=params) else: self.response('404 Not Found', [('Content-Type', 'text/html')]) return '<h1>Page not found</h1>'
def __parse_post_body(environ, ignore_get=False): post_data = {} content_type = environ[ "CONTENT_TYPE"] if "CONTENT_TYPE" in environ else None if content_type is not None: mimetype, options = cgi.parse_header(content_type) # accept post json if mimetype == "application/json" and environ[ "REQUEST_METHOD"] == "POST": storage = environ['wsgi.input'].read() if storage: return json.loads(storage) storage = FieldStorage(environ['wsgi.input'], environ=environ, keep_blank_values=True) # accept get querystring if not ignore_get: for k in storage.keys(): post_data[k] = storage.getvalue(k) return post_data
def handleNewArticle(self, post_vars=None): if not post_vars: contentType = 'Content-Type' in self.headers and self.headers['Content-Type'] or 'text/plain' post_vars = FieldStorage( fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD':'POST', 'CONTENT_TYPE': contentType } ) if not 'frontend' in post_vars: self.die('frontend not in post_vars') return frontend = post_vars['frontend'].value self.origin.log(self.origin.logger.INFO, "got incoming article from %s:%i for frontend '%s'" % (self.client_address[0], self.client_address[1], frontend)) if not 'target' in post_vars: self.die('target not in post_vars') return if not frontend in self.origin.frontends: self.die('{0} not in configured frontends'.format(frontend)) return for key in self.origin.frontends[frontend]['required_fields']: if not key in post_vars: self.die('{0} required but missing'.format(key)) return if 'hash' in post_vars: comment = base64.decodestring(post_vars.getvalue('comment', '')) else: comment = post_vars['comment'].value #TODO: UTF-8 strip? if comment.strip(' \t\n\r') == '': self.exit_redirect(9, '/overview.html', False, 'no message received. nothing to say?') return if 'enforce_board' in self.origin.frontends[frontend]: group = self.origin.frontends[frontend]['enforce_board'] else: group = post_vars['board'].value.split('\n')[0] if group == '': self.die('board is empty') return found = False for board in self.origin.frontends[frontend]['allowed_boards']: if (board[-1] == '*' and group.startswith(board[:-1])) or group == board: found = True break if not found: self.die('{0} not in allowed_boards'.format(group)) return redirect_duration = 4 if not 'allowed_files' in self.origin.frontends[frontend]: file_name = '' else: if 'hash' in post_vars: file_name = post_vars.getvalue('file_name', '') else: file_name = post_vars['file'].filename.split('\n')[0] # FIXME: add (allowed_extensions) to frontend config, remove this check once implemented if len(file_name) > 100: self.die('filename too large') return if file_name != '': if 'hash' in post_vars: content_type = post_vars.getvalue('file_ct', '') else: content_type = post_vars['file'].type allowed = False for mime in self.origin.frontends[frontend]['allowed_files']: if (mime[-1] == '*' and content_type.startswith(mime[:-1])) or content_type == mime: allowed = True break if not allowed: self.die('{0} not in allowed_files'.format(content_type)) return redirect_duration = 4 uid_host = self.origin.frontends[frontend]['uid_host'] name = self.origin.frontends[frontend]['defaults']['name'] email = self.origin.frontends[frontend]['defaults']['email'] subject = self.origin.frontends[frontend]['defaults']['subject'] if 'name' in post_vars: if post_vars['name'].value.split('\n')[0] != '': name = post_vars['name'].value.split('\n')[0] signature = False if 'allow_signatures' in self.origin.frontends[frontend]: if self.origin.frontends[frontend]['allow_signatures'].lower() in ('true', 'yes'): if '#' in name: if len(name) >= 65 and name[-65] == '#': try: keypair = nacl.signing.SigningKey(name[-64:], encoder=nacl.encoding.HexEncoder) signature = True except Exception as e: self.origin.log(self.origin.logger.INFO, "can't create keypair from user supplied secret key: %s" % e) name = name[:-65] else: parts = name.split('#', 1) if len(parts[1]) > 0: name = parts[0] try: private = parts[1][:32] out = list() counter = 0 for char in private: out.append(chr(ord(self.origin.seed[counter]) ^ ord(char))) counter += 1 for x in range(counter, 32): out.append(self.origin.seed[x]) del counter keypair = nacl.signing.SigningKey(sha256("".join(out)).digest()) del out signature = True except Exception as e: # FIXME remove "secret" trip? disable signature? self.origin.log(self.origin.logger.INFO, "can't create keypair from user supplied short trip: %s" % e) del parts if name == '': name = self.origin.frontends[frontend]['defaults']['name'] if 'email' in post_vars: #FIXME add email validation: .+@.+\..+ if post_vars['email'].value.split('\n')[0] != '': email = post_vars['email'].value.split('\n')[0] if 'subject' in post_vars: if post_vars['subject'].value.split('\n')[0] != '': subject = post_vars['subject'].value.split('\n')[0] sage = '' if 'allow_sage' in self.origin.frontends[frontend]: if self.origin.frontends[frontend]['allow_sage'].lower() in ('true', 'yes'): if (subject.lower().startswith('sage') or subject.lower().startswith('saging') or name.lower().startswith('sage') or name.lower().startswith('saging')): sage = "\nX-Sage: True" sender = '{0} <{1}>'.format(name, email) reply = '' if 'reply' in post_vars: reply = post_vars['reply'].value if reply != '': result = self.origin.sqlite.execute('SELECT message_id FROM article_hashes WHERE message_id_hash = ?', (reply,)).fetchone() if not result: self.die('hash {0} is not a valid hash'.format(reply)) return else: reply = result[0] self.origin.captcha_bypass_after_timestamp_reply = int(time.time()) + self.origin.captcha_bypass_after_seconds_reply uid_rnd = ''.join(random.choice(string.ascii_lowercase) for x in range(10)) uid_time = int(time.time()) message_uid = '<{0}{1}@{2}>'.format(uid_rnd, uid_time, self.origin.frontends[frontend]['uid_host']) if 'enforce_target' in self.origin.frontends[frontend]: redirect_target = self.origin.frontends[frontend]['enforce_target'].replace('%%sha1_message_uid_10%%', sha1(message_uid).hexdigest()[:10]) else: redirect_target = post_vars['target'].value.replace('%%sha1_message_uid_10%%', sha1(message_uid).hexdigest()[:10]) if 'hash' in post_vars: redirect_target = '/' + redirect_target boundary = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(40)) date = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S +0000') try: i2p_desthash = self.headers.get('X-I2P-DestHash') except: i2p_desthash = 'non-i2p' #f = open('tmp/' + boundary, 'w') if signature: link = os.path.join('incoming', 'tmp', boundary + '_') else: link = os.path.join('incoming', 'tmp', boundary) f = open(link, 'w') if file_name == '': f.write(self.origin.template_message_nopic.format(sender, date, group, subject, message_uid, reply, uid_host, comment, sage, i2p_desthash).replace('\r', '')) else: f.write(self.origin.template_message_pic.format(sender, date, group, subject, message_uid, reply, uid_host, boundary, comment, content_type, file_name, sage, i2p_desthash).replace('\r', '')) if 'hash' in post_vars: if self.origin.fast_uploads == True: # get file looking by file_name if file_name not in self.origin.temp_file_obj: self.origin.temp_file_obj[file_name] = ['', ''] f.write(self.origin.temp_file_obj[file_name][0].replace('\r', '')) del self.origin.temp_file_obj[file_name] self.cleanup_uploads() else: f.write(post_vars.getvalue('file_b64', '').replace('\r', '')) else: base64.encode(post_vars['file'].file, f) f.write('--{0}--\n'.format(boundary)) f.close() if signature: hasher = sha512() f = open(link, 'r') oldline = None for line in f: if oldline: hasher.update(oldline) oldline = line.replace("\n", "\r\n") #f.close() oldline = oldline.replace("\r\n", "") hasher.update(oldline) signature = hexlify(keypair.sign(hasher.digest()).signature) pubkey = hexlify(keypair.verify_key.encode()) signed = open(link[:-1], 'w') f = open(link, 'r') link = link[:-1] signed.write(self.origin.template_message_signed.format(sender, date, group, subject, message_uid, reply, uid_host, pubkey, signature, sage, i2p_desthash)) f.seek(0) for line in f: signed.write(line) f.close() signed.close() # FIXME unlink f() a.k.a. incoming/tmp/*_ del hasher del keypair del pubkey del signature try: if len(comment) > 40 and self.origin.spamprot_base64.match(comment): os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.origin.log(self.origin.logger.WARNING, "caught some new base64 spam for frontend %s: incoming/spam/%s" % (frontend, message_uid)) self.origin.log(self.origin.logger.WARNING, self.headers) #if self.origin.fake_ok: self.exit_redirect(redirect_duration, redirect_target, add_spamheader=True) elif len(subject) > 80 and self.origin.spamprot_base64.match(subject): os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.origin.log(self.origin.logger.WARNING, "caught some new large subject spam for frontend %s: incoming/spam/%s" % (frontend, message_uid)) self.origin.log(self.origin.logger.WARNING, self.headers) #if self.origin.fake_ok: self.exit_redirect(redirect_duration, redirect_target, add_spamheader=True) elif len(name) > 80 and self.origin.spamprot_base64.match(name): os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.origin.log(self.origin.logger.WARNING, "caught some new large name spam for frontend %s: incoming/spam/%s" % (frontend, message_uid)) self.origin.log(self.origin.logger.WARNING, self.headers) #if self.origin.fake_ok: self.exit_redirect(redirect_duration, redirect_target, add_spamheader=True) else: os.rename(link, os.path.join('incoming', boundary)) #os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.exit_redirect(redirect_duration, redirect_target) except socket.error as e: if e.errno == 32: self.origin.log(self.origin.logger.DEBUG, 'broken pipe: %s' % e) # Broken pipe pass else: self.origin.log(self.origin.logger.WARNING, 'unhandled exception while processing new post: %s' % e) self.origin.log(self.origin.logger.WARNING, traceback.format_exc())
''' convert domain to idna format''' dom_u = unicode(dom, 'utf-8') return dom_u.encode("idna") if __name__ == "__main__": chdir('/usr/local/ispmgr/') # activate logging # stderr ==> ispmgr.log log = Log(plugin=PLUGIN_NAME) stderr = log try: # get cgi vars req = FieldStorage(keep_blank_values=True) func = req.getvalue('func') elid = req.getvalue('elid') sok = req.getvalue('sok') log.write('func %s, elid %s, sok %s' % (func, elid, sok)) if func != 'wwwdomain.edit' or not sok: print xml_doc() raise ExitOk('no action') user = req.getvalue('owner') if not user: user = environ.get('REMOTE_USER') if not user: raise Exception('cant set user')
conf[token[0].strip(" ")] = token[1].strip(" ") """ remote = os.environ["REMOTE_ADDR"] if "REMOTE_ADDR" in os.environ else "" if len(remote) == 0 or (remote != "localhost" and remote != "127.0.0.1" and conf["public"] != "1"): print("[]") exit() """ form = FieldStorage() if "species" not in form: print(-1) exit() species = form.getvalue('species') hostname = form.getvalue('host') if "host" in form else "" try: a = int(species) except: print(-2) exit() if hostname != "": try: request = "&".join(["%s=%s" % (key, form.getvalue(key)) for key in form if key != "host"]) print(urlopen("%s/scripts/get-functions.py?%s" % (hostname, request), timeout = 2).read().decode("utf8"))
def send_captcha(self, message='', post_vars=None): failed = True if not post_vars: failed = False contentType = 'Content-Type' in self.headers and self.headers['Content-Type'] or 'text/plain' post_vars = FieldStorage( fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD':'POST', 'CONTENT_TYPE': contentType } ) # someone wants to f**k around if not 'frontend' in post_vars: self.die('frontend not in post_vars') return else: frontend = post_vars.getvalue('frontend', '').replace('"', '"') reply = post_vars.getvalue('reply', '').replace('"', '"') #if frontend == 'overchan' and reply != '': # # FIXME add ^ allow_reply_bypass to frontend configuration # if self.origin.captcha_bypass_after_timestamp_reply < int(time.time()): # self.origin.log(self.origin.logger.INFO, 'bypassing captcha for reply') # self.handleNewArticle(post_vars) # return board = post_vars.getvalue('board', '').replace('"', '"') target = post_vars.getvalue('target', '').replace('"', '"') name = post_vars.getvalue('name', '').replace('"', '"') email = post_vars.getvalue('email', '').replace('"', '"') subject = post_vars.getvalue('subject', '').replace('"', '"') if post_vars.getvalue('hash', '') != '': comment = post_vars.getvalue('comment', '').replace('"', '"') file_name = post_vars.getvalue('file_name', '').replace('"', '"') file_ct = post_vars.getvalue('file_ct', '').replace('"', '"') file_b64 = post_vars.getvalue('file_b64', '').replace('"', '"') else: comment = base64.encodestring(post_vars.getvalue('comment', '')) if not 'allowed_files' in self.origin.frontends[frontend]: file_name = '' file_ct = '' file_b64 = '' else: file_name = post_vars['file'].filename.replace('"', '"') if file_name == '': file_ct = '' file_b64 = '' else: file_ct = post_vars['file'].type.replace('"', '"') f = cStringIO.StringIO() base64.encode(post_vars['file'].file, f) file_b64 = f.getvalue() f.close() if failed: identifier = sha256() identifier.update(frontend + board + reply + target + name + email + subject) identifier.update(comment) self.origin.log(self.origin.logger.WARNING, 'failed capture try for %s' % identifier.hexdigest()) self.origin.log(self.origin.logger.WARNING, self.headers) passphrase = ''.join([random.choice(self.origin.captcha_alphabet) for i in xrange(6)]) #passphrase += ' ' + ''.join([random.choice(self.origin.captcha_alphabet) for i in xrange(6)]) b64 = self.origin.captcha_render_b64(passphrase, self.origin.captcha_tiles, self.origin.get_captcha_font(), self.origin.captcha_filter) if self.origin.captcha_require_cookie: cookie = ''.join(random.choice(self.origin.captcha_alphabet) for x in range(32)) expires, solution_hash = self.origin.captcha_generate(passphrase, self.origin.captcha_secret + cookie) self.send_response(200) self.send_header('Content-type', 'text/html') self.send_header('Set-Cookie', 'session=%s; path=/incoming/verify' % cookie) else: expires, solution_hash = self.origin.captcha_generate(passphrase, self.origin.captcha_secret) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() # use file_name as key and file content + current time as value if self.origin.fast_uploads == True: if file_b64 != '': # we can have empty file_b64 here whether captcha was entered wrong first time self.origin.temp_file_obj[file_name] = [file_b64, int(time.time())] self.wfile.write(self.origin.template_verify_fast.format(message, b64, solution_hash, expires, frontend, board, reply, target, name, email, subject, comment, file_name, file_ct)) else: self.wfile.write(self.origin.template_verify_slow.format(message, b64, solution_hash, expires, frontend, board, reply, target, name, email, subject, comment, file_name, file_ct, file_b64)) return
return html def parcours_q(id_debut): liste_choix_deter=[4,12,13,39,62];html=P+header()+startform() if id_debut!=89: try: for qCourante in range(id_debut,len(liste_question)+1): html+=str(print_q(qCourante,html)) if qCourante in liste_choix_deter:break except:afficherFin() html+=footer(id_debut);return html def recup_valeurs(): liste_tempo_csv=[];id_rand=str(randrange(0x9184e72a000,99999999999999)) if form: if form.getvalue(h)==g:html=parcours_q(1) else: for i in form: try: if V not in form[i].value.split(I)[0]: question=form[i].value.split(I)[0] try:reponse=form[i].value.split(I)[1] except IndexError:pass liste_tempo_csv.append(str(question)+I+str(reponse)) except AttributeError:pass liste_tempo_csv.sort();liste_tempo_csv.insert(0,id_rand);id_last_question=liste_tempo_csv[len(liste_tempo_csv)-1].split(I)[0];id_last_response=liste_tempo_csv[len(liste_tempo_csv)-1].split(I)[1];valeur=int(id_last_question);mareponse=int(id_last_response);return parcours_q(goto(valeur,mareponse)) else:return P html=recup_valeurs() if form.getvalue(h)==g:html=parcours_q(1) elif form.getvalue('next')!=V:html=header()+intro() print(html)
''' convert domain to idna format''' dom_u = unicode(dom, 'utf-8') return dom_u.encode("idna") if __name__ == "__main__": chdir('/usr/local/ispmgr/') # activate logging # stderr ==> ispmgr.log log = Log(plugin=PLUGIN_NAME) stderr = log try: # get cgi vars req = FieldStorage(keep_blank_values=True) func = req.getvalue('func') elid = req.getvalue('elid') sok = req.getvalue('sok') dir = req.getvalue('name') log.write('func %s, elid %s, sok %s' % (func, elid, sok)) if func != 'diraccess.edit' or not sok: print xml_doc() raise ExitOk('no action') user = req.getvalue('owner') if not user: user = environ.get('REMOTE_USER') if not user:
#!/usr/bin/python from cgi import FieldStorage import sys import os root = os.environ("HOME") sys.path.insert(0, root + "/python") from pages.settings import Settings Settings.setRootDirectory(root) from pages.pageloader import PageLoader import cgitb cgitb.enable() print("Content-Type: text/html\n") parms = FieldStorage() paramDict = {} for k in parms.keys(): paramDict[k] = parms.getvalue(k) print(PageLoader().getPage(paramDict))
else: return "Error" # if form.getvalue("update"): # result = updateSample(dbID, sampleID, data) # if not result: # dataFail. # else: # sampleID = form.getvalue("sampleID") # dataID = form.getvalue("dataID") # data = getData(cursor, dataID, sampleID) if form.getvalue("update"): sampleID = form.getvalue("sampleID") dataID = form.getvalue("dataID") data = form.getvalue("data") sampleData = ("Updating: ", dataID, sampleID, data) updateData(cursor, dataID, sampleID, data) if form.getvalue("upload"): print('HERE') dataID = form.getvalue("dataID") data = form.getvalue("data") print(dataID, data) sampleID = getNextSampleID(form.getvalue("dataID")) print(dataID, data) sampleData = ("Uploading: ", dataID, sampleID, data)
def handle_request(self): field_storage = FieldStorage() action = field_storage.getvalue('action') try: if action == 'policies': result = self.policies() elif action == 'check_acl': policy_file = field_storage.getvalue('policy_file') protocols = field_storage.getvalue('protocols') source_addresses = field_storage.getvalue('source_addresses') source_ports = field_storage.getvalue('source_ports') destination_addresses = field_storage.getvalue('destination_addresses') destination_ports = field_storage.getvalue('destination_ports') result = self.check_all(action, policy_file, protocols, source_addresses, source_ports, destination_addresses, destination_ports) elif action == 'check_utnet': protocols = field_storage.getvalue('protocols') addresses1 = field_storage.getvalue('addresses1') ports1 = field_storage.getvalue('ports1') addresses2 = field_storage.getvalue('addresses2') ports2 = field_storage.getvalue('ports2') result = self.check_all(action, None, protocols, addresses1, ports1, addresses2, ports2) elif action == 'reverse_dns': address = field_storage.getvalue('address') try: result = self.reverse_dns(address) except: result = '' except Exception as e: result = format_exc() print 'Content-type: application/json\n\n' print dumps(result)
self.tracks[name] = {} for trkseg in trk.getElementsByTagName('trkseg'): for trkpt in trkseg.getElementsByTagName('trkpt'): lat = float(trkpt.getAttribute('lat')) lon = float(trkpt.getAttribute('lon')) ele = float(trkpt.getElementsByTagName('ele')[0].firstChild.data) rfc3339 = trkpt.getElementsByTagName('time')[0].firstChild.data self.tracks[name][rfc3339] = {'lat':lat, 'lon':lon, 'ele':ele} def getTrack(self, name): times = self.tracks[name].keys() #print times points = [self.tracks[name][time] for time in times.sort()] return [(point['lat'], point['lon']) for point in points] if __name__ == '__main__': reload(sys) sys.setdefaultencoding("iso-8859-15") form = FieldStorage() base = form.getvalue('user', 'gc') print "Content-type: text/html;charset=utf-8" print parser = GPX_Parser('/home/%s/public_html/AllFound.gpx' % base) #parser.parseTracks() #print parser.getTrack('ACTIVE LOG') parser.parse_waypoints() #for wpt in parser.waypoints: # print wpt parser.print_map()
from sys import exit, stderr from cgi import FieldStorage from traceback import format_exc if __name__ == "__main__": chdir('/usr/local/ispmgr/') # activate logging # stderr ==> ispmgr.log log = Log(plugin=PLUGIN_NAME) stderr = log try: # get cgi vars req = FieldStorage(keep_blank_values=True) func = req.getvalue('func') elid = req.getvalue('elid') sok = req.getvalue('sok') log.write('func %s, elid %s, sok %s' % (func, elid, sok)) if func != 'backupplan' and sok: print xml_doc() raise ExitOk('no action') #assert not sok #assert func == 'backupplan' cagefs = CageFS(log) cagefs.run_cagefsctl('--hook-install') print xml_doc()
print "OK" elif args.list != None and args.has_key('oauth_token'): # auth callback. print print "logged OK" elif args.list != None and args.has_key('new'): # create changeset empty_changeset = """<?xml version="1.0" encoding="UTF-8"?> <osm> <changeset> <tag k="created_by" v="HTML editor 0.1 ([email protected])"/> <tag k="comment" v="%s"/> </changeset> </osm>"""%args.getvalue('new') changeset_id = api.put("/api/0.6/changeset/create", empty_changeset) session.data['changeset_id'] = changeset_id print if args.has_key('cb'): print "function %s() {return '%s'} "%(args.getvalue('cb'), changeset_id) else: print changeset_id elif args.list != None and args.has_key('close'): # close changeset result = api.put("/api/0.6/changeset/%s/close"%changeset_id) print if args.has_key('cb'):
#! /usr/bin/env python from cgi import FieldStorage form = FieldStorage() print "Content-type: text/html" print "Hello world from apache" print form.getvalue('user') print form.getvalue('email')
import cgitb import os import html from http import cookies gbook = Gbook() params = FieldStorage() admin = False if "HTTP_COOKIE" in os.environ: cookie = cookies.SimpleCookie(os.environ.get("HTTP_COOKIE")).get("admin") if cookie is not None: admin = True if os.environ.get("REQUEST_METHOD") == "POST": operation = params.getvalue("operation", "") if operation == "post": name = html.escape(params.getvalue("name")) email = html.escape(params.getvalue("email")) msg = html.escape(params.getvalue("msg")) gbook.save_msgs(name, email, msg) elif operation == "login": login = html.escape(params.getvalue("login")) password = html.escape(params.getvalue("password")) admin = gbook.login(login, password) elif operation == "logout": gbook.logout() admin = False if 'del' in params: id = int(params.getvalue("del")) if id:
from sys import exit,stderr from cgi import FieldStorage from traceback import format_exc if __name__ == "__main__": chdir('/usr/local/ispmgr/') # activate logging # stderr ==> ispmgr.log log = Log(plugin=PLUGIN_NAME) stderr = log try: # get cgi vars req = FieldStorage(keep_blank_values=True) func = req.getvalue('func') elid = req.getvalue('elid') sok = req.getvalue('sok') log.write('func %s, elid %s, sok %s' % (func, elid, sok)) if func != 'user.edit': print xml_doc() raise ExitOk('no action') if not sok: print xml_doc() raise ExitOk('no action') #assert sok #assert func == 'user.edit'
def do_POST(self): ''' This function sends search results ''' # TIME HAS STARTED start_time = time.time() form = FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'}) query = str(form.getvalue('query')) limit = form.getvalue("limit") if not limit: limit = 3 else: limit = int(limit) offset = form.getvalue("offset") if not offset or int(offset) < 0: offset = 0 else: offset = int(offset) doc_act = form.getvalue("action") if doc_act == "back" and offset != 0: offset = offset - limit elif doc_act == "forward": offset = offset + limit elif doc_act == "to the beginning": offset = 0 # field, button and query self.send_response(250) self.send_header("Content-type", "text/html; charset=utf-8") self.end_headers() self.wfile.write(bytes(""" <html> <body> <form method="post"> <input type="text" name="query" value="%s"/> <input type="submit" name="search" value="Search"/> <br> <br> <label for="limit"> Docs per page <input type="number" name="limit" placeholder="limit" value="%d"/> </label> <input type="hidden" name="offset" placeholder="offset"value="%d"/> """ % (query, limit, offset), encoding="utf-8")) # my list of (doclim,docset) pairs docs_list = [] for num in range(limit+1): # print('I am reading offsets and limits for quotes') quote_act = form.getvalue("action%d" % num) doclim = form.getvalue('doc%dlim' % num) # print(doclim, 'doclim') docset = form.getvalue('doc%dset' % num) # print(docset,'docset') if not doclim or doclim == "None": doclim = 3 else: doclim = int(doclim) if not docset or docset == "None": docset = 0 else: docset = int(docset) if docset < 0: docset = 0 # print('I am reading conditions for quote buttons') # надо чтобы при перелистывании на другую страницу, # оффсет и лимит для цитат сбрасывались до базовых # если я на 1 стр перелистнула цитаты, # то кнопка "назад" для цитат стала активной # но когда я перелистываю на 2 стр я хочу, # чтобы кнопка назад для цитат с новой стр, # которые я еще НЕ листала, была НЕ активной if doc_act == "forward": docset = 0 if quote_act == "back" and docset != 0: docset = docset - doclim # print(docset, 'docset for back') elif quote_act == "forward": docset = docset + doclim # print(docset, 'docset for forward') elif quote_act == "to the beginning": docset = 0 # print(docset,'docset as it is') # print(doclim, 'doclim as it is') # я добавляю к лимиту единицу, это чтобы листать цитаты # (если есть еще одна после лимита, то можно листать, иначе - кнопка не горит!!! и врут календари))) docs_list.append((doclim+1,docset)) num += 1 print(docs_list,'docs_list') my_search = SearchEngine('TolstoyDataBase') # print(query) # еще одна пара, чтобы искать следущий документ doc_limof = [] for pair in docs_list: doc_limof.append(pair) doc_limof.append((3,0)) print(doc_limof,'doc_limof') # здесь лимит по цитатам + 1 final = my_search.qulim_search_modified(query, 1, limit+1, offset, doc_limof) # условия горения кнопок по документам print(offset, 'offset') if offset == 0: self.wfile.write(bytes(""" <input type="submit" name="action" value="to the beginning" disabled/> <input type="submit" name="action" value="back"disabled/>""", encoding="UTF-8")) else: self.wfile.write(bytes(""" <input type="submit" name="action" value="to the beginning"/> <input type="submit" name="action" value="back"/>""", encoding="UTF-8")) print(len(final), 'len of final') if len(final.keys()) < limit +1: self.wfile.write(bytes(""" <input type="submit" name="action" value="forward" disabled/>""", encoding="UTF-8")) else: self.wfile.write(bytes(""" <input type="submit" name="action" value="forward"/>""", encoding="UTF-8")) # the beginning of ordered list self.wfile.write(bytes('<ol>', encoding="utf-8")) if not final: self.wfile.write(bytes('NOT FOUND, SORRY', encoding="utf-8")) # делаю срез, чтобы взять лимит минус 1 результатов, лимит+1 результат не надо показывать, он в уме for number,filename in enumerate(sorted(final)[:limit]): # create limit and offset for each document for it to have it's personal ones quote_lim = doc_limof[number][0] quote_offset = doc_limof[number][1] self.wfile.write(bytes('<li><p>%s</p>' % filename, encoding ="utf-8")) self.wfile.write(bytes(""" <label for="doc%dlim"> Quotes per doc <input type="number" name="doc%dlim" value="%d"/> </label> <input type="hidden" name="doc%dset" value="%d"/> """% (number, number, quote_lim-1, number, quote_offset), encoding="utf-8")) # условия горения кнопок по цитатам print(quote_offset,'quote_offset') if quote_offset == 0: self.wfile.write(bytes(""" <input type="submit" name="action%d" value="to the beginning"disabled/> <input type="submit" name="action%d" value="back"disabled/>""" %(number,number), encoding="UTF-8")) else: self.wfile.write(bytes(""" <input type="submit" name="action%d" value="to the beginning"/> <input type="submit" name="action%d" value="back"/>""" %(number,number), encoding="UTF-8")) print(len(final[filename]),'len(final[filename])') print(quote_lim, 'quote_lim') print(limit,'limit') print(offset,'offset') # quote_lim на самом деле уже содержит +1, поэтому еще раз прибавлять не надо if len(final[filename]) < quote_lim: self.wfile.write(bytes(""" <input type="submit" name="action%d" value="forward"disabled/>""" %number, encoding="UTF-8")) elif len(final[filename]) >= quote_lim: self.wfile.write(bytes(""" <input type="submit" name="action%d" value="forward"/>""" %number, encoding="UTF-8")) # the beginning of unordered list self.wfile.write(bytes('<ul>', encoding="utf-8")) # вывожу цитаты до лимита по цитатам - 1 for num, quote in enumerate (final[filename][:-1]): self.wfile.write(bytes('<li><p>%s</p></li>' % quote, encoding="utf-8")) self.wfile.write(bytes('</ul>', encoding="utf-8")) self.wfile.write(bytes("""</ol</form></body></html>""", encoding="utf-8")) print('time:', time.time() - start_time)
def send_captcha(self, message='', post_vars=None): failed = True if not post_vars: failed = False post_vars = FieldStorage( fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], } ) frontend = post_vars.getvalue('frontend', '').replace('"', '"') reply = post_vars.getvalue('reply', '').replace('"', '"') #if frontend == 'overchan' and reply != '': # # FIXME add ^ allow_reply_bypass to frontend configuration # if self.origin.captcha_bypass_after_timestamp_reply < int(time.time()): # self.origin.log(self.origin.logger.INFO, 'bypassing captcha for reply') # self.handleNewArticle(post_vars) # return board = post_vars.getvalue('board', '').replace('"', '"') target = post_vars.getvalue('target', '').replace('"', '"') name = post_vars.getvalue('name', '').replace('"', '"') email = post_vars.getvalue('email', '').replace('"', '"') subject = post_vars.getvalue('subject', '').replace('"', '"') if post_vars.getvalue('hash', '') != '': comment = post_vars.getvalue('comment', '').replace('"', '"') file_name = post_vars.getvalue('file_name', '').replace('"', '"') file_ct = post_vars.getvalue('file_ct', '').replace('"', '"') file_b64 = post_vars.getvalue('file_b64', '').replace('"', '"') else: comment = base64.encodestring(post_vars.getvalue('comment', '')) if not 'allowed_files' in self.origin.frontends[frontend]: file_name = '' file_ct = '' file_b64 = '' else: file_name = post_vars['file'].filename.replace('"', '"') if file_name == '': file_ct = '' file_b64 = '' else: file_ct = post_vars['file'].type.replace('"', '"') f = cStringIO.StringIO() base64.encode(post_vars['file'].file, f) file_b64 = f.getvalue() f.close() if failed: identifier = sha256() identifier.update(frontend + board + reply + target + name + email + subject) identifier.update(comment) self.origin.log(self.origin.logger.WARNING, 'failed capture try for %s' % identifier.hexdigest()) self.origin.log(self.origin.logger.WARNING, self.headers) passphrase = ''.join([random.choice(self.origin.captcha_alphabet) for i in xrange(6)]) #passphrase += ' ' + ''.join([random.choice(self.origin.captcha_alphabet) for i in xrange(6)]) b64 = self.origin.captcha_render_b64(passphrase, self.origin.captcha_tiles, self.origin.captcha_font, self.origin.captcha_filter) if self.origin.captcha_require_cookie: cookie = ''.join(random.choice(self.origin.captcha_alphabet) for x in range(32)) expires, solution_hash = self.origin.captcha_generate(passphrase, self.origin.captcha_secret + cookie) self.send_response(200) self.send_header('Content-type', 'text/html') self.send_header('Set-Cookie', 'session=%s; path=/incoming/verify' % cookie) else: expires, solution_hash = self.origin.captcha_generate(passphrase, self.origin.captcha_secret) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>straight into deep space</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="/styles.css" type="text/css"> <link rel="stylesheet" href="/user.css" type="text/css"> </head> <body class="mod"> <center> %s <br /> <br /> <img src="data:image/png;base64,%s" /> <br /> <form ACTION="/incoming/verify" METHOD="POST" enctype="multipart/form-data"> <input type="hidden" name="hash" value="%s" /> <input type="hidden" name="expires" value="%i" /> <input type="text" class="posttext" style="width: 150px;" name="solution" /> <input type="hidden" name="frontend" value="%s" /> <input type="hidden" name="board" value="%s" /> <input type="hidden" name="reply" value="%s" /> <input type="hidden" name="target" value="%s" /> <input type="hidden" name="name" value="%s" /> <input type="hidden" name="email" value="%s" /> <input type="hidden" name="subject" value="%s" /> <input type="hidden" name="comment" value="%s" /> <input type="hidden" name="file_name" value="%s" /> <input type="hidden" name="file_ct" value="%s" /> <input type="hidden" name="file_b64" value="%s" /> <br /> <input type="submit" class="postbutton" value="solve dat shit" /> </form> </center> </body> </html>''' % (message, b64, solution_hash, expires, frontend, board, reply, target, name, email, subject, comment, file_name, file_ct, file_b64)) return
def handleNewArticle(self, post_vars=None): if not post_vars: contentType = 'Content-Type' in self.headers and self.headers['Content-Type'] or 'text/plain' post_vars = FieldStorage( fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD':'POST', 'CONTENT_TYPE': contentType } ) if not 'frontend' in post_vars: self.die('frontend not in post_vars') return frontend = post_vars['frontend'].value self.origin.log(self.origin.logger.INFO, "got incoming article from %s:%i for frontend '%s'" % (self.client_address[0], self.client_address[1], frontend)) if not 'target' in post_vars: self.die('target not in post_vars') return if not frontend in self.origin.frontends: self.die('{0} not in configured frontends'.format(frontend)) return for key in self.origin.frontends[frontend]['required_fields']: if not key in post_vars: self.die('{0} required but missing'.format(key)) return if 'hash' in post_vars: comment = base64.decodestring(post_vars.getvalue('comment', '')) else: comment = post_vars['comment'].value #TODO: UTF-8 strip? if comment.strip(' \t\n\r') == '': self.exit_redirect(9, '/overview.html', False, 'no message received. nothing to say?') return if 'enforce_board' in self.origin.frontends[frontend]: group = self.origin.frontends[frontend]['enforce_board'] else: group = post_vars['board'].value.split('\n')[0] if group == '': self.die('board is empty') return found = False for board in self.origin.frontends[frontend]['allowed_boards']: if (board[-1] == '*' and group.startswith(board[:-1])) or group == board: found = True break if not found: self.die('{0} not in allowed_boards'.format(group)) return redirect_duration = 4 if not 'allowed_files' in self.origin.frontends[frontend]: file_name = '' else: if 'hash' in post_vars: file_name = post_vars.getvalue('file_name', '') else: file_name = post_vars['file'].filename.split('\n')[0] # FIXME: add (allowed_extensions) to frontend config, remove this check once implemented if len(file_name) > 100: self.die('filename too large') return if file_name != '': if 'hash' in post_vars: content_type = post_vars.getvalue('file_ct', '') else: content_type = post_vars['file'].type allowed = False for mime in self.origin.frontends[frontend]['allowed_files']: if (mime[-1] == '*' and content_type.startswith(mime[:-1])) or content_type == mime: allowed = True break if not allowed: self.die('{0} not in allowed_files'.format(content_type)) return redirect_duration = 4 if self.origin.overchan_fake_id and frontend.lower() == 'overchan': comment = self.fake_id_to_overchan_id(comment, group) uid_host = self.origin.frontends[frontend]['uid_host'] name = self.origin.frontends[frontend]['defaults']['name'] email = self.origin.frontends[frontend]['defaults']['email'] subject = self.origin.frontends[frontend]['defaults']['subject'] if 'name' in post_vars: if post_vars['name'].value.split('\n')[0] != '': name = post_vars['name'].value.split('\n')[0] signature = False if 'allow_signatures' in self.origin.frontends[frontend]: if self.origin.frontends[frontend]['allow_signatures'].lower() in ('true', 'yes'): if '#' in name: if len(name) >= 65 and name[-65] == '#': try: keypair = nacl.signing.SigningKey(name[-64:], encoder=nacl.encoding.HexEncoder) signature = True except Exception as e: self.origin.log(self.origin.logger.INFO, "can't create keypair from user supplied secret key: %s" % e) name = name[:-65] else: parts = name.split('#', 1) if len(parts[1]) > 0: name = parts[0] try: private = parts[1][:32] out = list() counter = 0 for char in private: out.append(chr(ord(self.origin.seed[counter]) ^ ord(char))) counter += 1 for x in range(counter, 32): out.append(self.origin.seed[x]) del counter keypair = nacl.signing.SigningKey(sha256("".join(out)).digest()) del out signature = True except Exception as e: # FIXME remove "secret" trip? disable signature? self.origin.log(self.origin.logger.INFO, "can't create keypair from user supplied short trip: %s" % e) del parts if name == '': name = self.origin.frontends[frontend]['defaults']['name'] if 'email' in post_vars: #FIXME add email validation: .+@.+\..+ if post_vars['email'].value.split('\n')[0] != '': email = post_vars['email'].value.split('\n')[0] if 'subject' in post_vars: if post_vars['subject'].value.split('\n')[0] != '': subject = post_vars['subject'].value.split('\n')[0] sage = '' if 'allow_sage' in self.origin.frontends[frontend]: if self.origin.frontends[frontend]['allow_sage'].lower() in ('true', 'yes'): if (subject.lower().startswith('sage') or subject.lower().startswith('saging') or name.lower().startswith('sage') or name.lower().startswith('saging')): sage = "\nX-Sage: True" sender = '{0} <{1}>'.format(name, email) reply = '' if 'reply' in post_vars: reply = post_vars['reply'].value if reply != '': result = self.origin.sqlite.execute('SELECT message_id FROM article_hashes WHERE message_id_hash = ?', (reply,)).fetchone() if not result: self.die('hash {0} is not a valid hash'.format(reply)) return else: reply = result[0] self.origin.captcha_bypass_after_timestamp_reply = int(time.time()) + self.origin.captcha_bypass_after_seconds_reply uid_rnd = ''.join(random.choice(string.ascii_lowercase) for x in range(10)) uid_time = int(time.time()) message_uid = '<{0}{1}@{2}>'.format(uid_rnd, uid_time, self.origin.frontends[frontend]['uid_host']) if 'enforce_target' in self.origin.frontends[frontend]: redirect_target = self.origin.frontends[frontend]['enforce_target'].replace('%%sha1_message_uid_10%%', sha1(message_uid).hexdigest()[:10]) else: redirect_target = post_vars['target'].value.replace('%%sha1_message_uid_10%%', sha1(message_uid).hexdigest()[:10]) if 'hash' in post_vars: redirect_target = '/' + redirect_target boundary = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(40)) date = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S +0000') try: i2p_desthash = self.headers.get('X-I2P-DestHash') except: i2p_desthash = 'non-i2p' #f = open('tmp/' + boundary, 'w') if signature: link = os.path.join('incoming', 'tmp', boundary + '_') else: link = os.path.join('incoming', 'tmp', boundary) f = open(link, 'w') if file_name == '': f.write(self.origin.template_message_nopic.format(sender, date, group, subject, message_uid, reply, uid_host, comment, sage, i2p_desthash).replace('\r', '')) else: f.write(self.origin.template_message_pic.format(sender, date, group, subject, message_uid, reply, uid_host, boundary, comment, content_type, file_name, sage, i2p_desthash).replace('\r', '')) if 'hash' in post_vars: if self.origin.fast_uploads == True: # get file looking by file_name if file_name not in self.origin.temp_file_obj: self.origin.temp_file_obj[file_name] = ['', ''] f.write(self.origin.temp_file_obj[file_name][0].replace('\r', '')) del self.origin.temp_file_obj[file_name] self.cleanup_uploads() else: f.write(post_vars.getvalue('file_b64', '').replace('\r', '')) else: base64.encode(post_vars['file'].file, f) f.write('--{0}--\n'.format(boundary)) f.close() if signature: hasher = sha512() f = open(link, 'r') oldline = None for line in f: if oldline: hasher.update(oldline) oldline = line.replace("\n", "\r\n") #f.close() oldline = oldline.replace("\r\n", "") hasher.update(oldline) signature = hexlify(keypair.sign(hasher.digest()).signature) pubkey = hexlify(keypair.verify_key.encode()) signed = open(link[:-1], 'w') f = open(link, 'r') link = link[:-1] signed.write(self.origin.template_message_signed.format(sender, date, group, subject, message_uid, reply, uid_host, pubkey, signature, sage, i2p_desthash)) f.seek(0) for line in f: signed.write(line) f.close() signed.close() # FIXME unlink f() a.k.a. incoming/tmp/*_ del hasher del keypair del pubkey del signature try: if len(comment) > 40 and self.origin.spamprot_base64.match(comment): os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.origin.log(self.origin.logger.WARNING, "caught some new base64 spam for frontend %s: incoming/spam/%s" % (frontend, message_uid)) self.origin.log(self.origin.logger.WARNING, self.headers) #if self.origin.fake_ok: self.exit_redirect(redirect_duration, redirect_target, add_spamheader=True) elif len(subject) > 80 and self.origin.spamprot_base64.match(subject): os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.origin.log(self.origin.logger.WARNING, "caught some new large subject spam for frontend %s: incoming/spam/%s" % (frontend, message_uid)) self.origin.log(self.origin.logger.WARNING, self.headers) #if self.origin.fake_ok: self.exit_redirect(redirect_duration, redirect_target, add_spamheader=True) elif len(name) > 80 and self.origin.spamprot_base64.match(name): os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.origin.log(self.origin.logger.WARNING, "caught some new large name spam for frontend %s: incoming/spam/%s" % (frontend, message_uid)) self.origin.log(self.origin.logger.WARNING, self.headers) #if self.origin.fake_ok: self.exit_redirect(redirect_duration, redirect_target, add_spamheader=True) else: os.rename(link, os.path.join('incoming', boundary)) #os.rename(link, os.path.join('incoming', 'spam', message_uid)) self.exit_redirect(redirect_duration, redirect_target) except socket.error as e: if e.errno == 32: self.origin.log(self.origin.logger.DEBUG, 'broken pipe: %s' % e) # Broken pipe pass else: self.origin.log(self.origin.logger.WARNING, 'unhandled exception while processing new post: %s' % e) self.origin.log(self.origin.logger.WARNING, traceback.format_exc())
import sys import os from cgi import FieldStorage root = os.getcwd() + "/../.." sys.path.insert(0, root + "/python") from pages.settings import Settings Settings.setRootDirectory(root) html = """ <html> <body> <p>{version}<p> <p>{syspath}<p> <p>{cwd}<p> <p>{params}</p> <p>{dataDir}</p> </body> </html> """ parms = FieldStorage() paramDict = {} for k in parms.keys(): paramDict[k] = parms.getvalue(k) print ("Content-Type: text/html\n") print (html.format(version=sys.version, syspath=sys.path, cwd=os.getcwd(), params=paramDict, dataDir=Settings.dataDirectory))