Socket response header as hexadecimal format on two digits - swift

I have a TCP socket connection where I am trying to respond to a request message. The specification I have states a response to a request should be in the format of:
Where the header contains the data length in hexadecimal format on two digits. My response data is "202000000000000TEST0_OK ".
As the response is 25 characters long, I assumed the header would be the hex representation of 25, so 0x19. However, when sending this, I'm getting an unknown error back from the device I'm replying to.
Using the BlueSocket library, I'm sending my response using:
if(message.contains("00000000000000001")) {
reply = "202000000000000TEST0_OK "
var header: UInt8 = 0x19
try socket.write(from: Data.init(bytes: &header, count: MemoryLayout<UInt8>.size))
try socket.write(from: reply)
}
Unfortunately, I don't have any further error information. I'm pretty confident my understanding of how to calculate and send the header is incorrect...
Edit: I've also tried the following responses which all failed:
"25XXXXXXXXXXXXXXXXXXXXXXXXX" Started with the decimal length of the data string (25).
"27XXXXXXXXXXXXXXXXXXXXXXXXX" Prepended with the entire length of the data and header string (27).
"19XXXXXXXXXXXXXXXXXXXXXXXXX" Prepended with the hex representation of the length of the data string (25 characters so 0x19).
"1BXXXXXXXXXXXXXXXXXXXXXXXXX" Prepended with the hex representation of the entire length of the data and header string (27 characters so 0x1B).

Related

Set kafka stream header from Int to Array[Byte] conversion

I'm using kafka streams on a project (using Scala) in which I need to include some Headers on the records that I'm sending to a topic. Specifically, a Header requires you to convert the value that you want to put on the Header (in my case Int and Long) to a Array[Byte]. If I try to convert an Int to a Array[Byte] using toByte function, I cannot recover the header from the topic (it appears as null). The only way to do it seems to be to convert it to a String and then use getBytes to store it on the header:
val counter: Int = 1
// counter_1 doesn't appear
context.headers().add("counter_1", Array[Byte](counter.toByte))
// counter_2 doesn't appear
context.headers().add("counter_2", ByteBuffer.allocate(4).putInt(counter).array())
// the value 1 appears on the header counter_3.
context.headers().add("counter_3", String.valueOf(counter).getBytes(StandardCharsets.UTF_8))
It doesn't seem to me that converting an int to a String is the correct way to do it. What's the right way to do it?
I'm recovering the records using the kafkacat command with the %h option. So I would get something like this:
...counter_1=,counter_2=,counter_3=1,....
Any help would be greatly appreciated.
Notice that Kafka Streams sends a stream of bytes without telling the Kafka topic whether these bytes are an Integer, Double, String or other type. Kafka is not aware of sent data type, it just gets some bytes.
When you fetch messages using Kafkacat it assumes the messages are Strings. So if you have sent a String encoded to bytes it is able to display it. However, when you send Integers encoded to bytes - then most likely these integers are converted to bytes representing ASCII codes of unprintable characters and that's why Kafkacat won't display them

javax.mail.Part and writeTo, unable to obtain the same "eml" file as the original one

My application parses many messages via javamail 1.5.6, it listens for incoming messages then store some info about them.
Almost all messages contain a digital signature, so my application needs to retrieve the full eml too, that is the raw file representing an email, in this way application users can always prove the validity of these messages.
So, once I have a javax.mail.Message, then I have to produces its eml, so I do:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
m.writeTo(baos);
this.originalMessage = baos.toString(StandardCharsets.UTF_8.name());
this approach generally works, but I had some multipart messages having part like the following:
This is a multi-part message in MIME format.
--------------55D0DAEBFD4BF19F87D16E72 Content-Type: text/plain; charset=iso-8859-15; format=flowed Content-Transfer-Encoding: 8bit
In allegato si notifica ai sensi e per gli effetti dell'art. 11 R.D.
1611/1993, al messaggio PEC, oltre alla Relata di Notifica e
contestuale attestazione di conformità,
--------------55D0DAEBFD4BF19F87D16E72
word "conformità" is not properly transformed in the resulting string, it becomes "conformit�", opening such eml for example with MS Outlook results in an invalid digital signature, so message appears corrupted, different from the original
Have you same idea? Thank you very much
The raw message is not a UTF-8 encoded string, nor is an "eml" file a UTF-8 encoded file. They are both byte streams, and your digital signature should work on byte streams.
In your particular example, the content of the message part is encoded using the iso-8859-15 charset, not UTF-8.

