def handle(socket): (method, url, version) = socket.readline().split(b" ") if b"?" in url: (path, query) = url.split(b"?", 2) else: (path, query) = (url, b"") while True: header = socket.readline() if header == b"": return if header == b"\r\n": break if version != b"HTTP/1.0\r\n" and version != b"HTTP/1.1\r\n": err(socket, "505", "Version Not Supported") elif method == b"GET": if path == b"/": ok(socket, query) else: err(socket, "404", "Not Found") elif method == b"POST": if path == b"/on": pin.high() ok(socket, query) elif path == b"/off": pin.low() ok(socket, query) else: err(socket, "404", "Not Found") else: err(socket, "501", "Not Implemented")
def handle(socket): global docPath, handlers currLine = str(socket.readline(), 'utf-8') request = currLine.split(" ") if len(request) != 3: # Discarded if it's a bad header return (method, url, version) = request if "?" in url: # Check if there's query string? (path, query) = url.split("?", 2) else: (path, query) = (url, "") args = {} if query: # Parsing the querying string argPairs = query.split("&") for argPair in argPairs: arg = argPair.split("=") args[arg[0]] = arg[1] while True: # Read until blank line after header header = socket.readline() if header == b"": return if header == b"\r\n": break # Check for supported HTTP version if version != "HTTP/1.0\r\n" and version != "HTTP/1.1\r\n": err(socket, "505", "Version Not Supported") elif method == "GET": # Only accept GET request if path in handlers: # Check for registered path handlers[path](socket, args) else: err(socket, "400", "Bad Request") else: err(socket, "501", "Not Implemented")
def handle(socket): global docPath, handlers currLine = str(socket.readline(), 'utf-8') request = currLine.split(" ") if len(request) != 3: # Discarded if it's a bad header return (method, url, version) = request if "?" in url: # Check if there's query string? (path, query) = url.split("?", 2) else: (path, query) = (url, "") args = {} if query: # Parsing the querying string argPairs = query.split("&") for argPair in argPairs: arg = argPair.split("=") args[arg[0]] = arg[1] while True: # Read until blank line after header header = socket.readline() if header == b"": return if header == b"\r\n": break # Check for supported HTTP version if version != "HTTP/1.0\r\n" and version != "HTTP/1.1\r\n": err(socket, "505", "Version Not Supported") elif method == "GET": # Only accept GET request if path.find(docPath) == 0: # Check for path to any document try: os.stat(path) # Check for file existence # Response header first socket.write("HTTP/1.1 200 OK\r\n\r\n") # Response the file content f = open(path, "rb") while True: data = f.read(64) if (data == b""): break socket.write(data) return except: # Can't find the file specified in path err(socket, "404", "Not Found") elif path in handlers: # Check for registered path handlers[path](socket, args) else: err(socket, "400", "Bad Request") else: err(socket, "501", "Not Implemented")
def read_and_print(socket): prefix = currentThread().getName() + ":" while True: line = socket.readline() self.read_and_print_out(line) if not line: print >> sys.stderr, prefix, "readline returned nothing quitting" # Most of the time the socket will throw an error as well, but not always self.connection_lost(self.get_cmdport(), output_read=True) break print >> sys.stderr, prefix, line.rstrip()
def put_client_media_files(self, environ, session_token): self.ui.status_bar_message("Receiving client media files...") try: session = self.sessions[session_token] socket = environ["wsgi.input"] size = int(socket.readline()) tar_pipe = tarfile.open(mode="r|", fileobj=socket) # Work around http://bugs.python.org/issue7693. tar_pipe.extractall(session.database.mediadir().encode("utf-8")) except: return "CANCEL" return "OK"
def communicate_with_host(self): inputs = [self.socket, sys.stdin] outputs = [self.socket] self.message_queue.put("PID:"+self.process_id+MSG_TERMINATOR) data = "" while True: read_sockets, write_sockets, error_sockets = select.select(inputs, outputs, []) # read data from console and socket for socket in read_sockets: if socket == sys.stdin: line = socket.readline() if line: if "READ" in line: self.read_event_handler() elif "LIKE" in line: try: line.split(":")[1] self.like_count_queue.put(int(line.split(":")[1])) except: self.like_count_queue.put(1) self.like_event_handler() elif "EXIT" in line: sys.exit() else: print "Enter READ, LIKE:<like_count> or EXIT" else: data = data + self.socket.recv(BUFFER_SIZE) if data: while MSG_TERMINATOR in data: pos = data.find(MSG_TERMINATOR) msg = data[:pos] data = data[pos+1:] print "Message received: " + msg if REQ in msg: self.request_message_handler(msg) if REP in msg: self.reply_message_handler(msg) if REL in msg: self.release_message_handler(msg) for socket in write_sockets: try: next_msg = self.message_queue.get_nowait() print "Message sent: " + next_msg time.sleep(MSG_DELAY) socket.send(next_msg) except Queue.Empty: pass for socket in error_sockets: print "error in sockets" pass
def PollSockets(self): events = self.poller.poll(0) while events: event = events.pop() fd, flag = event socket = self.fd_to_socket[fd] if socket == self.server_socket: connection, address = socket.accept() if len(self.sockets) == max_connections: print('signalk server: max connections reached!!!', len(self.sockets)) self.RemoveSocket(self.sockets[0]) # dump first socket?? socket = LineBufferedNonBlockingSocket(connection) self.sockets.append(socket) fd = socket.socket.fileno() # print('new client', address, fd) self.fd_to_socket[fd] = socket self.poller.register(fd, select.POLLIN) elif flag & (select.POLLHUP | select.POLLERR | select.POLLNVAL): self.RemoveSocket(socket) elif flag & select.POLLIN: if not socket.recv(): self.RemoveSocket(socket) while True: line = socket.readline() if not line: break try: self.HandleRequest(socket, line) except Exception as e: print('invalid request from socket', line, e) socket.send('invalid request: ' + line + '\n') # flush all sockets for socket in self.sockets: socket.flush()
def handle(socket): """Processing new GET request """ global docPath, handlers try: # capture timeout for wainting a line currLine = str(socket.readline(), 'utf-8') except: currLine = "" # readline timeout (not a complete line) request = currLine.split(" ") if len(request) != 3: # Discarded if it's a bad header return (method, url, version) = request if "?" in url: # Check if there's query string? (path, query) = url.split("?", 2) else: (path, query) = (url, "") args = {} if query: # Parsing the querying string argPairs = query.split("&") for argPair in argPairs: arg = argPair.split("=") args[arg[0]] = arg[1] while True: # Read until blank line after header header = socket.readline() if header == b"": return if header == b"\r\n": break # Check for supported HTTP version if version != "HTTP/1.0\r\n" and version != "HTTP/1.1\r\n": err(socket, "505", "Version Not Supported") elif method != "GET": # Only accept GET request err(socket, "501", "Not Implemented") elif path in handlers: # Check for registered path handlers[path](socket, args) elif not path.startswith(docPath): # Check for wrong path err(socket, "400", "Bad Request") else: # find file in the document path filePath = path fileFound = True # find the file if not __fileExist(filePath): if not path.endswith("/"): fileFound = False else: filePath = path + "index.html" # find index.html in the path if not __fileExist(filePath): filePath = path + "index.p.html" # find index.p.html in the path if not __fileExist(filePath): # no default html file found fileFound = False if not fileFound: # file or default html file specified in path not found if notFoundHandler: notFoundHandler(socket) else: err(socket, "404", "Not Found") return # Responds the header first socket.write("HTTP/1.1 200 OK\r\n") contentType = "text/html" for ext in mimeTypes: if filePath.endswith(ext): contentType = mimeTypes[ext] socket.write("Content-Type: " + contentType + "\r\n\r\n") # Responds the file content if filePath.endswith(".p.html"): print("template file.") f = open(filePath, "r") for l in f: socket.write(l.format(**tplData)) f.close() else: __sendPage(socket, filePath)
def handle(socket): """Processing new GET request """ global docPath, handlers currLine = str(socket.readline(), 'utf-8') request = currLine.split(" ") if len(request) != 3: # Discarded if it's a bad header return (method, url, version) = request if "?" in url: # Check if there's query string? (path, query) = url.split("?", 2) else: (path, query) = (url, "") args = {} if query: # Parsing the querying string argPairs = query.split("&") for argPair in argPairs: arg = argPair.split("=") args[arg[0]] = arg[1] while True: # Read until blank line after header header = socket.readline() if header == b"": return if header == b"\r\n": break # Check for supported HTTP version if version != "HTTP/1.0\r\n" and version != "HTTP/1.1\r\n": err(socket, "505", "Version Not Supported") elif method != "GET": # Only accept GET request err(socket, "501", "Not Implemented") elif path in handlers: # Check for registered path handlers[path](socket, args) #elif not path.startswith(docPath): # Check for path to any document # err(socket, "400", "Bad Request") else: filePath = path # find the file if not __fileExist(filePath): filePath = path + ("index.html" if path.endswith("/") else "/index.html") # find index.html in the path if not __fileExist(filePath): filePath = path + ("index.p.html" if path.endswith("/") else "/index.p.html") # find index.p.html in the path if not __fileExist(filePath): if notFoundHandler: notFoundHandler(socket) else: err(socket, "404", "Not Found") return # Responds the header first socket.write("HTTP/1.1 200 OK\r\n") socket.write("Content-Type: text/html\r\n\r\n") # Responds the file content if filePath.endswith(".p.html"): print("template file.") f = open(filePath, "r") for l in f: socket.write(l.format(**tplData)) f.close() else: __sendPage(socket, filePath)
def handle(socket): """Processing new GET request """ global docPath, handlers try: # capture timeout for wainting a line currLine = str(socket.readline(), 'utf-8') except: currLine = "" # readline timeout (not a complete line) request = currLine.split(" ") if len(request) != 3: # Discarded if it's a bad header return (method, url, version) = request if "?" in url: # Check if there's query string? (path, query) = url.split("?", 2) else: (path, query) = (url, "") args = {} contentType = "" content = b"" contentLength = 0 if query: # Parsing the querying string argPairs = query.split("&") for argPair in argPairs: arg = argPair.split("=") args[arg[0]] = arg[1] while True: # Read until blank line after header header = socket.readline() if header.startswith(b"Content-Length"): (key, contentLengthStr) = str(header).split(" ") contentLength = int(contentLengthStr[0:-5]) if (contentLength > maxContentLength): err(socket, "400", "Bad Request") return if (header.startswith(b"Content-Type")): (key, contentType) = str(header).split(" ") contentType = contentType[0:-5] if (header == b""): return if (header == b"\r\n" and contentLength > 0): while(len(content) < contentLength): content = content + socket.recv(contentLength) if (len(content) > maxContentLength): err(socket, "400", "Bad Request") return break elif header == b"\r\n": break # Check for supported HTTP version if version != "HTTP/1.0\r\n" and version != "HTTP/1.1\r\n": err(socket, "505", "Version Not Supported") elif (method != "GET" and method != "PUT" and method != "POST"): # Only accept GET,PUT and POST request err(socket, "501", "Not Implemented") elif path in handlers: # Check for registered path handlers[path](socket, args, method, contentType, content) elif not path.startswith(docPath): # Check for wrong path err(socket, "400", "Bad Request") else: # find file in the document path filePath = path print("Serve File " + filePath) __serveFile(socket, filePath)
if bool(args.l): connection.bind(('0.0.0.0', int(args.port))) connection.listen(1) inputSources = [connection, sys.stdin] try: while True: for socket in select.select(inputSources, [], [])[0]: # This means a new connection has been received if socket is connection: clientConnection, clientAddress = socket.accept() inputSources.append(clientConnection) # sys.stdin is the current readable source elif socket is sys.stdin: data = socket.readline() # TODO Encrypt message here encryptedData = data for source in inputSources: if source not in [sys.stdin, connection]: source.sendall(encryptedData.encode('utf-8')) # An actual client connection is the source else: data = socket.recv(1024) if data: # TODO Decrypt message here decryptedData = data sys.stdout.write(decryptedData.decode('utf-8')) else: inputSources.remove(socket) socket.close()