def handle_download(sock, parser): keepalived = parser.should_keep_alive() args = urlparse.parse_qs(parser.get_query_string()) logging.debug("args:%r", args) fileid = int(args["fileid"][0]) if args.has_key("fileid") else 0 _, fileid = parse_fileid(fileid) if not haystack.haystack_files.has_key(fileid): logging.debug("can't find file:%d", fileid) sock.send("HTTP/1.1 404 Not Found\r\n") sock.send("Content-Length: 0\r\n") if keepalived: sock.send("Connection: keep-alive\r\n") else: sock.send("Connection: close\r\n") sock.send("\r\n") else: sock.send("HTTP/1.1 200 OK\r\n") sock.send("Content-Type: application/octet-stream\r\n") offset, size = haystack.haystack_files[fileid] sock.send("Content-Length: %d\r\n" % size) if keepalived: sock.send("Connection: keep-alive\r\n") else: sock.send("Connection: close\r\n") sock.send("\r\n") logging.debug("offset:%d, size:%d\n", offset, size) sendfile(sock.fileno(), haystack.haystack_file.fileno(), offset + haystack.Needle.HEADER_SIZE, size) return bool(keepalived)
def post_file(sock, fileno): ip, port = sock.getpeername() if not haystack.haystack_files.has_key(fileno): logging.error("can't find file:%d", fileno) return False offset, size = haystack.haystack_files[fileno] logging.debug("post file:%d size:%d", fileno, size) sock.send("POST /sync_upload HTTP/1.1\r\n") sock.send("Host: %s:%d\r\n" % (ip, port)) sock.send("Content-Length: %d\r\n" % size) sock.send("Content-Type: application/octet-stream\r\n") sock.send("Connection: keep-alive\r\n") sock.send("FileNO: %d\r\n" % fileno) sock.send("\r\n") sendfile(sock.fileno(), haystack.haystack_file.fileno(), offset + haystack.Needle.HEADER_SIZE, size) return True