Пример #1
0
class FileServer:
	""" FileServer """
	def __init__(self, webServerConfig,debug):
		self.debug = Debug(debug)
		self.unimplementedRequestMethods = ['HEAD', 'POST', 'PUT', 'DELETE', 'LINK', 'UNLINK']
		self.webServerConfig = webServerConfig
		self.errorCodes = ErrorResponseCodes()
		self.filePath = ""

	def getResponse(self, htmlParser):
		self.filePath = ""

		# check if valid GET request
		self.debug.printMessage("Checking if valid GET request...")
		if not htmlParser.getMethod() == "GET":
			if htmlParser.getMethod() in self.unimplementedRequestMethods:
				return self.errorCodes.get501()
			return self.errorCodes.get400()

		# translate URI to filename
		self.debug.printMessage("Translating request to URL...")
		host = htmlParser.getHost()
		uri = htmlParser.getUri()
		filePath = self.webServerConfig.getPath(host) + uri
		if filePath[-1] == '/':
			filePath += "index.html"
		self.debug.printMessage("FilePath: " + filePath)

		# check if good filePath or no permissions given
		self.debug.printMessage("Checking if good filePath or no permissions given")
		try:
			f = open(filePath)
			self.debug.printMessage("Opened file just fine")
			self.filePath = filePath
		except IOError as (errno, strerror):
			if errno == 13:
				""" 403 Forbidden """
				return self.errorCodes.get403()
			elif errno == 2:
				""" 404 Not Found """
				return self.errorCodes.get404()
			else:
				""" 500 Internal Server Error """
				return self.errorCodes.get500()


		self.filePath = filePath

		self.debug.printMessage("Good message. Generating 200 OK response...")
		# html = "<html><body><h1>200 OK</h1></body></html>\r\n\r\n"

		statusLine = "HTTP/1.0 200 OK\r\n"

		t = time.time()
		current_time = self.errorCodes.get_time(t)
		headers = "Date: %s\r\n" % current_time

		headers += "Server: freeServer/1.0 totallyAwesome\r\n"

		fileExt = filePath.split(".")[-1]
		contentType = self.webServerConfig.getMediaType(fileExt)
		headers += "Content-Type: %s\r\n" % contentType

		size = os.stat(filePath).st_size
		headers += "Content-Length: %d\r\n" % size

		mod_time = os.stat(filePath).st_mtime
		gmtModTime = self.errorCodes.get_time(mod_time)
		headers += "Last-Modified: %s\r\n" % gmtModTime

		headers += "\r\n"
		response = statusLine + headers

		self.debug.printMessage("Response: " + response)
		return response
Пример #2
0
class HTMLParser:
    """ HTML Parser """
    def __init__(self,debug):
        self.debug = Debug(debug)


    def parse(self, request):
        """ Parse the message/request """
        if request == "":
            return False

        httpRequest = request.split("\r\n")

        self.debug.printMessage("Request: \n\"" + request + "\"")
        self.debug.printMessage("After splitting: ")
        self.debug.printMessage(httpRequest)

        for currentLine in httpRequest:
            pass

        #parsing Request line
        requestLine = httpRequest[0].split()
        self.method = requestLine[0]
        self.uri = requestLine[1]
        self.version = requestLine[2]

        #parsing Header lines
        self.headerDictionary = {}
        currentLine = 1
        currentString = httpRequest[currentLine]

        while currentString != "":
        	header = currentString.split()
        	self.headerDictionary[header[0]] = header[1]

        	currentLine += 1
        	currentString = httpRequest[currentLine]

        return True

    def getMethod(self):
        return self.method
    def getUri(self):
        return self.uri
    def getHost(self):
        if self.headerDictionary.has_key("Host:"):
            return self.headerDictionary["Host:"].split(":")[0]
        else:
            self.debug.printMessage("[Host:] was not found in GET request")
            return ""

    def printAll(self):
    	self.printItem("Method", self.method)
    	self.printItem("URI", self.uri)
    	self.printItem("Version", self.version)

    	for key, value in self.headerDictionary.iteritems():
    		self.printItem("Header Field Name", key)
    		self.printItem("\tHeader Value", value)
        return ""
    def printItem(self, title, message):
    	print title + ": " + "\"" + message + "\""
Пример #3
0
class WebServerConfig:
    """ WebServerConfig """
    def __init__(self,configFilePath,debug):
        self.debug = Debug(debug)
        self.configFilePath = configFilePath
        self.hosts = {}
        self.media = {}
        self.timeOutTime = 0
        self.parse()


    def parse(self):
        """ Parse the configFilePath """
        # open the file and place in string 
        configString = open(self.configFilePath).read()

        self.debug.printMessage("configString:")
        self.debug.printMessage(configString)

        # split up the different lines
        lines = configString.split("\n")
        self.debug.printMessage("After splitting up:")
        self.debug.printMessage(lines)

        # iterate through lines and place in correct dictionary or int
        for line in lines:
        	words = line.split()

        	if not len(words) == 3:
        		continue

        	self.debug.printMessage("Line:")
        	self.debug.printMessage(line)

        	self.debug.printMessage("After splitting up")
        	self.debug.printMessage(words)

        	if words[0] == "host":
        		self.hosts[words[1]] = words[2]
        	elif words[0] == "media":
        		self.media[words[1]] = words[2]
        	elif words[0] == "parameter":
        		self.timeOutTime = int(words[2])

    def getPath(self,host):
        """ Looks into dictionary and finds correct path """
        if self.hosts.has_key(host):
        	return self.hosts[host]
        else:
            return self.hosts["default"]


    def getMediaType(self,ext):
        """ Looks into dictionary and finds correct media type """
        if self.media.has_key(ext):
            return self.media[ext]
        else:
            return "text/plain"

    def getTimeOutTime(self):
        """ Returns timeout time based on web.conf file """
        return self.timeOutTime