Convert erlang binary pattern match to Elixir

I’m currently working on writing an SFTP server in Elixir, leveraging the OTP ssh daemon and sftp server functionality.

I need to improve my logging, and part of that is deciphering the messages sent via SSH.

Looking at the erlang code, I can see where it is happening in ssh_sftp.erl in handle_data/3 … but I’m sort of stumped when trying to pattern match out the op code/data from the raw binary in Elixir (mainly because I’m a little unfamiliar on where the Len is getting declared in these matches, I know that the ?UINT32 is unsigned-big-integer-32)

In elixir it is msg::binary-size(123) and rest::binary

2 Likes

I always struggle with the conversion from erlang to elixir pattern matching and I never remember where to find the documentation.

I think I’ve used this page in the past:
https://hexdocs.pm/elixir/Kernel.SpecialForms.html

and more specifically this section:

https://hexdocs.pm/elixir/Kernel.SpecialForms.html#<<>>/1

4 Likes

Awesome! Thank you both so much, this definitely helped unlock it for me.

Just to close the loop, this code is working for me. Looks like (based on your link @cmkarlsson), that Len is just a regular variable assigned, specifying the binary length of the message:

        <<message_length::unsigned-integer-32, message::binary-size(message_length),
            _rest::binary>> = raw
    <<op_code, _req_id::unsigned-big-integer-32, data::binary>> = message

Thanks again!

1 Like