def handleError(self, errno=400): response = httpparser.makeResHeader(errno) body = "<html><head><title>%s</title></head><body>%s</body></html>\n" % ( "Error", "You have encountered error %d (%s) while accessing this resource." % ( errno, response.errCodeDescription(), ) ) response.headers["Content-Length"] = len(body) response.headers["Content-Type"] = self.types["html"] self.send(response.toHttp()) self.send(body) return None
def handleRequest(self, request): response = httpparser.makeResHeader() if "X-Stress" in request.headers: self.remoteThreadID = request.headers["X-Stress"] # first, figure out what file they actually want if "Host" not in request.headers: self.handleError(400) return None host_pcs = request.headers["Host"].split(":") hostname = host_pcs[0] hostRoot = None if not hostname or not (hostname in self.hosts): hostRoot = self.hosts["default"] else: hostRoot = self.hosts[hostname] #absHostRoot = os.path.abspath(hostRoot) urlpath = request.path if urlpath[-1] == "/": urlpath = "index.html" #joinedpath = os.path.join(urlpath, hostRoot) joinedpath = hostRoot + "/" + urlpath filepath = os.path.abspath(joinedpath) #Print("combined", hostRoot, "with", urlpath, "to get", joinedpath, "which resolves to", filepath) # now open the file fd = None fileStats = None try: fd = os.open(filepath, os.O_RDONLY) fileStats = os.fstat(fd) except (OSError, IOError) as e: if fd is not None: os.close(fd) fd = None Print ("error accessing file:", filepath, e) if e.errno == errno.EACCES: self.handleError(403) return None elif e.errno == errno.ENOENT: self.handleError(404) return None else: self.handleError(500) return None # due to the exhaustive nature of the except: statement, we assume # the file exists. Print("file exists, fd: %s, stats: %s\n" % ( fd, fileStats, )) # test file access #if fileExists: #Print("line", os.read(fd, 16)) # inform the user about the size response.headers["Content-Length"] = fileStats.st_size # TODO make Last-Modified draw from fileStats response.headers["Last-Modified"] = httpparser.mkHttpTimestamp() # decide on a content type ext = filepath.split(".")[-1] if ext in self.types: contentType = self.types[ext] else: contentType = self.types["default"] response.headers["Content-Type"] = contentType # now handle the request per method if request.method == "GET" or request.method == "HEAD": Print("got", request.method) resStr = response.toHttp() Print("sending headers", resStr) self.send(resStr) if request.method == "GET": Print("sending file too") self.sendfile(fd) else: Print("got UNSUPPORTED method:", request.method) self.handleError(501) if fd is not None: os.close(fd) return None