def client_get(sock, file_name):
    '''
    downloads file from server to client
    '''
    # receive valid file indicator from server
    file_check_size = int(data_handling.receive_data(sock, HEADER_SIZE))
    file_check = data_handling.receive_data(sock, file_check_size)

    # check if file in server_files
    if file_check == '/FileNotFound':
        print(f'{file_name} does not exist in server')
        data_handling.send_data(sock, '/FileNotFound')
        return

    # get file size
    file_size = int(data_handling.receive_data(sock, HEADER_SIZE))

    print(f'Downloading {file_name} (Size: {file_size} B) from server...')

    # receive file data
    file_data = data_handling.receive_data(sock, file_size)

    # create file with received data in client_files directory
    file_path = os.path.join(CLIENT_FILES_DIR, file_name)
    file = open(file_path, 'w')
    file.write(file_data)
    file.close()

    print(f'Succesfully downloaded {file_name} from server')
Esempio n. 2
0
def run(args):
    # To run: python3 serv.py <PORT>
    if len(args) != 2:
        print("Usage: python3 " + args[0] + " <PORT>")
        sys.exit()

    port = args[1]

    # bind socket to a port
    servSocket = bind(int(port))
    if not servSocket:
        print("Failed bind to a port")
        sys.exit()

    while True:
        # keep listening for connections until user ends process
        print("Listening on port " + port)
        cliSocket, addr = servSocket.accept()
        print("Connected to: " + addr[0])

        while True:
            query = receive_data(cliSocket, const.HEADER_SIZE)
            # print(query)

            # get <FILE NAME>
            # sends <FILE NAME> to client
            if query == const.COMMANDS[0]:
                giveFromServer(cliSocket)

            # put <FILE NAME>
            # downloads <FILE NAME> from client
            elif query == const.COMMANDS[1]:
                receive_file(cliSocket)

            # ls
            # lists files on the server
            elif query == const.COMMANDS[2]:
                # get file names from folder
                files = os.listdir(const.SERVER_FOLDER)
                response = ""
                for file in files:
                    response += file + "  "
                response = response[:-2]

                # send response
                responseSize = size_padding(len(response), const.HEADER_SIZE)
                data = responseSize + response
                send_data(cliSocket, data)

            # quit
            # closes the connection
            elif query == const.COMMANDS[3]:
                cliSocket.close()
                print("Connection closed")
                break

            else:
                print("Invalid command. Closing connection")
                cliSocket.close()
                break
def server_ls(sock):
    '''
    lists files on server
    '''
    dir_list = os.listdir(SERVER_FILES_DIR)
    dir_list_str = '/'.join(dir_list)
    data_handling.send_data(sock, dir_list_str)
def server_get(sock, file_name):
    '''
    downloads file from server to client
    '''
    # check if file in server_files
    if file_name not in os.listdir(SERVER_FILES_DIR):
        data_handling.send_data(sock, '/FileNotFound')
        return 0
    else:
        data_handling.send_data(sock, '/ValidFile')

    # open file from server_files
    file = open(os.path.join(SERVER_FILES_DIR, file_name), 'r')
    # send file to client
    data_handling.send_file(sock, file)

    return 1
def main():
    # check correct number of arguments
    if len(sys.argv) < 3:
        print(f'USAGE: $ python {sys.argv[0]} <SERVER MACHINE> <SERVER PORT>')
        exit()

    # server address
    server_addr = sys.argv[1]
    # server port
    server_port = sys.argv[2]

    # create a socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # connect to server
    client_socket.connect((server_addr, int(server_port)))

    # loop until user enters 'exit' command
    while True:
        cmd = input('ftp> ')
        # check empty input
        if not cmd:
            continue
        # check file name
        if len(cmd.split()) > 2:
            print('Make sure file name has no spaces')
            continue

        # send command to server
        data_handling.send_data(client_socket, cmd)

        # split 'cmd' into list:
        #   cmd[0]: command
        #   cmd[1]: <FILE NAME> if exists
        cmd = cmd.split()

        # execute command
        if cmd[0] in cmds.CMDS:
            execute_cmd(cmd, client_socket)
        # invalid command check
        else:
            print(f'Invalid command: \'{cmd[0]}\'\n'
                  f'Available commands: {cmds.CMDS}')
