def send_get_request(self):
     # HTTPObject.convert_to_string(http_object)
     message = "GET " + str(HTTPObject.get_path(
         self.http_object)) + " HTTP/1.1\r\n"
     message += "Host: " + str(HTTPObject.get_host(
         self.http_object)) + "\r\n"
     for keys in HTTPObject.get_headers(
             self.http_object):  # iterate over headers stored in dictionary
         message += keys + ": " + HTTPObject.get_headers(
             self.http_object)[keys] + "\r\n"
     if "Content-Type" not in HTTPObject.get_headers(self.http_object):
         if str(HTTPObject.get_path(self.http_object)).endswith(".txt"):
             message += "Content-Type: text/plain" + "\r\n"
         elif str(HTTPObject.get_path(self.http_object)).endswith(".html"):
             message += "Content-Type: text/html" + "\r\n"
         elif str(HTTPObject.get_path(self.http_object)).endswith(".xml"):
             message += "Content-Type: text/xml" + "\r\n"
         elif str(HTTPObject.get_path(self.http_object)).endswith(".json"):
             message += "Content-Type: application/json" + "\r\n"
         else:
             message += "Content-Type: text/plain" + "\r\n"
     message += "\r\n"
     print("Sending message:\n")
     print(message + "\n")
     print("Starting to create packets of this message")
     # Here we start for the procedure so packect shoud be created and set and wait for acks
     self.communicate_with_server(message.encode('utf-8'))
     print("Data Send Complete")
     self.received_all_acks = False
Exemple #2
0
 def send_request(http_object):
     if HTTPObject.get_req_type(http_object) == "GET":
         HTTPConnection.send_get_request(
             http_object)  # send GET request based on type
     else:
         HTTPConnection.send_post_request(
             http_object)  # send POST request based on type
def test_write(p1, p2, val):
    my_http_obj = HTTPObject(
        "httpc post -v -h Content-type:text/plain -h Content-Disposition:inline "
        + "-d 'This line has been added by thread" + val + "' " +
        "'localhost:" + str(p2) + "/bar/test.txt'")
    http_con = client_HTTPConnection(my_http_obj, p2)
    http_con.send_request(p1)
    def send_request(self, client_port):
        print("Sending request")
        # Here before doing anything we are performing handshaking
        self.perform_handshaking(client_port)

        # from here we start things
        if HTTPObject.get_req_type(self.http_object) == "GET":
            self.send_get_request()  # send GET request based on type
        else:
            self.send_post_request()  # send POST request based on type
Exemple #5
0
def main():
    flag = "good"
    while flag:
        flag = "good"
        inputCommand = input("Please enter the command:\n")
        convertedArray = inputCommand.split()
        for x in convertedArray:
            if x.lower() == "help":
                helpCommand(convertedArray)
                flag = "help"
            if x.lower() == "exit":
                flag = "exit"
        if flag == "good":
            try:
                my_http_obj = HTTPObject(inputCommand)
                HTTPConnection.send_request(my_http_obj)
            except Exception:
                pass
        elif flag == "exit":
            break
Exemple #6
0
def test_read():
    HTTPConnection.send_request(
        HTTPObject(
            "httpc get -v -h Content-Disposition:inline '127.0.0.1:8080/bar/test.txt'"
        ))
Exemple #7
0
 def send_get_request(http_object):
     # HTTPObject.convert_to_string(http_object)
     socket_object = socket.socket()  # create socket object
     try:
         socket_object.connect(
             (HTTPObject.get_host(http_object),
              HTTPObject.get_port(http_object)))  # connect to server
         socket_object.settimeout(2)  # set timeout to 5sec
         if socket.gethostbyaddr(socket_object.getpeername()
                                 [0])[0]:  # check remote server name
             print("Connected to server.....")
     except socket.error as msg:  # handle socket errors
         print("Cannot connect to server. Try again!!!")
         return
     message = "GET " + str(
         HTTPObject.get_path(http_object)) + " HTTP/1.1\r\n"
     message += "Host: " + str(HTTPObject.get_host(http_object)) + "\r\n"
     for keys in HTTPObject.get_headers(
             http_object):  # iterate over headers stored in dictionary
         message += keys + ": " + HTTPObject.get_headers(
             http_object)[keys] + "\r\n"
     if "Content-Type" not in HTTPObject.get_headers(http_object):
         if str(HTTPObject.get_path(http_object)).endswith(".txt"):
             message += "Content-Type: text/plain" + "\r\n"
         elif str(HTTPObject.get_path(http_object)).endswith(".html"):
             message += "Content-Type: text/html" + "\r\n"
         elif str(HTTPObject.get_path(http_object)).endswith(".xml"):
             message += "Content-Type: text/xml" + "\r\n"
         elif str(HTTPObject.get_path(http_object)).endswith(".json"):
             message += "Content-Type: application/json" + "\r\n"
         else:
             message += "Content-Type: text/plain" + "\r\n"
     message += "\r\n"
     print("Sending message:\n")
     print(message + "\n")
     socket_object.sendall(bytes(message,
                                 'utf-8'))  # send message to remote server
     HTTPConnection.receive_response(
         http_object, socket_object)  # receive response from the server
