def _server_loop(sock): log.trace("Server is awaiting new connections.") while True: connection, client_address = sock.accept() if log.is_tracing(): log.trace("New request from: " + str(client_address[0])) conn_thread = threading.Thread(target=conn_handler.handle_conn, args=(connection, )) conn_thread.start()
def precache(destination, recursive=False): global _root_dir prep_dest = destination if destination.startswith(_root_dir) == False: prep_dest = _root_dir + prep_dest if os.path.isdir(prep_dest): if log.is_tracing(): log.trace("Caching folder content: " + prep_dest) for file_dest in glob.glob(prep_dest + "/*"): if os.path.isfile(file_dest): cache_file(file_dest) elif os.path.isdir(file_dest) and recursive == True: precache(file_dest, recursive=True) else: cache_file(prep_dest)
def file_exists(path, skip_rewrite=False, ignore_cache=False): if not skip_rewrite: rewritten_fp = rewriter.rewrite(path) else: rewritten_fp = path if log.is_tracing(): log.trace("Accessing path: " + rewritten_fp) if not ignore_cache: cached_file = file_cache.get_file(rewritten_fp) if cached_file != None: response.ok("") file = open(rewritten_fp, 'rb') if file == None: return response.not_found("") return response.ok("")
def serve(path, skip_rewrite=False, ignore_cache=False): if not skip_rewrite: rewritten_fp = rewriter.rewrite(path) else: rewritten_fp = path if log.is_tracing(): log.trace("Accessing path: " + rewritten_fp) if not ignore_cache: cached_file = file_cache.get_file(rewritten_fp) if cached_file != None: return response.build_from_bytes('200 OK', cached_file) file = open(rewritten_fp, 'rb') if file == None: return None return response.build_from_bytes('200 OK', file.read())
def handle_conn(conn): global MAX_REQUEST_SIZE req = conn.recv(MAX_REQUEST_SIZE) req_param_map, body, method = request_parser.parse(req) if method not in req_param_map: conn.close() log.warn("Method not found. Closing connection.") return interception_passed = interceptor.execute(method, req_param_map[method], req_param_map, body) if not interception_passed: if log.is_tracing(): log.trace("Request intercepted connection not allowed: " + req_param_map[method]) conn.send(response.forbidden("")) conn.close() return try: res = router.resolve(req_param_map, body) if res == None and method == 'GET': res = static.serve(req_param_map[method]) if res == None and method == 'HEAD': res = static.file_exists(req_param_map[method]) if res == None: raise Exception("Path not found: " + str(req_param_map)) conn.send(res) except Exception as e: log.error(e) conn.send(response.not_found("")) conn.close()