From 8598daf3b08752066096b3db4dab20c9a98722d1 Mon Sep 17 00:00:00 2001 From: s3lph Date: Fri, 20 Jul 2018 00:49:29 +0200 Subject: [PATCH] Catch potential file-magic exception. --- matemat/webserver/httpd.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/matemat/webserver/httpd.py b/matemat/webserver/httpd.py index 23045bc..795e0df 100644 --- a/matemat/webserver/httpd.py +++ b/matemat/webserver/httpd.py @@ -329,8 +329,14 @@ class HttpHandler(BaseHTTPRequestHandler): headers['Content-Length'] = str(len(data)) # If the pagelet did not set its own Content-Type header, use libmagic to guess an appropriate one if 'Content-Type' not in headers: - filemagic: magic.FileMagic = magic.detect_from_content(data) - headers['Content-Type'] = f'{filemagic.mime_type}; charset={filemagic.encoding}' + try: + filemagic: magic.FileMagic = magic.detect_from_content(data) + mimetype: str = filemagic.mime_type + charset: str = filemagic.encoding + except ValueError: + mimetype = 'application/octet-stream' + charset = 'binary' + headers['Content-Type'] = f'{mimetype}; charset={charset}' # Send all headers set by the pagelet for name, value in headers.items(): self.send_header(name, value) @@ -369,9 +375,13 @@ class HttpHandler(BaseHTTPRequestHandler): # File read successfully, send 'OK' header self.send_response(200) # Guess the MIME type and encoding using libmagic - filemagic: magic.FileMagic = magic.detect_from_filename(filepath) - mimetype: str = filemagic.mime_type - charset: str = filemagic.encoding + try: + filemagic: magic.FileMagic = magic.detect_from_filename(filepath) + mimetype: str = filemagic.mime_type + charset: str = filemagic.encoding + except ValueError: + mimetype = 'application/octet-stream' + charset = 'binary' # Send content type and length header self.send_header('Content-Type', f'{mimetype}; charset={charset}') self.send_header('Content-Length', str(len(data)))