コード例 #1
0
def getSharedKey(clientPort):
    msg = clientPort.recv(1024)
    msgLen = int(msg[:utils.HEADER_LENGTH])
    fullMsg = msg
    while len(fullMsg) < msgLen:
        msg = clientPort.recv(1024)
        fullMsg += msg
    msgFromClient = pickle.loads(fullMsg[utils.HEADER_LENGTH:])
    serverPublicKey, secret = utils.generatePublicKey(
        msgFromClient.publicKey.prime, msgFromClient.publicKey.root)
    sharedKey = utils.generateFullKey(msgFromClient.publicKey, secret)
    print(
        f"msgLength: {msgLen}, opcode: {msgFromClient.header.opcode}, prime: {msgFromClient.publicKey.prime}, root: {msgFromClient.publicKey.root}, publicKey: {msgFromClient.publicKey.pub_key}, secret: {secret}, \nShared Key: {sharedKey}"
    )
    SetHeaderValues = utils.Header(utils.opcodeDict["PUBKEY"],
                                   socket.gethostname(), None)
    SetPublicKey = utils.PublicKey(msgFromClient.publicKey.prime,
                                   msgFromClient.publicKey.root,
                                   serverPublicKey.pub_key)
    packet = utils.Packet(SetHeaderValues, SetPublicKey, None, None, None,
                          None)
    msgToSend = pickle.dumps(packet)
    msgToSend = bytes(f"{len(msgToSend):<{utils.HEADER_LENGTH}}",
                      "ascii") + msgToSend
    clientPort.sendall(msgToSend)
    print("Sent public key")
    return sharedKey
コード例 #2
0
def sendFileReq(filename):
	SetHeaderValues=utils.Header(utils.opcodeDict["REQSERV"], socket.gethostname(), HOST)
	packet = utils.Packet(SetHeaderValues, None, utils.ReqServ(filename), None, None, None)
	msgToSend = pickle.dumps(packet)
	extract_info(10)
	msgToSend = bytes(f"{len(msgToSend):<{utils.HEADER_LENGTH}}", "ascii") + msgToSend
	sock.sendall(msgToSend)
コード例 #3
0
def getKeyPacket():
    p = prime_generate()
    generatedKey, secret = utils.generatePublicKey()
    SetHeaderValues=utils.Header(utils.opcodeDict["PUBKEY"], socket.gethostname(), HOST)
    SetPublcKeyValues=utils.PublicKey(generatedKey.prime, generatedKey.root, generatedKey.pub_key)
    extract_info(10)
    packet = utils.Packet(SetHeaderValues,SetPublcKeyValues , None, None, None, None)
    msgToSend = pickle.dumps(packet)
    msgToSend = bytes(f"{len(msgToSend):<{utils.HEADER_LENGTH}}", "ascii") + msgToSend
    return msgToSend, secret
コード例 #4
0
def main():
    utils.initConfigs()
    utils.clear()
    print(
        'Using configs from config.xml Receiver(this): {}\nSender: {} Simulator: {}'
        .format(utils.RECEIVER_IP, utils.SIMULATOR_IP, utils.SENDER_IP))
    print('Missing packet timeout seconds:', utils.timeout_sec)
    print('Sender window size:', utils.window_size)
    simulatorSocket = utils.createUdpSocket(utils.RECV_PORT)
    simulatorHost = utils.SocketHost(simulatorSocket, utils.SIMULATOR_IP,
                                     utils.RECV_PORT)
    print('Receiver started, listening on port', utils.RECV_PORT,
          'ctrl+c to exit')
    try:
        sendSocketHost = utils.SocketHost(simulatorSocket, utils.SIMULATOR_IP,
                                          utils.SEND_PORT)
        ack_window = []
        while True:
            # block here until client connects
            data_packet = utils.readPacket(simulatorSocket)
            print('Packet recv\'d: {} {} {}'.format(
                utils.CMDS[data_packet.flag], data_packet.num,
                data_packet.payload))

            ack_packet = utils.Packet(utils.ACK, data_packet.num)
            if len(ack_window
                   ) < utils.window_size and ack_packet not in ack_window:
                ack_window.append(ack_packet)
                if len(ack_window) == utils.window_size:
                    print('window size {} filled, sending ACKs {}-{}'.format(
                        utils.window_size, ack_window[0].num,
                        ack_window[utils.window_size - 1].num))
                    for packet in ack_window:
                        utils.sendPacket(simulatorHost, packet)
                    ack_window = []
            else:
                print('Ignored dup packet, seq num {}. Curr window size {}'.
                      format(ack_packet.num, len(ack_window)))
    except KeyboardInterrupt:
        print('\nexit called.')
    except Exception as e:
        traceback.print_exc()
    finally:
        simulatorSocket.close()
