Skip to content

Commit

Permalink
Fix 8-bit decoding to preserve line breaks but restore wrapped lines
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewtimberlake committed Aug 23, 2024
1 parent 9141dba commit 07f2d29
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
19 changes: 12 additions & 7 deletions lib/mail/encoders/eight_bit.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,19 @@ defmodule Mail.Encoders.EightBit do
@doc """
Decodes an 8-bit encoded string.
"""
def decode(string), do: do_decode(string, "")
defp do_decode(<<>>, acc), do: acc
def decode(encoded_string), do: do_decode(encoded_string, "", 0)

defp do_decode(<<head, tail::binary>>, acc) do
{decoded, tail} = decode_char(head, tail)
do_decode(tail, acc <> decoded)
defp do_decode(<<>>, acc, _line_length), do: acc

defp do_decode(<<"\r\n", tail::binary>>, acc, 998) do
do_decode(tail, acc, 0)
end

defp do_decode(<<head, tail::binary>>, acc, line_length) do
{decoded, tail, length} = decode_char(head, tail)
do_decode(tail, acc <> decoded, line_length + length)
end

defp decode_char(?\r, <<?\n, tail::binary>>), do: {"", tail}
defp decode_char(char, <<tail::binary>>), do: {<<char>>, tail}
defp decode_char(?\0, _tail), do: raise(ArgumentError, message: "illegal NUL character")
defp decode_char(char, <<tail::binary>>), do: {<<char>>, tail, 1}
end
17 changes: 15 additions & 2 deletions test/mail/encoders/eight_bit_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,21 @@ defmodule Mail.Encoders.EightBitTest do
assert Mail.Encoders.EightBit.decode("") == ""
end

test "decode removes <CR><LF> pairs" do
test "decode preserves <CR><LF> pairs" do
message = "This is a \r\ntest\r\n"
assert Mail.Encoders.EightBit.decode(message) == "This is a test"
assert Mail.Encoders.EightBit.decode(message) == "This is a \r\ntest\r\n"
end

test "decode removes crlf wrapping characters" do
message = String.duplicate("-", 1000)
encoded = Mail.Encoders.EightBit.encode(message)
assert binary_part(encoded, 998, 2) == "\r\n"
assert message == Mail.Encoders.EightBit.decode(encoded)
end

test "decode raises if any character is <NUL>" do
assert_raise ArgumentError, fn ->
Mail.Encoders.EightBit.decode("\0")
end
end
end

0 comments on commit 07f2d29

Please sign in to comment.