Esempio n. 6
0
def receive_file(sock):
    # create new socket for data transfer
    servSocket = bind()

    # send port number to client
    servPort = servSocket.getsockname()[1]
    send_data(sock, str(servPort))

    # accept client connection
    print("Listening on port " + str(servPort))
    dataSocket, addr = servSocket.accept()
    print("Connected to: " + addr[0])

    # get payload sizes
    fileNameSize = receive_data(dataSocket, const.HEADER_SIZE)
    fileDataSize = receive_data(dataSocket, const.HEADER_SIZE)

    # error checking
    if fileNameSize == "":
        print("Failed to receive file name size")
        return

    if fileDataSize == "":
        print("Failed to receive file data size")
        return

    # read payload
    fileName = receive_data(dataSocket, int(fileNameSize))
    fileData = receive_data(dataSocket, int(fileDataSize))

    # write file
    filePath = const.SERVER_FOLDER + fileName
    userFile = open(filePath, "w")
    userFile.write(fileData)

    print(fileName + " received")
    print("File size: " + fileDataSize)

    # close file and connection
    userFile.close()
    dataSocket.close()
    print("Data transfer connection closed")
Esempio n. 7
0
def put_file(sock, address, fileName):
    # grab files only from client folder
    filePath = const.CLIENT_FOLDER + fileName

    # open file and get file size
    try:
        userFile = open(filePath, "r")
        fileSize = os.path.getsize(filePath)
    except Exception as e:
        print(e)
        # print("Failed to open file")
        return

    # get data channel port number from server
    dataPort = receive_data(sock, const.HEADER_SIZE)

    # connect to new port
    dataSocket = connect(address, int(dataPort))

    # if connection failed, exit
    if not dataSocket:
        print("Failed to connect to server")
        return

    # make file size and file name headers
    fileNameSize = size_padding(len(fileName), const.HEADER_SIZE)
    fileDataSize = size_padding(fileSize, const.HEADER_SIZE)
    fileData = userFile.read()

    # add headers to payload
    data = fileNameSize + fileDataSize + fileName + fileData

    # send data
    send_data(dataSocket, data)
    print(fileName + " upload successful.")
    print("Bytes sent: " + str(len(data)))

    # close file and connection
    userFile.close()
    dataSocket.close()
    print("Data transfer connection closed")
def client_put(sock, file_name):
    '''
    uploads file to the server from client
    '''
    # client_files list
    client_files = dir_list = os.listdir(CLIENT_FILES_DIR)
    # check if file in cient_files
    if file_name not in client_files:
        print(f'{file_name} does not exist in client')
        data_handling.send_data(sock, '/FileNotFound')
        return
    else:
        data_handling.send_data(sock, '/ValidFile')

    print(f'Uploading {file_name} to server...')

    # open file from client_files
    file = open(os.path.join(CLIENT_FILES_DIR, file_name), 'r')
    # send file to server
    data_handling.send_file(sock, file)

    print(f'Successfully uploaded {file_name} to server')
Esempio n. 9
0
def run(args):
    # To run: python3 cli.py <SERVER> <PORT>
    if len(args) != 3:
        print("Usage: python3 " + args[0] + " <SERVER> <PORT>")
        sys.exit()

    server = args[1]
    port = args[2]

    # connect to server
    cliSocket = connect(server, int(port))
    if not cliSocket:
        print("Failed to connect to " + server)
        sys.exit()

    query = ""

    while True:
        query = (input("ftp> ")).lower().split()
        # print(query)

        # get <FILE NAME>
        # downloads <FILE NAME> from the server
        if query[0] == const.COMMANDS[0]:
            if len(query) != 2:
                print("Usage: get <FILE NAME>")
            else:
                send_data(cliSocket, query[0])
                getFromServer(cliSocket, query[1])

        # put <FILE NAME>
        # uploads <FILE NAME> to the server
        elif query[0] == const.COMMANDS[1]:
            if len(query) != 2:
                print("Usage: put <FILE NAME>")
            else:
                send_data(cliSocket, query[0])
                put_file(cliSocket, server, query[1])

        # ls
        # lists files on the server
        elif query[0] == const.COMMANDS[2]:
            # send query
            send_data(cliSocket, query[0])

            # get size of response
            responseSize = receive_data(cliSocket, const.HEADER_SIZE)

            if responseSize == "":
                print("Failed to receive size of response")
            else:
                response = receive_data(cliSocket, int(responseSize))
                print(response)

        # quit
        # disconnects from the server and exits
        elif query[0] == const.COMMANDS[3]:
            send_data(cliSocket, query[0])
            cliSocket.close()
            print("Connection closed")
            break

        else:
            print("Invalid command")