コード例 #5
0
def serveRequest(key, clientPort):
    key = f"{key:<{utils.KEY_LENGTH}}"
    msg = clientPort.recv(1024)
    msgLen = int(msg[:utils.HEADER_LENGTH])
    fullMsg = msg
    while len(fullMsg) < msgLen:
        msg = self.request.recv(1024)
        fullMsg += msg
    extract_info(10)
    msgFromClient = pickle.loads(fullMsg[utils.HEADER_LENGTH:])
    filename = msgFromClient.reqServ.filename
    print(f"Requested file: {filename}")
    try:
        filepath = "files/" + filename
        with open(filepath, 'rb') as file:
            fileInfo = os.stat(filepath)
            fileSize = fileInfo.st_size
            # print(f"File size: {fileSize} bytes.")
            extract_info(10)
            # n=fileSize//1024
            # r=fileSize%1024
            # Info=FileINFO(n,r)
            # infopacket = pickle.dumps(Info)
            # clientPort.sendall(infopacket)
            data = file.read(1024)
            cipher = DES3.new(key)
            while len(data) > 0:
                blockLength = len(data)
                if (blockLength < 1024):
                    rem = blockLength % 1024
                    if rem:
                        data += bytes(1024 - rem)
                encrypted_text = cipher.encrypt(data)
                dec_text = cipher.decrypt(encrypted_text)
                SetHeadervalues = utils.Header(utils.opcodeDict["ENCMSG"],
                                               socket.gethostname(), None)
                packet = utils.Packet(
                    SetHeadervalues, None, None, None,
                    utils.EncodedMsg(encrypted_text, blockLength), None)
                msgToSend = pickle.dumps(packet)
                msgToSend = bytes(f"{len(msgToSend):<{utils.HEADER_LENGTH}}",
                                  "ascii") + msgToSend
                # print("s:,", len(msgToSend))
                clientPort.sendall(msgToSend)
                data = file.read(1024)
                extract_info(10)
        SetHeadervalues = utils.Header(utils.opcodeDict["REQCOM"],
                                       socket.gethostname(), None)
        packet = utils.Packet(SetHeadervalues, None, None, utils.ReqComp(400),
                              None, None)
        msgToSend = pickle.dumps(packet)
        msgToSend = bytes(f"{len(msgToSend):<{utils.HEADER_LENGTH}}",
                          "ascii") + msgToSend
        clientPort.sendall(msgToSend)
        print("file sent")
    except FileNotFoundError:
        print("File not found")
        extract_info(10)
        packet = utils.Packet(
            utils.Header(utils.opcodeDict["DISCONNECT"], socket.gethostname(),
                         None), None, None, None, None, utils.Disconnect())
        msgToSend = pickle.dumps(packet)
        clientPort.sendall(msgToSend)
コード例 #6
0
def main():
    utils.initConfigs()
    utils.clear()
    print(
        'Using configs from config.xml: Sender (this) {}\n Simulator: {} Receiver: {}'
        .format(utils.SENDER_IP, utils.SIMULATOR_IP, utils.RECEIVER_IP))
    print('ACK timeout seconds: ', utils.timeout_sec)
    print('Window size: ', utils.window_size)
    simulatorSocket = utils.createUdpSocket(utils.SEND_PORT)
    simulatorHost = utils.SocketHost(simulatorSocket, utils.SIMULATOR_IP,
                                     utils.SEND_PORT)
    print('Sender started, connecting to simulator ', utils.SIMULATOR_IP,
          ' ctrl+c to exit')
    try:
        # make packets
        window = []
        seqNum = 1
        while True:
            for x in range(1, utils.window_size):
                packet = utils.Packet(utils.DATA, seqNum, getRngString())
                seqNum = seqNum + 1 if seqNum <= 998 else 1
                window.append(packet)
            packet = utils.Packet(utils.EOT, seqNum, getRngString())
            seqNum += 1
            window.append(packet)

            retransmit = True
            while retransmit:
                retransmit = False
                timed_out = False
                for packet in window:
                    utils.sendPacket(simulatorHost, packet)
                    print('packet to simulator: {} {} {}'.format(
                        utils.CMDS[packet.flag], packet.num, packet.payload))
                    time.sleep(utils.send_delay_sec)
                print('window sent included packets {}-{}'.format(
                    window[0].num, window[utils.window_size - 1].num))
                for x in window:
                    ack_packet = utils.readPacket(simulatorSocket,
                                                  utils.timeout_sec)
                    if ack_packet.flag == utils.TIMEOUT:
                        timeout_msg = 'timeout while waiting for ACKs, resending packets {}-{}'.format(
                            window[0].num, window[utils.window_size - 1].num)
                        print(timeout_msg)
                        info_packet = utils.Packet(utils.TIMEOUT, 0,
                                                   timeout_msg)
                        utils.sendPacket(simulatorHost, info_packet)
                        timed_out = True
                        break
                    else:
                        print('ACK recv\'d: {} {} {}'.format(
                            utils.CMDS[ack_packet.flag], ack_packet.num,
                            ack_packet.payload))
                if timed_out:
                    retransmit = True
            # end retransmit
            window = []
    except KeyboardInterrupt:
        print('\nexit called.')
    except Exception as e:
        traceback.print_exc()
    finally:
        simulatorSocket.close()