Beispiel #1
0
    def readfile(self, templateSyntax, templateVariables={}):
        syntaxArguments = self.parseArguments(templateSyntax)
        Mode = self.detectMode(syntaxArguments[0])

        if Mode == "variable":
            try:
                variableValue = templateVariables[syntaxArguments[1]]
                variableValue = readFile(variableValue)
                return variableValue
            except Exception:
                showError(exceptionRule="Variables Error", Message="The variable you're using isn't defined")
                return ""
        else:
            replaceString = syntaxArguments[1]
            replaceString = readFile(replaceString)
            return replaceString
Beispiel #2
0
def returnRenderedTemplate(filePath, responseHeaders={}, responseCode=200, templateVariables={}):
    global detectedStrings, detectedFunctions, replacedFileContent

    filePath = f"{TEMPLATES_PATH}/{filePath}"
    requestFileContent = readFileByLines(filePath)
    realFileContent = readFile(filePath)

    if not requestFileContent:
        return '500 Internal Server Error', {}, 500
    else:
        Parser = templatesParser()
        for singleLine in requestFileContent:
            detectedStrings += Parser.detectStrings(lineOfCode=singleLine)
            detectedFunctions += Parser.detectFunctions(lineOfCode=singleLine)

        if len(detectedStrings) != 0:
            for dString in detectedStrings:
                dRealString = dString[2:][:-2].strip()

                try:
                    userString = templateVariables[dRealString]
                    replacedFileContent = realFileContent.replace(f"{dString},", str(userString))
                    realFileContent = replacedFileContent
                except Exception:
                    showError(exceptionRule="Template Error", Message=f"You're using an undefined variable '{dRealString}' on your template")
                    exit()

        if len(detectedFunctions) != 0:
            for dFunction in detectedFunctions:
                dRealFunction = dFunction[2:][:-2].strip()
                charactersList = []

                for singleCharacter in dRealFunction:
                    if singleCharacter != "(":
                        charactersList.append(singleCharacter)
                    else:
                        break

                functionName = ''.join(charactersList)

                if functionName in __FUNCTIONS__:
                    parserFunction = getattr(Parser, functionName)
                    responseContent = parserFunction(dRealFunction, templateVariables)

                    replacedFileContent = realFileContent.replace(f"{dFunction},", responseContent)
                    realFileContent = replacedFileContent
                else:
                    showError(exceptionRule="Template Error", Message=f"You're using a template function '{dRealFunction}' that doesn't exists")
                    exit()

    return replacedFileContent, responseHeaders, responseCode
Beispiel #3
0
    def readfile(self, templateSyntax, templateVariables={}):
        detectPattern = r"readfile\((.*|)\)"

        detectFunction = re.search(detectPattern, templateSyntax)
        if detectFunction != None:
            functionsArgument = detectFunction.group()[8:][1:][:-1]
            functionsArgument = functionsArgument.replace('"', '').replace(
                "'", '').strip()

            try:
                replaceString = templateVariables[functionsArgument]
                rString = readFile(replaceString)

                if not rString: return ""
                else: return rString
            except Exception as e:
                showError(
                    exceptionRule="Template Error",
                    Message=
                    "You're using a template variable that doesn't exists")
                return ""
        else:
            return ""
Beispiel #4
0
def returnBasicFileContent(filePath, responseHeaders={}, responseCode=200):
    filePath = f"{TEMPLATES_PATH}/{filePath}"
    requestFileContent = readFile(filePath)

    if not requestFileContent: return '500 Internal Server Error', {}, 500
    else: return requestFileContent, responseHeaders, responseCode
