Beispiel #1
0
 def get_content(self, path, method):
     response = HttpResponse(code=ResponseCode.OK)
     with open(path, 'rb') as f:
         content = f.read()
         response.body = content if method != "HEAD" else b''
         response.content_length = len(content)
         response.content_type = self.get_content_type(path)
     return response
Beispiel #2
0
def lambda_handler(event, context):
    """
    Returns completed request with response code (used by the lambda handler)
    """
    if event["pathParameters"]["domain"] is not None:
        return email(event["pathParameters"]["domain"])
    return HttpResponse.failure(status=HTTPStatus.BAD_REQUEST,
                                error="No domain included in the request")
Beispiel #3
0
def email(domain):
    """
    Finds the relevant abuse email address for the domain
    """
    if validate_domain(domain):
        try:
            emails = whois(domain).emails
            if isinstance(emails, list):
                for email in emails:
                    if "abuse" in email:
                        return HttpResponse.success(status=HTTPStatus.OK,
                                                    email=email)
            else:
                return HttpResponse.failure(status=HTTPStatus.BAD_REQUEST,
                                            error="WHOIS lookup has failed")
        except:
            return HttpResponse.failure(status=HTTPStatus.BAD_REQUEST,
                                        error="TLD is not yet supported")
    return HttpResponse.failure(
        status=HTTPStatus.BAD_REQUEST,
        error="Domain (%s) is invalid or not supported." % domain)
Beispiel #4
0
    def handle(self, request):
        method = request.split(b' ')[0].decode()
        path = self.parse_url(request)
        if method not in METHODS:
            return HttpResponse(code=ResponseCode.NOT_ALLOWED)

        # нормализую путь, убирая избыточные разделители и ссылки на предыдущие директории
        full_path = os.path.normpath(self.root_dir + '/' + path)

        if os.path.commonprefix([full_path, self.root_dir]) != self.root_dir:
            return HttpResponse(code=ResponseCode.NOT_FOUND)                    # случай /../../../ ...

        path_to_index = os.path.join(full_path, 'index.html')
        if os.path.isfile(path_to_index):
            full_path = path_to_index
        elif not os.path.exists(os.path.join(full_path)):
            return HttpResponse(code=ResponseCode.NOT_FOUND)

        try:
            return self.get_content(full_path, method)
        except IOError:
            return HttpResponse(code=ResponseCode.FORBIDDEN)
Beispiel #5
0
    def main(self):
        with socket.socket(socket.AF_INET,
                           socket.SOCK_STREAM) as server_socket:
            server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            server_socket.bind(("localhost", 8090))
            server_socket.listen(1)
            print(ServerMessage.WAITING_CONNECTION.value)

            while True:
                client_socket, address = server_socket.accept()
                print(ServerMessage.CONNECTED.value)

                request = HttpRequest(client_socket.recv(4096))

                with open("./resource/server/recv.txt", "wb") as f:
                    f.write(request.as_bytes())

                print(f"requested resouce is {DOCUMENT_ROOT + request.path}")

                try:
                    with open(DOCUMENT_ROOT + request.path, "rb") as f:
                        content = f.read()
                except FileNotFoundError:
                    thread = HttpResponseThread(client_socket,
                                                HttpResponse404())

                else:
                    ext = request.path.split(".")[-1]
                    if ext == "html":
                        content_type = "text/html"
                    elif ext == "css":
                        content_type = "text/css"
                    elif ext == "js":
                        content_type = "text/javascript"

                    thread = HttpResponseThread(
                        client_socket, HttpResponse(content, content_type))

                thread.start()
 def handle_read(self):
     try:
         logging.debug('Connection.handle_read - id=%d' % self.id)
         b = self.sock.recv(2048)
         logging.debug('Connection.handle_read - received buffer size is %d bytes' % len(b))
         logging.debug('Connection.handle_read - received buffer is : \n%s' % b)
         if not len(b):
             logging.debug('Connection.handle_read - 0 bytes received on %d. closing' %
                           self.id)
             self.close()
             return
         self.read_buf += b
     except socket.error as err:
         if err.args[0] not in NONBLOCKING:
             self.handle_error('%s' % args[1])
         else :
             logging.error('Connection.handle_read - NONBLOCKING event on read : %s' % args[1])
     else:
         # check if we have a full http request
         parser = HttpParser()
         recved = len(self.read_buf)
         nparsed = parser.execute(self.read_buf, recved)
         assert nparsed == recved
         if not parser.is_message_complete():
             # we got a partial request keep on reading
             logging.debug(
                 'Connection.handle_read - partial buffer received : \n%s' % 
                  self.read_buf)
             self.reset(pyev.EV_READ)
         else :
             # we got a full request
             self.read_buf = ''
             # match the verb with URI and call
             # after that register for write to send response
             verb = parser.get_method()
             url = parser.get_path()
             logging.debug('Connection.handle_read - id  %d - method is %s and url %s' % 
                 (self.id, verb, url))
             call, keyword_args = register.get_callable(url, verb)
             if not call :
                 err = HttpResponse()
                 err.status_code = 404
                 err.status_string = 'Not Found'
                 err.headers['Content-Type'] = 'application/txt'                    
                 err.body = 'URI Not Found\r\n'
                 self.write_buf = err.to_string()
             else :        
                 keyword_args['http_request'] = parser
                 logging.debug('Connection.handle_read - kargs=%s' % keyword_args)
                 try :
                     response = call(*[register.handler,], **keyword_args)
                     self.write_buf = response.to_string()
                 except :
                     err = HttpResponse()
                     err.status_code = 500
                     err.status_string = 'Internal Server Error'
                     err.headers['Content-Type'] = 'application/txt'                    
                     err.body = 'Upsssss.\r\n'
                     self.write_buf = err.to_string()
             logging.debug('Connection.handle_read - requesting write %d' % self.id)
             self.reset(pyev.EV_WRITE)