HTTP multipart/form-data. What happends when binary data has no string representation?

I want to write an HTTP implementation.
I've been looking around for a few days about sending files over HTTP with Content-Type: multipart/form-data, and I'm really interested about how browsers (or any HTTP client) creates that kind of request.
I already took a look at a lots of questions about it here at stackoverflow like:
How does HTTP file upload work?
What does enctype='multipart/form-data' mean?
I dig into RFCs 2616 (and newer versions), 2046, etc. But I didn't find a clear answer (obviously I did not get the idea behind it).At most articles and answers I found this piece of request string, that's is simple to me to interpret, all these things are documented at RFCs...
POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object
... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--
...and it would be simple to implement an HTTP client to construct a piece of string that way in any language.The problem becomes at ... contents of file goes here ..., there's little information about what "contents of file" is. I know it's binary data with a certain type and encoding, but It's difficult to think out of string data, how I would add a piece of binary data that has no string representation inside a string.
I would like to see examples of low level implementations of HTTP protocol with any language. And maybe in depth explanations about binary data transfer over HTTP, how client creates requests and how server read/parse it. PD. I know this question my look a duplicate but most of the answers are not focused on explaining binary data transfer (like media).
You should not try to handle strings on this part of the body, you should send binary data, see it as reading bytes from the resource and sending theses bytes unaltered.
So especially no encoding applied, no utf-8, no base64, HTTP is not a protocol with an ascii7 restriction like smtp, where base64 encoding is applied to ensure only ascii7 characters are used.
There is, by definition, no string version of this data, and looking at raw HTTP transfer (with wireshark for example) you should see binary data, bytes, stuff.
This is why most HTTP servers uses C to manage HTTP, they parse the HTTP communication byte per byte (as the protocol headers are ascii 7 only, certainly not multibytes characters) and they can also read/write arbitrary
binary data for the body quite easily (or even using system calls like readfile to let the kernel manage the binary part).
Now, about examples.
When you use Content-Length and no multipart stuff the body is exactly (content-length) bytes long, so the client parsing your sent data will just read this number of bytes and will treat this whole raw data as the body content (which may have a mime type and and encoding information, but that's just informations for layers set on top of the HTTP protocol).
When you use Transfer-Encoding: chunked, the raw binary body is separated into pieces, each part is then prefixed by an hexadecimal number (the size of the chunk) and the end of line marker. With a final null marker at the end.
If we take the wikipedia example:
4\r\n
Wiki\r\n
5\r\n
pedia\r\n
E\r\n
in\r\n
\r\n
chunks.\r\n
0\r\n
\r\n
We could replace each ascii7 letter by any byte, even a byte that would have no ascii7 representation, Ill use a * character for each real body byte:
4\r\n
****\r\n
5\r\n
*****\r\n
E\r\n
**************\r\n
0\r\n
\r\n
All the other characters are part of the HTTP protocol (here a chunked body transmission). I could also use a \n representation of binary data, and send only the null byte for each byte of the body, that would be:
4\r\n
\0\0\0\0\0\r\n
5\r\n
\0\0\0\0\0\0\r\n
E\r\n
\0\0\0\0\0\0\0\0\0\0\0\0\0\0\r\n
0\r\n
\r\n
That's just a representation, we could also use \xNN or \NN representations, in reality these are bytes, 8 bits (too lazy to write the 0/1 representation of this body :-) ).
If the text of the example, instead of being:
Wikipedia in\r\n
\r\n
chunks.
It could have been a more complex one, with multibytes characters (here a é in utf-8):
Wikipédia in\r\n
\r\n
chunks.
This é is in fact 11000011:10101001 in utf-8, two bytes: \xc3\xa9 in \xNN representation), instead of the simple 01100101 / \x65 / echaracter. The HTTP body is now (see that second chunk size is 6 and not 5):
4\r\n
Wiki\r\n
6\r\n
p\xc3\xa9dia\r\n
E\r\n
in\r\n
\r\n
chunks.\r\n
0\r\n
\r\n
But this is only valid if the source data was effectively in utf-8, could have been another encoding. By default, unless you have some specific configuration settings available in your web server where you enforce a conversion of the source document in a specific encoding, that's not really the job of the web server to convert the source document, you take what you have, and you maybe add an header to tell the client what encoding was defined on the source document.
Finally we have the multipart way of transmitting the body, like in your question, it's a lot like the chunked version, except here boundaries and intermediary headers are used, but for the binary data between these boundaries, headers, and line endings control characters it is the same rule, everything inside are just bytes...