Beispiel #5
0
    def do_GET(self):
        self.realPath = self.path.replace('//', '/')
        self.applicationConfig = buildConfig()
        self.requestHeaders = bHeaders(self.headers)
        self.securityHeaders = buildHeaders(self.requestHeaders)

        self.requestHeaders['client-ip'] = self.client_address[0]
        self.requestHeaders['request-method'] = "GET"

        if self.realPath[-1:] == "/" and len(self.realPath) > 1:
            self.realPath = self.realPath[:-1]

        if self.realPath == "/":
            try:
                serverHandler = routes['/']
                Content, Headers, Code = callHanlder(serverHandler,
                                                     self.requestHeaders)

                self.send_response(Code)
                if len(Headers) != 0:
                    for serverHeader, headerValue in Headers.items():
                        self.send_header(serverHeader, headerValue)

                for serverHeader, headerValue in self.securityHeaders.items():
                    self.send_header(serverHeader, headerValue)

                self.end_headers()
                self.wfile.write(Content.encode())
                writeLogs(clientIP=self.requestHeaders['client-ip'],
                          userAgent=self.requestHeaders['user-agent'],
                          endpointVisited=self.realPath,
                          responseCode=Code,
                          requestMethod=self.requestHeaders['request-method'])
            except Exception as e:
                Content, Headers, Code = callHanlder("500Handler.py",
                                                     self.requestHeaders)

                self.send_response(Code)

                if len(Headers) != 0:
                    for serverHeader, headerValue in Headers.items():
                        self.send_header(serverHeader, headerValue)

                for serverHeader, headerValue in self.securityHeaders.items():
                    self.send_header(serverHeader, headerValue)

                self.end_headers()
                self.wfile.write(Content.encode())
                writeLogs(clientIP=self.requestHeaders['client-ip'],
                          userAgent=self.requestHeaders['user-agent'],
                          endpointVisited=self.realPath,
                          responseCode=Code,
                          requestMethod=self.requestHeaders['request-method'])
        elif self.realPath[:len(STATIC_PATH)].replace(
                '/', '') == STATIC_PATH.replace('/', ''):
            # static content should be served
            fileExtension = "".join(self.realPath.split('.')[-1:])

            try:
                contentType = __CT__[fileExtension]
            except Exception:
                contentType = "text/plain"

            responseContent = readFile(self.realPath[1:])

            if not responseContent:
                Content, Headers, Code = callHanlder("404Handler.py",
                                                     self.requestHeaders)

                self.send_response(Code)

                if len(Headers) != 0:
                    for serverHeader, headerValue in Headers.items():
                        self.send_header(serverHeader, headerValue)

                for serverHeader, headerValue in self.securityHeaders.items():
                    self.send_header(serverHeader, headerValue)

                self.end_headers()
                self.wfile.write(Content.encode())
                writeLogs(clientIP=self.requestHeaders['client-ip'],
                          userAgent=self.requestHeaders['user-agent'],
                          endpointVisited=self.realPath,
                          responseCode=Code,
                          requestMethod=self.requestHeaders['request-method'])
            elif responseContent == True:
                Content, Headers, Code = callHanlder("403Handler.py",
                                                     self.requestHeaders)

                self.send_response(Code)

                if len(Headers) != 0:
                    for serverHeader, headerValue in Headers.items():
                        self.send_header(serverHeader, headerValue)

                for serverHeader, headerValue in self.securityHeaders.items():
                    self.send_header(serverHeader, headerValue)

                self.end_headers()
                self.wfile.write(Content.encode())
                writeLogs(clientIP=self.requestHeaders['client-ip'],
                          userAgent=self.requestHeaders['user-agent'],
                          endpointVisited=self.realPath,
                          responseCode=Code,
                          requestMethod=self.requestHeaders['request-method'])
            else:
                self.send_response(200)
                self.send_header('content-type', contentType)

                for serverHeader, headerValue in self.securityHeaders.items():
                    self.send_header(serverHeader, headerValue)

                self.end_headers()
                self.wfile.write(responseContent.encode())
                writeLogs(clientIP=self.requestHeaders['client-ip'],
                          userAgent=self.requestHeaders['user-agent'],
                          endpointVisited=self.realPath,
                          responseCode=200,
                          requestMethod=self.requestHeaders['request-method'])
        else:
            if self.realPath[-1:] == "/":
                checkString = self.realPath[:-1]
            else:
                checkString = self.realPath

            if checkString in BLOCKED_PATHS:
                Content, Headers, Code = callHanlder("403Handler.py",
                                                     self.requestHeaders)

                self.send_response(Code)

                if len(Headers) != 0:
                    for serverHeader, headerValue in Headers.items():
                        self.send_header(serverHeader, headerValue)

                for serverHeader, headerValue in self.securityHeaders.items():
                    self.send_header(serverHeader, headerValue)

                self.end_headers()
                self.wfile.write(Content.encode())
                writeLogs(clientIP=self.requestHeaders['client-ip'],
                          userAgent=self.requestHeaders['user-agent'],
                          endpointVisited=self.realPath,
                          responseCode=Code,
                          requestMethod=self.requestHeaders['request-method'])
            else:
                try:
                    serverHandler = routes[self.realPath]
                    Content, Headers, Code = callHanlder(
                        serverHandler, self.requestHeaders)

                    self.send_response(Code)
                    if len(Headers) != 0:
                        for serverHeader, headerValue in Headers.items():
                            self.send_header(serverHeader, headerValue)

                    for serverHeader, headerValue in self.securityHeaders.items(
                    ):
                        self.send_header(serverHeader, headerValue)

                    self.end_headers()
                    self.wfile.write(Content.encode())
                    writeLogs(
                        clientIP=self.requestHeaders['client-ip'],
                        userAgent=self.requestHeaders['user-agent'],
                        endpointVisited=self.realPath,
                        responseCode=Code,
                        requestMethod=self.requestHeaders['request-method'])
                except Exception as e:
                    Content, Headers, Code = callHanlder(
                        "404Handler.py", self.requestHeaders)

                    self.send_response(Code)

                    if len(Headers) != 0:
                        for serverHeader, headerValue in Headers.items():
                            self.send_header(serverHeader, headerValue)

                    for serverHeader, headerValue in self.securityHeaders.items(
                    ):
                        self.send_header(serverHeader, headerValue)

                    self.end_headers()
                    self.wfile.write(Content.encode())
                    writeLogs(
                        clientIP=self.requestHeaders['client-ip'],
                        userAgent=self.requestHeaders['user-agent'],
                        endpointVisited=self.realPath,
                        responseCode=Code,
                        requestMethod=self.requestHeaders['request-method'])