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): def request(self, resource, host, itemtype, port=70):
#connects to server and returns list with response type and body #connects to server and returns list with response type and body
socket_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_conn.settimeout(5.0)
try: try:
socket_conn.connect((host, port)) socket_conn.connect((host, port))
@ -17,15 +18,20 @@ class connect:
response = socket_conn.makefile(mode = 'rb', errors = 'ignore') response = socket_conn.makefile(mode = 'rb', errors = 'ignore')
else: else:
response = socket_conn.makefile(mode = 'r', errors = 'ignore') response = socket_conn.makefile(mode = 'r', errors = 'ignore')
except: except socket.timeout:
print('Socket timeout')
socket_conn.close() 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: try:
self.raw_response = response.read() self.raw_response = response.read()
self.filetype = itemtype self.filetype = itemtype
except UnicodeDecodeError: 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' self.filetype = '3'
socket_conn.close() socket_conn.close()

View File

@ -15,6 +15,8 @@ class parser:
def parse_url(self, url): def parse_url(self, url):
# Take in a URL and output a dict of the url parts # 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>(?:\/.*)?)?$' 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: if not match:
return False return False
protocol = match.group('protocol') try:
itemtype = match.group('type') protocol = match.group('protocol')
host = match.group('host') itemtype = match.group('type')
port = match.group('port') host = match.group('host')
resource = match.group('resource') port = match.group('port')
resource = match.group('resource')
if not host: except:
return False return False
if not resource: if not resource: