Added some basic error handling to conenction module and exception handling to the parser module

This commit is contained in:
sloumdrone 2018-11-03 10:16:48 -07:00
parent 6ad39e8d4e
commit 61aff9b9af
2 changed files with 18 additions and 10 deletions

View File

@ -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()

View File

@ -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<protocol>(?:(gopher|http):\/\/)?)?(?P<host>[\w\.\d]+)(?P<port>(?::\d+)?)?(?P<type>(?:\/[\dgIp])?)?(?P<resource>(?:\/.*)?)?$'
@ -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: