diff --git a/gophersrv.py b/gophersrv.py index d097116..09b5113 100644 --- a/gophersrv.py +++ b/gophersrv.py @@ -68,9 +68,11 @@ def normalizepath(path): return '/'.join(path) # Error handling -def notfounderror(conn, path): +def notfounderror(conn, path, ishttp): + sendheader(conn, ishttp, '1', '404 Not Found') conn.sendall('3"%s" does not exist\t/\t(null)\t0\n' % path) -def notallowederror(conn, path): +def notallowederror(conn, path, ishttp): + sendheader(conn, ishttp, '1', '403 Forbidden') conn.sendall('3Access denied\t/\t(null)\t0\n') # Server implementation @@ -119,7 +121,7 @@ def getselector(request): # If a HTTP request with selector is used, this extrac return ([reqpath] + args, selector) -def sendheader(conn, ishttp, selector): +def sendheader(conn, ishttp, selector, code = '200 OK'): if ishttp: # All others can safely be made text/plain contenttypes = {'5': 'application/octet-stream', @@ -134,9 +136,9 @@ def sendheader(conn, ishttp, selector): else: contenttype = 'text/plain; charset=utf-8' # Default to text/plain - conn.sendall('HTTP/1.1 200 OK\r\n' + conn.sendall('HTTP/1.1 %s\r\n' 'Content-type: %s\r\n' - '\r\n' % contenttype) + '\r\n' % (code, contenttype)) def serveurlredirect(conn, path): path = path[4:] @@ -164,7 +166,13 @@ def servefile(conn, path): f = open(path, 'r') servecommon(conn, f) -def serverequest(conn, request): +def serverequest(conn, request, ishttp): + # Extract selector if needed + if ishttp: + request, selector = getselector(request) + else: + selector = None + # URL link extension if len(request[0]) >= 4 and request[0][:4] == 'URL:': return serveurlredirect(conn, request[0]) @@ -172,18 +180,20 @@ def serverequest(conn, request): reqpath = normalizepath(request[0]) if reqpath == None: - return notallowederror(conn, reqpath) + return notallowederror(conn, reqpath, ishttp) path = gopherroot + '/' + reqpath if not exist(path): - return notfounderror(conn, reqpath) + return notfounderror(conn, reqpath, ishttp) if isdir(path): if exist(path + '/gophermap'): path = path + '/gophermap' else: - return notfounderror(conn, reqpath) + return notfounderror(conn, reqpath, ishttp) + + sendheader(conn, ishttp, selector) if isexecutable(path): servecgi(conn, path) @@ -203,13 +213,7 @@ class Serve(threading.Thread): self.conn.close() return - if ishttp: - request, selector = getselector(request) - else: - selector = None - sendheader(conn, ishttp, selector) - - serverequest(self.conn, request) + serverequest(self.conn, request, ishttp) self.conn.shutdown(socket.SHUT_RDWR) self.conn.close()