stringdelphistream

Decoding an old mail protocol called B2F


I am struggling to decode a weird email protocol called B2F: https://www.winlink.org/B2F

What I have to do is this:

Load the entire file, which includes compressed (binary) attachments.

I then have to start reading lines, until I reach an empty line. The is the demarcation between the headers and the body of the message.

Then I have to read X characters (not lines) (where X is a value mentioned in the headers) of the body + an additional LF.

After that last LF, I have to read the binary file into a stream, so I can then decompress it.

Loading into a TStringList does not allow me to locate the position of the binaries. Loading into a TMemoryStream, I am not sure how I can read strings from this, and afterwards know the exact position from where I can copy the binaries into another stream for decompresion.

I also looked at TStringStream but I don't quite understand how that works.

NOTE: All data is in ASCII, not Unicode.

Maybe I am making it too complicated for myself?


Solution

  • A TFileStream or TMemoryStream will suffice. Break up each step into separate operations. Don't try to do everything all at once.

    First, write a function (or use a 3rd party function 1) that reads 1 byte at a time from a TStream until it reaches a [CR]LF terminator, and then returns the read bytes as a String, omitting the terminator.

    1: such as Indy's ReadLnFromStream() function.

    Then, load the file into the TStream.

    Then, call that reading function in a loop, storing each string in a TStringList or other suitable container 2, until a blank string is returned. That's the end of the headers.

    2: such as Indy's TIdHeaderList class.

    Now, find the Body entry in the header list, parse out its count and read the specified number of bytes from the TStream, plus an extra [CR]LF terminator.

    Now, iterate the header list, and for each File entry, parse out its count and read the specified number of bytes from the TStream, plus an extra [CR]LF terminator. Decompress the bytes as needed.