1 // Toy program to send email. This is used to test my SMTP server,
2 // mostly. It's overgrown a bit.
4 #include <gflags/gflags.h>
6 // in case we didn't have one
9 // This needs to be at least the length of each string it's trying to match.
10 DEFINE_uint64(bfr_size
, 4 * 1024, "parser buffer size");
12 DEFINE_bool(selftest
, false, "run a self test");
14 DEFINE_bool(badpipline
, false, "send two NOOPs back-to-back");
15 DEFINE_bool(bare_lf
, false, "send a bare LF");
16 DEFINE_bool(huge_size
, false, "attempt with huge size");
17 DEFINE_bool(long_line
, false, "super long text line");
18 DEFINE_bool(noconn
, false, "don't connect to any host");
19 DEFINE_bool(noop
, false, "send a NOOP right after EHLO");
20 DEFINE_bool(nosend
, false, "don't actually send any mail");
21 DEFINE_bool(pipe
, false, "send to stdin/stdout");
24 "send the body exactly as is, don't fix CRLF issues "
25 "or escape leading dots");
26 DEFINE_bool(require_tls
, true, "use STARTTLS or die");
28 DEFINE_bool(slow_strangle
, false, "super slow mo");
29 DEFINE_bool(to_the_neck
, false, "shove data forever");
31 DEFINE_bool(use_8bitmime
, true, "use 8BITMIME extension");
32 DEFINE_bool(use_binarymime
, true, "use BINARYMIME extension");
33 DEFINE_bool(use_chunking
, true, "use CHUNKING extension");
34 DEFINE_bool(use_deliverby
, false, "use DELIVERBY extension");
35 DEFINE_bool(use_esmtp
, true, "use ESMTP (EHLO)");
36 DEFINE_bool(use_pipelining
, true, "use PIPELINING extension");
37 DEFINE_bool(use_size
, true, "use SIZE extension");
38 DEFINE_bool(use_smtputf8
, true, "use SMTPUTF8 extension");
39 DEFINE_bool(use_tls
, true, "use STARTTLS extension");
41 // To force it, set if you have UTF8 in the local part of any RFC5321
43 DEFINE_bool(force_smtputf8
, false, "force SMTPUTF8 extension");
45 DEFINE_string(sender
, "", "FQDN of sending node");
47 DEFINE_string(local_address
, "", "local address to bind");
48 DEFINE_string(mx_host
, "", "FQDN of receiving node");
49 DEFINE_string(service
, "smtp-test", "service name");
50 DEFINE_string(client_id
, "", "client name (ID) for EHLO/HELO");
52 DEFINE_string(from
, "", "RFC5322 From: address");
53 DEFINE_string(from_name
, "", "RFC5322 From: name");
55 DEFINE_string(to
, "", "RFC5322 To: address");
56 DEFINE_string(to_name
, "", "RFC5322 To: name");
58 DEFINE_string(smtp_from
, "", "RFC5321 MAIL FROM address");
59 DEFINE_string(smtp_to
, "", "RFC5321 RCPT TO address");
61 DEFINE_string(subject
, "testing one, two, three...", "RFC5322 Subject");
62 DEFINE_string(keywords
, "", "RFC5322 Keywords: header");
63 DEFINE_string(references
, "", "RFC5322 References: header");
64 DEFINE_string(in_reply_to
, "", "RFC5322 In-Reply-To: header");
65 DEFINE_string(reply_to
, "", "RFC5322 Reply-To: header");
67 DEFINE_bool(4, false, "use only IP version 4");
68 DEFINE_bool(6, false, "use only IP version 6");
70 DEFINE_string(username
, "", "AUTH username");
71 DEFINE_string(password
, "", "AUTH password");
73 DEFINE_bool(use_dkim
, true, "sign with DKIM");
74 DEFINE_string(selector
, "ghsmtp", "DKIM selector");
75 DEFINE_string(dkim_key_file
, "", "DKIM key file");
78 #include "DNS-fcrdns.hpp"
84 #include "Mailbox.hpp"
85 #include "Message.hpp"
87 #include "OpenDKIM.hpp"
91 #include "imemstream.hpp"
103 #include <string_view>
104 #include <unordered_map>
107 #include <sys/socket.h>
108 #include <sys/types.h>
110 #include <fmt/format.h>
111 #include <fmt/ostream.h>
113 #include <boost/algorithm/string/case_conv.hpp>
115 #include <boost/iostreams/device/mapped_file.hpp>
117 #include <tao/pegtl.hpp>
118 #include <tao/pegtl/contrib/abnf.hpp>
120 using namespace tao::pegtl
;
121 using namespace tao::pegtl::abnf
;
123 using namespace std::string_literals
;
126 constexpr auto read_timeout
= std::chrono::seconds(30);
127 constexpr auto write_timeout
= std::chrono::minutes(3);
128 } // namespace Config
133 struct tail
: range
<'\x80', '\xBF'> {};
135 struct ch_1
: range
<'\x00', '\x7F'> {};
137 struct ch_2
: seq
<range
<'\xC2', '\xDF'>, tail
> {};
139 struct ch_3
: sor
<seq
<one
<'\xE0'>, range
<'\xA0', '\xBF'>, tail
>,
140 seq
<range
<'\xE1', '\xEC'>, rep
<2, tail
>>,
141 seq
<one
<'\xED'>, range
<'\x80', '\x9F'>, tail
>,
142 seq
<range
<'\xEE', '\xEF'>, rep
<2, tail
>>> {};
144 struct ch_4
: sor
<seq
<one
<'\xF0'>, range
<'\x90', '\xBF'>, rep
<2, tail
>>,
145 seq
<range
<'\xF1', '\xF3'>, rep
<3, tail
>>,
146 seq
<one
<'\xF4'>, range
<'\x80', '\x8F'>, rep
<2, tail
>>> {};
148 struct u8char
: sor
<ch_1
, ch_2
, ch_3
, ch_4
> {};
150 struct non_ascii
: sor
<ch_2
, ch_3
, ch_4
> {};
152 struct ascii_only
: seq
<star
<ch_1
>, eof
> {};
154 struct utf8_only
: seq
<star
<u8char
>, eof
> {};
159 struct VUCHAR
: sor
<VCHAR
, chars::non_ascii
> {};
161 using dot
= one
<'.'>;
162 using colon
= one
<':'>;
164 // All 7-bit ASCII except NUL (0), LF (10) and CR (13).
165 struct text_ascii
: ranges
<1, 9, 11, 12, 14, 127> {};
167 // Short lines of ASCII text. LF or CRLF line separators.
168 struct body_ascii
: seq
<star
<seq
<rep_max
<998, text_ascii
>, eol
>>,
169 opt
<rep_max
<998, text_ascii
>>, eof
> {};
171 struct text_utf8
: sor
<text_ascii
, chars::non_ascii
> {};
173 // Short lines of UTF-8 text. LF or CRLF line separators.
174 struct body_utf8
: seq
<star
<seq
<rep_max
<998, text_utf8
>, eol
>>,
175 opt
<rep_max
<998, text_utf8
>>, eof
> {};
177 struct FWS
: seq
<opt
<seq
<star
<WSP
>, eol
>>, plus
<WSP
>> {};
179 struct qtext
: sor
<one
<33>, ranges
<35, 91, 93, 126>, chars::non_ascii
> {};
181 struct quoted_pair
: seq
<one
<'\\'>, sor
<VUCHAR
, WSP
>> {};
183 struct atext
: sor
<ALPHA
, DIGIT
,
194 chars::non_ascii
> {};
196 // ctext is ASCII not '(' or ')' or '\\'
197 struct ctext
: sor
<ranges
<33, 39, 42, 91, 93, 126>, chars::non_ascii
> {};
201 struct ccontent
: sor
<ctext
, quoted_pair
, comment
> {};
204 : seq
<one
<'('>, star
<seq
<opt
<FWS
>, ccontent
>>, opt
<FWS
>, one
<')'>> {};
206 struct CFWS
: sor
<seq
<plus
<seq
<opt
<FWS
>, comment
>, opt
<FWS
>>>, FWS
> {};
208 struct qcontent
: sor
<qtext
, quoted_pair
> {};
210 // Corrected in errata ID: 3135
214 sor
<seq
<star
<seq
<opt
<FWS
>, qcontent
>>, opt
<FWS
>>, FWS
>,
218 // *([FWS] VCHAR) *WSP
219 struct unstructured
: seq
<star
<seq
<opt
<FWS
>, VUCHAR
>>, star
<WSP
>> {};
221 struct atom
: seq
<opt
<CFWS
>, plus
<atext
>, opt
<CFWS
>> {};
223 struct dot_atom_text
: list
<plus
<atext
>, dot
> {};
225 struct dot_atom
: seq
<opt
<CFWS
>, dot_atom_text
, opt
<CFWS
>> {};
227 struct word
: sor
<atom
, quoted_string
> {};
229 struct phrase
: plus
<word
> {};
231 struct local_part
: sor
<dot_atom
, quoted_string
> {};
233 // from '!' to '~' excluding 91 92 93 '[' '\\' ']'
235 struct dtext
: ranges
<33, 90, 94, 126> {};
237 struct domain_literal
: seq
<opt
<CFWS
>,
239 star
<seq
<opt
<FWS
>, dtext
>>,
244 struct domain
: sor
<dot_atom
, domain_literal
> {};
246 struct addr_spec
: seq
<local_part
, one
<'@'>, domain
> {};
248 struct postmaster
: TAO_PEGTL_ISTRING("Postmaster") {};
250 struct addr_spec_or_postmaster
: sor
<addr_spec
, postmaster
> {};
252 struct addr_spec_only
: seq
<addr_spec_or_postmaster
, eof
> {};
254 struct display_name
: phrase
{};
256 struct display_name_only
: seq
<display_name
, eof
> {};
260 // struct name_addr : seq<opt<display_name>, angle_addr> {};
262 // struct mailbox : sor<name_addr, addr_spec> {};
264 template <typename Rule
>
265 struct inaction
: nothing
<Rule
> {
268 template <typename Rule
>
269 struct action
: nothing
<Rule
> {
273 struct action
<local_part
> {
274 template <typename Input
>
275 static void apply(Input
const& in
, Mailbox
& mbx
)
277 mbx
.set_local(in
.string());
282 struct action
<domain
> {
283 template <typename Input
>
284 static void apply(Input
const& in
, Mailbox
& mbx
)
286 mbx
.set_domain(in
.string());
289 } // namespace RFC5322
296 std::string server_id
;
298 std::string ehlo_keyword
;
299 std::vector
<std::string
> ehlo_param
;
300 std::unordered_map
<std::string
, std::vector
<std::string
>> ehlo_params
;
302 std::string reply_code
;
304 bool greeting_ok
{false};
307 bool has_extension(char const* name
) const
309 return ehlo_params
.find(name
) != end(ehlo_params
);
312 Connection(int fd_in
, int fd_out
, std::function
<void(void)> read_hook
)
314 fd_in
, fd_out
, read_hook
, Config::read_timeout
, Config::write_timeout
)
321 using dot
= one
<'.'>;
322 using colon
= one
<':'>;
323 using dash
= one
<'-'>;
325 struct u_let_dig
: sor
<ALPHA
, DIGIT
, chars::non_ascii
> {};
327 struct u_ldh_tail
: star
<sor
<seq
<plus
<one
<'-'>>, u_let_dig
>, u_let_dig
>> {};
329 struct u_label
: seq
<u_let_dig
, u_ldh_tail
> {};
331 struct let_dig
: sor
<ALPHA
, DIGIT
> {};
333 struct ldh_tail
: star
<sor
<seq
<plus
<one
<'-'>>, let_dig
>, let_dig
>> {};
335 struct ldh_str
: seq
<let_dig
, ldh_tail
> {};
337 struct label
: ldh_str
{};
339 struct sub_domain
: sor
<label
, u_label
> {};
341 struct domain
: list
<sub_domain
, dot
> {};
343 struct dec_octet
: sor
<seq
<string
<'2','5'>, range
<'0','5'>>,
344 seq
<one
<'2'>, range
<'0','4'>, DIGIT
>,
345 seq
<range
<'0', '1'>, rep
<2, DIGIT
>>,
346 rep_min_max
<1, 2, DIGIT
>> {};
348 struct IPv4_address_literal
349 : seq
<dec_octet
, dot
, dec_octet
, dot
, dec_octet
, dot
, dec_octet
> {};
351 struct h16
: rep_min_max
<1, 4, HEXDIG
> {};
353 struct ls32
: sor
<seq
<h16
, colon
, h16
>, IPv4_address_literal
> {};
355 struct dcolon
: two
<':'> {};
357 struct IPv6address
: sor
<seq
< rep
<6, h16
, colon
>, ls32
>,
358 seq
< dcolon
, rep
<5, h16
, colon
>, ls32
>,
359 seq
<opt
<h16
>, dcolon
, rep
<4, h16
, colon
>, ls32
>,
360 seq
<opt
<h16
, opt
< colon
, h16
>>, dcolon
, rep
<3, h16
, colon
>, ls32
>,
361 seq
<opt
<h16
, rep_opt
<2, colon
, h16
>>, dcolon
, rep
<2, h16
, colon
>, ls32
>,
362 seq
<opt
<h16
, rep_opt
<3, colon
, h16
>>, dcolon
, h16
, colon
, ls32
>,
363 seq
<opt
<h16
, rep_opt
<4, colon
, h16
>>, dcolon
, ls32
>,
364 seq
<opt
<h16
, rep_opt
<5, colon
, h16
>>, dcolon
, h16
>,
365 seq
<opt
<h16
, rep_opt
<6, colon
, h16
>>, dcolon
>> {};
367 struct IPv6_address_literal
: seq
<TAO_PEGTL_ISTRING("IPv6:"), IPv6address
> {};
369 struct dcontent
: ranges
<33, 90, 94, 126> {};
371 struct standardized_tag
: ldh_str
{};
373 struct general_address_literal
: seq
<standardized_tag
, colon
, plus
<dcontent
>> {};
375 // See rfc 5321 Section 4.1.3
376 struct address_literal
: seq
<one
<'['>,
377 sor
<IPv4_address_literal
,
378 IPv6_address_literal
,
379 general_address_literal
>,
383 struct qtextSMTP
: sor
<ranges
<32, 33, 35, 91, 93, 126>, chars::non_ascii
> {};
384 struct graphic
: range
<32, 126> {};
385 struct quoted_pairSMTP
: seq
<one
<'\\'>, graphic
> {};
386 struct qcontentSMTP
: sor
<qtextSMTP
, quoted_pairSMTP
> {};
388 // excluded from atext: "(),.@[]"
389 struct atext
: sor
<ALPHA
, DIGIT
,
400 chars::non_ascii
> {};
401 struct atom
: plus
<atext
> {};
402 struct dot_string
: list
<atom
, dot
> {};
403 struct quoted_string
: seq
<one
<'"'>, star
<qcontentSMTP
>, one
<'"'>> {};
404 struct local_part
: sor
<dot_string
, quoted_string
> {};
405 struct non_local_part
: sor
<domain
, address_literal
> {};
406 struct mailbox
: seq
<local_part
, one
<'@'>, non_local_part
> {};
408 struct at_domain
: seq
<one
<'@'>, domain
> {};
410 struct a_d_l
: list
<at_domain
, one
<','>> {};
412 struct path
: seq
<opt
<seq
<a_d_l
, colon
>>, mailbox
> {};
414 struct path_only
: seq
<path
, eof
> {};
416 // textstring = 1*(%d09 / %d32-126) ; HT, SP, Printable US-ASCII
418 // Although not explicit in the grammar of RFC-6531, in practice UTF-8
419 // is used in the replys.
421 // struct textstring : plus<sor<one<9>, range<32, 126>>> {};
423 struct textstring
: plus
<sor
<one
<9>, range
<32, 126>, chars::non_ascii
>> {};
425 struct server_id
: sor
<domain
, address_literal
> {};
427 // Greeting = ( "220 " (Domain / address-literal) [ SP textstring ] CRLF )
429 // ( "220-" (Domain / address-literal) [ SP textstring ] CRLF
430 // *( "220-" [ textstring ] CRLF )
431 // "220 " [ textstring ] CRLF )
434 : sor
<seq
<TAO_PEGTL_ISTRING("220 "), server_id
, opt
<textstring
>, CRLF
>,
435 seq
<TAO_PEGTL_ISTRING("220-"), server_id
, opt
<textstring
>, CRLF
,
436 star
<seq
<TAO_PEGTL_ISTRING("220-"), opt
<textstring
>, CRLF
>>,
437 seq
<TAO_PEGTL_ISTRING("220 "), opt
<textstring
>, CRLF
>>> {};
439 // Reply-code = %x32-35 %x30-35 %x30-39
442 : seq
<range
<0x32, 0x35>, range
<0x30, 0x35>, range
<0x30, 0x39>> {};
444 // Reply-line = *( Reply-code "-" [ textstring ] CRLF )
445 // Reply-code [ SP textstring ] CRLF
448 : seq
<star
<seq
<reply_code
, one
<'-'>, opt
<textstring
>, CRLF
>>,
449 seq
<reply_code
, opt
<seq
<SP
, textstring
>>, CRLF
>> {};
452 : sor
<greeting_ok
, reply_lines
> {};
454 // ehlo-greet = 1*(%d0-9 / %d11-12 / %d14-127)
455 // ; string of any characters other than CR or LF
457 struct ehlo_greet
: plus
<ranges
<0, 9, 11, 12, 14, 127>> {};
459 // ehlo-keyword = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")
460 // ; additional syntax of ehlo-params depends on
463 // The '.' we also allow in ehlo-keyword since it has been seen in the
464 // wild at least at 263.net.
466 struct ehlo_keyword
: seq
<sor
<ALPHA
, DIGIT
>, star
<sor
<ALPHA
, DIGIT
, dash
, dot
>>> {};
468 // ehlo-param = 1*(%d33-126)
469 // ; any CHAR excluding <SP> and all
470 // ; control characters (US-ASCII 0-31 and 127
473 struct ehlo_param
: plus
<range
<33, 126>> {};
475 // ehlo-line = ehlo-keyword *( SP ehlo-param )
477 // The AUTH= thing is so common with some servers (postfix) that I
478 // guess we have to accept it.
481 : seq
<ehlo_keyword
, star
<seq
<sor
<SP
,one
<'='>>, ehlo_param
>>> {};
483 // ehlo-ok-rsp = ( "250 " Domain [ SP ehlo-greet ] CRLF )
485 // ( "250-" Domain [ SP ehlo-greet ] CRLF
486 // *( "250-" ehlo-line CRLF )
487 // "250 " ehlo-line CRLF )
489 // The last line having the optional ehlo_line is not strictly correct.
490 // Was added to work with postfix/src/smtpstone/smtp-sink.c.
493 : sor
<seq
<TAO_PEGTL_ISTRING("250 "), server_id
, opt
<ehlo_greet
>, CRLF
>,
495 seq
<TAO_PEGTL_ISTRING("250-"), server_id
, opt
<ehlo_greet
>, CRLF
,
496 star
<seq
<TAO_PEGTL_ISTRING("250-"), ehlo_line
, CRLF
>>,
497 seq
<TAO_PEGTL_ISTRING("250 "), opt
<ehlo_line
>, CRLF
>>
501 : sor
<ehlo_ok_rsp
, reply_lines
> {};
504 : seq
<TAO_PEGTL_ISTRING("250 "), server_id
, opt
<ehlo_greet
>, CRLF
> {};
506 struct auth_login_username
507 : seq
<TAO_PEGTL_STRING("334 VXNlcm5hbWU6"), CRLF
> {};
509 struct auth_login_password
510 : seq
<TAO_PEGTL_STRING("334 UGFzc3dvcmQ6"), CRLF
> {};
514 template <typename Rule
>
515 struct inaction
: nothing
<Rule
> {
518 template <typename Rule
>
519 struct action
: nothing
<Rule
> {
523 struct action
<server_id
> {
524 template <typename Input
>
525 static void apply(Input
const& in
, Connection
& cnn
)
527 cnn
.server_id
= in
.string();
532 struct action
<local_part
> {
533 template <typename Input
>
534 static void apply(Input
const& in
, Mailbox
& mbx
)
536 mbx
.set_local(in
.string());
541 struct action
<non_local_part
> {
542 template <typename Input
>
543 static void apply(Input
const& in
, Mailbox
& mbx
)
545 mbx
.set_domain(in
.string());
550 struct action
<greeting_ok
> {
551 template <typename Input
>
552 static void apply(Input
const& in
, Connection
& cnn
)
554 cnn
.greeting_ok
= true;
555 imemstream stream
{begin(in
), size(in
)};
557 while (std::getline(stream
, line
)) {
558 LOG(INFO
) << " S: " << line
;
564 struct action
<ehlo_ok_rsp
> {
565 template <typename Input
>
566 static void apply(Input
const& in
, Connection
& cnn
)
569 imemstream stream
{begin(in
), size(in
)};
571 while (std::getline(stream
, line
)) {
572 LOG(INFO
) << " S: " << line
;
578 struct action
<ehlo_keyword
> {
579 template <typename Input
>
580 static void apply(Input
const& in
, Connection
& cnn
)
582 cnn
.ehlo_keyword
= in
.string();
583 boost::to_upper(cnn
.ehlo_keyword
);
588 struct action
<ehlo_param
> {
589 template <typename Input
>
590 static void apply(Input
const& in
, Connection
& cnn
)
592 cnn
.ehlo_param
.push_back(in
.string());
597 struct action
<ehlo_line
> {
598 template <typename Input
>
599 static void apply(Input
const& in
, Connection
& cnn
)
601 cnn
.ehlo_params
.emplace(std::move(cnn
.ehlo_keyword
),
602 std::move(cnn
.ehlo_param
));
607 struct action
<reply_lines
> {
608 template <typename Input
>
609 static void apply(Input
const& in
, Connection
& cnn
)
611 imemstream stream
{begin(in
), size(in
)};
613 while (std::getline(stream
, line
)) {
614 LOG(INFO
) << " S: " << line
;
620 struct action
<reply_code
> {
621 template <typename Input
>
622 static void apply(Input
const& in
, Connection
& cnn
)
624 cnn
.reply_code
= in
.string();
627 } // namespace RFC5321
631 int conn(DNS::Resolver
& res
, Domain
const& node
, uint16_t port
)
633 auto const use_4
{!FLAGS_6
};
634 auto const use_6
{!FLAGS_4
};
637 auto const fd
{socket(AF_INET6
, SOCK_STREAM
, 0)};
638 PCHECK(fd
>= 0) << "socket() failed";
640 if (!FLAGS_local_address
.empty()) {
641 auto loc
{sockaddr_in6
{}};
642 loc
.sin6_family
= AF_INET6
;
644 != inet_pton(AF_INET6
, FLAGS_local_address
.c_str(),
645 reinterpret_cast<void*>(&loc
.sin6_addr
))) {
646 LOG(FATAL
) << "can't interpret " << FLAGS_local_address
647 << " as IPv6 address";
649 PCHECK(0 == bind(fd
, reinterpret_cast<sockaddr
*>(&loc
), sizeof(loc
)));
652 auto addrs
{std::vector
<std::string
>{}};
654 if (node
.is_address_literal()) {
655 if (IP6::is_address(node
.ascii())) {
656 addrs
.push_back(node
.ascii());
658 if (IP6::is_address_literal(node
.ascii())) {
659 auto const addr
= IP6::as_address(node
.ascii());
660 addrs
.push_back(std::string(addr
.data(), addr
.length()));
664 addrs
= res
.get_strings(DNS::RR_type::AAAA
, node
.ascii());
666 for (auto const& addr
: addrs
) {
667 auto in6
{sockaddr_in6
{}};
668 in6
.sin6_family
= AF_INET6
;
669 in6
.sin6_port
= htons(port
);
670 CHECK_EQ(inet_pton(AF_INET6
, addr
.c_str(),
671 reinterpret_cast<void*>(&in6
.sin6_addr
)),
673 if (connect(fd
, reinterpret_cast<const sockaddr
*>(&in6
), sizeof(in6
))) {
674 PLOG(WARNING
) << "connect failed [" << addr
<< "]:" << port
;
678 LOG(INFO
) << fd
<< " connected to [" << addr
<< "]:" << port
;
685 auto fd
{socket(AF_INET
, SOCK_STREAM
, 0)};
686 PCHECK(fd
>= 0) << "socket() failed";
688 if (!FLAGS_local_address
.empty()) {
689 auto loc
{sockaddr_in
{}};
690 loc
.sin_family
= AF_INET
;
692 != inet_pton(AF_INET
, FLAGS_local_address
.c_str(),
693 reinterpret_cast<void*>(&loc
.sin_addr
))) {
694 LOG(FATAL
) << "can't interpret " << FLAGS_local_address
695 << " as IPv4 address";
697 PCHECK(0 == bind(fd
, reinterpret_cast<sockaddr
*>(&loc
), sizeof(loc
)));
700 auto addrs
{std::vector
<std::string
>{}};
701 if (node
.is_address_literal()) {
702 if (IP4::is_address(node
.ascii())) {
703 addrs
.push_back(node
.ascii());
705 if (IP4::is_address_literal(node
.ascii())) {
706 auto const addr
= IP4::as_address(node
.ascii());
707 addrs
.push_back(std::string(addr
.data(), addr
.length()));
711 addrs
= res
.get_strings(DNS::RR_type::A
, node
.ascii());
713 for (auto addr
: addrs
) {
714 auto in4
{sockaddr_in
{}};
715 in4
.sin_family
= AF_INET
;
716 in4
.sin_port
= htons(port
);
717 CHECK_EQ(inet_pton(AF_INET
, addr
.c_str(),
718 reinterpret_cast<void*>(&in4
.sin_addr
)),
720 if (connect(fd
, reinterpret_cast<const sockaddr
*>(&in4
), sizeof(in4
))) {
721 PLOG(WARNING
) << "connect failed " << addr
<< ":" << port
;
725 LOG(INFO
) << fd
<< " connected to " << addr
<< ":" << port
;
737 void add_hdr(std::string name
, std::string value
)
739 hdrs_
.push_back(std::make_pair(name
, value
));
742 void foreach_hdr(std::function
<void(std::string
const& name
,
743 std::string
const& value
)> func
)
745 for (auto const& [name
, value
] : hdrs_
) {
751 std::vector
<std::pair
<std::string
, std::string
>> hdrs_
;
753 friend std::ostream
& operator<<(std::ostream
& os
, Eml
const& eml
)
755 for (auto const& [name
, value
] : eml
.hdrs_
) {
756 os
<< name
<< ": " << value
<< "\r\n";
758 return os
<< "\r\n"; // end of headers
762 // // clang-format off
763 // char const* const signhdrs[] = {
779 // "Content-Transfer-Encoding",
785 enum class transfer_encoding
{
793 enum class data_type
{
794 ascii
, // 7bit, quoted-printable and base64
799 data_type
type(std::string_view d
)
802 auto in
{memory_input
<>{d
.data(), d
.size(), "data"}};
803 if (parse
<RFC5322::body_ascii
>(in
)) {
804 return data_type::ascii
;
808 auto in
{memory_input
<>{d
.data(), d
.size(), "data"}};
809 if (parse
<RFC5322::body_utf8
>(in
)) {
810 return data_type::utf8
;
814 return data_type::binary
;
819 content(char const* path
)
822 auto const body_sz
{fs::file_size(path_
)};
823 CHECK(body_sz
) << "no body";
825 type_
= ::type(*this);
828 char const* data() const { return file_
.data(); }
829 size_t size() const { return file_
.size(); }
830 data_type
type() const { return type_
; }
832 bool empty() const { return size() == 0; }
833 operator std::string_view() const { return std::string_view(data(), size()); }
838 boost::iostreams::mapped_file_source file_
;
841 template <typename Input
>
842 void fail(Input
& in
, RFC5321::Connection
& cnn
)
844 LOG(INFO
) << " C: QUIT";
845 cnn
.sock
.out() << "QUIT\r\n" << std::flush
;
846 // we might have a few error replies stacked up if we're pipelining
847 // CHECK((parse<RFC5321::reply_lines, RFC5321::action>(in, cnn)));
851 template <typename Input
>
852 void check_for_fail(Input
& in
, RFC5321::Connection
& cnn
, std::string_view cmd
)
854 cnn
.sock
.out() << std::flush
;
855 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
856 if (cnn
.reply_code
.at(0) != '2') {
857 LOG(ERROR
) << cmd
<< " returned " << cnn
.reply_code
;
863 bool validate_name(const char* flagname
, std::string
const& value
)
865 if (value
.empty()) // empty name needs to validate, but
866 return true; // will not be used
867 memory_input
<> name_in(value
.c_str(), "name");
868 if (!parse
<RFC5322::display_name_only
, RFC5322::inaction
>(name_in
)) {
869 LOG(ERROR
) << "bad name syntax " << value
;
875 DEFINE_validator(from_name
, &validate_name
);
876 DEFINE_validator(to_name
, &validate_name
);
878 bool validate_address_RFC5322(const char* flagname
, std::string
const& value
)
880 if (value
.empty()) // empty name needs to validate, but
881 return true; // will not be used
882 memory_input
<> name_in(value
.c_str(), "address");
883 if (!parse
<RFC5322::addr_spec_only
, RFC5322::inaction
>(name_in
)) {
884 LOG(ERROR
) << "bad address syntax " << value
;
890 DEFINE_validator(from
, &validate_address_RFC5322
);
891 DEFINE_validator(to
, &validate_address_RFC5322
);
893 bool validate_address_RFC5321(const char* flagname
, std::string
const& value
)
895 if (value
.empty()) // empty name needs to validate, but
896 return true; // will not be used
897 memory_input
<> name_in(value
.c_str(), "path");
898 if (!parse
<RFC5321::path_only
, RFC5321::inaction
>(name_in
)) {
899 LOG(ERROR
) << "bad address syntax " << value
;
905 DEFINE_validator(smtp_from
, &validate_address_RFC5321
);
906 DEFINE_validator(smtp_to
, &validate_address_RFC5321
);
910 CHECK(validate_name("selftest", ""s
));
911 CHECK(validate_name("selftest", "Elmer J Fudd"s
));
912 CHECK(validate_name("selftest", "\"Elmer J. Fudd\""s
));
913 CHECK(validate_name("selftest", "Elmer! J! Fudd!"s
));
915 CHECK(validate_address_RFC5321("selftest", "foo@digilicious.com"s
));
916 CHECK(validate_address_RFC5321("selftest", "\"foo\"@digilicious.com"s
));
917 CHECK(validate_address_RFC5321(
919 "\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@digilicious.com"s
));
921 CHECK(validate_address_RFC5322("selftest", "foo@digilicious.com"s
));
922 CHECK(validate_address_RFC5322("selftest", "\"foo\"@digilicious.com"s
));
923 CHECK(validate_address_RFC5322(
925 "\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@digilicious.com"s
));
927 auto const read_hook
{[]() {}};
929 const char* greet_list
[]{
930 "220-mtaig-aak03.mx.aol.com ESMTP Internet Inbound\r\n"
931 "220-AOL and its affiliated companies do not\r\n"
932 "220-authorize the use of its proprietary computers and computer\r\n"
933 "220-networks to accept, transmit, or distribute unsolicited bulk\r\n"
934 "220-e-mail sent from the internet.\r\n"
935 "220-Effective immediately:\r\n"
936 "220-AOL may no longer accept connections from IP addresses\r\n"
937 "220 which no do not have reverse-DNS (PTR records) assigned.\r\n",
939 "421 mtaig-maa02.mx.aol.com Service unavailable - try again later\r\n",
942 for (auto i
: greet_list
) {
943 auto cnn
{RFC5321::Connection(0, 1, read_hook
)};
944 auto in
{memory_input
<>{i
, i
}};
945 if (!parse
<RFC5321::greeting
, RFC5321::action
/*, tao::pegtl::tracer*/>(
947 LOG(FATAL
) << "Error parsing greeting \"" << i
<< "\"";
949 if (cnn
.greeting_ok
) {
950 LOG(WARNING
) << "greeting ok";
953 LOG(WARNING
) << "greeting was not in the affirmative";
957 const char* ehlo_rsp_list
[]{
958 "250-HELLO, SAILOR!\r\n"
959 "250-NO-SOLICITING\r\n"
962 "250-digilicious.com at your service, localhost. [IPv6:::1]\r\n"
963 "250-SIZE 15728640\r\n"
966 "250-ENHANCEDSTATUSCODES\r\n"
972 "500 5.5.1 command unrecognized: \"EHLO digilicious.com\\r\\n\"\r\n",
974 "250-263xmail at your service\r\n"
977 "250-263.net\r\n" // the '.' is not RFC complaint
978 "250-SIZE 104857600\r\n"
980 "250-ENHANCEDSTATUSCODES\r\n"
985 for (auto i
: ehlo_rsp_list
) {
986 auto cnn
{RFC5321::Connection(0, 1, read_hook
)};
987 auto in
{memory_input
<>{i
, i
}};
988 if (!parse
<RFC5321::ehlo_rsp
, RFC5321::action
/*, tao::pegtl::tracer*/>(
990 LOG(FATAL
) << "Error parsing ehlo response \"" << i
<< "\"";
993 LOG(WARNING
) << "ehlo ok";
996 LOG(WARNING
) << "ehlo response was not in the affirmative";
1003 if (FLAGS_sender
.empty()) {
1004 FLAGS_sender
= {[] {
1005 if (!FLAGS_client_id
.empty())
1006 return FLAGS_client_id
;
1008 auto const id_from_env
{getenv("GHSMTP_CLIENT_ID")};
1010 return std::string
{id_from_env
};
1012 auto const hostname
{osutil::get_hostname()};
1013 if (hostname
.find('.') != std::string::npos
)
1016 LOG(FATAL
) << "can't determine my client ID, set GHSMTP_CLIENT_ID maybe";
1020 auto const sender
{Domain
{FLAGS_sender
}};
1022 if (FLAGS_from
.empty()) {
1023 FLAGS_from
= "test-it@"s
+ sender
.utf8();
1026 if (FLAGS_to
.empty()) {
1027 FLAGS_to
= "test-it@"s
+ sender
.utf8();
1033 bool is_localhost(DNS::RR
const& rr
)
1035 if (std::holds_alternative
<DNS::RR_MX
>(rr
)) {
1036 if (iequal(std::get
<DNS::RR_MX
>(rr
).exchange(), "localhost"))
1042 bool starts_with(std::string_view str
, std::string_view prefix
)
1044 if (str
.size() >= prefix
.size())
1045 if (str
.compare(0, prefix
.size(), prefix
) == 0)
1050 bool sts_rec(std::string
const& sts_rec
)
1052 return starts_with(sts_rec
, "v=STSv1");
1056 get_receivers(DNS::Resolver
& res
, Mailbox
const& to_mbx
, bool& enforce_dane
)
1058 auto receivers
{std::vector
<Domain
>{}};
1060 // User provided explicit host to receive mail.
1061 if (!FLAGS_mx_host
.empty()) {
1062 receivers
.emplace_back(FLAGS_mx_host
);
1066 // Non-local part is an address literal.
1067 if (to_mbx
.domain().is_address_literal()) {
1068 receivers
.emplace_back(to_mbx
.domain());
1072 // RFC 5321 section 5.1 "Locating the Target Host"
1074 // “The lookup first attempts to locate an MX record associated with
1075 // the name. If a CNAME record is found, the resulting name is
1076 // processed as if it were the initial name.”
1078 // Our (full) resolver will traverse any CNAMEs for us and return
1079 // the CNAME and MX records all together.
1081 auto const& domain
= to_mbx
.domain().ascii();
1083 auto q_sts
{DNS::Query
{res
, DNS::RR_type::TXT
, "_mta-sts."s
+ domain
}};
1084 if (q_sts
.has_record()) {
1085 auto sts_records
= q_sts
.get_strings();
1086 sts_records
.erase(std::remove_if(begin(sts_records
), end(sts_records
),
1087 std::not_fn(sts_rec
)),
1089 if (size(sts_records
) == 1) {
1090 LOG(INFO
) << "### This domain implements MTA-STS ###";
1094 LOG(INFO
) << "MTA-STS record not found for domain " << domain
;
1097 auto q
{DNS::Query
{res
, DNS::RR_type::MX
, domain
}};
1098 if (q
.has_record()) {
1099 if (q
.authentic_data()) {
1100 LOG(INFO
) << "### MX records authentic for domain " << domain
<< " ###";
1103 LOG(INFO
) << "MX records can't be authenticated for domain " << domain
;
1104 enforce_dane
= false;
1107 auto mxs
{q
.get_records()};
1109 mxs
.erase(std::remove_if(begin(mxs
), end(mxs
), is_localhost
), end(mxs
));
1111 auto const nmx
= std::count_if(begin(mxs
), end(mxs
), [](auto const& rr
) {
1112 return std::holds_alternative
<DNS::RR_MX
>(rr
);
1116 for (auto const& mx
: mxs
) {
1117 if (std::holds_alternative
<DNS::RR_MX
>(mx
)) {
1118 // RFC 7505 null MX record
1119 if ((std::get
<DNS::RR_MX
>(mx
).preference() == 0)
1120 && (std::get
<DNS::RR_MX
>(mx
).exchange().empty()
1121 || (std::get
<DNS::RR_MX
>(mx
).exchange() == "."))) {
1122 LOG(INFO
) << "domain " << domain
<< " does not accept mail";
1131 receivers
.emplace_back(domain
);
1135 // […] then the sender-SMTP MUST randomize them to spread the load
1136 // across multiple mail exchangers for a specific organization.
1137 std::shuffle(begin(mxs
), end(mxs
), std::random_device());
1138 std::sort(begin(mxs
), end(mxs
), [](auto const& a
, auto const& b
) {
1139 if (std::holds_alternative
<DNS::RR_MX
>(a
)
1140 && std::holds_alternative
<DNS::RR_MX
>(b
)) {
1141 return std::get
<DNS::RR_MX
>(a
).preference()
1142 < std::get
<DNS::RR_MX
>(b
).preference();
1148 LOG(INFO
) << "MXs for " << domain
<< " are:";
1150 for (auto const& mx
: mxs
) {
1151 if (std::holds_alternative
<DNS::RR_MX
>(mx
)) {
1152 receivers
.emplace_back(std::get
<DNS::RR_MX
>(mx
).exchange());
1153 LOG(INFO
) << std::setfill(' ') << std::setw(3)
1154 << std::get
<DNS::RR_MX
>(mx
).preference() << " "
1155 << std::get
<DNS::RR_MX
>(mx
).exchange();
1162 auto parse_mailboxes()
1164 auto from_mbx
{Mailbox
{}};
1165 auto from_in
{memory_input
<>{FLAGS_from
, "from"}};
1166 if (!parse
<RFC5322::addr_spec_only
, RFC5322::action
>(from_in
, from_mbx
)) {
1167 LOG(FATAL
) << "bad From: address syntax <" << FLAGS_from
<< ">";
1169 LOG(INFO
) << " from_mbx == " << from_mbx
;
1171 auto local_from
{memory_input
<>{from_mbx
.local_part(), "from.local"}};
1172 FLAGS_force_smtputf8
|= !parse
<chars::ascii_only
>(local_from
);
1174 auto to_mbx
{Mailbox
{}};
1175 auto to_in
{memory_input
<>{FLAGS_to
, "to"}};
1176 if (!parse
<RFC5322::addr_spec_only
, RFC5322::action
>(to_in
, to_mbx
)) {
1177 LOG(FATAL
) << "bad To: address syntax <" << FLAGS_to
<< ">";
1179 LOG(INFO
) << " to_mbx == " << to_mbx
;
1181 auto local_to
{memory_input
<>{to_mbx
.local_part(), "to.local"}};
1182 FLAGS_force_smtputf8
|= !parse
<chars::ascii_only
>(local_to
);
1184 auto smtp_from_mbx
{Mailbox
{}};
1185 auto smtp_from_in
{memory_input
<>{FLAGS_smtp_from
, "SMTP.from"}};
1186 if (!FLAGS_smtp_from
.empty()) {
1187 if (!parse
<RFC5321::path_only
, RFC5321::action
>(smtp_from_in
,
1189 LOG(FATAL
) << "bad MAIL FROM: address syntax <" << FLAGS_smtp_from
<< ">";
1191 LOG(INFO
) << " smtp_from_mbx == " << smtp_from_mbx
;
1192 auto local_smtp_from
{
1193 memory_input
<>{smtp_from_mbx
.local_part(), "SMTP.from.local"}};
1194 FLAGS_force_smtputf8
|= !parse
<chars::ascii_only
>(local_smtp_from
);
1197 auto smtp_to_mbx
{Mailbox
{}};
1198 auto smtp_to_in
{memory_input
<>{FLAGS_smtp_to
, "SMTP.to"}};
1199 if (!FLAGS_smtp_to
.empty()) {
1200 if (!parse
<RFC5321::path_only
, RFC5321::action
>(smtp_to_in
, smtp_to_mbx
)) {
1201 LOG(FATAL
) << "bad RCPT TO: address syntax <" << FLAGS_smtp_to
<< ">";
1203 LOG(INFO
) << " smtp_to_mbx == " << smtp_to_mbx
;
1206 memory_input
<>{smtp_to_mbx
.local_part(), "SMTP.to.local"}};
1207 FLAGS_force_smtputf8
|= !parse
<chars::ascii_only
>(local_smtp_to
);
1210 return std::tuple(from_mbx
, to_mbx
, smtp_from_mbx
, smtp_to_mbx
);
1213 auto create_eml(Domain
const& sender
,
1214 std::string
const& from
,
1215 std::string
const& to
,
1216 std::vector
<content
> const& bodies
,
1220 auto const date
{Now
{}};
1221 auto const pill
{Pill
{}};
1223 auto mid_str
= fmt::format("<{}.{}@{}>", date
.sec(), pill
, sender
.ascii());
1224 eml
.add_hdr("Message-ID", mid_str
.c_str());
1225 eml
.add_hdr("Date", date
.c_str());
1227 if (!FLAGS_from_name
.empty())
1228 eml
.add_hdr("From", fmt::format("{} <{}>", FLAGS_from_name
, from
));
1230 eml
.add_hdr("From", from
);
1232 if (!FLAGS_to_name
.empty())
1233 eml
.add_hdr("To", fmt::format("{} <{}>", FLAGS_to_name
, to
));
1235 eml
.add_hdr("To", to
);
1237 eml
.add_hdr("Subject", FLAGS_subject
);
1239 if (!FLAGS_keywords
.empty())
1240 eml
.add_hdr("Keywords", FLAGS_keywords
);
1242 if (!FLAGS_references
.empty())
1243 eml
.add_hdr("References", FLAGS_references
);
1245 if (!FLAGS_in_reply_to
.empty())
1246 eml
.add_hdr("In-Reply-To", FLAGS_in_reply_to
);
1248 if (!FLAGS_reply_to
.empty())
1249 eml
.add_hdr("Reply-To", FLAGS_reply_to
);
1251 eml
.add_hdr("MIME-Version", "1.0");
1252 eml
.add_hdr("Content-Language", "en-US");
1254 auto magic
{Magic
{}}; // to ID buffer contents
1256 eml
.add_hdr("Content-Type", magic
.buffer(bodies
[0]));
1261 void sign_eml(Eml
& eml
,
1262 Mailbox
const& from_mbx
,
1263 std::vector
<content
> const& bodies
)
1265 auto const body_type
= (bodies
[0].type() == data_type::binary
)
1266 ? OpenDKIM::sign::body_type::binary
1267 : OpenDKIM::sign::body_type::text
;
1269 auto const key_file
= FLAGS_dkim_key_file
.empty()
1270 ? (FLAGS_selector
+ ".private")
1271 : FLAGS_dkim_key_file
;
1272 std::ifstream
keyfs(key_file
.c_str());
1273 CHECK(keyfs
.good()) << "can't access " << key_file
;
1274 std::string
key(std::istreambuf_iterator
<char>{keyfs
}, {});
1275 OpenDKIM::sign
dks(key
.c_str(), FLAGS_selector
.c_str(),
1276 from_mbx
.domain().ascii().c_str(), body_type
);
1277 eml
.foreach_hdr([&dks
](std::string
const& name
, std::string
const& value
) {
1278 auto header
= name
+ ": "s
+ value
;
1279 dks
.header(header
.c_str());
1282 for (auto const& body
: bodies
) {
1286 eml
.add_hdr("DKIM-Signature"s
, dks
.getsighdr());
1289 template <typename Input
>
1290 void do_auth(Input
& in
, RFC5321::Connection
& cnn
)
1292 if (FLAGS_username
.empty() && FLAGS_password
.empty())
1295 auto const auth
= cnn
.ehlo_params
.find("AUTH");
1296 if (auth
== end(cnn
.ehlo_params
)) {
1297 LOG(ERROR
) << "server doesn't support AUTH";
1301 // Perfer PLAIN mechanism.
1302 if (std::find(begin(auth
->second
), end(auth
->second
), "PLAIN")
1303 != end(auth
->second
)) {
1304 LOG(INFO
) << "C: AUTH PLAIN";
1305 auto const tok
= fmt::format("\0{}\0{}"s
, FLAGS_username
, FLAGS_password
);
1306 cnn
.sock
.out() << "AUTH PLAIN " << Base64::enc(tok
) << "\r\n" << std::flush
;
1307 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1308 if (cnn
.reply_code
!= "235") {
1309 LOG(ERROR
) << "AUTH PLAIN returned " << cnn
.reply_code
;
1313 // The LOGIN SASL mechanism is obsolete.
1314 else if (std::find(begin(auth
->second
), end(auth
->second
), "LOGIN")
1315 != end(auth
->second
)) {
1316 LOG(INFO
) << "C: AUTH LOGIN";
1317 cnn
.sock
.out() << "AUTH LOGIN\r\n" << std::flush
;
1318 CHECK((parse
<RFC5321::auth_login_username
>(in
)));
1319 cnn
.sock
.out() << Base64::enc(FLAGS_username
) << "\r\n" << std::flush
;
1320 CHECK((parse
<RFC5321::auth_login_password
>(in
)));
1321 cnn
.sock
.out() << Base64::enc(FLAGS_password
) << "\r\n" << std::flush
;
1322 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1323 if (cnn
.reply_code
!= "235") {
1324 LOG(ERROR
) << "AUTH LOGIN returned " << cnn
.reply_code
;
1329 LOG(ERROR
) << "server doesn't support AUTH methods PLAIN or LOGIN";
1334 // Do various bad things during the DATA transfer.
1336 template <typename Input
>
1337 void bad_daddy(Input
& in
, RFC5321::Connection
& cnn
)
1339 LOG(INFO
) << "C: DATA";
1340 cnn
.sock
.out() << "DATA\r\n";
1341 cnn
.sock
.out() << std::flush
;
1343 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1344 if (cnn
.reply_code
!= "354") {
1345 LOG(ERROR
) << "DATA returned " << cnn
.reply_code
;
1349 // cnn.sock.out() << "\r\nThis ->\n<- is a bare LF!\r\n";
1351 cnn
.sock
.out() << "\n.\n\r\n";
1353 if (FLAGS_to_the_neck
) {
1355 cnn
.sock
.out() << "####################"
1356 "####################"
1357 "####################"
1362 if (FLAGS_long_line
) {
1363 for (auto i
{0}; i
< 10000; ++i
) {
1364 cnn
.sock
.out() << 'X';
1366 cnn
.sock
.out() << "\r\n" << std::flush
;
1369 while (FLAGS_slow_strangle
) {
1370 for (auto i
{0}; i
< 500; ++i
) {
1371 cnn
.sock
.out() << 'X' << std::flush
;
1374 cnn
.sock
.out() << "\r\n";
1378 cnn
.sock
.out() << ".\r\n" << std::flush
;
1379 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1381 LOG(INFO
) << "reply_code == " << cnn
.reply_code
;
1382 CHECK_EQ(cnn
.reply_code
.at(0), '2');
1384 LOG(INFO
) << "C: QUIT";
1385 cnn
.sock
.out() << "QUIT\r\n" << std::flush
;
1386 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1389 bool snd(fs::path config_path
,
1392 Domain
const& sender
,
1393 Domain
const& receiver
,
1394 DNS::RR_collection
const& tlsa_rrs
,
1396 Mailbox
const& from_mbx
,
1397 Mailbox
const& to_mbx
,
1398 Mailbox
const& smtp_from_mbx
,
1399 Mailbox
const& smtp_to_mbx
,
1400 std::vector
<content
> const& bodies
)
1402 auto constexpr read_hook
{[]() {}};
1404 auto cnn
{RFC5321::Connection(fd_in
, fd_out
, read_hook
)};
1407 istream_input
<eol::crlf
, 1>{cnn
.sock
.in(), FLAGS_bfr_size
, "session"}};
1408 if (!parse
<RFC5321::greeting
, RFC5321::action
>(in
, cnn
)) {
1409 LOG(WARNING
) << "can't parse greeting";
1413 if (!cnn
.greeting_ok
) {
1414 LOG(WARNING
) << "greeting was not in the affirmative, skipping";
1420 if (FLAGS_use_esmtp
) {
1421 LOG(INFO
) << "C: EHLO " << sender
.ascii();
1423 if (FLAGS_slow_strangle
) {
1424 auto ehlo_str
= fmt::format("EHLO {}\r\n", sender
.ascii());
1425 for (auto ch
: ehlo_str
) {
1426 cnn
.sock
.out() << ch
<< std::flush
;
1431 cnn
.sock
.out() << "EHLO " << sender
.ascii() << "\r\n" << std::flush
;
1434 CHECK((parse
<RFC5321::ehlo_rsp
, RFC5321::action
>(in
, cnn
)));
1437 if (FLAGS_force_smtputf8
) {
1438 LOG(WARNING
) << "ehlo response was not in the affirmative, skipping";
1442 LOG(WARNING
) << "ehlo response was not in the affirmative, trying HELO";
1443 FLAGS_use_esmtp
= false;
1447 if (!FLAGS_use_esmtp
) {
1448 LOG(INFO
) << "C: HELO " << sender
.ascii();
1449 cnn
.sock
.out() << "HELO " << sender
.ascii() << "\r\n" << std::flush
;
1450 if (!parse
<RFC5321::helo_ok_rsp
, RFC5321::action
>(in
, cnn
)) {
1451 LOG(WARNING
) << "HELO didn't work, skipping";
1458 auto bad_dad
= FLAGS_bare_lf
|| FLAGS_slow_strangle
|| FLAGS_to_the_neck
;
1461 FLAGS_use_chunking
= false;
1462 FLAGS_use_size
= false;
1465 auto const ext_8bitmime
{FLAGS_use_8bitmime
&& cnn
.has_extension("8BITMIME")};
1467 auto const ext_chunking
{FLAGS_use_chunking
&& cnn
.has_extension("CHUNKING")};
1469 auto const ext_binarymime
{FLAGS_use_binarymime
&& ext_chunking
1470 && cnn
.has_extension("BINARYMIME")};
1472 auto const ext_deliverby
{FLAGS_use_deliverby
1473 && cnn
.has_extension("DELIVERBY")};
1475 auto const ext_pipelining
{FLAGS_use_pipelining
1476 && cnn
.has_extension("PIPELINING")};
1478 auto const ext_size
{FLAGS_use_size
&& cnn
.has_extension("SIZE")};
1480 auto const ext_smtputf8
{FLAGS_use_smtputf8
&& cnn
.has_extension("SMTPUTF8")};
1482 auto const ext_starttls
{FLAGS_use_tls
&& cnn
.has_extension("STARTTLS")};
1484 if (FLAGS_force_smtputf8
&& !ext_smtputf8
) {
1485 LOG(WARNING
) << "no SMTPUTF8, skipping";
1490 LOG(INFO
) << "C: STARTTLS";
1491 cnn
.sock
.out() << "STARTTLS\r\n" << std::flush
;
1492 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1494 // LOG(INFO) << "cnn.sock.starttls_client(" << receiver.ascii() << ");";
1495 cnn
.sock
.starttls_client(config_path
, sender
.ascii().c_str(),
1496 receiver
.ascii().c_str(), tlsa_rrs
, enforce_dane
);
1498 LOG(INFO
) << "TLS: " << cnn
.sock
.tls_info();
1500 LOG(INFO
) << "C: EHLO " << sender
.ascii();
1501 cnn
.sock
.out() << "EHLO " << sender
.ascii() << "\r\n" << std::flush
;
1502 CHECK((parse
<RFC5321::ehlo_ok_rsp
, RFC5321::action
>(in
, cnn
)));
1504 else if (FLAGS_require_tls
) {
1505 LOG(ERROR
) << "No TLS extension, won't send mail in plain text without "
1506 "--require_tls=false.";
1507 LOG(INFO
) << "C: QUIT";
1508 cnn
.sock
.out() << "QUIT\r\n" << std::flush
;
1509 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1514 LOG(INFO
) << "C: NOOP";
1515 cnn
.sock
.out() << "NOOP\r\n" << std::flush
;
1518 if (receiver
!= cnn
.server_id
) {
1519 LOG(INFO
) << "server identifies as " << cnn
.server_id
;
1522 if (FLAGS_force_smtputf8
&& !ext_smtputf8
) {
1523 LOG(WARNING
) << "does not support SMTPUTF8";
1527 if (ext_smtputf8
&& !ext_8bitmime
) {
1529 << "SMTPUTF8 requires 8BITMIME, see RFC-6531 section 3.1 item 8.";
1530 LOG(INFO
) << "C: QUIT";
1531 cnn
.sock
.out() << "QUIT\r\n" << std::flush
;
1532 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1536 auto max_msg_size
{0u};
1538 if (!cnn
.ehlo_params
["SIZE"].empty()) {
1540 max_msg_size
= strtoul(cnn
.ehlo_params
["SIZE"][0].c_str(), &ep
, 10);
1541 if (ep
&& (*ep
!= '\0')) {
1542 LOG(WARNING
) << "garbage in SIZE argument: "
1543 << cnn
.ehlo_params
["SIZE"][0];
1548 auto deliver_by
{0u};
1549 if (ext_deliverby
) {
1550 if (!cnn
.ehlo_params
["DELIVERBY"].empty()) {
1552 max_msg_size
= strtoul(cnn
.ehlo_params
["DELIVERBY"][0].c_str(), &ep
, 10);
1553 if (ep
&& (*ep
!= '\0')) {
1554 LOG(WARNING
) << "garbage in DELIVERBY argument: "
1555 << cnn
.ehlo_params
["DELIVERBY"][0];
1563 auto enc
= FLAGS_force_smtputf8
? Mailbox::domain_encoding::utf8
1564 : Mailbox::domain_encoding::ascii
;
1566 std::string from
= smtp_from_mbx
.empty() ? from_mbx
.as_string(enc
)
1567 : smtp_from_mbx
.as_string(enc
);
1568 std::string to
= smtp_to_mbx
.empty() ? to_mbx
.as_string(enc
)
1569 : smtp_to_mbx
.as_string(enc
);
1571 auto eml
{create_eml(sender
, from
, to
, bodies
, ext_smtputf8
)};
1573 if (FLAGS_use_dkim
) {
1574 sign_eml(eml
, from_mbx
, bodies
);
1577 // Get the header as one big string
1578 std::ostringstream hdr_stream
;
1580 auto const& hdr_str
= hdr_stream
.str();
1582 // In the case of DATA style transfer, this total_size number is an
1583 // *estimate* only, as line endings may be translated or added
1584 // during transfer. In the BDAT case, this number must be exact.
1586 auto total_size
= hdr_str
.size();
1587 for (auto const& body
: bodies
)
1588 total_size
+= body
.size();
1590 if (ext_size
&& max_msg_size
&& (total_size
> max_msg_size
)) {
1591 LOG(ERROR
) << "message size " << total_size
<< " exceeds size limit of "
1593 LOG(INFO
) << "C: QUIT";
1594 cnn
.sock
.out() << "QUIT\r\n" << std::flush
;
1595 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1599 std::ostringstream param_stream
;
1600 if (FLAGS_huge_size
&& ext_size
) {
1601 // Claim some huge size.
1602 param_stream
<< " SIZE=" << std::numeric_limits
<std::streamsize
>::max();
1604 else if (ext_size
) {
1605 param_stream
<< " SIZE=" << total_size
;
1608 if (ext_binarymime
) {
1609 param_stream
<< " BODY=BINARYMIME";
1611 else if (ext_8bitmime
) {
1612 param_stream
<< " BODY=8BITMIME";
1615 if (ext_deliverby
) {
1616 param_stream
<< " BY=1200;NT";
1620 param_stream
<< " SMTPUTF8";
1623 if (FLAGS_badpipline
) {
1624 LOG(INFO
) << "C: NOOP NOOP";
1625 cnn
.sock
.out() << "NOOP\r\nNOOP\r\n" << std::flush
;
1628 auto param_str
= param_stream
.str();
1630 LOG(INFO
) << "C: MAIL FROM:<" << from
<< '>' << param_str
;
1631 cnn
.sock
.out() << "MAIL FROM:<" << from
<< '>' << param_str
<< "\r\n";
1632 if (!ext_pipelining
) {
1633 check_for_fail(in
, cnn
, "MAIL FROM");
1636 LOG(INFO
) << "C: RCPT TO:<" << to
<< ">";
1637 cnn
.sock
.out() << "RCPT TO:<" << to
<< ">\r\n";
1638 if (!ext_pipelining
) {
1639 check_for_fail(in
, cnn
, "RCPT TO");
1643 LOG(INFO
) << "C: QUIT";
1644 cnn
.sock
.out() << "QUIT\r\n" << std::flush
;
1645 if (ext_pipelining
) {
1646 check_for_fail(in
, cnn
, "MAIL FROM");
1647 check_for_fail(in
, cnn
, "RCPT TO");
1649 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1650 LOG(INFO
) << "no-sending";
1655 if (ext_pipelining
) {
1656 cnn
.sock
.out() << std::flush
;
1657 check_for_fail(in
, cnn
, "MAIL FROM");
1658 check_for_fail(in
, cnn
, "RCPT TO");
1664 auto msg
= std::make_unique
<Message
>();
1666 // if service is smtp (i.e. sending real mail, not smtp-test)
1668 msg
->open(sender
.ascii(), total_size
* 2, ".Sent");
1669 msg
->write(hdr_str
.data(), hdr_str
.size());
1670 for (auto const& body
: bodies
) {
1671 msg
->write(body
.data(), body
.size());
1674 catch (std::system_error
const& e
) {
1679 LOG(FATAL
) << "no space";
1684 LOG(ERROR
) << "errno==" << errno
<< ": " << strerror(errno
);
1685 LOG(FATAL
) << e
.what();
1688 catch (std::exception
const& e
) {
1691 LOG(FATAL
) << e
.what();
1695 std::ostringstream bdat_stream
;
1696 bdat_stream
<< "BDAT " << total_size
<< " LAST";
1697 LOG(INFO
) << "C: " << bdat_stream
.str();
1699 cnn
.sock
.out() << bdat_stream
.str() << "\r\n";
1700 cnn
.sock
.out().write(hdr_str
.data(), hdr_str
.size());
1701 CHECK(cnn
.sock
.out().good());
1703 for (auto const& body
: bodies
) {
1704 cnn
.sock
.out().write(body
.data(), body
.size());
1705 CHECK(cnn
.sock
.out().good());
1708 cnn
.sock
.out() << std::flush
;
1709 CHECK(cnn
.sock
.out().good());
1711 // NOW check returns
1712 if (ext_pipelining
) {
1713 check_for_fail(in
, cnn
, "MAIL FROM");
1714 check_for_fail(in
, cnn
, "RCPT TO");
1717 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1718 if (cnn
.reply_code
!= "250") {
1719 LOG(ERROR
) << "BDAT returned " << cnn
.reply_code
;
1724 LOG(INFO
) << "C: DATA";
1725 cnn
.sock
.out() << "DATA\r\n";
1727 // NOW check returns
1728 if (ext_pipelining
) {
1729 check_for_fail(in
, cnn
, "MAIL FROM");
1730 check_for_fail(in
, cnn
, "RCPT TO");
1732 cnn
.sock
.out() << std::flush
;
1733 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1734 if (cnn
.reply_code
!= "354") {
1735 LOG(ERROR
) << "DATA returned " << cnn
.reply_code
;
1739 cnn
.sock
.out() << eml
;
1741 for (auto const& body
: bodies
) {
1743 auto line
{std::string
{}};
1744 auto isbody
{imemstream
{body
.data(), body
.size()}};
1745 while (std::getline(isbody
, line
)) {
1747 if (!cnn
.sock
.out().good()) {
1748 cnn
.sock
.log_stats();
1749 LOG(FATAL
) << "output no good at line " << lineno
;
1752 // This adds a final newline at the end of the file, if no
1753 // line ending was present.
1754 cnn
.sock
.out() << line
<< '\n';
1757 // This code converts single LF line endings into CRLF.
1758 // This code does nothing to fix single CR characters not
1759 // part of a CRLF pair.
1761 // This loop adds a CRLF and the end of the transmission if
1762 // the file doesn't already end with one. This is a
1763 // requirement of the SMTP DATA protocol.
1765 if (line
.length() && (line
.at(0) == '.')) {
1766 cnn
.sock
.out() << '.';
1768 cnn
.sock
.out() << line
;
1769 if (line
.back() != '\r')
1770 cnn
.sock
.out() << '\r';
1771 cnn
.sock
.out() << '\n';
1775 CHECK(cnn
.sock
.out().good());
1778 cnn
.sock
.out() << ".\r\n" << std::flush
;
1779 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1781 if (cnn
.reply_code
.at(0) == '2') {
1783 LOG(INFO
) << "mail was sent successfully";
1787 LOG(INFO
) << "C: QUIT";
1788 cnn
.sock
.out() << "QUIT\r\n" << std::flush
;
1789 CHECK((parse
<RFC5321::reply_lines
, RFC5321::action
>(in
, cnn
)));
1795 get_tlsa_rrs(DNS::Resolver
& res
, Domain
const& domain
, uint16_t port
)
1797 auto const tlsa
= fmt::format("_{}._tcp.{}", port
, domain
.ascii());
1799 DNS::Query
q(res
, DNS::RR_type::TLSA
, tlsa
);
1801 if (q
.nx_domain()) {
1802 LOG(INFO
) << "TLSA data not found for " << domain
<< ':' << port
;
1805 if (q
.bogus_or_indeterminate()) {
1806 LOG(WARNING
) << "TLSA data is bogus or indeterminate";
1809 auto tlsa_rrs
= q
.get_records();
1810 if (!tlsa_rrs
.empty()) {
1811 LOG(INFO
) << "### TLSA data found for " << domain
<< ':' << port
<< " ###";
1818 int main(int argc
, char* argv
[])
1820 std::ios::sync_with_stdio(false);
1822 { // Need to work with either namespace.
1823 using namespace gflags
;
1824 using namespace google
;
1825 ParseCommandLineFlags(&argc
, &argv
, true);
1828 auto const config_path
= osutil::get_config_dir();
1830 auto sender
= get_sender();
1832 if (FLAGS_selftest
) {
1837 auto bodies
{std::vector
<content
>{}};
1838 for (int a
= 1; a
< argc
; ++a
) {
1839 if (!fs::exists(argv
[a
]))
1840 LOG(FATAL
) << "can't find mail body part " << argv
[a
];
1841 bodies
.push_back(argv
[a
]);
1845 bodies
.push_back("body.txt");
1847 CHECK_EQ(bodies
.size(), 1) << "only one body part for now";
1848 CHECK(!(FLAGS_4
&& FLAGS_6
)) << "must use /some/ IP version";
1850 if (FLAGS_force_smtputf8
)
1851 FLAGS_use_smtputf8
= true;
1853 auto&& [from_mbx
, to_mbx
, smtp_from_mbx
, smtp_to_mbx
] = parse_mailboxes();
1855 if (to_mbx
.domain().empty() && FLAGS_mx_host
.empty()) {
1856 LOG(ERROR
) << "don't know who to send this mail to";
1860 auto const port
{osutil::get_port(FLAGS_service
.c_str(), "tcp")};
1862 auto res
{DNS::Resolver
{config_path
}};
1863 auto tlsa_rrs
{get_tlsa_rrs(res
, to_mbx
.domain(), port
)};
1866 return snd(config_path
, STDIN_FILENO
, STDOUT_FILENO
, sender
,
1867 to_mbx
.domain(), tlsa_rrs
, false, from_mbx
, to_mbx
,
1868 smtp_from_mbx
, smtp_to_mbx
, bodies
)
1873 bool enforce_dane
= true;
1874 auto const receivers
= get_receivers(res
, to_mbx
, enforce_dane
);
1876 if (receivers
.empty()) {
1877 LOG(INFO
) << "no place to send this mail";
1878 return EXIT_SUCCESS
;
1881 for (auto const& receiver
: receivers
) {
1882 LOG(INFO
) << "trying " << receiver
<< ":" << FLAGS_service
;
1885 LOG(INFO
) << "skipping";
1889 auto fd
= conn(res
, receiver
, port
);
1891 LOG(WARNING
) << "no connection, skipping";
1895 // Get our local IP address as "us".
1897 sa::sockaddrs us_addr
{};
1898 socklen_t us_addr_len
{sizeof us_addr
};
1899 char us_addr_str
[INET6_ADDRSTRLEN
]{'\0'};
1900 std::vector
<std::string
> fcrdns
;
1901 bool private_addr
= false;
1903 if (-1 == getsockname(fd
, &us_addr
.addr
, &us_addr_len
)) {
1904 // Ignore ENOTSOCK errors from getsockname, useful for testing.
1905 PLOG_IF(WARNING
, ENOTSOCK
!= errno
) << "getsockname failed";
1908 switch (us_addr_len
) {
1909 case sizeof(sockaddr_in
):
1910 PCHECK(inet_ntop(AF_INET
, &us_addr
.addr_in
.sin_addr
, us_addr_str
,
1913 if (IP4::is_private(us_addr_str
))
1914 private_addr
= true;
1916 fcrdns
= DNS::fcrdns4(res
, us_addr_str
);
1919 case sizeof(sockaddr_in6
):
1920 PCHECK(inet_ntop(AF_INET6
, &us_addr
.addr_in6
.sin6_addr
, us_addr_str
,
1923 if (IP6::is_private(us_addr_str
))
1924 private_addr
= true;
1926 fcrdns
= DNS::fcrdns6(res
, us_addr_str
);
1930 LOG(FATAL
) << "bogus address length (" << us_addr_len
1931 << ") returned from getsockname";
1935 if (fcrdns
.size()) {
1936 LOG(INFO
) << "our names are:";
1937 for (auto const& fc
: fcrdns
) {
1938 LOG(INFO
) << " " << fc
;
1942 if (!private_addr
) {
1943 // look at from_mbx.domain() and get SPF records
1945 // also look at our ID to get SPF records.
1948 if (to_mbx
.domain() == receiver
) {
1949 if (snd(config_path
, fd
, fd
, sender
, receiver
, tlsa_rrs
, enforce_dane
,
1950 from_mbx
, to_mbx
, smtp_from_mbx
, smtp_to_mbx
, bodies
)) {
1951 return EXIT_SUCCESS
;
1955 auto tlsa_rrs_mx
{get_tlsa_rrs(res
, receiver
, port
)};
1956 tlsa_rrs_mx
.insert(end(tlsa_rrs_mx
), begin(tlsa_rrs
), end(tlsa_rrs
));
1957 if (snd(config_path
, fd
, fd
, sender
, receiver
, tlsa_rrs_mx
, enforce_dane
,
1958 from_mbx
, to_mbx
, smtp_from_mbx
, smtp_to_mbx
, bodies
)) {
1959 return EXIT_SUCCESS
;
1966 LOG(ERROR
) << "we ran out of hosts to try";