Beispiel #7
0
 def bar(self, name, qualifier, http_request):
     r = HttpResponse()
     r.headers['Host'] = 'localhost'
     r.headers['Content-Type'] = 'application/json'
     r.body = '{"status": %s}' % qualifier
     return r
Beispiel #8
0
httpheader = '''\
HTTP/1.1 200 OK
Context-Type: text/html
Server: Python-slp version 1.0
Context-Length: '''

lisfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lisfd.bind((HOST, PORT))
lisfd.listen(2)

signal.signal(signal.SIGINT, sigIntHander)

runflag = True

response = HttpResponse()

while runflag:
    try:
        confd, addr = lisfd.accept()
    except socket.error as e:
        if e.errno == errno.EINTR:
            print 'get a except EINTR'
        else:
            print 'get a error', e.errno
            raise
        continue
    if runflag == False:
        break

    print "connect by ", addr
Beispiel #9
0
 def bar(self, name, qualifier, http_request):
     r = HttpResponse()
     r.headers["Host"] = "localhost"
     r.headers["Content-Type"] = "application/json"
     r.body = '{"status": %s}' % qualifier
     return r
Beispiel #10
0
 def handle_read(self):
     try:
         logging.debug('Connection.handle_read - id=%d' % self.id)
         b = self.sock.recv(2048)
         logging.debug(
             'Connection.handle_read - received buffer size is %d bytes' %
             len(b))
         logging.debug(
             'Connection.handle_read - received buffer is : \n%s' % b)
         if not len(b):
             logging.debug(
                 'Connection.handle_read - 0 bytes received on %d. closing'
                 % self.id)
             self.close()
             return
         self.read_buf += b
     except socket.error as err:
         if err.args[0] not in NONBLOCKING:
             self.handle_error('%s' % args[1])
         else:
             logging.error(
                 'Connection.handle_read - NONBLOCKING event on read : %s' %
                 args[1])
     else:
         # check if we have a full http request
         parser = HttpParser()
         recved = len(self.read_buf)
         nparsed = parser.execute(self.read_buf, recved)
         assert nparsed == recved
         if not parser.is_message_complete():
             # we got a partial request keep on reading
             logging.debug(
                 'Connection.handle_read - partial buffer received : \n%s' %
                 self.read_buf)
             self.reset(pyev.EV_READ)
         else:
             # we got a full request
             self.read_buf = ''
             # match the verb with URI and call
             # after that register for write to send response
             verb = parser.get_method()
             url = parser.get_path()
             logging.debug(
                 'Connection.handle_read - id  %d - method is %s and url %s'
                 % (self.id, verb, url))
             call, keyword_args = register.get_callable(url, verb)
             if not call:
                 err = HttpResponse()
                 err.status_code = 404
                 err.status_string = 'Not Found'
                 err.headers['Content-Type'] = 'application/txt'
                 err.body = 'URI Not Found\r\n'
                 self.write_buf = err.to_string()
             else:
                 keyword_args['http_request'] = parser
                 logging.debug('Connection.handle_read - kargs=%s' %
                               keyword_args)
                 try:
                     response = call(*[
                         register.handler,
                     ], **keyword_args)
                     self.write_buf = response.to_string()
                 except:
                     err = HttpResponse()
                     err.status_code = 500
                     err.status_string = 'Internal Server Error'
                     err.headers['Content-Type'] = 'application/txt'
                     err.body = 'Upsssss.\r\n'
                     self.write_buf = err.to_string()
             logging.debug('Connection.handle_read - requesting write %d' %
                           self.id)
             self.reset(pyev.EV_WRITE)