Exemple #8
0
 def receive_response(http_object, socket_object):
     # print("Inside receive response")
     _receive_data = []
     begin = time.time()  # stores current time
     while 1:
         if _receive_data and time.time() - begin > socket_object.gettimeout(
         ):  # break if time elapsed since \
             # last receive is greater than the timeout
             break
         elif time.time() - begin > socket_object.gettimeout() * 2:
             break
         try:
             _tmp = socket_object.recv(2048)  # receive 2048 bytes at a time
             if _tmp:
                 _tmp = _tmp.decode("utf-8")  # convert to text string
                 _receive_data.append(_tmp)  # append to receive array
                 begin = time.time()  # set begin to current time
         except:
             pass
     str_received_data = ''
     for data in _receive_data:
         str_received_data += data  # convert received array to string
     print("Received data:\n")
     # print(str_received_data)
     header_body = str_received_data.split(
         "\r\n\r\n")  # split header and body
     print_data = ''
     if HTTPObject.get_is_verbose(
             http_object) == "true":  # check if verbose option is enabled
         print_data += header_body[0] + "\n"
     if len(header_body
            ) == 2:  # check if body is contained in received data
         print_data += "\n" + header_body[1] + "\n"
     my_header = header_body[0].split(" ")
     if my_header[1].startswith("3") and 300 <= int(
             my_header[1]
     ) <= 304:  # check if body contains redirection code
         socket_object.close()
         loc_index = header_body[0].replace("location:", "Location:").find(
             "Location:")  # find location of new url
         start = header_body[0].find(":", loc_index) + 2
         # get start index of new url, +2 for // in http://
         end = header_body[0].find("\r\n", start)
         # get end index of new url
         --end  # move to one previous location
         HTTPObject.set_path(
             http_object, header_body[0][start:end].strip())  # set new path
         HTTPObject.set_url(http_object,
                            HTTPConnection.find_url(
                                header_body[1]))  # set new url
         HTTPConnection.send_request(
             http_object)  # send new request to redirected url
         return
     headers = {}
     count = 0
     for line in header_body[0].split("\r\n"):
         if count != 0:
             headers[line.split(":")[0].strip()] = line.split(
                 ":")[1].strip()
         else:
             count = count + 1
     if "Content-Disposition" in headers:
         if headers["Content-Disposition"].startswith("attachment"):
             pos = (headers["Content-Disposition"]).find("/")
             file = (headers["Content-Disposition"])[pos + 1:]
             if headers["Content-Type"] == "text/plain":
                 file += ".txt"
             elif headers["Content-Type"] == "text/html":
                 file += ".html"
             elif headers["Content-Type"] == "text/xml":
                 file += ".xml"
             elif headers["Content-Type"] == "application/json":
                 file += ".json"
             else:
                 file += ".txt"
             if len(header_body) > 1:
                 HTTPConnection.write_to_file(file, header_body[1])
     if HTTPObject.get_write_file(
             http_object
     ) == "true":  # check if data is to be written to a file
         HTTPConnection.write_to_file(HTTPObject.get_file2(http_object),
                                      print_data)  # write data to the file
     else:
         print(print_data)  # print data to console
 def send_post_request(self):
     # HTTPObject.convert_to_string(self.http_object)  # print request object
     message = "POST " + str(HTTPObject.get_path(
         self.http_object)) + " HTTP/1.1\r\n"
     message += "Host: " + str(HTTPObject.get_host(
         self.http_object)) + "\r\n"
     for keys in HTTPObject.get_headers(
             self.http_object):  # iterate over headers stored in dictionary
         message += keys + ": " + HTTPObject.get_headers(
             self.http_object)[keys] + "\r\n"
     if HTTPObject.get_inline(
             self.http_object
     ) == "true":  # check if data is provided as inline
         if "Content-Type" not in HTTPObject.get_headers(self.http_object):
             message += "Content-Type: text/plain" + "\r\n"
         message += "Content-Length: " + str(
             len(HTTPObject.get_data(self.http_object))) + "\r\n\r\n"
         message += str(HTTPObject.get_data(self.http_object))
     elif HTTPObject.get_read_file(
             self.http_object
     ) == "true":  # check if data is to be read from the file
         if "Content-Type" not in HTTPObject.get_headers(self.http_object):
             if str(HTTPObject.get_file1(
                     self.http_object)).endswith(".txt"):
                 message += "Content-Type: text/plain" + "\r\n"
             elif str(HTTPObject.get_file1(
                     self.http_object)).endswith(".html"):
                 message += "Content-Type: text/html" + "\r\n"
             elif str(HTTPObject.get_file1(
                     self.http_object)).endswith(".xml"):
                 message += "Content-Type: text/xml" + "\r\n"
             elif str(HTTPObject.get_file1(
                     self.http_object)).endswith(".json"):
                 message += "Content-Type: application/json" + "\r\n"
             else:
                 message += "Content-Type: text/plain" + "\r\n"
         message += "Content-Length: " + str(
             len(HTTPConnection.read_from_file(HTTPObject.get_file1(self.http_object)))) \
                    + "\r\n\r\n"
         message += HTTPConnection.read_from_file(
             HTTPObject.get_file1(self.http_object))
     print("Sending message:\n")
     print(message)
     self.communicate_with_server(message.encode('utf-8'))
     print("Data Send Complete")
 def convert_response(self):
     str_received_data = ''
     for some_data in sorted(self.payload.items()):
         str_received_data += some_data[
             1]  # convert received array to string
     print("Received data:\n")
     print(str_received_data)
     header_body = str_received_data.split(
         "\r\n\r\n")  # split header and body
     print_data = ''
     if HTTPObject.get_is_verbose(
             self.http_object
     ) == "true":  # check if verbose option is enabled
         print_data += header_body[0] + "\n"
     if len(header_body
            ) == 2:  # check if body is contained in received data
         print_data += "\n" + header_body[1] + "\n"
     my_header = header_body[0].split(" ")
     if my_header[1].startswith("3") and 300 <= int(
             my_header[1]
     ) <= 304:  # check if body contains redirection code
         # socket_object.close()
         loc_index = header_body[0].replace("location:", "Location:").find(
             "Location:")  # find location of new url
         start = header_body[0].find(":", loc_index) + 2
         # get start index of new url, +2 for // in http://
         end = header_body[0].find("\r\n", start)
         # get end index of new url
         --end  # move to one previous location
         HTTPObject.set_path(
             self.http_object,
             header_body[0][start:end].strip())  # set new path
         HTTPObject.set_url(self.http_object,
                            HTTPConnection.find_url(
                                header_body[1]))  # set new url
         HTTPConnection.send_request(
             self.http_object)  # send new request to redirected url
         return
     headers = {}
     count = 0
     for line in header_body[0].split("\r\n"):
         if count != 0:
             headers[line.split(":")[0].strip()] = line.split(
                 ":")[1].strip()
         else:
             count = count + 1
     if "Content-Disposition" in headers:
         if headers["Content-Disposition"].startswith("attachment"):
             pos = (headers["Content-Disposition"]).find("/")
             file = (headers["Content-Disposition"])[pos + 1:]
             if headers["Content-Type"] == "text/plain":
                 file += ".txt"
             elif headers["Content-Type"] == "text/html":
                 file += ".html"
             elif headers["Content-Type"] == "text/xml":
                 file += ".xml"
             elif headers["Content-Type"] == "application/json":
                 file += ".json"
             else:
                 file += ".txt"
             if len(header_body) > 1:
                 HTTPConnection.write_to_file(file, header_body[1])
     if HTTPObject.get_write_file(
             self.http_object
     ) == "true":  # check if data is to be written to a file
         HTTPConnection.write_to_file(HTTPObject.get_file2(
             self.http_object), print_data)  # write data to the file
     else:
         print(print_data)  # print data to console """
def test_read(p1, p2):
    my_http_obj = HTTPObject(
        "httpc get -v -h Content-Disposition:inline 'localhost:" + str(p2) +
        "/bar/test.txt'")
    http_con = client_HTTPConnection(my_http_obj, p2)
    http_con.send_request(p1)
Exemple #12
0
def test_write(val):
    HTTPConnection.send_request(
        HTTPObject(
            "httpc post -v -h Content-type:text/plain -h Content-Disposition:inline "
            + "-d 'This line has been added by thread" + val + "' " +
            "'127.0.0.1/bar/test.txt'"))