forked from gen-smtp/gen_smtp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmimemail.erl
3606 lines (3464 loc) · 160 KB
/
mimemail.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%% Copyright 2009 Andrew Thompson <andrew@hijacked.us>. All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions are met:
%%%
%%% 1. Redistributions of source code must retain the above copyright notice,
%%% this list of conditions and the following disclaimer.
%%% 2. Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in the
%%% documentation and/or other materials provided with the distribution.
%%%
%%% THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR
%%% IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
%%% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
%%% EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
%%% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
%%% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
%%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
%%% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
%%% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%% @doc A module for decoding/encoding MIME 1.0 email.
%% The encoder and decoder operate on the same data structure, which is as follows:
%% A 5-tuple with the following elements: `{Type, SubType, Headers, Parameters, Body}'.
%%
%% `Type' and `SubType' are the MIME type of the email, examples are `text/plain' or
%% `multipart/alternative'. The decoder splits these into 2 fields so you can filter by
%% the main type or by the subtype.
%%
%% `Headers' consists of a list of key/value pairs of binary values eg.
%% `{<<"From">>, <<"Andrew Thompson <andrew@hijacked.us>">>}'. There is no parsing of
%% the header aside from un-wrapping the lines and splitting the header name from the
%% header value.
%%
%% `Parameters' is a list of 3 key/value tuples. The 3 keys are `<<"content-type-params">>',
%% `<<"disposition">>' and `<<"disposition-params">>'.
%% `content-type-params' is a key/value list of parameters on the content-type header, this
%% usually consists of things like charset and the format parameters. `disposition' indicates
%% how the data wants to be displayed, this is usually 'inline'. `disposition-params' is a list of
%% disposition information, eg. the filename this section should be saved as, the modification
%% date the file should be saved with, etc.
%%
%% Finally, `Body' can be one of several different types, depending on the structure of the email.
%% For a simple email, the body will usually be a binary consisting of the message body, In the
%% case of a multipart email, its a list of these 5-tuple MIME structures. The third possibility,
%% in the case of a message/rfc822 attachment, body can be a single 5-tuple MIME structure.
%%
%% You should see the relevant RFCs (2045, 2046, 2047, etc.) for more information.
%%
%% Note that parts of this module (e.g., `decode/2') use the
%% <a href="https://hex.pm/packages/iconv"><tt>iconv</tt></a> library for string conversion,
%% which you will need to explicitly list as a dependency.
-module(mimemail).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-export([rfc2047_utf8_encode/1]).
-endif.
-export([encode/1, encode/2, decode/2, decode/1, get_header_value/2, get_header_value/3, parse_headers/1]).
-export([encode_quoted_printable/1, decode_quoted_printable/1]).
-export_type([
mimetuple/0,
mime_type/0,
mime_subtype/0,
headers/0,
parameters/0,
options/0,
dkim_options/0
]).
-include_lib("kernel/include/logger.hrl").
-define(LOGGER_META, #{domain => [gen_smtp]}).
-define(DEFAULT_MIME_VERSION, <<"1.0">>).
-define(DEFAULT_OPTIONS, [
% default encoding is utf-8 if we can find the iconv module
{encoding, get_default_encoding()},
% should we decode any base64/quoted printable attachments?
{decode_attachments, true},
% should we assume default mime version
{allow_missing_version, true},
% default mime version
{default_mime_version, ?DEFAULT_MIME_VERSION}
]).
% `<<"text">>'
-type mime_type() :: binary().
% `<<"plain">>'
-type mime_subtype() :: binary().
% `[{<<"Content-Type">>, <<"text/plain">>}]'
-type headers() :: [{binary(), binary()}].
-type parameters() ::
%% <<"7bit">> | <<"base64">> | <<"quoted-printable">> etc
#{
transfer_encoding => binary(),
%% [{<<"charset">>, <<"utf-8">>} | {<<"boundary">>, binary()} | {<<"name">>, binary()} etc...]
content_type_params => [{binary(), binary()}],
%% <<"inline">> | <<"attachment">> etc...
disposition => binary(),
%% [{<<"filename">>, binary()}, ]
disposition_params => [{binary(), binary()}]
}.
-type mimetuple() :: {
mime_type(),
mime_subtype(),
headers(),
parameters(),
Body :: binary() | mimetuple() | [mimetuple()]
}.
-type dkim_priv_key() ::
{pem_plain, binary()}
| {pem_encrypted, Key :: binary(), Passwd :: string()}.
-type dkim_options() :: [
{h, [binary()]}
| {d, binary()}
| {s, binary()}
| {t, now | calendar:datetime()}
| {x, calendar:datetime()}
| {c, {simple | relaxed, simple | relaxed}}
| {a, 'rsa-sha256' | 'ed25519-sha256'}
| {private_key, dkim_priv_key()}
].
-type options() :: [
{encoding, binary()}
| {decode_attachment, boolean()}
| {dkim, dkim_options()}
| {allow_missing_version, boolean()}
| {default_mime_version, binary()}
].
-spec decode(Email :: binary()) -> mimetuple().
%% @doc Decode a MIME email from a binary.
decode(All) ->
{Headers, Body} = parse_headers(All),
decode(Headers, Body, ?DEFAULT_OPTIONS).
-spec decode(Email :: binary(), Options :: options()) -> mimetuple().
%% @doc Decode with custom options
decode(All, Options) when is_binary(All), is_list(Options) ->
{Headers, Body} = parse_headers(All),
decode(Headers, Body, Options).
decode(OrigHeaders, Body, Options) ->
?LOG_DEBUG("headers: ~p", [OrigHeaders], ?LOGGER_META),
Encoding = proplists:get_value(encoding, Options, none),
%FixedHeaders = fix_headers(Headers),
Headers = decode_headers(OrigHeaders, [], Encoding),
case parse_with_comments(get_header_value(<<"MIME-Version">>, Headers)) of
undefined ->
AllowMissingVersion = proplists:get_value(allow_missing_version, Options, false),
case parse_content_type(get_header_value(<<"Content-Type">>, Headers)) of
{<<"multipart">>, _SubType, _Parameters} when AllowMissingVersion ->
MimeVersion = proplists:get_value(default_mime_version, Options, ?DEFAULT_MIME_VERSION),
decode_component(Headers, Body, MimeVersion, Options);
{<<"multipart">>, _SubType, _Parameters} ->
erlang:error(non_mime_multipart);
{Type, SubType, CTParameters} ->
NewBody = decode_body(
get_header_value(<<"Content-Transfer-Encoding">>, Headers),
Body,
proplists:get_value(<<"charset">>, CTParameters),
Encoding
),
{Disposition, DispositionParams} =
case parse_content_disposition(get_header_value(<<"Content-Disposition">>, Headers)) of
undefined ->
{<<"inline">>, []};
Disp ->
Disp
end,
Parameters = #{
content_type_params => CTParameters,
disposition => Disposition,
disposition_params => DispositionParams
},
{Type, SubType, Headers, Parameters, NewBody};
undefined ->
Parameters = #{
content_type_params => [{<<"charset">>, <<"us-ascii">>}],
disposition => <<"inline">>,
disposition_params => []
},
{<<"text">>, <<"plain">>, Headers, Parameters,
decode_body(get_header_value(<<"Content-Transfer-Encoding">>, Headers), Body)}
end;
Other ->
decode_component(Headers, Body, Other, Options)
end.
-spec encode(MimeMail :: mimetuple()) -> binary().
encode(MimeMail) ->
encode(MimeMail, []).
%% @doc Encode a MIME tuple to a binary.
encode({Type, Subtype, Headers, ContentTypeParams, Parts}, Options) ->
{FixedParams, FixedHeaders} = ensure_content_headers(Type, Subtype, ContentTypeParams, Headers, Parts, true),
CheckedHeaders = check_headers(FixedHeaders),
EncodedBody = binstr:join(
encode_component(Type, Subtype, CheckedHeaders, FixedParams, Parts),
"\r\n"
),
EncodedHeaders = encode_headers(CheckedHeaders),
SignedHeaders =
case proplists:get_value(dkim, Options) of
undefined -> EncodedHeaders;
DKIM -> dkim_sign_email(EncodedHeaders, EncodedBody, DKIM)
end,
list_to_binary([
binstr:join(SignedHeaders, "\r\n"),
"\r\n\r\n",
EncodedBody
]);
encode(_, _) ->
?LOG_DEBUG("Not a mime-decoded DATA", ?LOGGER_META),
erlang:error(non_mime).
decode_headers(Headers, _, none) ->
Headers;
decode_headers([], Acc, _Charset) ->
lists:reverse(Acc);
decode_headers([{Key, Value} | Headers], Acc, Charset) ->
decode_headers(Headers, [{Key, decode_header(Value, Charset)} | Acc], Charset).
decode_header(Value, Charset) ->
RTokens = tokenize_header(Value, []),
Tokens = lists:reverse(RTokens),
Decoded =
try
decode_header_tokens_strict(Tokens, Charset)
catch
Type:Reason:Stacktrace ->
case decode_header_tokens_permissive(Tokens, Charset, []) of
{ok, Dec} ->
Dec;
error ->
% re-throw original error
erlang:raise(Type, Reason, Stacktrace)
end
end,
iolist_to_binary(Decoded).
-type hdr_token() :: binary() | {Encoding :: binary(), Data :: binary()}.
-spec tokenize_header(binary(), [hdr_token()]) -> [hdr_token()].
tokenize_header(<<>>, Acc) ->
Acc;
tokenize_header(Value, Acc) ->
%% maybe replace "?([^\s]+)\\?" with "?([^\s]*)\\?"?
%% see msg lvuvmm593b8s7pqqfhu7cdtqd4g4najh
%% Subject: =?utf-8?Q??=
%% =?utf-8?Q?=D0=9F=D0=BE=D0=B4=D1=82=D0=B2=D0=B5=D1=80=D0=B4=D0=B8=D1=82=D0=B5=20?=
%% =?utf-8?Q?=D1=80=D0=B5=D0=B3=D0=B8=D1=81=D1=82=D1=80=D0=B0=D1=86=D0=B8=D1=8E=20?=
%% =?utf-8?Q?=D0=B2=20Moy-Rebenok.ru?=
case re:run(Value, "=\\?([-A-Za-z0-9_]+)\\?([qQbB])\\?([^\s]+)\\?=", [ungreedy]) of
nomatch ->
[Value | Acc];
{match, [{AllStart, AllLen}, {EncodingStart, EncodingLen}, {TypeStart, _}, {DataStart, DataLen}]} ->
%% RFC 2047 #2 (encoded-word)
Encoding = binstr:substr(Value, EncodingStart + 1, EncodingLen),
Type = binstr:to_lower(binstr:substr(Value, TypeStart + 1, 1)),
Data = binstr:substr(Value, DataStart + 1, DataLen),
EncodedData =
case Type of
<<"q">> ->
%% RFC 2047 #5. (3)
decode_quoted_printable(binary:replace(Data, <<"_">>, <<"=20">>, [global]));
<<"b">> ->
decode_base64(binary:replace(Data, <<"_">>, <<" ">>, [global]))
end,
Offset =
case
re:run(
binstr:substr(Value, AllStart + AllLen + 1),
"^([\s\t\n\r]+)=\\?[-A-Za-z0-9_]+\\?[^\s]\\?[^\s]+\\?=",
[ungreedy]
)
of
nomatch ->
% no 2047 block immediately following
1;
{match, [{_, _}, {_, WhiteSpaceLen}]} ->
1 + WhiteSpaceLen
end,
NewAcc =
case binstr:substr(Value, 1, AllStart) of
<<>> -> [{fix_encoding(Encoding), EncodedData} | Acc];
Other -> [{fix_encoding(Encoding), EncodedData}, Other | Acc]
end,
tokenize_header(binstr:substr(Value, AllStart + AllLen + Offset), NewAcc)
end.
decode_header_tokens_strict([], _) ->
[];
decode_header_tokens_strict([{Encoding, Data} | Tokens], Charset) ->
{ok, S} = convert(Charset, Encoding, Data),
[S | decode_header_tokens_strict(Tokens, Charset)];
decode_header_tokens_strict([Data | Tokens], Charset) ->
[Data | decode_header_tokens_strict(Tokens, Charset)].
%% this decoder can handle folded not-by-RFC UTF headers, when somebody split
%% multibyte string not by characters, but by bytes. It first join folded
%% string and only then decode it with iconv.
decode_header_tokens_permissive([], _, [Result]) when is_binary(Result) ->
{ok, Result};
decode_header_tokens_permissive([], _, Stack) ->
case lists:all(fun erlang:is_binary/1, Stack) of
true -> {ok, lists:reverse(Stack)};
false -> error
end;
decode_header_tokens_permissive([{Enc, Data} | Tokens], Charset, [{Enc, PrevData} | Stack]) ->
NewData = iolist_to_binary([PrevData, Data]),
{ok, S} = convert(Charset, Enc, NewData),
decode_header_tokens_permissive(Tokens, Charset, [S | Stack]);
decode_header_tokens_permissive([NextToken | _] = Tokens, Charset, [{_, _} | Stack]) when
is_binary(NextToken) orelse is_tuple(NextToken)
->
%% practically very rare case "=?utf-8?Q?BROKEN?=\r\n\t=?windows-1251?Q?maybe-broken?="
%% or "=?utf-8?Q?BROKEN?= raw-ascii-string"
%% drop broken value from stack
decode_header_tokens_permissive(Tokens, Charset, Stack);
decode_header_tokens_permissive([Data | Tokens], Charset, Stack) ->
decode_header_tokens_permissive(Tokens, Charset, [Data | Stack]).
%% x-binaryenc is not a real encoding and is not used for text, so let it pass through
convert(_To, <<"x-binaryenc">>, Data) ->
{ok, Data};
convert(To, From, Data) ->
Result = iconv:convert(From, To, Data),
{ok, Result}.
decode_component(Headers, Body, MimeVsn = <<"1.0", _/binary>>, Options) ->
case parse_content_disposition(get_header_value(<<"Content-Disposition">>, Headers)) of
{Disposition, DispositionParams} ->
ok;
% defaults
_ ->
Disposition = <<"inline">>,
DispositionParams = []
end,
case parse_content_type(get_header_value(<<"Content-Type">>, Headers)) of
{<<"multipart">>, SubType, Parameters} ->
case proplists:get_value(<<"boundary">>, Parameters) of
undefined ->
erlang:error(no_boundary);
Boundary ->
?LOG_DEBUG(
"this is a multipart email of type: ~s and boundary ~s", [SubType, Boundary], ?LOGGER_META
),
Parameters2 = #{
content_type_params => Parameters,
disposition => Disposition,
disposition_params => DispositionParams
},
{<<"multipart">>, SubType, Headers, Parameters2,
split_body_by_boundary(Body, list_to_binary(["--", Boundary]), MimeVsn, Options)}
end;
{<<"message">>, <<"rfc822">>, Parameters} ->
{NewHeaders, NewBody} = parse_headers(Body),
Parameters2 = #{
content_type_params => Parameters,
disposition => Disposition,
disposition_params => DispositionParams
},
{<<"message">>, <<"rfc822">>, Headers, Parameters2, decode(NewHeaders, NewBody, Options)};
{Type, SubType, Parameters} ->
?LOG_DEBUG("body is ~s/~s", [Type, SubType], ?LOGGER_META),
Parameters2 = #{
content_type_params => Parameters,
disposition => Disposition,
disposition_params => DispositionParams
},
{Type, SubType, Headers, Parameters2,
decode_body(
get_header_value(<<"Content-Transfer-Encoding">>, Headers),
Body,
proplists:get_value(<<"charset">>, Parameters),
proplists:get_value(encoding, Options, none)
)};
% defaults
undefined ->
Type = <<"text">>,
SubType = <<"plain">>,
Parameters = #{
content_type_params => [{<<"charset">>, <<"us-ascii">>}],
disposition => Disposition,
disposition_params => DispositionParams
},
{Type, SubType, Headers, Parameters,
decode_body(get_header_value(<<"Content-Transfer-Encoding">>, Headers), Body)}
end;
decode_component(_Headers, _Body, Other, _Options) ->
erlang:error({mime_version, Other}).
-spec get_header_value(Needle :: binary(), Headers :: [{binary(), binary()}], Default :: any()) -> binary() | any().
%% @doc Do a case-insensitive header lookup to return that header's value, or the specified default.
get_header_value(Needle, Headers, Default) ->
?LOG_DEBUG("Headers: ~p", [Headers], ?LOGGER_META),
NeedleLower = binstr:to_lower(Needle),
F =
fun({Header, _Value}) ->
binstr:to_lower(Header) =:= NeedleLower
end,
case lists:search(F, Headers) of
% TODO if there's duplicate headers, should we use the first or the last?
{value, {_Header, Value}} ->
Value;
false ->
Default
end.
-spec get_header_value(Needle :: binary(), Headers :: [{binary(), binary()}]) -> binary() | 'undefined'.
%% @doc Do a case-insensitive header lookup to return the header's value, or `undefined'.
get_header_value(Needle, Headers) ->
get_header_value(Needle, Headers, undefined).
-spec parse_with_comments
(Value :: binary()) -> binary() | no_return();
(Value :: atom()) -> atom().
parse_with_comments(Value) when is_binary(Value) ->
parse_with_comments(Value, [], 0, false);
parse_with_comments(Value) ->
Value.
-spec parse_with_comments(Value :: binary(), Acc :: list(), Depth :: non_neg_integer(), Quotes :: boolean()) ->
binary() | no_return().
parse_with_comments(<<>>, _Acc, _Depth, Quotes) when Quotes ->
erlang:error(unterminated_quotes);
parse_with_comments(<<>>, _Acc, Depth, _Quotes) when Depth > 0 ->
erlang:error(unterminated_comment);
parse_with_comments(<<>>, Acc, _Depth, _Quotes) ->
binstr:strip(list_to_binary(lists:reverse(Acc)));
parse_with_comments(<<$\\, H, Tail/binary>>, Acc, Depth, Quotes) when Depth > 0, H > 32, H < 127 ->
parse_with_comments(Tail, Acc, Depth, Quotes);
parse_with_comments(<<$\\, Tail/binary>>, Acc, Depth, Quotes) when Depth > 0 ->
parse_with_comments(Tail, Acc, Depth, Quotes);
parse_with_comments(<<$\\, H, Tail/binary>>, Acc, Depth, Quotes) when H > 32, H < 127 ->
parse_with_comments(Tail, [H | Acc], Depth, Quotes);
parse_with_comments(<<$\\, Tail/binary>>, Acc, Depth, Quotes) ->
parse_with_comments(Tail, [$\\ | Acc], Depth, Quotes);
parse_with_comments(<<$(, Tail/binary>>, Acc, Depth, Quotes) when not Quotes ->
parse_with_comments(Tail, Acc, Depth + 1, Quotes);
parse_with_comments(<<$), Tail/binary>>, Acc, Depth, Quotes) when Depth > 0, not Quotes ->
parse_with_comments(Tail, Acc, Depth - 1, Quotes);
parse_with_comments(<<_, Tail/binary>>, Acc, Depth, Quotes) when Depth > 0 ->
parse_with_comments(Tail, Acc, Depth, Quotes);
%"
parse_with_comments(<<$", T/binary>>, Acc, Depth, true) ->
parse_with_comments(T, Acc, Depth, false);
%"
parse_with_comments(<<$", T/binary>>, Acc, Depth, false) ->
parse_with_comments(T, Acc, Depth, true);
parse_with_comments(<<H, Tail/binary>>, Acc, Depth, Quotes) ->
parse_with_comments(Tail, [H | Acc], Depth, Quotes).
-spec parse_content_type
(Value :: 'undefined') -> 'undefined';
(Value :: binary()) -> {binary(), binary(), [{binary(), binary()}]}.
parse_content_type(undefined) ->
undefined;
parse_content_type(String) ->
try parse_content_disposition(String) of
{RawType, Parameters} ->
case binstr:strchr(RawType, $/) of
Index when Index < 2 ->
throw(bad_content_type);
Index ->
Type = binstr:substr(RawType, 1, Index - 1),
SubType = binstr:substr(RawType, Index + 1),
{binstr:to_lower(Type), binstr:to_lower(SubType), Parameters}
end
catch
bad_disposition ->
throw(bad_content_type)
end.
-spec parse_content_disposition
(Value :: 'undefined') -> 'undefined';
(String :: binary()) -> {binary(), [{binary(), binary()}]}.
parse_content_disposition(undefined) ->
undefined;
parse_content_disposition(String) ->
[Disposition | Parameters] = binstr:split(parse_with_comments(String), <<";">>),
F =
fun(X) ->
Y = binstr:strip(binstr:strip(X), both, $\t),
case binstr:strchr(Y, $=) of
Index when Index < 2 ->
throw(bad_disposition);
Index ->
Key = binstr:substr(Y, 1, Index - 1),
Value = binstr:substr(Y, Index + 1),
{binstr:to_lower(Key), Value}
end
end,
Params = lists:map(F, Parameters),
{binstr:to_lower(Disposition), Params}.
split_body_by_boundary(Body, Boundary, MimeVsn, Options) ->
% find the indices of the first and last boundary
case {binstr:strpos(Body, Boundary), binstr:strpos(Body, list_to_binary([Boundary, "--"]))} of
{0, _} ->
erlang:error(missing_boundary);
{_, 0} ->
erlang:error(missing_last_boundary);
{Start, End} ->
NewBody = binstr:substr(Body, Start + byte_size(Boundary), End - Start),
% from now on, we can be sure that each boundary is preceded by a CRLF
Parts = split_body_by_boundary_(NewBody, list_to_binary(["\r\n", Boundary]), [], Options),
[
decode_component(Headers, Body2, MimeVsn, Options)
|| {Headers, Body2} <- [V || {_, Body3} = V <- Parts, byte_size(Body3) =/= 0]
]
end.
split_body_by_boundary_(<<>>, _Boundary, Acc, _Options) ->
lists:reverse(Acc);
split_body_by_boundary_(Body, Boundary, Acc, Options) ->
% trim the incomplete first line
TrimmedBody = binstr:substr(Body, binstr:strpos(Body, "\r\n") + 2),
case binstr:strpos(TrimmedBody, Boundary) of
0 ->
lists:reverse([{[], TrimmedBody} | Acc]);
Index ->
{ParsedHdrs, BodyRest} = parse_headers(binstr:substr(TrimmedBody, 1, Index - 1)),
DecodedHdrs = decode_headers(ParsedHdrs, [], proplists:get_value(encoding, Options, none)),
split_body_by_boundary_(
binstr:substr(TrimmedBody, Index + byte_size(Boundary)),
Boundary,
[{DecodedHdrs, BodyRest} | Acc],
Options
)
end.
-spec parse_headers(Body :: binary()) -> {[{binary(), binary()}], binary()}.
%% @doc Parse the headers off of a message and return a list of headers and the trailing body.
parse_headers(Body) ->
case binstr:strpos(Body, "\r\n") of
0 ->
{[], Body};
1 ->
{[], binstr:substr(Body, 3)};
Index ->
parse_headers(binstr:substr(Body, Index + 2), binstr:substr(Body, 1, Index - 1), [])
end.
parse_headers(Body, <<H, Tail/binary>>, []) when H =:= $\s; H =:= $\t ->
% folded headers
{[], list_to_binary([H, Tail, "\r\n", Body])};
parse_headers(Body, <<H, T/binary>>, Headers) when H =:= $\s; H =:= $\t ->
% folded headers
[{FieldName, OldFieldValue} | OtherHeaders] = Headers,
FieldValue = list_to_binary([OldFieldValue, T]),
?LOG_DEBUG("~p = ~p", [FieldName, FieldValue], ?LOGGER_META),
case binstr:strpos(Body, "\r\n") of
0 ->
{lists:reverse([{FieldName, FieldValue} | OtherHeaders]), Body};
1 ->
{lists:reverse([{FieldName, FieldValue} | OtherHeaders]), binstr:substr(Body, 3)};
Index2 ->
parse_headers(binstr:substr(Body, Index2 + 2), binstr:substr(Body, 1, Index2 - 1), [
{FieldName, FieldValue} | OtherHeaders
])
end;
parse_headers(Body, Line, Headers) ->
?LOG_DEBUG("line: ~p", [Line], ?LOGGER_META),
case binstr:strchr(Line, $:) of
0 ->
{lists:reverse(Headers), list_to_binary([Line, "\r\n", Body])};
Index ->
FieldName = binstr:substr(Line, 1, Index - 1),
F = fun(X) -> X > 32 andalso X < 127 end,
case binstr:all(F, FieldName) of
true ->
F2 = fun(X) -> (X > 31 andalso X < 127) orelse X == 9 end,
FValue = binstr:strip(binstr:substr(Line, Index + 1)),
FieldValue =
case binstr:all(F2, FValue) of
true ->
FValue;
_ ->
% I couldn't figure out how to use a pure binary comprehension here :(
list_to_binary([filter_non_ascii(C) || <<C:8>> <= FValue])
end,
case binstr:strpos(Body, "\r\n") of
0 ->
{lists:reverse([{FieldName, FieldValue} | Headers]), Body};
1 ->
{lists:reverse([{FieldName, FieldValue} | Headers]), binstr:substr(Body, 3)};
Index2 ->
parse_headers(binstr:substr(Body, Index2 + 2), binstr:substr(Body, 1, Index2 - 1), [
{FieldName, FieldValue} | Headers
])
end;
false ->
{lists:reverse(Headers), list_to_binary([Line, "\r\n", Body])}
end
end.
filter_non_ascii(C) when (C > 31 andalso C < 127); C == 9 ->
<<C>>;
filter_non_ascii(_C) ->
<<"?">>.
decode_body(Type, Body, _InEncoding, none) ->
decode_body(Type, <<<<X/integer>> || <<X>> <= Body, X < 128>>);
decode_body(Type, Body, undefined, _OutEncoding) ->
decode_body(Type, <<<<X/integer>> || <<X>> <= Body, X < 128>>);
decode_body(Type, Body, <<"x-binaryenc">>, _OutEncoding) ->
% Not IANA and does not represent text, so we pass it through
decode_body(Type, Body);
decode_body(Type, Body, InEncoding, OutEncoding) ->
NewBody = decode_body(Type, Body),
InEncodingFixed = fix_encoding(InEncoding),
{ok, ConvertedBody} = convert(OutEncoding, InEncodingFixed, NewBody),
ConvertedBody.
-spec decode_body(Type :: binary() | 'undefined', Body :: binary()) -> binary().
decode_body(undefined, Body) ->
Body;
decode_body(Type, Body) ->
case binstr:to_lower(Type) of
<<"quoted-printable">> ->
decode_quoted_printable(Body);
<<"base64">> ->
decode_base64(Body);
_Other ->
Body
end.
decode_base64(Body) ->
base64:mime_decode(Body).
decode_quoted_printable(Body) ->
decode_quoted_printable(Body, false, <<>>, <<>>).
%% End of Body
decode_quoted_printable(<<>>, _HasSoftEOL, _WSPs, Acc) ->
Acc;
%% CRLF after Soft Linebreak
decode_quoted_printable(<<$\r, $\n, More/binary>>, true, _WSPs, Acc) ->
decode_quoted_printable(More, false, <<>>, Acc);
%% Space or Tab after Soft Linebreak
decode_quoted_printable(<<C, More/binary>>, true, _WSPs, Acc) when C =:= $\s; C =:= $\t ->
decode_quoted_printable(More, true, <<>>, Acc);
%% Other character after Soft Linebreak
decode_quoted_printable(_Body, true, _WSPs, _Acc) ->
throw(badchar);
%% CRLF
decode_quoted_printable(<<$\r, $\n, More/binary>>, false, _WSPs, Acc) ->
decode_quoted_printable(More, false, <<>>, <<Acc/binary, $\r, $\n>>);
%% Space or Tab
decode_quoted_printable(<<C, More/binary>>, false, WSPs, Acc) when C =:= $\s; C =:= $\t ->
decode_quoted_printable(More, false, <<WSPs/binary, C>>, Acc);
%% Encoded char
decode_quoted_printable(<<$=, C1, C2, More/binary>>, false, WSPs, Acc) when
C1 >= $0 andalso C1 =< $9 orelse C1 >= $A andalso C1 =< $F orelse C1 >= $a andalso C1 =< $f,
C2 >= $0 andalso C2 =< $9 orelse C2 >= $A andalso C2 =< $F orelse C2 >= $a andalso C2 =< $f
->
decode_quoted_printable(More, false, <<>>, <<Acc/binary, WSPs/binary, (unhex(C1)):4, (unhex(C2)):4>>);
%% Soft Linebreak
decode_quoted_printable(<<$=, More/binary>>, false, WSPs, Acc) ->
decode_quoted_printable(More, true, <<>>, <<Acc/binary, WSPs/binary>>);
%% Plain character
decode_quoted_printable(<<C, More/binary>>, false, WSPs, Acc) ->
decode_quoted_printable(More, false, <<>>, <<Acc/binary, WSPs/binary, C>>).
check_headers(Headers) ->
Checked = [<<"MIME-Version">>, <<"Date">>, <<"From">>, <<"Message-ID">>, <<"References">>, <<"Subject">>],
check_headers(Checked, lists:reverse(Headers)).
check_headers([], Headers) ->
lists:reverse(Headers);
check_headers([Header | Tail], Headers) ->
case get_header_value(Header, Headers) of
undefined when Header == <<"MIME-Version">> ->
check_headers(Tail, [{<<"MIME-Version">>, <<"1.0">>} | Headers]);
undefined when Header == <<"Date">> ->
check_headers(Tail, [{<<"Date">>, list_to_binary(smtp_util:rfc5322_timestamp())} | Headers]);
undefined when Header == <<"From">> ->
erlang:error(missing_from);
undefined when Header == <<"Message-ID">> ->
check_headers(Tail, [{<<"Message-ID">>, list_to_binary(smtp_util:generate_message_id())} | Headers]);
undefined when Header == <<"References">> ->
case get_header_value(<<"In-Reply-To">>, Headers) of
undefined ->
% ok, whatever
check_headers(Tail, Headers);
ReplyID ->
check_headers(Tail, [{<<"References">>, ReplyID} | Headers])
end;
References when Header == <<"References">> ->
% check if the in-reply-to header, if present, is in references
case get_header_value(<<"In-Reply-To">>, Headers) of
undefined ->
% ok, whatever
check_headers(Tail, Headers);
ReplyID ->
case binstr:strpos(binstr:to_lower(References), binstr:to_lower(ReplyID)) of
0 ->
% okay, tack on the reply-to to the end of References
check_headers(Tail, [
{<<"References">>, list_to_binary([References, " ", ReplyID])}
| proplists:delete(<<"References">>, Headers)
]);
_Index ->
% nothing to do
check_headers(Tail, Headers)
end
end;
_ ->
check_headers(Tail, Headers)
end.
ensure_content_headers(Type, SubType, Parameters, Headers, Body, Toplevel) ->
CheckHeaders = [<<"Content-Type">>, <<"Content-Disposition">>, <<"Content-Transfer-Encoding">>],
CheckHeadersValues = [{Name, get_header_value(Name, Headers)} || Name <- CheckHeaders],
ensure_content_headers(CheckHeadersValues, Type, SubType, Parameters, lists:reverse(Headers), Body, Toplevel).
ensure_content_headers([], _, _, Parameters, Headers, _, _) ->
{Parameters, lists:reverse(Headers)};
ensure_content_headers(
[{<<"Content-Type">>, undefined} | Tail], Type, SubType, Parameters, Headers, Body, Toplevel
) when
(Type == <<"text">> andalso SubType =/= <<"plain">>) orelse Type =/= <<"text">>
->
%% no content-type header, and its not text/plain
CT = io_lib:format("~s/~s", [Type, SubType]),
CTP =
case Type of
<<"multipart">> ->
Boundary =
case proplists:get_value(<<"boundary">>, maps:get(content_type_params, Parameters, [])) of
undefined ->
list_to_binary(smtp_util:generate_message_boundary());
B ->
B
end,
[
{<<"boundary">>, Boundary}
| proplists:delete(<<"boundary">>, maps:get(content_type_params, Parameters, []))
];
<<"text">> ->
Charset =
case proplists:get_value(<<"charset">>, maps:get(content_type_params, Parameters, [])) of
undefined ->
guess_charset(Body);
C ->
C
end,
[
{<<"charset">>, Charset}
| proplists:delete(<<"charset">>, maps:get(content_type_params, Parameters, []))
];
_ ->
maps:get(content_type_params, Parameters, [])
end,
%%CTP = proplists:get_value(<<"content-type-params">>, Parameters, [guess_charset(Body)]),
CTH = binstr:join([CT | encode_parameters(CTP)], ";"),
NewParameters = Parameters#{content_type_params => CTP},
ensure_content_headers(Tail, Type, SubType, NewParameters, [{<<"Content-Type">>, CTH} | Headers], Body, Toplevel);
ensure_content_headers(
[{<<"Content-Type">>, undefined} | Tail],
<<"text">> = Type,
<<"plain">> = SubType,
Parameters,
Headers,
Body,
Toplevel
) ->
%% no content-type header and its text/plain
Charset =
case proplists:get_value(<<"charset">>, maps:get(content_type_params, Parameters, [])) of
undefined ->
guess_charset(Body);
C ->
binstr:to_lower(C)
end,
case Charset of
<<"us-ascii">> ->
% the default
ensure_content_headers(Tail, Type, SubType, Parameters, Headers, Body, Toplevel);
_ ->
CTP = [
{<<"charset">>, Charset}
| proplists:delete(<<"charset">>, maps:get(content_type_params, Parameters, []))
],
CTH = binstr:join([<<"text/plain">> | encode_parameters(CTP)], ";"),
NewParameters = Parameters#{content_type_params => CTP},
ensure_content_headers(
Tail, Type, SubType, NewParameters, [{<<"Content-Type">>, CTH} | Headers], Body, Toplevel
)
end;
ensure_content_headers(
[{<<"Content-Transfer-Encoding">>, undefined} | Tail], Type, SubType, Parameters, Headers, Body, Toplevel
) when
Type =/= <<"multipart">>
->
Enc =
case maps:get(transfer_encoding, Parameters, undefined) of
undefined ->
guess_best_encoding(Body);
Value ->
Value
end,
case Enc of
<<"7bit">> ->
ensure_content_headers(Tail, Type, SubType, Parameters, Headers, Body, Toplevel);
_ ->
ensure_content_headers(
Tail, Type, SubType, Parameters, [{<<"Content-Transfer-Encoding">>, Enc} | Headers], Body, Toplevel
)
end;
ensure_content_headers(
[{<<"Content-Disposition">>, undefined} | Tail], Type, SubType, Parameters, Headers, Body, false = Toplevel
) ->
CD = maps:get(disposition, Parameters, <<"inline">>),
CDP = maps:get(disposition_params, Parameters, []),
CDH = binstr:join([CD | encode_parameters(CDP)], ";"),
ensure_content_headers(
Tail, Type, SubType, Parameters, [{<<"Content-Disposition">>, CDH} | Headers], Body, Toplevel
);
ensure_content_headers([_ | Tail], Type, SubType, Parameters, Headers, Body, Toplevel) ->
ensure_content_headers(Tail, Type, SubType, Parameters, Headers, Body, Toplevel).
guess_charset(Body) ->
case binstr:all(fun(X) -> X < 128 end, Body) of
true -> <<"us-ascii">>;
false -> <<"utf-8">>
end.
guess_best_encoding(Body) ->
case valid_7bit(Body) of
true ->
<<"7bit">>;
false ->
choose_transformation(Body)
end.
choose_transformation(<<Chunk:200/binary, _, _/binary>>) ->
%% Optimization - only analyze 1st 200 bytes
choose_transformation(Chunk);
choose_transformation(Body) ->
{Readable, Encoded} = partition_count_bytes(
fun(C) ->
C >= 16#20 andalso C =< 16#7E orelse C =:= $\r orelse C =:= $\n
end,
Body
),
%based on the % of printable characters, choose an encoding
if
% same as 100 * Readable / (Readable + Encoded) >= 80, but avoiding division
Readable >= 4 * Encoded ->
%% >80% printable characters
<<"quoted-printable">>;
true ->
%% =<80% printable characters
<<"base64">>
end.
%% https://tools.ietf.org/html/rfc2045#section-2.7:
%% * ASCII codes from 1 to 127
%% * \r and \n are only allowed as `\r\n' pair, but not standalone (bare)
%% * No lines over 998 chars
%%
%% Unfortunately, any string that ends with `\n` matches the regexp, so, we need some pre-checks
valid_7bit(<<"\n">>) ->
false;
valid_7bit(<<"\r">>) ->
false;
valid_7bit(<<>>) ->
true;
valid_7bit(<<_>>) ->
true;
valid_7bit(Body) ->
Size = byte_size(Body),
case binary:at(Body, Size - 1) =:= $\n andalso binary:at(Body, Size - 2) =/= $\r of
true ->
%% last element is \n, but the one before the last is not \r
false;
false ->
%% So: (all except `\r` and `\n` in 1-127 range) OR (`\r\n`)
case re:run(Body, "^([\x01-\x09\x0b-\x0c\x0e-\x7f]|(\r\n))*$", [{capture, none}]) of
match -> not has_lines_over_998(Body);
nomatch -> false
end
end.
%% @doc If `Body' has at least one line (ending with `\r\n') that is longer than 998 chars
has_lines_over_998(Body) ->
Pattern = binary:compile_pattern(<<"\r\n">>),
has_lines_over_998(Body, binary:match(Body, Pattern), 0, Pattern).
has_lines_over_998(Bin, nomatch, Offset, _) ->
%% Last line is over 998?
(byte_size(Bin) - Offset) >= 998;
has_lines_over_998(_Bin, {FoundAt, 2}, Offset, _Patern) when (FoundAt - Offset) >= 998 ->
true;
has_lines_over_998(Bin, {FoundAt, 2}, _, Pattern) ->
NewOffset = FoundAt + 2,
Len = byte_size(Bin) - NewOffset,
has_lines_over_998(
Bin, binary:match(Bin, Pattern, [{scope, {NewOffset, Len}}]), NewOffset, Pattern
).
-spec encode_parameters([{Name :: binary(), Value :: binary()}]) -> [Parameter :: binary()].
encode_parameters([[]]) ->
[];
encode_parameters(Parameters) ->
lists:foldr(
fun({Name, Value}, Acc) ->
{Method, EncLen} = decide_param_encoding_method(Value),
EncParams = encode_parameter(Method, Name, Value, EncLen),
EncParams ++ Acc
end,
[],
Parameters
).
%% Encode a parameter value according to the determined representation
%% (see decide_param_encoding_method/1).
%%
%% If necessary, ie when lines would become longer than 76 characters
%% (leaving room for the leading continuation WSP and the ending semicolon),
%% the values are folded following the schema described in RFC2231 section 3.
-spec encode_parameter(
Method :: (plain | quote | encode | encode_utf8), Name :: binary(), Value :: binary(), EncLen :: non_neg_integer()
) -> [ChunkParameter :: binary()].
encode_parameter(Method, Name, Value, EncLen) ->
encode_parameter(Method, Name, 0, Value, EncLen, []).
encode_parameter(_Method, _Name, _Index, <<>>, _EncLen, Acc) ->
lists:reverse(Acc);
encode_parameter(encode_utf8, Name, 0, Value, EncLen, _Acc) when byte_size(Name) + 9 + EncLen =< 76 ->
{Encoded, <<>>} = encode_param_value(encode, Value, 67 - byte_size(Name)),
[<<Name/binary, "*=UTF-8''", Encoded/binary>>];
encode_parameter(encode_utf8, Name, 0, Value, EncLen, Acc) ->
{Encoded, More} = encode_param_value(encode, Value, 65 - byte_size(Name)),
encode_parameter(encode, Name, 1, More, EncLen, [<<Name/binary, "*0*=UTF-8''", Encoded/binary>> | Acc]);
encode_parameter(encode, Name, 0, Value, EncLen, _Acc) when byte_size(Name) + 4 + EncLen =< 76 ->
{Encoded, <<>>} = encode_param_value(encode, Value, 72 - byte_size(Name)),
[<<Name/binary, "*=''", Encoded/binary>>];
encode_parameter(encode, Name, 0, Value, EncLen, Acc) ->
Prefix = <<Name/binary, $*, $0, $*>>,
{Encoded, More} = encode_param_value(encode, Value, 73 - byte_size(Prefix)),
encode_parameter(encode, Name, 1, More, EncLen, [<<Prefix/binary, "=''", Encoded/binary>> | Acc]);
encode_parameter(encode, Name, Index, Value, EncLen, Acc) ->
Prefix = <<Name/binary, $*, (integer_to_binary(Index))/binary, $*>>,
{Encoded, More} = encode_param_value(encode, Value, 75 - byte_size(Prefix)),
encode_parameter(encode, Name, Index + 1, More, EncLen, [<<Prefix/binary, "=", Encoded/binary>> | Acc]);
encode_parameter(quote, Name, 0, Value, EncLen, _Acc) when byte_size(Name) + 2 + EncLen + 1 =< 76 ->
{Quoted, <<>>} = encode_param_value(quote, Value, 73 - byte_size(Name)),
[<<Name/binary, $=, $", Quoted/binary, $">>];
encode_parameter(quote, Name, Index, Value, EncLen, Acc) ->
Prefix = <<Name/binary, $*, (integer_to_binary(Index))/binary>>,
{Quoted, More} = encode_param_value(quote, Value, 73 - byte_size(Prefix)),
encode_parameter(quote, Name, Index + 1, More, EncLen, [<<Prefix/binary, $=, $", Quoted/binary, $">> | Acc]);
encode_parameter(plain, Name, 0, Value, EncLen, _Acc) when byte_size(Name) + 1 + EncLen =< 76 ->
{Plain, <<>>} = encode_param_value(plain, Value, 75 - byte_size(Name)),
[<<Name/binary, $=, Plain/binary>>];
encode_parameter(plain, Name, Index, Value, EncLen, Acc) ->
Prefix = <<Name/binary, $*, (integer_to_binary(Index))/binary>>,
{Plain, More} = encode_param_value(plain, Value, 75 - byte_size(Prefix)),
encode_parameter(plain, Name, Index + 1, More, EncLen, [<<Prefix/binary, $=, Plain/binary>> | Acc]).
%% Encode a parameter value according to the method
%% given as the first argument.
-spec encode_param_value(Method :: (plain | quote | encode), Value :: binary(), Len :: integer()) ->
{Chunk :: binary(), Rest :: binary()}.
encode_param_value(plain, Value, Len) ->
%% No encoding necessary, return (part of) the
%% value as-is.
Len1 = max(Len, 1),
case Value of
<<Part:Len1/bytes, More/binary>> ->
{Part, More};
_ ->
{Value, <<>>}
end;
encode_param_value(quote, Value, Len) ->
%% See encode_param_value_quote/3
encode_param_value_quote(Value, Len, <<>>);
encode_param_value(encode, Value, Len) ->
%% See encode_param_value_encode/3
encode_param_value_encode(Value, Len, <<>>).
%% Encode (part of) a parameter value by quoting.