def generate_get_response(request_uri): if request_uri.endswith("/"): # access directory return utils.encode_http_response(404, {}, "Permission Denied") file_path = request_uri[1:] # remove / at the beginning full_file_path = os.path.join(WEB_SERVER_ROOT_DIR, file_path) if not os.path.exists(full_file_path): return utils.encode_http_response(404, {}, "File Not Found: {0}".format(full_file_path)) with open(full_file_path, "r") as fp: content = fp.read() return utils.encode_http_response(200, {}, content)
def generate_get_response(request_uri): if request_uri.endswith("/"): # access directory return utils.encode_http_response(404, {}, "Permission Denied") file_path = request_uri[1:] # remove / at the beginning full_file_path = os.path.join(WEB_SERVER_ROOT_DIR, file_path) if not os.path.exists(full_file_path): return utils.encode_http_response( 404, {}, "File Not Found: {0}".format(full_file_path)) if full_file_path.endswith(".php"): output = get_php_output(full_file_path) return utils.encode_http_response(200, {}, output) else: with open(full_file_path, "rb") as fp: content = fp.read() headers = {"Content-Type": "text/html;charset=utf-8"} return utils.encode_http_response(200, headers, content)
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((WEB_SERVER_HOST, WEB_SERVER_PORT)) s.listen(5) print "server is listenning on {0}:{1}".format(WEB_SERVER_HOST, WEB_SERVER_PORT) while True: # accept connection client_sock, address = s.accept() print "received connection from {0}".format(address) # get http request raw_request = client_sock.recv(1024).decode("utf-8") if raw_request: print(raw_request) request_method, request_uri, request_body, _ = utils.parse_http_request( raw_request) if request_method.upper() == "GET": response = generate_get_response(GET_RESPONSE) elif request_method.upper() == "POST": post_params = parse_params(request_body) username = post_params["username"] password = post_params["password"] if username == "admin" and password == "admin": response = generate_get_response( POST_RESPONSE_SUCCESSFUL.format(username)) else: response = generate_get_response(POST_RESPONSE_FAILED) else: response = utils.encode_http_response( 404, {}, "Invalid HTTP Method {0}".format(request_method)) # send http response to client client_sock.send(response) # close connection client_sock.close()
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((WEB_SERVER_HOST, WEB_SERVER_PORT)) s.listen(5) print "server is listenning on {0}:{1}".format(WEB_SERVER_HOST, WEB_SERVER_PORT) while True: # accept connection client_sock, address = s.accept() print "received connection from {0}".format(address) # get http request #TODO: for demo purpose, should improve it raw_request = client_sock.recv(1024).decode("utf-8") if raw_request: print(raw_request) request_method, request_uri, _, _ = utils.parse_http_request(raw_request) if request_method.upper() == "GET": response = generate_get_response(request_uri) else: response = utils.encode_http_response(404, {}, "Invalid HTTP Method {0}".format(request_method)) # send http response to client client_sock.send(response) # close connection client_sock.close()
def client_handler(client_sock, address): print("received connection from {0}".format(address)) # get http request raw_request = client_sock.recv(1024).decode("utf-8") if raw_request: print(raw_request) request_method, request_uri, request_body, _ = utils.parse_http_request( raw_request) if request_method.upper() == "GET": response = generate_get_response(request_uri) else: response = utils.encode_http_response( 404, {}, "Invalid HTTP Method {0}".format(request_method)) # send http response to client client_sock.send(response) # close connection client_sock.close()
class SimpleHTTPServerProtocol(basic.LineReceiver, policies.TimeoutMixin): START_EVENT_STREAM = \ "HTTP/1.1 200 OK\r\n"\ "Content-Type: text/event-stream\r\n"\ "Access-Control-Allow-Origin: *\r\n"\ "Cache-Control: no-cache\r\n"\ "Transfert-Encoding: identity\r\n"\ "Connection: close\r\n\r\n" MAX_LENGTH_ERROR = encode_http_response(413, 'Request Entity Too Large') MAX_REQUEST_TRANSMIT_TIME_ERROR = encode_http_response( 408, 'Request Timeout') delimiter = "\r\n\r\n" request = None def __init__(self, maxLength, timeout): self.MAX_LENGTH = maxLength self.MAX_REQUEST_TRANSMIT_TIME = timeout def lineLengthExceeded(self, line): self.log.msg("request too large, disconnecting") self.sendError(self.MAX_LENGTH_ERROR) def connectionMade(self): self.setTimeout(self.MAX_REQUEST_TRANSMIT_TIME) self.log = customLog.getLogger(self.transport.logstr) self.log.msg('connectionMade') def timeoutConnection(self): self.log.msg("request transmission takes too long, timing out") self.sendError(self.MAX_REQUEST_TRANSMIT_TIME_ERROR) def connectionLost(self, reason=None): self.log.msg('Connection closed because %s' % reason) if hasattr(self, 'producer'): self.producer.stopProducing() def lineReceived(self, line): """parse incoming http request, and start streaming...""" self.log.msg("received HTTP request, attending to parse it") self.resetTimeout() self.request = EventSourceRequest(line) if self.request._error is not None: self.log.msg("Got HTTP error %(status)s" % self.request._error) self.sendError(self.request.error) else: # send response headers self.startResponse() # register EventSource producer self.producer = CooperativePushProducer(self.buildEventStream()) self.transport.registerProducer(self.producer, True) d = self.producer.whenDone() d.addCallback(lambda _: self.transport.loseConnection()) def sendError(self, error): """send error response and close connection""" self.transport.write(error) self.transport.loseConnection() def startResponse(self): """send response that starts EventSource stream...""" self.transport.write(self.START_EVENT_STREAM) def buildEventStream(self): lastEvtId = self.request.evsLastId evtSource = TestSource(messages=self.factory.messages, **self.request.evsArgs) evtSequence = evtSource.visit_from(lastEvtId + 1) if lastEvtId > -1: self.log.msg("restart streaming from : %d" % lastEvtId) else: self.log.msg("new eventsource stream...") restart = lambda: None for message in evtSequence: # extract start of message... msgstart = message[:message.find(":", 0, 8) + 12] self.log.msg("new event line : %s..." % msgstart) for part in split_by(message, RND.randint(1, 3)): self.transport.write(part) yield deferLater(reactor, RND.uniform(0.05, 0.3), restart)
def generate_get_response(html_content): headers = {"Content-Type": "text/html;charset=utf-8"} return utils.encode_http_response(200, headers, html_content.encode("utf-8"))