Detailed TFTP

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/young2415/article/details/91125718

Outline

TFTP, stands for Trivial File Transfer Protocol (Trivial File Transfer Protocol), UDP-based implementation, the agreement can only be simple to read data from a remote server or upload data to a remote server. TFTP has three modes: netascii, which is in the form of 8-bit ASCII code; OCTET other is, that the source data type is 8; the last mail is no longer supported, it returns the data directly back to the user rather than saved as a file.

Although TFTP usually do not have many of the features of FTP, TFTP but learning can help us understand the basic principles of the work process and network communication protocols, follow-up study of more complex protocols are very helpful.

First, look at the type of TFTP packets, TFTP 5 types of packages:
Here Insert Picture Description

establish connection

By default, as the host A TFTP server listening port 69, when as a host B client wants to download or upload files, contain read the file (download) request or write files (upload) sent to the port host A 69 request packet. Host A receives the write request, a random port is opened further, transmits an acknowledgment packet to the host B through this port, the packet error or packet.

download

The client sends the server port 69 (usually) a read request, after the server receives the read request, opens a further random port (port number is assumed 59509), and then look for the file in its default path , find the file after the file is read every 512 bytes, 512 bytes through these ports 59509 to the client into a data packet, the data packet also includes an opcode and a number of data blocks, a block number counting from the start; after the client receives the packet, sends an acknowledgment packet to port 59509 of the server, which contains the block numbers of packets it receives; after the server receives the acknowledgment packet, continue to send the file the next 512 bytes.

After so the cycle will automatically until the end of the file, the size of the last data block of a data packet will be less than 512 bytes, then the server that the transmission has ended, and so that he receives an acknowledgment packet is the last packet close the connection. After the client receives less than 512 bytes of this packet is also transmitted over that, after completing the transmission confirmation packet will close the connection.

There may be an extreme case, the file size is exactly a multiple of 512 bytes, so the last packet size is 512 bytes, then the server transmits a packet containing the file data after completion, but also additional transmitting a packet contains zero bytes, as the last packet, so as to ensure the size of the last data packet received by the client is always less than 512 bytes. That is, for the clients, as long as it receives the size of the data packet is less than 512 bytes, it regards that the transmission has ended, it will close the connection.

The following are TFTP download icon:
Here Insert Picture Description

Upload

The client 69 sends a write to the server port (usually) request, after the server receives the write request, will open another random port (port number is assumed 59509), it sends an acknowledgment packet to the client, wherein the block number is 0, in order to tell the client you are ready to receive the file, and tells the client port number to receive their own files.

Send an acknowledgment packet to the client after the client then began to send packets to port 59509 server, the server receives data packets until the entire file has been sent. This process and downloads are the same, but the two sides of the roles were reversed, the client became one of the data sent, and the server is the party that receives the data.

The following are TFTP upload icon:
Here Insert Picture Description

Error mechanism

TFTP provides some error mechanism, if an error occurs, the server will send ERROR packet to the client, the packet format is as follows:
Here Insert Picture Description
The first two byte opcode, the value is 5, which is representative of a ERROR packet. The next two bytes is an error code, representing the type of error, the following type of error is different error codes corresponding to:

Error code meaning
1 File not found. (File not found, the server is not specified in the request to download a file found)
2 Access violation. (Access violations, program the default path for server does not have write access to)
3 Disk full or allocation exceeded. (Disk full or allocation exceeded, this error may occur when uploading files)
4 Illegal TFTP operation. (TFTP illegal operation, the server does not recognize the packet opcodes TFTP)
5 Unknown transfer ID. (Unknown transmission identification)
6 File already exists. (File already exists, to upload the file already exists in the server)
7 No such user. (Not the user)

The next n bytes used to store the error message, this part can decide what information is stored by the programmer. The last byte is 0 is used to identify the end.

Code

Below to download the file, for example, a client with a Python implementation of the TFTP.

lab environment

  • Windows 10
  • VMware 15, which installed the Windows 10 operating system virtual machine
  • Python 3.7
  • tftpd64 (a TFTP protocol support software, install Windows 10 inside the virtual machine as a server)

Here is the Python code:

#filename: tftp_client_download.py
import struct
from socket import *

'''
第一个参数是要下载的文件名,类型是字符串
第二个参数是服务器的IP地址和端口号,类型是元组,
元组中有两个元素,第一个元素是IP地址,类型是字符串,第二个元素是端口号,类型是整数。
比如:('192.168.1.2', 69)
'''
def download(file_name, servAddr):
    file_name_byte_array = file_name.encode('gb2312')
    #组包,octet 代表TFTP协议的一种模式
    sendData = struct.pack('!H'+str(len(file_name_byte_array))+'sb5sb', 
                           1, file_name_byte_array, 0, b'octet', 0) 

    udpSocket = socket(AF_INET, SOCK_DGRAM)
    udpSocket.sendto(sendData, servAddr)

    newFile = open(file_name, 'wb')
    while True:
        #等待接收数据
        recvInfo = udpSocket.recvfrom(1024) #1024表示本次接受的最大字节数
        transPort = recvInfo[1][1] #传输端口
        data = recvInfo[0] #TFTP数据包的字节流
        len_data = len(data)
        result = struct.unpack("!H", data[:2]) #解包
        opcode = result[0] #获取操作码
        if opcode == 3: #如果操作码是3,说明是DATA包
            result = struct.unpack('!H'+str(len_data-4)+'s', data[2:len_data])
            block = result[0] #获取块编号
            fileStream = result[1] #文件字节流
            newFile.write(fileStream)

            #向服务器发送一个确认包
            ackInfo = struct.pack('!HH', 4, block)
            udpSocket.sendto(ackInfo, (servAddr[0], transPort))
            if len(fileStream) < 512:
                break
        elif opcode == 5: #如果操作码是5,说明是ERROR包
            result = struct.unpack('!H'+str(len_data-5)+'s', data[2:len_data-1])
            print('传输出现异常!')
            print(result[1].decode('gb2312')) #输出错误信息
            break
    newFile.close()
    udpSocket.close()

def main():
    #服务器的IP地址
    serverIP = '192.168.133.135'
    #服务器监听端口,默认是69,这只是用来监听客户端请求的端口,另外还有操作系统随机分配的用来传输文件的端口
    serverPort = 69 
    servAddr = (serverIP, serverPort)
    filename = 'zoro.png'
    download(filename, servAddr)
   
if __name__ == '__main__':
    main()

experiment procedure

Open in a virtual machine tftpd64, select Tftp Server tab, click on the Browse button in the upper right corner, choose a home directory in the future when the download request is received, the program looks for the file download requests in this directory of your choice.
Here Insert Picture Description

Look at the IP address of the virtual machine, the server IP address above Python code into IP address of the virtual machine, run Python code in a real computer.
Here Insert Picture Description
As shown, if any error message does not appear, on the instructions to download the file successfully, the file has been downloaded to the current directory.

extend

During the operation of the code, you can also open the Wireshark , gripping TFTP packets, view the detailed contents.
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/young2415/article/details/91125718