def end_headers(self): # RangeRequestHandler only sends Accept-Ranges header if Range header # is present, see https://github.com/danvk/RangeHTTPServer/issues/23 if not self.headers.get("Range"): self.send_header("Accept-Ranges", "bytes") # Add a checksum header file = self.translate_path(self.path) if not os.path.isdir(file) and os.path.exists(file): with open(file, "rb") as fd: data = fd.read() checksum = hashlib.md5(data).hexdigest() self.send_header("Content-MD5", checksum) RangeRequestHandler.end_headers(self)
def copyfile(self, src, dest): buffer_size = 1024*16 sleep_times = ThrottledReqHandler.sleep_times if not self.range: cnt = 0 while True: data = src.read(buffer_size) if not data: break cnt += len(data) if sleep_times and cnt > ThrottledReqHandler.threshold: time.sleep(1) sleep_times -= 1 dest.write(data) else: RangeRequestHandler.copyfile(self, src, dest)
def end_headers(self): # RangeRequestHandler only sends Accept-Ranges header if Range header # is present, see https://github.com/danvk/RangeHTTPServer/issues/23 if not self.headers.get("Range"): self.send_header("Accept-Ranges", "bytes") # Add a checksum header if self.checksum_header: file = self.translate_path(self.path) if not os.path.isdir(file) and os.path.exists(file): with open(file) as fd: encoded_text = fd.read().encode("utf8") checksum = hashlib.md5(encoded_text).hexdigest() self.send_header(self.checksum_header, checksum) RangeRequestHandler.end_headers(self)
def do_GET(self) -> None: logging.info("Get request received by HTTP server") # Only serve the specific file requested on the command line, # and only to Sonos speakers in the Sonos system error = False if self.path.replace("/", "") != self.filename: logging.info("Access to file '{}' forbidden".format(self.path)) error = True if self.client_address[0] not in self.speaker_ips: logging.info("Access from IP '{}' forbidden".format(self.client_address[0])) error = True if error: RangeRequestHandler.send_error( self, code=403, message="SoCo-CLI HTTP Server: Access forbidden" ) return # Forward the GET request try: super().do_GET() except Exception as e: # It's normal to hit some exceptions with Sonos logging.info("Exception ignored: {}".format(e))
def handle(self): try: RangeRequestHandler.handle(self) except socket.error: pass