How to make sure that you have read the "full message" when using "Transfer-Encoding:chunked" http response

I am using HttpUrlConnection (java) to read the http chunked response(Transfer-Encoding:chunked) like following and I am able to read the message. But, how can I make sure that I have read all the chunks the correctly and the message read is intact..
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Hey I'm sorry for the late response but, as you might guess, I only just came across your question.
You seem to have a small misunderstanding of what chunked transfer encoding means. It does not mean that the message will be sent in CRLF ended lines. That seems to be what you're trying to implement, but it's a little more complicated than that.
Incase you're not familiar with what a CRLF is, it just means Carriage-Return Line-Feed (or \r\n in traditional Unix escape sequences).
Chunked transfer encoding means that the message will be sent in chunks not lines. Each chunk has a format that is even more self explanatory than a line ending in a CRLF.
How Chunks Work
Each chunk begins with a sequence of characters in the range [0-9, 'a'-'f']. This is a hexadecimal number representing the length, in bytes, of the chunk. This hexadecimal number will be followed by a CRLF. This will be followed by the chunk data (hopefully with the specified length). The chunk data will be ended with another CRLF.
You will get several of these chunks sequentially, and it is your job to concatenate them in the order in which they arrived. You read them in order until you get a special chunk that signals the end of the message body. The only thing special about this last chunk is that it will have a length of zero and contain no data, i.e. the chunk will be 0\r\n\r\n.
Unfortunately Java's HttpURLConnection class only implements automatic chunked transfer encoding, and you have to do the decoding yourself.
Cumbersome as it might be, if you implement this protocol you can be confident about whether you have read the entire message...with one caveat...
You Might Have to Look for Trailers
Trailers are the same as headers except they come at the end of an HTTP message, whereas headers come at the beginning. Chunked transfer encoding will allow you to find the end of a message body but the full HTTP message might continue.
The HttpURLConnection class will not parse trailers for you. The class parses the HTTP head (status line and headers) before directing its socket (or whatever it uses) to the connection's OutputStream. Once the socket is directed toward that OutputStream it doesn't go back. It's up to you to process the data from then on.
Luckily trailers are much more predictable than headers...or at least they are supposed to be. Every trailer the server will send is supposed to be specified in a semicolon separated list in the Trailers header field, i.e. Trailers: Content-disposition; Cache-control; From in the headers means you should look for Content-disposition, Cache-control, and From trailer fields after the message.
Trailers are allowed only in chunked encoded messages, and they follow the same format as headers: field name, colon, space, field value, CRLF. Just like with headers, if a trailer is followed by two CRLF's instead of one that means it was the last trailer.

How to retrieve a IMAP body with the right charset?

I'm trying to make an "IMAP fetch" command to retrieve the message body. I need to pass/use the correct charset, otherwise the response will come with special characters.
How can I make the IMAP request/command to consider the charset I received in the BODYSTRUCTURE result??
The IMAP server will send non-ASCII message body data as an 8-bit "literal", which is essentially an array of bytes. You can't make the FETCH command use a specific charset, as far as I know.
It's up to the IMAP library or your application to decode the byte array into a string representation using the appropriate charset you received in the BODYSTRUCTURE response.