forked from gen-smtp/gen_smtp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen_smtp_server_session.erl
3711 lines (3644 loc) · 169 KB
/
gen_smtp_server_session.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 Process representing a SMTP session, extensible via a callback module. This
%% module is implemented as a behaviour that the callback module should
%% implement. To see the details of the required callback functions to provide,
%% please see `smtp_server_example'.
%% @see smtp_server_example
-module(gen_smtp_server_session).
-behaviour(gen_server).
-behaviour(ranch_protocol).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%10mb
-define(DEFAULT_MAXSIZE, 10485760).
-define(BUILTIN_EXTENSIONS, [
{"SIZE", integer_to_list(?DEFAULT_MAXSIZE)},
{"8BITMIME", true},
{"PIPELINING", true},
{"SMTPUTF8", true}
]).
% 3 minutes
-define(TIMEOUT, 180000).
%% External API
-export([start_link/3, start_link/4]).
-export([ranch_init/1]).
%% gen_server callbacks
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-export_type([options/0, error_class/0, protocol_message/0]).
-include_lib("kernel/include/logger.hrl").
-define(LOGGER_META, #{domain => [gen_smtp, server]}).
-record(envelope, {
from :: binary() | 'undefined',
to = [] :: [binary()],
data = <<>> :: binary(),
expectedsize = 0 :: pos_integer() | 0,
% {"username", "password"}
auth = {<<>>, <<>>} :: {binary(), binary()},
flags = [] :: [smtputf8 | '8bitmime' | '7bit']
}).
-record(state, {
socket = erlang:error({undefined, socket}) :: port() | tuple(),
module = erlang:error({undefined, module}) :: atom(),
transport :: module(),
ranch_ref :: ranch:ref(),
envelope = undefined :: 'undefined' | #envelope{},
extensions = [] :: [{string(), string()}],
maxsize = ?DEFAULT_MAXSIZE :: pos_integer() | 'infinity',
waitingauth = false :: 'false' | 'plain' | 'login' | 'cram-md5',
authdata :: 'undefined' | binary(),
readmessage = false :: boolean(),
tls = false :: boolean(),
callbackstate :: any(),
protocol = smtp :: 'smtp' | 'lmtp',
options = [] :: [tuple()]
}).
-type tls_opt() :: ssl:tls_server_option().
-type options() :: [
{callbackoptions, any()}
% deprecated, see tls_options
| {certfile, file:name_all()}
% deprecated, see tls_options
| {keyfile, file:name_all()}
| {allow_bare_newlines, false | ignore | fix | strip}
| {hostname, inet:hostname()}
| {protocol, smtp | lmtp}
| {tls_options, [tls_opt()]}
].
-type state() :: any().
-type error_message() :: {error, string(), state()}.
-type error_class() ::
tcp_closed
| tcp_error
| ssl_closed
| ssl_error
| data_rejected
| timeout
| out_of_order
| ssl_handshake_error
| send_error
| setopts_error
| data_receive_error.
-type protocol_message() :: string() | iodata().
-callback init(
Hostname :: inet:hostname(),
_SessionCount,
Peername :: inet:ip_address(),
Opts :: any()
) ->
{ok, Banner :: iodata(), CallbackState :: state()}
| {stop, Reason :: any(), Message :: iodata()}
| ignore.
-callback code_change(OldVsn :: any(), State :: state(), Extra :: any()) -> {ok, state()}.
-callback handle_HELO(Hostname :: binary(), State :: state()) ->
{ok, pos_integer() | 'infinity', state()} | {ok, state()} | error_message().
-callback handle_EHLO(Hostname :: binary(), Extensions :: list(), State :: state()) ->
{ok, list(), state()} | error_message().
-callback handle_STARTTLS(state()) -> state().
-callback handle_AUTH(
AuthType :: login | plain | 'cram-md5',
Username :: binary(),
Credential :: binary() | {binary(), binary()},
State :: state()
) ->
{ok, state()} | any().
-callback handle_MAIL(From :: binary(), State :: state()) ->
{ok, state()} | {error, string(), state()}.
-callback handle_MAIL_extension(Extension :: binary(), State :: state()) ->
{ok, state()} | error.
-callback handle_RCPT(To :: binary(), State :: state()) ->
{ok, state()} | {error, string(), state()}.
-callback handle_RCPT_extension(Extension :: binary(), State :: state()) ->
{ok, state()} | error.
-callback handle_DATA(From :: binary(), To :: [binary(), ...], Data :: binary(), State :: state()) ->
{ok | error, protocol_message(), state()}
| {multiple, [{ok | error, protocol_message()}], state()}.
% the 'multiple' reply is only available for LMTP
-callback handle_RSET(State :: state()) -> state().
-callback handle_VRFY(Address :: binary(), State :: state()) ->
{ok, string(), state()} | {error, string(), state()}.
-callback handle_other(Verb :: binary(), Args :: binary(), state()) ->
{string() | noreply, state()}.
-callback handle_info(Info :: term(), State :: state()) ->
{noreply, NewState :: state()}
| {noreply, NewState :: state(), timeout() | hibernate}
| {stop, Reason :: term(), NewState :: term()}.
-callback handle_error(error_class(), any(), state()) ->
{ok, state()} | {stop, Reason :: any(), state()}.
-callback terminate(Reason :: any(), state()) -> {ok, Reason :: any(), state()}.
-optional_callbacks([handle_info/2, handle_AUTH/4, handle_error/3]).
%% @doc Start a SMTP session linked to the calling process.
-spec start_link(
Ref :: ranch:ref(),
Transport :: module(),
{Callback :: module(), Options :: options()}
) ->
{'ok', pid()}.
start_link(Ref, Transport, Options) ->
{ok, proc_lib:spawn_link(?MODULE, ranch_init, [{Ref, Transport, Options}])}.
start_link(Ref, _Sock, Transport, Options) ->
start_link(Ref, Transport, Options).
ranch_init({Ref, Transport, {Callback, Opts}}) ->
{ok, Socket} = ranch:handshake(Ref),
case init([Ref, Transport, Socket, Callback, Opts]) of
{ok, State, Timeout} ->
gen_server:enter_loop(?MODULE, [], State, Timeout);
{stop, Reason} ->
exit(Reason);
ignore ->
ok
end.
%% @private
-spec init(Args :: list()) -> {'ok', #state{}, ?TIMEOUT} | {'stop', any()} | 'ignore'.
init([Ref, Transport, Socket, Module, Options]) ->
Protocol = proplists:get_value(protocol, Options, smtp),
PeerName =
case Transport:peername(Socket) of
{ok, {IPaddr, _Port}} -> IPaddr;
{error, _} -> error
end,
case
PeerName =/= error andalso
Module:init(
hostname(Options),
%FIXME
proplists:get_value(sessioncount, Options, 0),
PeerName,
proplists:get_value(callbackoptions, Options, [])
)
of
false ->
Transport:close(Socket),
ignore;
{ok, Banner, CallbackState} ->
Transport:send(Socket, ["220 ", Banner, "\r\n"]),
ok = Transport:setopts(Socket, [
{active, once},
{packet, line},
binary
]),
{ok,
#state{
socket = Socket,
transport = Transport,
module = Module,
ranch_ref = Ref,
protocol = Protocol,
options = Options,
callbackstate = CallbackState
},
?TIMEOUT};
{stop, Reason, Message} ->
Transport:send(Socket, [Message, "\r\n"]),
Transport:close(Socket),
{stop, Reason};
ignore ->
Transport:close(Socket),
ignore
end.
%% @hidden
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(Request, _From, State) ->
{reply, {unknown_call, Request}, State}.
%% @hidden
handle_cast(_Msg, State) ->
{noreply, State}.
%% @hidden
-spec handle_info(Message :: any(), State :: #state{}) ->
{'noreply', #state{}} | {'stop', any(), #state{}}.
handle_info({receive_data, {error, size_exceeded}}, #state{readmessage = true} = State) ->
send(State, "552 Message too large\r\n"),
setopts(State, [{active, once}]),
State1 = handle_error(data_rejected, size_exceeded, State),
{noreply, State1#state{readmessage = false, envelope = #envelope{}}, ?TIMEOUT};
handle_info({receive_data, {error, bare_newline}}, #state{readmessage = true} = State) ->
send(State, "451 Bare newline detected\r\n"),
setopts(State, [{active, once}]),
State1 = handle_error(data_rejected, bare_neline, State),
{noreply, State1#state{readmessage = false, envelope = #envelope{}}, ?TIMEOUT};
handle_info({receive_data, {error, Other}}, #state{readmessage = true} = State) ->
State1 = handle_error(data_receive_error, Other, State),
{stop, {error_receiving_data, Other}, State1};
handle_info(
{receive_data, Body, Rest},
#state{
socket = Socket,
transport = Transport,
readmessage = true,
envelope = Env,
module = Module,
callbackstate = OldCallbackState,
maxsize = MaxSize
} = State
) ->
% send the remainder of the data...
case Rest of
% no remaining data
<<>> -> ok;
_ -> self() ! {Transport:name(), Socket, Rest}
end,
setopts(State, [{packet, line}]),
%% Unescape periods at start of line (rfc5321 4.5.2)
Data = re:replace(Body, <<"^\\\.">>, <<>>, [global, multiline, {return, binary}]),
#envelope{from = From, to = To} = Env,
case MaxSize =:= infinity orelse byte_size(Data) =< MaxSize of
true ->
{ResponseType, Value, CallbackState} = Module:handle_DATA(
From, To, Data, OldCallbackState
),
report_recipient(ResponseType, Value, State),
setopts(State, [{active, once}]),
{noreply,
State#state{
readmessage = false,
envelope = #envelope{},
callbackstate = CallbackState
},
?TIMEOUT};
false ->
send(State, "552 Message too large\r\n"),
setopts(State, [{active, once}]),
% might not even be able to get here anymore...
{noreply, State#state{readmessage = false, envelope = #envelope{}}, ?TIMEOUT}
end;
handle_info(
{SocketType, Socket, Packet},
#state{socket = Socket, transport = Transport, waitingauth = false} = State
) when
SocketType =:= tcp; SocketType =:= ssl
->
case handle_request(parse_request(Packet), State) of
{ok, #state{options = Options, readmessage = true, maxsize = MaxSize} = NewState} ->
Session = self(),
Size = 0,
setopts(NewState, [{packet, raw}]),
%% TODO: change to receive asynchronously in the same process
spawn_opt(
fun() ->
receive_data([], Transport, Socket, 0, Size, MaxSize, Session, Options)
end,
[link, {fullsweep_after, 0}]
),
{noreply, NewState, ?TIMEOUT};
{ok, NewState} ->
setopts(NewState, [{active, once}]),
{noreply, NewState, ?TIMEOUT};
{stop, Reason, NewState} ->
{stop, Reason, NewState}
end;
handle_info({SocketType, Socket, Packet}, #state{socket = Socket} = State) when
SocketType =:= tcp; SocketType =:= ssl
->
%% We are in SASL state RFC-4954
Request = binstr:strip(
binstr:strip(binstr:strip(binstr:strip(Packet, right, $\n), right, $\r), right, $\s),
left,
$\s
),
?LOG_DEBUG("Got SASL request ~p", [Request], ?LOGGER_META),
{ok, NewState} = handle_sasl(base64:decode(Request), State),
setopts(NewState, [{active, once}]),
{noreply, NewState, ?TIMEOUT};
handle_info({Kind, _Socket}, State) when
Kind == tcp_closed;
Kind == ssl_closed
->
State1 = handle_error(Kind, [], State),
{stop, normal, State1};
handle_info({Kind, _Socket, Reason}, State) when
Kind == ssl_error;
Kind == tcp_error
->
State1 = handle_error(Kind, Reason, State),
{stop, normal, State1};
handle_info(timeout, #state{socket = Socket, transport = Transport} = State) ->
send(State, "421 Error: timeout exceeded\r\n"),
Transport:close(Socket),
State1 = handle_error(timeout, [], State),
{stop, normal, State1};
handle_info(Info, #state{module = Module, callbackstate = OldCallbackState} = State) ->
case erlang:function_exported(Module, handle_info, 2) of
true ->
case Module:handle_info(Info, OldCallbackState) of
{noreply, NewCallbackState} ->
{noreply, State#state{callbackstate = NewCallbackState}};
{noreply, NewCallbackState, Action} ->
{noreply, State#state{callbackstate = NewCallbackState}, Action};
{stop, Reason, NewCallbackState} ->
{stop, Reason, State#state{callbackstate = NewCallbackState}}
end;
false ->
?LOG_DEBUG("Ignored message ~p", [Info], ?LOGGER_META),
{noreply, State, ?TIMEOUT}
end.
%% @hidden
-spec terminate(Reason :: any(), State :: #state{}) -> 'ok'.
terminate(Reason, #state{
socket = Socket,
transport = Transport,
module = Module,
callbackstate = CallbackState
}) ->
ok = Transport:close(Socket),
Module:terminate(Reason, CallbackState).
%% @hidden
-spec code_change(OldVsn :: any(), State :: #state{}, Extra :: any()) -> {'ok', #state{}}.
code_change(OldVsn, #state{module = Module, callbackstate = CallbackState} = State, Extra) ->
% TODO - this should probably be the callback module's version or its checksum
CallbackState =
case catch Module:code_change(OldVsn, CallbackState, Extra) of
{ok, NewCallbackState} -> NewCallbackState;
_ -> CallbackState
end,
{ok, State#state{callbackstate = CallbackState}}.
-spec parse_request(Packet :: binary()) -> {binary(), binary()}.
parse_request(Packet) ->
Request = binstr:strip(
binstr:strip(binstr:strip(binstr:strip(Packet, right, $\n), right, $\r), right, $\s),
left,
$\s
),
case binstr:strchr(Request, $\s) of
0 ->
?LOG_DEBUG("got a ~s request", [Request], ?LOGGER_META),
{binstr:to_upper(Request), <<>>};
Index ->
Verb = binstr:substr(Request, 1, Index - 1),
Parameters = binstr:strip(binstr:substr(Request, Index + 1), left, $\s),
?LOG_DEBUG("got a ~s request with parameters ~s", [Verb, Parameters], ?LOGGER_META),
{binstr:to_upper(Verb), Parameters}
end.
-spec handle_request({Verb :: binary(), Args :: binary()}, State :: #state{}) ->
{'ok', #state{}} | {'stop', any(), #state{}}.
handle_request({<<>>, _Any}, State) ->
send(State, "500 Error: bad syntax\r\n"),
{ok, State};
handle_request({Command, <<>>}, State) when
Command == <<"HELO">>; Command == <<"EHLO">>; Command == <<"LHLO">>
->
send(State, ["501 Syntax: ", Command, " hostname\r\n"]),
{ok, State};
handle_request({<<"LHLO">>, _Any}, #state{protocol = smtp} = State) ->
send(State, "500 Error: SMTP should send HELO or EHLO instead of LHLO\r\n"),
{ok, State};
handle_request({Msg, _Any}, #state{protocol = lmtp} = State) when
Msg == <<"HELO">>; Msg == <<"EHLO">>
->
send(State, "500 Error: LMTP should replace HELO and EHLO with LHLO\r\n"),
{ok, State};
handle_request(
{<<"HELO">>, Hostname},
#state{options = Options, module = Module, callbackstate = OldCallbackState} = State
) ->
case Module:handle_HELO(Hostname, OldCallbackState) of
{ok, MaxSize, CallbackState} when MaxSize =:= infinity; is_integer(MaxSize) ->
Data = ["250 ", hostname(Options), "\r\n"],
send(State, Data),
{ok, State#state{
maxsize = MaxSize,
envelope = #envelope{},
callbackstate = CallbackState
}};
{ok, CallbackState} ->
Data = ["250 ", hostname(Options), "\r\n"],
send(State, Data),
{ok, State#state{envelope = #envelope{}, callbackstate = CallbackState}};
{error, Message, CallbackState} ->
send(State, [Message, "\r\n"]),
{ok, State#state{callbackstate = CallbackState}}
end;
handle_request(
{Msg, Hostname},
#state{options = Options, module = Module, callbackstate = OldCallbackState, tls = Tls} = State
) when
Msg == <<"EHLO">>; Msg == <<"LHLO">>
->
case Module:handle_EHLO(Hostname, ?BUILTIN_EXTENSIONS, OldCallbackState) of
{ok, [], CallbackState} ->
Data = ["250 ", hostname(Options), "\r\n"],
send(State, Data),
{ok, State#state{extensions = [], callbackstate = CallbackState}};
{ok, Extensions, CallbackState} ->
ExtensionsUpper = lists:map(fun({X, Y}) -> {string:to_upper(X), Y} end, Extensions),
{Extensions1, MaxSize} =
case lists:keyfind("SIZE", 1, ExtensionsUpper) of
{"SIZE", "0"} ->
{lists:keydelete("SIZE", 1, ExtensionsUpper), infinity};
{"SIZE", MaxSizeString} when is_list(MaxSizeString) ->
{ExtensionsUpper, list_to_integer(MaxSizeString)};
false ->
{ExtensionsUpper, State#state.maxsize}
end,
Extensions2 =
case Tls of
true ->
lists:delete({"STARTTLS", true}, Extensions1);
false ->
Extensions1
end,
Response = (fun
F([{E, true}]) -> ["250 ", E, "\r\n"];
F([{E, V}]) -> ["250 ", E, " ", V, "\r\n"];
F([Line]) -> ["250 ", Line, "\r\n"];
F([{E, true} | More]) -> ["250-", E, "\r\n" | F(More)];
F([{E, V} | More]) -> ["250-", E, " ", V, "\r\n" | F(More)];
F([Line | More]) -> ["250-", Line, "\r\n" | F(More)]
end)(
[hostname(Options) | Extensions2]
),
%?debugFmt("Respponse ~p~n", [lists:reverse(Response)]),
send(State, Response),
{ok, State#state{
extensions = Extensions2,
maxsize = MaxSize,
envelope = #envelope{},
callbackstate = CallbackState
}};
{error, Message, CallbackState} ->
send(State, [Message, "\r\n"]),
{ok, State#state{callbackstate = CallbackState}}
end;
handle_request({<<"AUTH">> = C, _Args}, #state{envelope = undefined, protocol = Protocol} = State) ->
send(State, ["503 Error: send ", lhlo_if_lmtp(Protocol, "EHLO"), " first\r\n"]),
State1 = handle_error(out_of_order, C, State),
{ok, State1};
handle_request(
{<<"AUTH">>, Args},
#state{extensions = Extensions, envelope = Envelope, options = Options} = State
) ->
case binstr:strchr(Args, $\s) of
0 ->
AuthType = Args,
Parameters = false;
Index ->
AuthType = binstr:substr(Args, 1, Index - 1),
Parameters = binstr:strip(binstr:substr(Args, Index + 1), left, $\s)
end,
case has_extension(Extensions, "AUTH") of
false ->
send(State, "502 Error: AUTH not implemented\r\n"),
{ok, State};
{true, AvailableTypes} ->
case
lists:member(
string:to_upper(binary_to_list(AuthType)),
string:tokens(AvailableTypes, " ")
)
of
false ->
send(State, "504 Unrecognized authentication type\r\n"),
{ok, State};
true ->
case binstr:to_upper(AuthType) of
<<"LOGIN">> ->
% smtp_socket:send(Socket, "334 " ++ base64:encode_to_string("Username:")),
send(State, "334 VXNlcm5hbWU6\r\n"),
{ok, State#state{
waitingauth = 'login',
envelope = Envelope#envelope{auth = {<<>>, <<>>}}
}};
<<"PLAIN">> when Parameters =/= false ->
% TODO - duplicated below in handle_request waitingauth PLAIN
case binstr:split(base64:decode(Parameters), <<0>>) of
[_Identity, Username, Password] ->
try_auth('plain', Username, Password, State);
[Username, Password] ->
try_auth('plain', Username, Password, State);
_ ->
% TODO error
{ok, State}
end;
<<"PLAIN">> ->
send(State, "334\r\n"),
{ok, State#state{
waitingauth = 'plain',
envelope = Envelope#envelope{auth = {<<>>, <<>>}}
}};
<<"CRAM-MD5">> ->
% ensure crypto is started, we're gonna need it
crypto:start(),
String = smtp_util:get_cram_string(hostname(Options)),
send(State, ["334 ", String, "\r\n"]),
{ok, State#state{
waitingauth = 'cram-md5',
authdata = base64:decode(String),
envelope = Envelope#envelope{auth = {<<>>, <<>>}}
}}
%"DIGEST-MD5" -> % TODO finish this? (see rfc 2831)
%crypto:start(), % ensure crypto is started, we're gonna need it
%Nonce = get_digest_nonce(),
%Response = io_lib:format("nonce=\"~s\",realm=\"~s\",qop=\"auth\",algorithm=md5-sess,charset=utf-8", Nonce, State#state.hostname),
%smtp_socket:send(Socket, "334 "++Response++"\r\n"),
%{ok, State#state{waitingauth = "DIGEST-MD5", authdata=base64:decode_to_string(Nonce), envelope = Envelope#envelope{auth = {[], []}}}}
end
end
end;
handle_request({<<"MAIL">> = C, _Args}, #state{envelope = undefined, protocol = Protocol} = State) ->
send(State, ["503 Error: send ", lhlo_if_lmtp(Protocol, "HELO/EHLO"), " first\r\n"]),
State1 = handle_error(out_of_order, C, State),
{ok, State1};
handle_request(
{<<"MAIL">>, Args},
#state{
module = Module,
envelope = Envelope0,
callbackstate = OldCallbackState,
extensions = Extensions,
maxsize = MaxSize
} = State
) ->
case Envelope0#envelope.from of
undefined ->
case binstr:strpos(binstr:to_upper(Args), <<"FROM:">>) of
1 ->
Address = binstr:strip(binstr:substr(Args, 6), left, $\s),
case
parse_encoded_address(
Address, has_extension(Extensions, "SMTPUTF8") =/= false
)
of
error ->
send(State, "501 Bad sender address syntax\r\n"),
{ok, State};
{ParsedAddress, <<>>} ->
?LOG_DEBUG("From address ~s (parsed as ~s)", [Address, ParsedAddress], ?LOGGER_META),
case Module:handle_MAIL(ParsedAddress, OldCallbackState) of
{ok, CallbackState} ->
send(State, "250 sender Ok\r\n"),
{ok, State#state{
envelope = Envelope0#envelope{from = ParsedAddress},
callbackstate = CallbackState
}};
{error, Message, CallbackState} ->
send(State, [Message, "\r\n"]),
{ok, State#state{callbackstate = CallbackState}}
end;
{ParsedAddress, ExtraInfo} ->
?LOG_DEBUG(
"From address ~s (parsed as ~s) with extra info ~s",
[
Address, ParsedAddress, ExtraInfo
],
?LOGGER_META
),
Options = [binstr:to_upper(X) || X <- binstr:split(ExtraInfo, <<" ">>)],
?LOG_DEBUG("options are ~p", [Options], ?LOGGER_META),
F = fun
(_, {error, Message}) ->
{error, Message};
(
<<"SIZE=", Size/binary>>,
#state{envelope = Envelope} = InnerState
) when MaxSize =:= 'infinity' ->
InnerState#state{
envelope = Envelope#envelope{
expectedsize = binary_to_integer(Size)
}
};
(
<<"SIZE=", Size/binary>>,
#state{envelope = Envelope} = InnerState
) ->
case binary_to_integer(Size) > MaxSize of
true ->
{error, [
"552 Estimated message length ",
Size,
" exceeds limit of ",
integer_to_binary(MaxSize),
"\r\n"
]};
false ->
InnerState#state{
envelope = Envelope#envelope{
expectedsize = binary_to_integer(Size)
}
}
end;
(
<<"BODY=", BodyType/binary>>,
#state{envelope = #envelope{flags = Flags} = Envelope} =
InnerState
) ->
case has_extension(Extensions, "8BITMIME") of
{true, _} ->
Flag = maps:get(BodyType, #{
<<"8BITMIME">> => '8bitmime',
<<"7BIT">> => '7bit'
}),
InnerState#state{
envelope = Envelope#envelope{flags = [Flag | Flags]}
};
false ->
{error, "555 Unsupported option BODY\r\n"}
end;
(
<<"SMTPUTF8">>,
#state{envelope = #envelope{flags = Flags} = Envelope} =
InnerState
) ->
case has_extension(Extensions, "SMTPUTF8") of
{true, _} ->
InnerState#state{
envelope = Envelope#envelope{
flags = ['smtputf8' | Flags]
}
};
false ->
{error, "555 Unsupported option SMTPUTF8\r\n"}
end;
(X, InnerState) ->
case Module:handle_MAIL_extension(X, OldCallbackState) of
{ok, CallbackState} ->
InnerState#state{callbackstate = CallbackState};
error ->
{error, ["555 Unsupported option: ", ExtraInfo, "\r\n"]}
end
end,
case lists:foldl(F, State, Options) of
{error, Message} ->
?LOG_DEBUG("error: ~s", [Message], ?LOGGER_META),
send(State, Message),
{ok, State};
#state{envelope = Envelope} = NewState ->
?LOG_DEBUG("OK", ?LOGGER_META),
case Module:handle_MAIL(ParsedAddress, State#state.callbackstate) of
{ok, CallbackState} ->
send(State, "250 sender Ok\r\n"),
{ok, State#state{
envelope = Envelope#envelope{from = ParsedAddress},
callbackstate = CallbackState
}};
{error, Message, CallbackState} ->
send(State, [Message, "\r\n"]),
{ok, NewState#state{callbackstate = CallbackState}}
end
end
end;
_Else ->
send(State, "501 Syntax: MAIL FROM:<address>\r\n"),
{ok, State}
end;
_Other ->
send(State, "503 Error: Nested MAIL command\r\n"),
{ok, State}
end;
handle_request({<<"RCPT">> = C, _Args}, #state{envelope = undefined} = State) ->
send(State, "503 Error: need MAIL command\r\n"),
State1 = handle_error(out_of_order, C, State),
{ok, State1};
handle_request(
{<<"RCPT">>, Args},
#state{
envelope = Envelope,
module = Module,
callbackstate = OldCallbackState,
extensions = Extensions
} = State
) ->
case binstr:strpos(binstr:to_upper(Args), <<"TO:">>) of
1 ->
Address = binstr:strip(binstr:substr(Args, 4), left, $\s),
case parse_encoded_address(Address, has_extension(Extensions, "SMTPUTF8") =/= false) of
error ->
send(State, "501 Bad recipient address syntax\r\n"),
{ok, State};
{<<>>, _} ->
% empty rcpt to addresses aren't cool
send(State, "501 Bad recipient address syntax\r\n"),
{ok, State};
{ParsedAddress, <<>>} ->
?LOG_DEBUG("To address ~s (parsed as ~s)", [Address, ParsedAddress], ?LOGGER_META),
case Module:handle_RCPT(ParsedAddress, OldCallbackState) of
{ok, CallbackState} ->
send(State, "250 recipient Ok\r\n"),
{ok, State#state{
envelope = Envelope#envelope{
to = Envelope#envelope.to ++ [ParsedAddress]
},
callbackstate = CallbackState
}};
{error, Message, CallbackState} ->
send(State, [Message, "\r\n"]),
{ok, State#state{callbackstate = CallbackState}}
end;
{ParsedAddress, ExtraInfo} ->
% TODO - are there even any RCPT extensions?
?LOG_DEBUG(
"To address ~s (parsed as ~s) with extra info ~s",
[
Address, ParsedAddress, ExtraInfo
],
?LOGGER_META
),
send(State, ["555 Unsupported option: ", ExtraInfo, "\r\n"]),
{ok, State}
end;
_Else ->
send(State, "501 Syntax: RCPT TO:<address>\r\n"),
{ok, State}
end;
handle_request({<<"DATA">> = C, <<>>}, #state{envelope = undefined, protocol = Protocol} = State) ->
send(State, ["503 Error: send ", lhlo_if_lmtp(Protocol, "HELO/EHLO"), " first\r\n"]),
State1 = handle_error(out_of_order, C, State),
{ok, State1};
handle_request({<<"DATA">> = C, <<>>}, #state{envelope = Envelope} = State) ->
case {Envelope#envelope.from, Envelope#envelope.to} of
{undefined, _} ->
send(State, "503 Error: need MAIL command\r\n"),
State1 = handle_error(out_of_order, C, State),
{ok, State1};
{_, []} ->
send(State, "503 Error: need RCPT command\r\n"),
State1 = handle_error(out_of_order, C, State),
{ok, State1};
_Else ->
send(State, "354 enter mail, end with line containing only '.'\r\n"),
?LOG_DEBUG("switching to data read mode", [], ?LOGGER_META),
{ok, State#state{readmessage = true}}
end;
handle_request(
{<<"RSET">>, _Any},
#state{envelope = Envelope, module = Module, callbackstate = OldCallbackState} = State
) ->
send(State, "250 Ok\r\n"),
% if the client sends a RSET before a HELO/EHLO don't give them a valid envelope
NewEnvelope =
case Envelope of
undefined -> undefined;
_Something -> #envelope{}
end,
{ok, State#state{envelope = NewEnvelope, callbackstate = Module:handle_RSET(OldCallbackState)}};
handle_request({<<"NOOP">>, _Any}, State) ->
send(State, "250 Ok\r\n"),
{ok, State};
handle_request({<<"QUIT">>, _Any}, State) ->
send(State, "221 Bye\r\n"),
{stop, normal, State};
handle_request(
{<<"VRFY">>, Address},
#state{module = Module, callbackstate = OldCallbackState, extensions = Extensions} = State
) ->
case parse_encoded_address(Address, has_extension(Extensions, "SMTPUTF8") =/= false) of
{ParsedAddress, <<>>} ->
case Module:handle_VRFY(ParsedAddress, OldCallbackState) of
{ok, Reply, CallbackState} ->
send(State, ["250 ", Reply, "\r\n"]),
{ok, State#state{callbackstate = CallbackState}};
{error, Message, CallbackState} ->
send(State, [Message, "\r\n"]),
{ok, State#state{callbackstate = CallbackState}}
end;
_Other ->
send(State, "501 Syntax: VRFY username/address\r\n"),
{ok, State}
end;
handle_request(
{<<"STARTTLS">>, <<>>},
#state{
socket = Socket,
module = Module,
tls = false,
extensions = Extensions,
callbackstate = OldCallbackState,
options = Options
} = State
) ->
case has_extension(Extensions, "STARTTLS") of
{true, _} ->
send(State, "220 OK\r\n"),
TlsOpts0 = proplists:get_value(tls_options, Options, []),
TlsOpts1 =
case proplists:get_value(certfile, Options) of
undefined ->
TlsOpts0;
CertFile ->
[{certfile, CertFile} | TlsOpts0]
end,
TlsOpts2 =
case proplists:get_value(keyfile, Options) of
undefined ->
TlsOpts1;
KeyFile ->
[{keyfile, KeyFile} | TlsOpts1]
end,
%% Assert that socket is in passive state
{ok, [{active, false}]} = inet:getopts(Socket, [active]),
%XXX: see smtp_socket:?SSL_LISTEN_OPTIONS
case
ranch_ssl:handshake(
Socket, [{packet, line}, {mode, list}, {ssl_imp, new} | TlsOpts2], 5000
)
of
{ok, NewSocket} ->
?LOG_DEBUG("SSL negotiation successful", ?LOGGER_META),
ranch_ssl:setopts(NewSocket, [{packet, line}, binary]),
{ok, State#state{
socket = NewSocket,
transport = ranch_ssl,
envelope = undefined,
authdata = undefined,
waitingauth = false,
readmessage = false,
tls = true,
callbackstate = Module:handle_STARTTLS(OldCallbackState)
}};
{error, Reason} ->
?LOG_INFO("SSL handshake failed : ~p", [Reason], ?LOGGER_META),
send(State, "454 TLS negotiation failed\r\n"),
State1 = handle_error(ssl_handshake_error, Reason, State),
{ok, State1}
end;
false ->
send(State, "500 Command unrecognized\r\n"),
{ok, State}
end;
handle_request({<<"STARTTLS">> = C, <<>>}, State) ->
send(State, "500 TLS already negotiated\r\n"),
State1 = handle_error(out_of_order, C, State),
{ok, State1};
handle_request({<<"STARTTLS">>, _Args}, State) ->
send(State, "501 Syntax error (no parameters allowed)\r\n"),
{ok, State};
handle_request({Verb, Args}, #state{module = Module, callbackstate = OldCallbackState} = State) ->
CallbackState =
case Module:handle_other(Verb, Args, OldCallbackState) of
{noreply, CState1} ->
CState1;
{Message, CState1} ->
send(State, [Message, "\r\n"]),
CState1
end,
{ok, State#state{callbackstate = CallbackState}}.
%% @doc handle SASL client response to `334' challenge - RFC-4954
% the client sends a response to auth-cram-md5
handle_sasl(
UserDigest,
#state{waitingauth = 'cram-md5', envelope = #envelope{auth = {<<>>, <<>>}}, authdata = AuthData} =
State
) ->
case binstr:split(UserDigest, <<" ">>) of
[Username, Digest] ->
try_auth('cram-md5', Username, {Digest, AuthData}, State#state{authdata = undefined});
_ ->
% TODO error
{ok, State#state{waitingauth = false, authdata = undefined}}
end;
% the client sends a \0username\0password response to auth-plain
handle_sasl(
UserPass, #state{waitingauth = 'plain', envelope = #envelope{auth = {<<>>, <<>>}}} = State
) ->
case binstr:split(UserPass, <<0>>) of
[_Identity, Username, Password] ->
try_auth('plain', Username, Password, State);
[Username, Password] ->
try_auth('plain', Username, Password, State);
_ ->
% TODO error
{ok, State#state{waitingauth = false}}
end;
% the client sends a username response to auth-login
handle_sasl(
Username, #state{waitingauth = 'login', envelope = #envelope{auth = {<<>>, <<>>}}} = State
) ->
Envelope = State#state.envelope,
% smtp_socket:send(Socket, "334 " ++ base64:encode_to_string("Password:")),
send(State, "334 UGFzc3dvcmQ6\r\n"),
% store the provided username in envelope.auth
NewState = State#state{envelope = Envelope#envelope{auth = {Username, <<>>}}},
{ok, NewState};
% the client sends a password response to auth-login
handle_sasl(
Password, #state{waitingauth = 'login', envelope = #envelope{auth = {Username, <<>>}}} = State
) ->
try_auth('login', Username, Password, State).
-spec handle_error(error_class(), any(), #state{}) -> #state{}.
handle_error(Kind, Details, #state{module = Module, callbackstate = OldCallbackState} = State) ->
case erlang:function_exported(Module, handle_error, 3) of
true ->
case Module:handle_error(Kind, Details, OldCallbackState) of
{ok, CallbackState} ->
State#state{callbackstate = CallbackState};
{stop, Reason, CallbackState} ->
throw({stop, Reason, State#state{callbackstate = CallbackState}})
end;
false ->
State
end.
%% pa = parse address
%% ab = angular brackets
-record(pa, {
quotes = false,
ab = true,
utf8 = false
}).
%% https://datatracker.ietf.org/doc/html/rfc5321#section-4.1.2
-spec parse_encoded_address(Address :: binary(), Utf8 :: boolean()) ->
{binary(), binary()} | 'error'.
parse_encoded_address(<<>>, _) ->
% empty
error;