From 61aff9b9afe07fffb28bd2feef4ede6140aad9da Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Sat, 3 Nov 2018 10:16:48 -0700 Subject: [PATCH] Added some basic error handling to conenction module and exception handling to the parser module --- connect.py | 12 +++++++++--- parser.py | 16 +++++++++------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/connect.py b/connect.py index 7bf2f16..bfa108a 100644 --- a/connect.py +++ b/connect.py @@ -8,6 +8,7 @@ class connect: def request(self, resource, host, itemtype, port=70): #connects to server and returns list with response type and body socket_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + socket_conn.settimeout(5.0) try: socket_conn.connect((host, port)) @@ -17,15 +18,20 @@ class connect: response = socket_conn.makefile(mode = 'rb', errors = 'ignore') else: response = socket_conn.makefile(mode = 'r', errors = 'ignore') - except: + except socket.timeout: + print('Socket timeout') socket_conn.close() - return False + return {'type': '3', 'body': '3ERROR: Server request timed out\tfalse\tnull.host\t1'} + except Exception as e: + print('Misc socket error: ', e) + socket_conn.close() + return {'type': '3', 'body': '3ERROR: Unable to communicate with remote server\tfalse\tnull.host\t1'} try: self.raw_response = response.read() self.filetype = itemtype except UnicodeDecodeError: - self.raw_response = '3Error decoding server response\tfalse\tnull.host\t1' + self.raw_response = '3ERROR: Unable to decode server response\tfalse\tnull.host\t1' self.filetype = '3' socket_conn.close() diff --git a/parser.py b/parser.py index b6f8bc4..5fb6210 100644 --- a/parser.py +++ b/parser.py @@ -15,6 +15,8 @@ class parser: def parse_url(self, url): # Take in a URL and output a dict of the url parts + if url == 'home': + return False regex = r'^(?P(?:(gopher|http):\/\/)?)?(?P[\w\.\d]+)(?P(?::\d+)?)?(?P(?:\/[\dgIp])?)?(?P(?:\/.*)?)?$' @@ -23,13 +25,13 @@ class parser: if not match: return False - protocol = match.group('protocol') - itemtype = match.group('type') - host = match.group('host') - port = match.group('port') - resource = match.group('resource') - - if not host: + try: + protocol = match.group('protocol') + itemtype = match.group('type') + host = match.group('host') + port = match.group('port') + resource = match.group('resource') + except: return False if not resource: