pythonsocketsstructunpacktftp

Struct unpacking a Read Request in TFTP implementation


Regarding the RFC of TFTP (Trivial File Transfer Protocol), the RRQ/WRQ (Read\write requests) packet has this format:

    2 bytes     string    1 byte     string   1 byte
    ------------------------------------------------
    | Opcode |  Filename  |   0  |    Mode    |   0 |
    ------------------------------------------------

Mode can be either "netascii", "octet" (equivalent to binary) or "mail". The thing is netascii is 8 letters, octet has 5 and mail has 4.

I am creating my packet in my client like this:

paq = struct.pack('!H'+str(len(fileName))+'sB'+str(len(mode))+'sB', 02, fileName, 0, mode, 0)

And then I send the packet to the server so the server knows what to expect (A read in case of an RRQ or a write otherwise).

The thing is, I don't know how to unpack the packet if I don't know the string lengths on the server's side... Only the client knows the file length and the mode length, since he makes the packet.

Should I send the lengths to the server before the RRQ/WRQ packet so I know the format to use when unpacking? Is there another way?

Thank you!


Solution

  • If the received packet is in the byte array p, you can search for the 0 delimiters with find().

    opcode = p[0:2].decode('ASCII')
    nameEnd = p.find(b'\0', start=2)
    filename = p[2:nameEnd].decode('ASCII')
    modeEnd = p.find(b'\0', start=nameEnd+1)
    mode = p[nameEnd+1:modeEnd].decode('ASCII')