Rewrite the project

The previous project architecture was far too complicated and hard to
maintain. The new one is much more simple. Although procedural macros
are cools, they are a no-go on Rust-OpenSMTPD.

Reports and filter are implemented (except data-line) but untested.
This commit is contained in:
Rodolphe Bréard 2020-11-25 18:04:16 +01:00
parent fc072743ad
commit a6d4dd21c1
48 changed files with 1723 additions and 1493 deletions

View file

@ -1,5 +1,23 @@
[workspace] [package]
members = [ name = "opensmtpd"
"opensmtpd", version = "0.2.0"
"opensmtpd-derive" authors = ["Rodolphe Bréard <rodolphe@what.tf>"]
] edition = "2018"
description = "Interface for OpenSMTPD filters"
keywords = ["opensmtpd", "filter", "mail"]
documentation = "https://docs.rs/opensmtpd/"
repository = "https://github.com/breard-r/rust-opensmtpd"
readme = "README.md"
license = "MIT OR Apache-2.0"
include = ["src/**/*", "Cargo.toml", "LICENSE-*.txt"]
[dependencies]
log = "0.4"
nom = "6.0"
[dev-dependencies]
simplelog = "0.8"
[[example]]
name = "counter"
path = "examples/counter.rs"

45
examples/counter.rs Normal file
View file

@ -0,0 +1,45 @@
use log;
use opensmtpd::{register, run_filter, Address, Filter, ReportEntry};
use simplelog::{Config, LevelFilter, TermLogger, TerminalMode};
#[derive(Default)]
struct MyCounter {
nb_connected: u64,
nb_total: u64,
}
impl Filter for MyCounter {
register!(has_report_link_connect);
fn on_report_link_connect(
&mut self,
_entry: &ReportEntry,
_rdns: &str,
_fcrdns: &str,
_src: &Address,
_dest: &Address,
) {
self.nb_connected += 1;
self.nb_total += 1;
log::info!(
"New client (connected: {}, total: {})",
self.nb_connected,
self.nb_total
);
}
register!(has_report_link_disconnect);
fn on_report_link_disconnect(&mut self, _entry: &ReportEntry) {
self.nb_connected -= 1;
log::info!(
"Client left (connected: {}, total: {})",
self.nb_connected,
self.nb_total
);
}
}
fn main() {
TermLogger::init(LevelFilter::Debug, Config::default(), TerminalMode::Mixed).unwrap();
let mut my_counter: MyCounter = Default::default();
run_filter(&mut my_counter);
}

View file

@ -0,0 +1,4 @@
config|smtpd-version|6.6.1
config|smtp-session-timeout|300
config|subsystem|smtp-in
config|ready

View file

@ -0,0 +1,6 @@
config|smtpd-version|6.6.1
config|smtp-session-timeout|300
config|subsystem|smtp-in
config|ready
report|0.5|1576146008.006099|smtp-in|link-connect|7641df9771b4ed00|mail.openbsd.org|pass|199.185.178.25:33174|45.77.67.80:25
report|0.5|1576147242.200225|smtp-in|link-disconnect|7641dfb3798eb5bf

View file

@ -1,19 +0,0 @@
[package]
name = "opensmtpd_derive"
version = "0.2.0"
authors = ["Rodolphe Bréard <rodolphe@what.tf>"]
edition = "2018"
description = "Interface for OpenSMTPD filters"
keywords = ["opensmtpd", "filter", "mail"]
documentation = "https://docs.rs/opensmtpd-derive/"
repository = "https://github.com/breard-r/rust-opensmtpd"
readme = "README.md"
license = "MIT OR Apache-2.0"
include = ["src/**/*", "Cargo.toml", "LICENSE-*.txt"]
[lib]
proc-macro = true
[dependencies]
quote = "1.0"
syn = { version = "1.0", features = ["full", "extra-traits"] }

View file

@ -1,113 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{parenthesized, Ident, Result, Token};
#[derive(Debug)]
pub(crate) struct OpenSmtpdAttributes {
version: Ident,
subsystem: Ident,
events: Punctuated<Ident, Token![,]>,
}
impl Parse for OpenSmtpdAttributes {
fn parse(input: ParseStream) -> Result<Self> {
let version = input.parse()?;
let _: Token![,] = input.parse()?;
let subsystem = input.parse()?;
let _: Token![,] = input.parse()?;
let _match: Token![match] = input.parse()?;
let content;
let _ = parenthesized!(content in input);
let events = content.parse_terminated(Ident::parse)?;
Ok(OpenSmtpdAttributes {
version,
subsystem,
events,
})
}
}
impl OpenSmtpdAttributes {
pub(crate) fn get_version(&self) -> String {
format!(
"opensmtpd::entry::Version::{}",
self.version.to_string().to_uppercase()
)
}
pub(crate) fn get_subsystem(&self) -> String {
let subsystem = match self.subsystem.to_string().as_str() {
"smtp_in" => "SmtpIn",
"smtp_out" => "SmtpOut",
_ => "",
};
format!("opensmtpd::entry::Subsystem::{}", subsystem)
}
pub(crate) fn get_events(&self) -> String {
let events = if self
.events
.iter()
.any(|e| e.to_string().to_lowercase().as_str() == "all")
{
let lst = [
"LinkAuth",
"LinkConnect",
"LinkDisconnect",
"LinkIdentify",
"LinkReset",
"LinkTls",
"TxBegin",
"TxMail",
"TxRcpt",
"TxEnvelope",
"TxData",
"TxCommit",
"TxRollback",
"ProtocolClient",
"ProtocolServer",
"FilterResponse",
"Timeout",
];
lst.iter()
.map(|e| format!("opensmtpd::entry::Event::{}", e))
.collect::<Vec<String>>()
} else {
self.events
.iter()
.map(|e| {
let name = match e.to_string().as_str() {
"link_auth" => "LinkAuth",
"link_connect" => "LinkConnect",
"link_disconnect" => "LinkDisconnect",
"link_identify" => "LinkIdentify",
"link_reset" => "LinkReset",
"link_tls" => "LinkTls",
"tx_begin" => "TxBegin",
"tx_mail" => "TxMail",
"tx_rcpt" => "TxRcpt",
"tx_envelope" => "TxEnvelope",
"tx_data" => "TxData",
"tx_commit" => "TxCommit",
"tx_rollback" => "TxRollback",
"protocol_client" => "ProtocolClient",
"protocol_server" => "ProtocolServer",
"filter_response" => "FilterResponse",
"timeout" => "Timeout",
_ => "",
};
format!("opensmtpd::entry::Event::{}", name)
})
.collect::<Vec<String>>()
};
format!("[{}]", events.join(", "))
}
}

View file

@ -1,115 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate proc_macro;
mod attributes;
use attributes::OpenSmtpdAttributes;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ExprArray, ExprTry, ItemFn, ReturnType, TypePath};
macro_rules! parse_item {
($item: expr, $type: ty) => {
match syn::parse_str::<$type>($item) {
Ok(i) => i,
Err(e) => {
return TokenStream::from(e.to_compile_error());
}
}
};
}
fn get_has_result(ret: &ReturnType) -> bool {
match ret {
ReturnType::Default => false,
ReturnType::Type(_, _) => true,
}
}
fn get_inner_call(nb_args: usize, has_output: bool, has_result: bool) -> String {
let mut call_params = Vec::new();
if has_output {
call_params.push("_output");
}
call_params.push("_entry");
if nb_args >= 2 {
call_params.push("_filter_ctx");
}
if nb_args >= 3 {
call_params.push("_session_ctx");
}
let call_params = call_params.join(", ");
let s = format!("inner_fn({})", &call_params);
if has_result {
return format!("{}?", s);
}
format!(
"(|{params}| -> Result<(), String> {{ {inner_fn}; Ok(()) }})({params})?",
params = &call_params,
inner_fn = s
)
}
fn get_tokenstream(
attr: TokenStream,
input: TokenStream,
type_str: &str,
has_output: bool,
) -> TokenStream {
let kind = parse_item!(type_str, TypePath);
// Parse the procedural macro attributes
let attr = parse_macro_input!(attr as OpenSmtpdAttributes);
let version = parse_item!(&attr.get_version(), TypePath);
let subsystem = parse_item!(&attr.get_subsystem(), TypePath);
let events = parse_item!(&attr.get_events(), ExprArray);
// Parse the user-supplied function
let item = parse_macro_input!(input as ItemFn);
let fn_name = &item.sig.ident;
let fn_params = &item.sig.inputs;
let fn_return = &item.sig.output;
let fn_body = &item.block;
let has_result = get_has_result(&item.sig.output);
let inner_call = parse_item!(
&get_inner_call(fn_params.len(), has_output, has_result),
ExprTry
);
// Build the new function
let output = quote! {
fn #fn_name() -> opensmtpd::Handler::<OpenSmtpdSessionContextType, OpenSmtpdFilterContextType> {
opensmtpd::Handler::new(
#version,
#kind,
#subsystem,
&#events,
|_output: &mut dyn opensmtpd::output::FilterOutput, _entry: &opensmtpd::entry::Entry, _session_ctx: &mut OpenSmtpdSessionContextType, _filter_ctx: &mut OpenSmtpdFilterContextType| {
let inner_fn = |#fn_params| #fn_return {
#fn_body
};
let _ = #inner_call;
Ok(())
},
)
}
};
output.into()
}
#[proc_macro_attribute]
pub fn report(attr: TokenStream, input: TokenStream) -> TokenStream {
get_tokenstream(attr, input, "opensmtpd::entry::Kind::Report", false)
}
#[proc_macro_attribute]
pub fn filter(attr: TokenStream, input: TokenStream) -> TokenStream {
get_tokenstream(attr, input, "opensmtpd::entry::Kind::Filter", true)
}

View file

@ -1,29 +0,0 @@
[package]
name = "opensmtpd"
version = "0.2.0"
authors = ["Rodolphe Bréard <rodolphe@what.tf>"]
edition = "2018"
description = "Interface for OpenSMTPD filters"
keywords = ["opensmtpd", "filter", "mail"]
documentation = "https://docs.rs/opensmtpd/"
repository = "https://github.com/breard-r/rust-opensmtpd"
readme = "README.md"
license = "MIT OR Apache-2.0"
include = ["src/**/*", "Cargo.toml", "LICENSE-*.txt"]
[dependencies]
log = {version = "0.4", features = ["std"]}
nom = "6.0"
opensmtpd_derive = { path = "../opensmtpd-derive", version = "0.2" }
[[example]]
name = "hello"
path = "examples/hello.rs"
[[example]]
name = "echo"
path = "examples/echo.rs"
[[example]]
name = "counter"
path = "examples/report_counter.rs"

View file

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,7 +0,0 @@
Copyright 2019 Rodolphe Bréard
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,13 +0,0 @@
use opensmtpd::entry::Entry;
use opensmtpd::{register_no_context, report, simple_filter};
register_no_context!();
#[report(v1, smtp_in, match(all))]
fn echo(entry: &Entry) {
log::info!("New entry: {:?}", entry);
}
fn main() {
simple_filter!([echo]);
}

View file

@ -1,13 +0,0 @@
use opensmtpd::entry::Entry;
use opensmtpd::{register_no_context, report, simple_filter};
register_no_context!();
#[report(v1, smtp_in, match(link_connect))]
fn hello(entry: &Entry) {
log::info!("Hello {}!", entry.get_session_id());
}
fn main() {
simple_filter!([hello]);
}

View file

@ -1,26 +0,0 @@
use log;
use opensmtpd::entry::Entry;
use opensmtpd::{register_contexts, report, simple_filter};
#[derive(Clone, Default)]
struct MyCounter {
nb: usize,
}
register_contexts!(MyCounter, MyCounter);
#[report(v1, smtp_in, match(all))]
fn on_report(entry: &Entry, total: &mut MyCounter, session: &mut MyCounter) {
total.nb += 1;
session.nb += 1;
log::info!(
"Event received for session {}: {} (total: {})",
entry.get_session_id(),
session.nb,
total.nb
);
}
fn main() {
simple_filter!(MyCounter, MyCounter, [on_report]);
}

View file

@ -1,10 +0,0 @@
report|1|1546681202.276920|smtp-in|link-connect|dbd829906c50e764|localhost|pass|127.0.0.1:34818|127.0.0.1:25
report|1|1546681202.277715|smtp-in|filter-response|dbd829906c50e764|connected|proceed
report|1|1546681202.276920|smtp-in|link-connect|4b0148c60f798628|localhost|pass|127.0.0.1:34818|127.0.0.1:25
report|1|1546681202.277715|smtp-in|filter-response|4b0148c60f798628|connected|proceed
report|1|1546681202.277761|smtp-in|protocol-server|dbd829906c50e764|220 laptop.home ESMTP OpenSMTPD
report|1|1546681232.283049|smtp-in|timeout|dbd829906c50e764
report|1|1546681202.277761|smtp-in|protocol-server|4b0148c60f798628|220 laptop.home ESMTP OpenSMTPD
report|1|1546681232.283049|smtp-in|timeout|4b0148c60f798628
report|1|1546681232.283083|smtp-in|link-disconnect|dbd829906c50e764
report|1|1546681232.283083|smtp-in|link-disconnect|4b0148c60f798628

View file

@ -1,29 +0,0 @@
report|1|1562870145.607116|smtp-in|link-connect|4c8aad137c3de7cb|localhost|pass|127.0.0.1:21438|127.0.0.1:25
report|1|1562870145.607395|smtp-in|filter-response|4c8aad137c3de7cb|connected|proceed
report|1|1562870145.607402|smtp-in|protocol-server|4c8aad137c3de7cb|220 mx.example.org ESMTP OpenSMTPD
report|1|1562870149.811367|smtp-in|protocol-client|4c8aad137c3de7cb|HELO localhost
report|1|1562870149.813732|smtp-in|filter-response|4c8aad137c3de7cb|helo|proceed
report|1|1562870149.813744|smtp-in|link-identify|4c8aad137c3de7cb|localhost
report|1|1562870149.813763|smtp-in|protocol-server|4c8aad137c3de7cb|250 mx.example.org Hello localhost [127.0.0.1], pleased to meet you
report|1|1562870154.283507|smtp-in|protocol-client|4c8aad137c3de7cb|MAIL FROM:<derp@toto.example.com>
report|1|1562870154.286255|smtp-in|filter-response|4c8aad137c3de7cb|mail-from|proceed
report|1|1562870154.288148|smtp-in|tx-begin|4c8aad137c3de7cb|20ec19f5
report|1|1562870154.288165|smtp-in|tx-mail|4c8aad137c3de7cb|20ec19f5|<derp@toto.example.com>|ok
report|1|1562870154.288181|smtp-in|protocol-server|4c8aad137c3de7cb|250 2.0.0: Ok
report|1|1562870159.284269|smtp-in|protocol-client|4c8aad137c3de7cb|RCPT TO:<elsa@localhost>
report|1|1562870159.286969|smtp-in|filter-response|4c8aad137c3de7cb|rcpt-to|proceed
report|1|1562870159.291856|smtp-in|tx-envelope|4c8aad137c3de7cb|20ec19f5|20ec19f543927eb5
report|1|1562870159.291907|smtp-in|tx-rcpt|4c8aad137c3de7cb|20ec19f5|<elsa@localhost>|ok
report|1|1562870159.291925|smtp-in|protocol-server|4c8aad137c3de7cb|250 2.1.5 Destination address valid: Recipient ok
report|1|1562870163.451339|smtp-in|protocol-client|4c8aad137c3de7cb|DATA
report|1|1562870163.453789|smtp-in|filter-response|4c8aad137c3de7cb|data|proceed
report|1|1562870163.455790|smtp-in|tx-data|4c8aad137c3de7cb|20ec19f5|ok
report|1|1562870163.455811|smtp-in|protocol-server|4c8aad137c3de7cb|354 Enter mail, end with "." on a line by itself
report|1|1562870224.765630|smtp-in|protocol-client|4c8aad137c3de7cb|.
report|1|1562870224.767139|smtp-in|filter-response|4c8aad137c3de7cb|commit|proceed
report|1|1562870224.767275|smtp-in|tx-commit|4c8aad137c3de7cb|20ec19f5|562
report|1|1562870224.770499|smtp-in|protocol-server|4c8aad137c3de7cb|250 2.0.0: 20ec19f5 Message accepted for delivery
report|1|1562870229.128193|smtp-in|protocol-client|4c8aad137c3de7cb|QUIT
report|1|1562870229.130522|smtp-in|filter-response|4c8aad137c3de7cb|quit|proceed
report|1|1562870229.130547|smtp-in|protocol-server|4c8aad137c3de7cb|221 2.0.0: Bye
report|1|1562870229.131314|smtp-in|link-disconnect|4c8aad137c3de7cb

View file

@ -1,5 +0,0 @@
report|1|1546681202.276920|smtp-in|link-connect|dbd829906c50e764|localhost|pass|127.0.0.1:34818|127.0.0.1:25
report|1|1546681202.277715|smtp-in|filter-response|dbd829906c50e764|connected|proceed
report|1|1546681202.277761|smtp-in|protocol-server|dbd829906c50e764|220 laptop.home ESMTP OpenSMTPD
report|1|1546681232.283049|smtp-in|timeout|dbd829906c50e764
report|1|1546681232.283083|smtp-in|link-disconnect|dbd829906c50e764

View file

@ -1,298 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::errors::Error;
use nom::branch::alt;
use nom::bytes::streaming::{tag, take_till};
use nom::character::streaming::{digit1, hex_digit1, line_ending};
use nom::combinator::{map_res, value};
use nom::multi::many0;
use nom::Err::Incomplete;
use nom::IResult;
use std::str::FromStr;
pub type SessionId = u64;
pub type Token = u64;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Version {
V1,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Kind {
Report,
Filter,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Subsystem {
SmtpIn,
SmtpOut,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Event {
LinkAuth,
LinkConnect,
LinkDisconnect,
LinkIdentify,
LinkReset,
LinkTls,
TxBegin,
TxMail,
TxRcpt,
TxEnvelope,
TxData,
TxCommit,
TxRollback,
ProtocolClient,
ProtocolServer,
FilterResponse,
Timeout,
}
impl FromStr for Event {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.to_lowercase();
let s = if !s.contains('-') {
s.replace("link", "link-")
.replace("tx", "tx-")
.replace("protocol", "protocol-")
.replace("filter", "filter-")
} else {
s
};
let (_, evt) = parse_event(&s)?;
Ok(evt)
}
}
impl ToString for Event {
fn to_string(&self) -> String {
let s = match self {
Event::LinkAuth => "link-auth",
Event::LinkConnect => "link-connect",
Event::LinkDisconnect => "link-disconnect",
Event::LinkIdentify => "link-identify",
Event::LinkReset => "link-reset",
Event::LinkTls => "link-tls",
Event::TxBegin => "tx-begin",
Event::TxMail => "tx-mail",
Event::TxRcpt => "tx-rcpt",
Event::TxEnvelope => "tx-envelope",
Event::TxData => "tx-data",
Event::TxCommit => "tx-commit",
Event::TxRollback => "tx-rollback",
Event::ProtocolClient => "protocol-client",
Event::ProtocolServer => "protocol-server",
Event::FilterResponse => "filter-response",
Event::Timeout => "timeout",
};
String::from(s)
}
}
#[derive(Debug)]
pub struct TimeVal {
pub sec: i64,
pub usec: i64,
}
impl ToString for TimeVal {
fn to_string(&self) -> String {
format!("{}.{}", self.sec, self.usec)
}
}
#[derive(Debug)]
pub enum Entry {
V1Report(V1Report),
V1Filter(V1Filter),
}
impl Entry {
pub fn new(entry: &str) -> Result<(String, Option<Self>), Error> {
match parse_entry(entry) {
Ok((remainder, entry)) => Ok((remainder.to_string(), Some(entry))),
Err(e) => match e {
Incomplete(_) => Ok((String::new(), None)),
_ => Err(e.into()),
},
}
}
pub fn get_event(&self) -> Event {
match self {
Entry::V1Report(r) => r.event.to_owned(),
Entry::V1Filter(f) => f.event.to_owned(),
}
}
pub fn get_session_id(&self) -> SessionId {
match self {
Entry::V1Report(r) => r.session_id,
Entry::V1Filter(f) => f.session_id,
}
}
pub fn is_disconnect(&self) -> bool {
match self {
Entry::V1Report(r) => r.event == Event::LinkDisconnect,
Entry::V1Filter(_) => false,
}
}
}
#[derive(Debug)]
pub struct V1Report {
pub timestamp: TimeVal,
pub subsystem: Subsystem,
pub event: Event,
pub session_id: SessionId,
pub params: Vec<String>,
}
#[derive(Debug)]
pub struct V1Filter {
pub timestamp: TimeVal,
pub subsystem: Subsystem,
pub event: Event,
pub session_id: SessionId,
pub token: Token,
pub params: Vec<String>,
}
fn separator(input: &str) -> IResult<&str, &str> {
tag("|")(input)
}
fn parse_kind(input: &str) -> IResult<&str, Kind> {
alt((
value(Kind::Report, tag("report")),
value(Kind::Filter, tag("filter")),
))(input)
}
fn parse_version(input: &str) -> IResult<&str, Version> {
value(Version::V1, tag("1"))(input)
}
fn parse_timestamp(input: &str) -> IResult<&str, TimeVal> {
let (input, sec) = map_res(digit1, |s: &str| s.parse::<i64>())(input)?;
let (input, _) = tag(".")(input)?;
let (input, usec) = map_res(digit1, |s: &str| s.parse::<i64>())(input)?;
let timestamp = TimeVal { sec, usec };
Ok((input, timestamp))
}
fn parse_subsystem(input: &str) -> IResult<&str, Subsystem> {
alt((
value(Subsystem::SmtpIn, tag("smtp-in")),
value(Subsystem::SmtpOut, tag("smtp-out")),
))(input)
}
fn parse_event(input: &str) -> IResult<&str, Event> {
alt((
value(Event::LinkAuth, tag("link-auth")),
value(Event::LinkConnect, tag("link-connect")),
value(Event::LinkDisconnect, tag("link-disconnect")),
value(Event::LinkIdentify, tag("link-identify")),
value(Event::LinkReset, tag("link-reset")),
value(Event::LinkTls, tag("link-tls")),
value(Event::TxBegin, tag("tx-begin")),
value(Event::TxMail, tag("tx-mail")),
value(Event::TxRcpt, tag("tx-rcpt")),
value(Event::TxEnvelope, tag("tx-envelope")),
value(Event::TxData, tag("tx-data")),
value(Event::TxCommit, tag("tx-commit")),
value(Event::TxRollback, tag("tx-rollback")),
value(Event::ProtocolClient, tag("protocol-client")),
value(Event::ProtocolServer, tag("protocol-server")),
value(Event::FilterResponse, tag("filter-response")),
value(Event::Timeout, tag("timeout")),
))(input)
}
fn parse_token(input: &str) -> IResult<&str, Token> {
map_res(hex_digit1, |s: &str| Token::from_str_radix(s, 16))(input)
}
fn parse_session_id(input: &str) -> IResult<&str, SessionId> {
map_res(hex_digit1, |s: &str| SessionId::from_str_radix(s, 16))(input)
}
fn parse_param(input: &str) -> IResult<&str, String> {
let (input, _) = separator(input)?;
let (input, param) = take_till(is_end_param)(input)?;
Ok((input, param.to_string()))
}
fn is_end_param(c: char) -> bool {
c == '|' || c == '\r' || c == '\n'
}
fn parse_v1_report(input: &str) -> IResult<&str, Entry> {
let (input, timestamp) = parse_timestamp(input)?;
let (input, _) = separator(input)?;
let (input, subsystem) = parse_subsystem(input)?;
let (input, _) = separator(input)?;
let (input, event) = parse_event(input)?;
let (input, _) = separator(input)?;
let (input, session_id) = parse_session_id(input)?;
let (input, params) = many0(parse_param)(input)?;
let (input, _) = line_ending(input)?;
let report = V1Report {
timestamp,
subsystem,
event,
session_id,
params,
};
Ok((input, Entry::V1Report(report)))
}
fn parse_v1_filter(input: &str) -> IResult<&str, Entry> {
let (input, timestamp) = parse_timestamp(input)?;
let (input, _) = separator(input)?;
let (input, subsystem) = parse_subsystem(input)?;
let (input, _) = separator(input)?;
let (input, event) = parse_event(input)?;
let (input, _) = separator(input)?;
let (input, session_id) = parse_session_id(input)?;
let (input, _) = separator(input)?;
let (input, token) = parse_token(input)?;
let (input, params) = many0(parse_param)(input)?;
let (input, _) = line_ending(input)?;
let filter = V1Filter {
timestamp,
subsystem,
event,
session_id,
token,
params,
};
Ok((input, Entry::V1Filter(filter)))
}
fn parse_entry(input: &str) -> IResult<&str, Entry> {
let (input, kind) = parse_kind(input)?;
let (input, _) = separator(input)?;
let (input, version) = parse_version(input)?;
let (input, _) = separator(input)?;
let (input, entry) = match version {
Version::V1 => match kind {
Kind::Report => parse_v1_report(input)?,
Kind::Filter => parse_v1_filter(input)?,
},
};
Ok((input, entry))
}

View file

@ -1,62 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt;
pub struct Error {
message: String,
}
impl Error {
pub fn new(msg: &str) -> Self {
Error {
message: msg.to_string(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Error::new(&format!("IO error: {}", error))
}
}
impl From<std::string::String> for Error {
fn from(error: std::string::String) -> Self {
Error { message: error }
}
}
impl From<std::str::Utf8Error> for Error {
fn from(error: std::str::Utf8Error) -> Self {
Error::new(&format!("UTF8 error: {}", error))
}
}
impl From<log::SetLoggerError> for Error {
fn from(error: log::SetLoggerError) -> Self {
Error::new(&format!("Logger error: {}", error))
}
}
impl From<nom::Err<(&str, nom::error::ErrorKind)>> for Error {
fn from(error: nom::Err<(&str, nom::error::ErrorKind)>) -> Self {
let msg = match error {
nom::Err::Incomplete(_) => "not enough data".to_string(),
nom::Err::Error(c) => format!("{:?}", c),
nom::Err::Failure(c) => format!("{:?}", c),
};
Error::new(&format!("Parsing error: {}", msg))
}
}

View file

@ -1,85 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::entry::{Entry, Event, Kind, Subsystem, Version};
use crate::errors::Error;
use crate::output::FilterOutput;
use std::collections::HashSet;
macro_rules! handle {
($self: ident, $obj: ident, $version: expr, $kind: expr, $entry: ident, $output: ident, $session_ctx: ident, $filter_ctx: ident) => {{
if $self.version == $version
&& $self.kind == $kind
&& $self.subsystem == $obj.subsystem
&& $self.events.contains(&$obj.event)
{
($self.action)($output, $entry, $session_ctx, $filter_ctx)?;
}
Ok(())
}};
}
type Callback<S, F> = fn(&mut dyn FilterOutput, &Entry, &mut S, &mut F) -> Result<(), String>;
#[derive(Clone)]
pub struct Handler<S, F> {
version: Version,
pub(crate) kind: Kind,
pub(crate) subsystem: Subsystem,
pub(crate) events: HashSet<Event>,
action: Callback<S, F>,
}
impl<S, F> Handler<S, F> {
pub fn new(
version: Version,
kind: Kind,
subsystem: Subsystem,
events: &[Event],
action: Callback<S, F>,
) -> Self {
Handler {
version,
kind,
subsystem,
events: events.iter().cloned().collect(),
action,
}
}
pub fn send(
&self,
entry: &Entry,
output: &mut dyn FilterOutput,
session_ctx: &mut S,
filter_ctx: &mut F,
) -> Result<(), Error> {
match entry {
Entry::V1Report(report) => handle!(
self,
report,
Version::V1,
Kind::Report,
entry,
output,
session_ctx,
filter_ctx
),
Entry::V1Filter(filter) => handle!(
self,
filter,
Version::V1,
Kind::Filter,
entry,
output,
session_ctx,
filter_ctx
),
}
}
}

View file

@ -1,17 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::entry::Entry;
use crate::errors::Error;
pub trait FilterInput {
fn next(&mut self) -> Result<Entry, Error>;
}
mod stdin;
pub use stdin::StdIn;

View file

@ -1,78 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::entry::Entry;
use crate::errors::Error;
use crate::input::FilterInput;
use std::default::Default;
use std::io::{self, ErrorKind, Read};
use std::str;
const BUFFER_SIZE: usize = 4096;
pub struct StdIn {
buffer: [u8; BUFFER_SIZE],
stdin: io::Stdin,
input: String,
}
impl Default for StdIn {
fn default() -> Self {
StdIn {
buffer: [0; BUFFER_SIZE],
stdin: io::stdin(),
input: String::new(),
}
}
}
impl FilterInput for StdIn {
fn next(&mut self) -> Result<Entry, Error> {
let mut force_read = false;
loop {
if force_read || self.input.is_empty() {
// Reset the flag
force_read = false;
// Read stdin in self.buffer
self.buffer.copy_from_slice(&[0; BUFFER_SIZE]);
let len = match self.stdin.read(&mut self.buffer) {
Ok(n) => n,
Err(e) => match e.kind() {
ErrorKind::Interrupted => {
continue;
}
_ => {
return Err(e.into());
}
},
};
if len == 0 {
return Err(Error::new("Unable to read on stdin."));
}
// Put the buffer's content in self.input
self.input += match self.buffer.iter().position(|&x| x == 0) {
Some(i) => str::from_utf8(&self.buffer[..i]),
None => str::from_utf8(&self.buffer),
}?;
}
// Try to build an entry from self.input
let (remainder, entry_opt) = Entry::new(&self.input)?;
match entry_opt {
// We have at least one entry.
Some(entry) => {
self.input = remainder;
return Ok(entry);
}
// The data is incomplete, no entry could be built.
None => {
force_read = true;
}
};
}
}
}

View file

@ -1,234 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
mod errors;
mod handler;
mod logger;
pub mod entry;
pub mod input;
pub mod output;
use crate::entry::{Kind, SessionId, Subsystem};
use log;
use std::collections::{HashMap, HashSet};
use std::default::Default;
pub use crate::errors::Error;
pub use crate::handler::Handler;
pub use crate::logger::SmtpdLogger;
pub use opensmtpd_derive::report;
#[macro_export]
macro_rules! register_contexts {
($context: ty) => {
opensmtpd::register_contexts!($context, $context);
};
($session_context: ty, $filter_context: ty) => {
type OpenSmtpdFilterContextType = $filter_context;
type OpenSmtpdSessionContextType = $session_context;
};
}
#[macro_export]
macro_rules! register_filter_context_only {
($context: ty) => {
type OpenSmtpdFilterContextType = $context;
type OpenSmtpdSessionContextType = opensmtpd::NoContext;
};
}
#[macro_export]
macro_rules! register_session_context_only {
($context: ty) => {
type OpenSmtpdFilterContextType = opensmtpd::NoContext;
type OpenSmtpdSessionContextType = $context;
};
}
#[macro_export]
macro_rules! register_no_context {
() => {
type OpenSmtpdFilterContextType = opensmtpd::NoContext;
type OpenSmtpdSessionContextType = opensmtpd::NoContext;
};
}
#[macro_export]
macro_rules! simple_filter {
($handlers: expr) => {
opensmtpd::simple_filter!(
log::Level::Info,
opensmtpd::NoContext,
opensmtpd::NoContext,
$handlers
);
};
($filter_ctx: ty, $handlers: expr) => {
opensmtpd::simple_filter!(
log::Level::Info,
opensmtpd::NoContext,
$filter_ctx,
$handlers
);
};
($sesion_ctx: ty, $filter_ctx: ty, $handlers: expr) => {
opensmtpd::simple_filter!(log::Level::Info, $sesion_ctx, $filter_ctx, $handlers);
};
($log_level: path, $sesion_ctx: ty, $filter_ctx: ty, $handlers: expr) => {
let handlers = ($handlers)
.iter()
.map(|f| f())
.collect::<Vec<opensmtpd::Handler<$sesion_ctx, $filter_ctx>>>();
let _ = opensmtpd::SmtpdLogger::new().set_level($log_level).init();
opensmtpd::Filter::<
opensmtpd::input::StdIn,
opensmtpd::output::StdOut,
$sesion_ctx,
$filter_ctx,
>::default()
.set_handlers(handlers.as_slice())
.register_events()
.run();
};
}
macro_rules! fatal_error {
($error: ident) => {
log::error!("Error: {}", $error);
std::process::exit(1);
};
}
macro_rules! insert_events {
($handler: ident, $set: ident) => {{
for e in $handler.events.iter() {
$set.insert(e);
}
}};
}
macro_rules! register_events {
($output: expr, $set: ident, $kind: expr, $subsystem: expr) => {
for e in $set.iter() {
let msg = format!("register|{}|{}|{}", $kind, $subsystem, e.to_string());
if let Err(e) = $output.send(&msg) {
fatal_error!(e);
};
}
};
}
#[derive(Clone, Default)]
pub struct NoContext;
pub struct Filter<I, O, S, F>
where
I: crate::input::FilterInput + Default,
O: crate::output::FilterOutput + Default,
S: Default,
F: Default,
{
input: I,
output: O,
session_ctx: HashMap<SessionId, S>,
filter_ctx: F,
handlers: Vec<Handler<S, F>>,
}
impl<I, O, S, F> Default for Filter<I, O, S, F>
where
I: crate::input::FilterInput + Default,
O: crate::output::FilterOutput + Default,
S: Default,
F: Default,
{
fn default() -> Self {
Filter {
input: I::default(),
output: O::default(),
session_ctx: HashMap::new(),
filter_ctx: F::default(),
handlers: Vec::new(),
}
}
}
impl<I, O, S, F> Filter<I, O, S, F>
where
I: crate::input::FilterInput + Default,
O: crate::output::FilterOutput + Default,
S: Clone + Default,
F: Clone + Default,
{
pub fn set_handlers(&mut self, handlers: &[Handler<S, F>]) -> &mut Self {
self.handlers = handlers.to_vec();
self
}
pub fn register_events(&mut self) -> &mut Self {
let mut report_smtp_in = HashSet::new();
let mut report_smtp_out = HashSet::new();
let mut filter_smtp_in = HashSet::new();
let mut filter_smtp_out = HashSet::new();
for h in self.handlers.iter() {
match h.kind {
Kind::Report => match h.subsystem {
Subsystem::SmtpIn => insert_events!(h, report_smtp_in),
Subsystem::SmtpOut => insert_events!(h, report_smtp_out),
},
Kind::Filter => match h.subsystem {
Subsystem::SmtpIn => insert_events!(h, filter_smtp_in),
Subsystem::SmtpOut => insert_events!(h, filter_smtp_out),
},
};
}
register_events!(self.output, report_smtp_in, "report", "smtp-in");
register_events!(self.output, report_smtp_out, "report", "smtp-out");
register_events!(self.output, filter_smtp_in, "filter", "smtp-in");
register_events!(self.output, filter_smtp_out, "filter", "smtp-out");
self
}
pub fn run(&mut self) {
loop {
match self.input.next() {
Ok(entry) => {
log::debug!("{:?}", entry);
let session_id = entry.get_session_id();
let mut session_ctx = match self.session_ctx.get_mut(&session_id) {
Some(c) => c,
None => {
self.session_ctx.insert(session_id, S::default());
self.session_ctx.get_mut(&session_id).unwrap()
}
};
for h in self.handlers.iter() {
match h.send(
&entry,
&mut self.output,
&mut session_ctx,
&mut self.filter_ctx,
) {
Ok(_) => {}
Err(e) => {
log::warn!("Warning: {}", e);
}
};
}
if entry.is_disconnect() {
self.session_ctx.remove(&session_id);
}
}
Err(e) => {
fatal_error!(e);
}
};
}
}
}

View file

@ -1,56 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::errors::Error;
use log::{Level, Metadata, Record};
use std::io::{self, Write};
#[derive(Clone)]
pub struct SmtpdLogger {
level: Level,
}
impl SmtpdLogger {
pub fn new() -> Self {
SmtpdLogger::default()
}
pub fn set_level(&mut self, level: Level) -> Self {
self.level = level;
self.clone()
}
pub fn init(self) -> Result<(), Error> {
let level = self.level.to_level_filter();
log::set_boxed_logger(Box::new(self))?;
log::set_max_level(level);
Ok(())
}
}
impl Default for SmtpdLogger {
fn default() -> Self {
SmtpdLogger { level: Level::Warn }
}
}
impl log::Log for SmtpdLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= self.level
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let stderr = io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "{}: {}", record.level(), record.args()).unwrap();
}
}
fn flush(&self) {}
}

View file

@ -1,19 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::errors::Error;
pub trait FilterOutput {
fn send(&mut self, msg: &str) -> Result<(), Error>;
}
mod null;
mod stdout;
pub use null::NullOutput;
pub use stdout::{StdErr, StdOut};

View file

@ -1,25 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::errors::Error;
use crate::output::FilterOutput;
use std::default::Default;
pub struct NullOutput {}
impl Default for NullOutput {
fn default() -> Self {
NullOutput {}
}
}
impl FilterOutput for NullOutput {
fn send(&mut self, _msg: &str) -> Result<(), Error> {
Ok(())
}
}

View file

@ -1,33 +0,0 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::errors::Error;
use crate::output::FilterOutput;
use std::default::Default;
macro_rules! new_stdout {
($name: ident, $out: ident) => {
pub struct $name {}
impl Default for $name {
fn default() -> Self {
$name {}
}
}
impl FilterOutput for $name {
fn send(&mut self, msg: &str) -> Result<(), Error> {
$out!("{}", msg);
Ok(())
}
}
};
}
new_stdout!(StdOut, println);
new_stdout!(StdErr, eprintln);

View file

@ -0,0 +1,20 @@
use std::net::SocketAddr;
use std::path::PathBuf;
#[derive(Debug)]
pub enum Address {
Ip(SocketAddr),
UnixSocket(PathBuf),
}
impl ToString for Address {
fn to_string(&self) -> String {
match self {
Address::Ip(a) => a.to_string(),
Address::UnixSocket(a) => match a.clone().into_os_string().into_string() {
Ok(s) => s,
Err(_) => String::new(),
},
}
}
}

View file

@ -0,0 +1,31 @@
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuthResult {
Pass,
Fail,
Error,
}
impl ToString for AuthResult {
fn to_string(&self) -> String {
match self {
AuthResult::Pass => String::from("pass"),
AuthResult::Fail => String::from("fail"),
AuthResult::Error => String::from("error"),
}
}
}
impl FromStr for AuthResult {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"pass" => Ok(AuthResult::Pass),
"fail" => Ok(AuthResult::Fail),
"error" => Ok(AuthResult::Error),
_ => Err(()),
}
}
}

View file

@ -0,0 +1,79 @@
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Event {
LinkAuth,
LinkConnect,
LinkDisconnect,
LinkGreeting,
LinkIdentify,
LinkTls,
TxBegin,
TxMail,
TxReset,
TxRcpt,
TxEnvelope,
TxData,
TxCommit,
TxRollback,
ProtocolClient,
ProtocolServer,
FilterResponse,
FilterReport,
Timeout,
}
impl ToString for Event {
fn to_string(&self) -> String {
match self {
Event::LinkAuth => String::from("link-auth"),
Event::LinkConnect => String::from("link-connect"),
Event::LinkDisconnect => String::from("link-disconnect"),
Event::LinkGreeting => String::from("link-greeting"),
Event::LinkIdentify => String::from("link-identify"),
Event::LinkTls => String::from("link-tls"),
Event::TxBegin => String::from("tx-begin"),
Event::TxMail => String::from("tx-mail"),
Event::TxReset => String::from("tx-reset"),
Event::TxRcpt => String::from("tx-rcpt"),
Event::TxEnvelope => String::from("tx-envelope"),
Event::TxData => String::from("tx-data"),
Event::TxCommit => String::from("tx-commit"),
Event::TxRollback => String::from("tx-rollback"),
Event::ProtocolClient => String::from("protocol-client"),
Event::ProtocolServer => String::from("protocol-server"),
Event::FilterResponse => String::from("filter-response"),
Event::FilterReport => String::from("filter-report"),
Event::Timeout => String::from("timeout"),
}
}
}
impl FromStr for Event {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"link-auth" => Ok(Event::LinkAuth),
"link-connect" => Ok(Event::LinkConnect),
"link-disconnect" => Ok(Event::LinkDisconnect),
"link-greeting" => Ok(Event::LinkGreeting),
"link-identify" => Ok(Event::LinkIdentify),
"link-tls" => Ok(Event::LinkTls),
"tx-begin" => Ok(Event::TxBegin),
"tx-mail" => Ok(Event::TxMail),
"tx-reset" => Ok(Event::TxReset),
"tx-rcpt" => Ok(Event::TxRcpt),
"tx-envelope" => Ok(Event::TxEnvelope),
"tx-data" => Ok(Event::TxData),
"tx-commit" => Ok(Event::TxCommit),
"tx-rollback" => Ok(Event::TxRollback),
"protocol-client" => Ok(Event::ProtocolClient),
"protocol-server" => Ok(Event::ProtocolServer),
"filter-response" => Ok(Event::FilterResponse),
"filter-report" => Ok(Event::FilterReport),
"timeout" => Ok(Event::Timeout),
_ => Err(()),
}
}
}

View file

@ -0,0 +1,28 @@
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FilterKind {
Builtin,
Proc,
}
impl ToString for FilterKind {
fn to_string(&self) -> String {
match self {
FilterKind::Builtin => String::from("builtin"),
FilterKind::Proc => String::from("proc"),
}
}
}
impl FromStr for FilterKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"builtin" => Ok(FilterKind::Builtin),
"proc" => Ok(FilterKind::Proc),
_ => Err(()),
}
}
}

View file

@ -0,0 +1,52 @@
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FilterPhase {
Connect,
Helo,
Ehlo,
StartTls,
Auth,
MailFrom,
RcptTo,
Data,
DataLine,
Commit,
}
impl ToString for FilterPhase {
fn to_string(&self) -> String {
match self {
FilterPhase::Connect => String::from("connect"),
FilterPhase::Helo => String::from("helo"),
FilterPhase::Ehlo => String::from("ehlo"),
FilterPhase::StartTls => String::from("starttls"),
FilterPhase::Auth => String::from("auth"),
FilterPhase::MailFrom => String::from("mail-from"),
FilterPhase::RcptTo => String::from("rcpt-to"),
FilterPhase::Data => String::from("data"),
FilterPhase::DataLine => String::from("data-line"),
FilterPhase::Commit => String::from("commit"),
}
}
}
impl FromStr for FilterPhase {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"connect" => Ok(FilterPhase::Connect),
"helo" => Ok(FilterPhase::Helo),
"ehlo" => Ok(FilterPhase::Ehlo),
"starttls" => Ok(FilterPhase::StartTls),
"auth" => Ok(FilterPhase::Auth),
"mail-from" => Ok(FilterPhase::MailFrom),
"rcpt-to" => Ok(FilterPhase::RcptTo),
"data" => Ok(FilterPhase::Data),
"data-line" => Ok(FilterPhase::DataLine),
"commit" => Ok(FilterPhase::Commit),
_ => Err(()),
}
}
}

View file

@ -0,0 +1,24 @@
use crate::SmtpStatusCode;
#[derive(Clone, Debug)]
pub enum FilterResponse {
Proceed,
Junk,
Reject(SmtpStatusCode),
Disconnect(SmtpStatusCode),
Rewrite(String),
Report(String),
}
impl ToString for FilterResponse {
fn to_string(&self) -> String {
match self {
FilterResponse::Proceed => String::from("proceed"),
FilterResponse::Junk => String::from("junk"),
FilterResponse::Reject(e) => format!("reject|{}", e.to_string()),
FilterResponse::Disconnect(e) => format!("disconnect|{}", e.to_string()),
FilterResponse::Rewrite(s) => format!("rewrite|{}", s),
FilterResponse::Report(s) => format!("report|{}", s),
}
}
}

View file

@ -0,0 +1,31 @@
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MailResult {
Ok,
PermFail,
TempFail,
}
impl ToString for MailResult {
fn to_string(&self) -> String {
match self {
MailResult::Ok => String::from("ok"),
MailResult::PermFail => String::from("permfail"),
MailResult::TempFail => String::from("tempfail"),
}
}
}
impl FromStr for MailResult {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ok" => Ok(MailResult::Ok),
"permfail" => Ok(MailResult::PermFail),
"tempfail" => Ok(MailResult::TempFail),
_ => Err(()),
}
}
}

View file

@ -0,0 +1,28 @@
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Method {
Helo,
Ehlo,
}
impl ToString for Method {
fn to_string(&self) -> String {
match self {
Method::Helo => String::from("HELO"),
Method::Ehlo => String::from("EHLO"),
}
}
}
impl FromStr for Method {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"HELO" => Ok(Method::Helo),
"EHLO" => Ok(Method::Ehlo),
_ => Err(()),
}
}
}

View file

@ -0,0 +1,11 @@
pub(crate) mod address;
pub(crate) mod auth_result;
pub(crate) mod event;
pub(crate) mod filter_kind;
pub(crate) mod filter_phase;
pub(crate) mod filter_response;
pub(crate) mod mail_result;
pub(crate) mod method;
pub(crate) mod smtp_status;
pub(crate) mod subsystem;
pub(crate) mod timeval;

View file

@ -0,0 +1,116 @@
#[derive(Clone, Debug)]
pub struct SmtpStatusCode {
pub number: usize,
pub text: String,
}
impl SmtpStatusCode {
pub fn from_number(error_number: usize) -> Self {
match error_number {
211 => SmtpStatusCode {
number: 211,
text: String::from("System status"),
},
220 => SmtpStatusCode {
number: 220,
text: String::from("Service ready"),
},
250 => SmtpStatusCode {
number: 250,
text: String::from("Requested mail action okay, completed"),
},
251 => SmtpStatusCode {
number: 251,
text: String::from("User not local; will forward"),
},
252 => SmtpStatusCode {
number: 252,
text: String::from(
"Cannot verify the user, but it will try to deliver the message anyway",
),
},
354 => SmtpStatusCode {
number: 354,
text: String::from("Start mail input"),
},
421 => SmtpStatusCode {
number: 421,
text: String::from("Service is unavailable because the server is shutting down"),
},
450 => SmtpStatusCode {
number: 450,
text: String::from("Requested mail action not taken: mailbox unavailable"),
},
451 => SmtpStatusCode {
number: 451,
text: String::from("Requested action aborted: local error in processing"),
},
452 => SmtpStatusCode {
number: 452,
text: String::from("Requested action not taken: insufficient system storage"),
},
455 => SmtpStatusCode {
number: 455,
text: String::from("Server unable to accommodate parameters"),
},
500 => SmtpStatusCode {
number: 500,
text: String::from("Syntax error, command unrecognized"),
},
501 => SmtpStatusCode {
number: 501,
text: String::from("Syntax error in parameters or arguments"),
},
502 => SmtpStatusCode {
number: 502,
text: String::from("Command not implemented"),
},
503 => SmtpStatusCode {
number: 503,
text: String::from("Bad sequence of commands"),
},
504 => SmtpStatusCode {
number: 504,
text: String::from("Command parameter is not implemented"),
},
521 => SmtpStatusCode {
number: 521,
text: String::from("Server does not accept mail"),
},
523 => SmtpStatusCode {
number: 523,
text: String::from("Encryption Needed"),
},
550 => SmtpStatusCode {
number: 550,
text: String::from("Requested action not taken: mailbox unavailable"),
},
552 => SmtpStatusCode {
number: 552,
text: String::from("Requested mail action aborted: exceeded storage allocation"),
},
553 => SmtpStatusCode {
number: 553,
text: String::from("Requested action not taken: mailbox name not allowed"),
},
554 => SmtpStatusCode {
number: 554,
text: String::from("Transaction has failed"),
},
556 => SmtpStatusCode {
number: 556,
text: String::from("Domain does not accept mail"),
},
nb => SmtpStatusCode {
number: nb,
text: String::new(),
},
}
}
}
impl ToString for SmtpStatusCode {
fn to_string(&self) -> String {
format!("{} {}", self.number, self.text)
}
}

View file

@ -0,0 +1,25 @@
use std::str::FromStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SubSystem {
SmtpIn,
}
impl ToString for SubSystem {
fn to_string(&self) -> String {
match self {
SubSystem::SmtpIn => String::from("smtp-in"),
}
}
}
impl FromStr for SubSystem {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"smtp-in" => Ok(SubSystem::SmtpIn),
_ => Err(()),
}
}
}

View file

@ -0,0 +1,11 @@
#[derive(Debug, Eq, PartialEq)]
pub struct TimeVal {
pub sec: i64,
pub usec: i64,
}
impl ToString for TimeVal {
fn to_string(&self) -> String {
format!("{}.{}", self.sec, self.usec)
}
}

219
src/filter.rs Normal file
View file

@ -0,0 +1,219 @@
use crate::{
Address, AuthResult, FilterEntry, FilterKind, FilterPhase, FilterResponse, MailResult, Method,
ReportEntry,
};
pub trait Filter {
fn on_report_link_auth(&mut self, _entry: &ReportEntry, _username: &str, _result: AuthResult) {}
fn has_report_link_auth(&self) -> bool {
return false;
}
fn on_report_link_connect(
&mut self,
_entry: &ReportEntry,
_rdns: &str,
_fcrdns: &str,
_src: &Address,
_dest: &Address,
) {
}
fn has_report_link_connect(&self) -> bool {
return false;
}
fn on_report_link_disconnect(&mut self, _entry: &ReportEntry) {}
fn has_report_link_disconnect(&self) -> bool {
return false;
}
fn on_report_link_greeting(&mut self, _entry: &ReportEntry, _hostname: &str) {}
fn has_report_link_greeting(&self) -> bool {
return false;
}
fn on_report_link_identify(&mut self, _entry: &ReportEntry, _method: Method, _identity: &str) {}
fn has_report_link_identify(&self) -> bool {
return false;
}
fn on_report_link_tls(&mut self, _entry: &ReportEntry, _tls_string: &str) {}
fn has_report_link_tls(&self) -> bool {
return false;
}
fn on_report_tx_begin(&mut self, _entry: &ReportEntry, _message_id: &str) {}
fn has_report_tx_begin(&self) -> bool {
return false;
}
fn on_report_tx_mail(
&mut self,
_entry: &ReportEntry,
_message_id: &str,
_result: MailResult,
_address: &str,
) {
}
fn has_report_tx_mail(&self) -> bool {
return false;
}
fn on_report_tx_reset(&mut self, _entry: &ReportEntry, _message_id: &Option<String>) {}
fn has_report_tx_reset(&self) -> bool {
return false;
}
fn on_report_tx_rcpt(
&mut self,
_entry: &ReportEntry,
_message_id: &str,
_result: MailResult,
_address: &str,
) {
}
fn has_report_tx_rcpt(&self) -> bool {
return false;
}
fn on_report_tx_envelope(
&mut self,
_entry: &ReportEntry,
_message_id: &str,
_envelope_id: &str,
) {
}
fn has_report_tx_envelope(&self) -> bool {
return false;
}
fn on_report_tx_data(&mut self, _entry: &ReportEntry, _message_id: &str, _result: MailResult) {}
fn has_report_tx_data(&self) -> bool {
return false;
}
fn on_report_tx_commit(
&mut self,
_entry: &ReportEntry,
_message_id: &str,
_message_size: usize,
) {
}
fn has_report_tx_commit(&self) -> bool {
return false;
}
fn on_report_tx_rollback(&mut self, _entry: &ReportEntry, _message_id: &str) {}
fn has_report_tx_rollback(&self) -> bool {
return false;
}
fn on_report_protocol_client(&mut self, _entry: &ReportEntry, _command: &str) {}
fn has_report_protocol_client(&self) -> bool {
return false;
}
fn on_report_protocol_server(&mut self, _entry: &ReportEntry, _response: &str) {}
fn has_report_protocol_server(&self) -> bool {
return false;
}
fn on_report_filter_response(
&mut self,
_entry: &ReportEntry,
_phase: FilterPhase,
_response: &str,
_param: &Option<String>,
) {
}
fn has_report_filter_response(&self) -> bool {
return false;
}
fn on_report_filter_report(
&mut self,
_entry: &ReportEntry,
_filter_kind: FilterKind,
_name: &str,
_message: &str,
) {
}
fn has_report_filter_report(&self) -> bool {
return false;
}
fn on_report_timeout(&mut self, _entry: &ReportEntry) {}
fn has_report_timeout(&self) -> bool {
return false;
}
fn on_filter_auth(&mut self, _entry: &FilterEntry, _auth: &str) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_auth(&self) -> bool {
return false;
}
fn on_filter_commit(&mut self, _entry: &FilterEntry) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_commit(&self) -> bool {
return false;
}
fn on_filter_connect(
&mut self,
_entry: &FilterEntry,
_rdns: &str,
_fcrdns: &str,
_src: &Address,
_dest: &Address,
) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_connect(&self) -> bool {
return false;
}
fn on_filter_data(&mut self, _entry: &FilterEntry) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_data(&self) -> bool {
return false;
}
fn on_filter_ehlo(&mut self, _entry: &FilterEntry, _identity: &str) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_ehlo(&self) -> bool {
return false;
}
fn on_filter_helo(&mut self, _entry: &FilterEntry, _identity: &str) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_helo(&self) -> bool {
return false;
}
fn on_filter_mail_from(&mut self, _entry: &FilterEntry, _address: &str) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_mail_from(&self) -> bool {
return false;
}
fn on_filter_rcpt_to(&mut self, _entry: &FilterEntry, _address: &str) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_rcpt_to(&self) -> bool {
return false;
}
fn on_filter_starttls(&mut self, _entry: &FilterEntry, _tls_string: &str) -> FilterResponse {
FilterResponse::Proceed
}
fn has_filter_starttls(&self) -> bool {
return false;
}
}

46
src/io.rs Normal file
View file

@ -0,0 +1,46 @@
use std::io::{self, ErrorKind, Read};
use std::sync::mpsc::Sender;
pub(crate) fn read_stdin(tx: &Sender<Vec<u8>>) {
if let Err(e) = do_read_stdin(tx) {
log::error!("{}", e);
}
}
fn do_read_stdin(tx: &Sender<Vec<u8>>) -> Result<(), String> {
let mut read_buffer: [u8; crate::BUFFER_SIZE] = [0; crate::BUFFER_SIZE];
let mut line_buffer: Vec<u8> = Vec::with_capacity(crate::BUFFER_SIZE);
let mut stdin = io::stdin();
loop {
read_buffer.copy_from_slice(&[0; crate::BUFFER_SIZE]);
let len = match stdin.read(&mut read_buffer) {
Ok(n) => n,
Err(e) => match e.kind() {
ErrorKind::Interrupted => {
continue;
}
_ => {
return Err(e.to_string());
}
},
};
if len == 0 {
return Err(String::from("unable to read on stdin"));
}
line_buffer.extend_from_slice(&read_buffer);
loop {
match line_buffer.iter().position(|i| *i == b'\n') {
Some(id) => {
let pos = id + 1;
let mut line = Vec::with_capacity(pos);
line.extend_from_slice(&line_buffer[..pos]);
tx.send(line).unwrap();
line_buffer.drain(..pos);
}
None => {
break;
}
};
}
}
}

92
src/lib.rs Normal file
View file

@ -0,0 +1,92 @@
mod data_structures;
mod filter;
mod io;
mod parsers;
mod process;
pub use crate::data_structures::address::Address;
pub use crate::data_structures::auth_result::AuthResult;
pub use crate::data_structures::event::Event;
pub use crate::data_structures::filter_kind::FilterKind;
pub use crate::data_structures::filter_phase::FilterPhase;
pub use crate::data_structures::filter_response::FilterResponse;
pub use crate::data_structures::mail_result::MailResult;
pub use crate::data_structures::method::Method;
pub use crate::data_structures::smtp_status::SmtpStatusCode;
pub use crate::data_structures::subsystem::SubSystem;
pub use crate::data_structures::timeval::TimeVal;
pub use crate::filter::Filter;
pub use crate::parsers::entry::{FilterEntry, ReportEntry};
use crate::parsers::handshake::parse_handshake;
use std::sync::mpsc::channel;
use std::thread;
const BUFFER_SIZE: usize = 4096;
#[macro_export]
macro_rules! register {
($name: ident) => {
fn $name(&self) -> bool {
return true;
}
};
}
macro_rules! recv {
($rx: ident) => {
match $rx.recv() {
Ok(b) => b,
Err(e) => {
log::error!("{}", e);
return;
}
}
};
}
pub fn run_filter<T>(user_object: &mut T)
where
T: Filter,
{
// IO init
let (tx, rx) = channel::<Vec<u8>>();
thread::spawn(move || {
io::read_stdin(&tx);
});
// Handshake
let mut handshake_buffer: Vec<u8> = Vec::with_capacity(BUFFER_SIZE);
let handshake = loop {
let buffer = recv!(rx);
handshake_buffer.extend_from_slice(&buffer);
if let Ok((_, handshake)) = parse_handshake(&handshake_buffer) {
break handshake;
}
};
handshake_reply(user_object, handshake.subsystem);
// Read and process input
loop {
let buffer = recv!(rx);
if let Err(msg) = process::line(user_object, &buffer) {
log::error!("{}", msg);
}
}
}
macro_rules! handshake_register {
($obj: ident, $func: ident, $subsystem: expr, $type: expr, $name: expr) => {
if $obj.$func() {
println!("register|{}|{}|{}", $type, $subsystem.to_string(), $name);
}
};
}
fn handshake_reply<T>(obj: &mut T, ss: SubSystem)
where
T: Filter,
{
handshake_register!(obj, has_report_link_connect, ss, "report", "link-connect");
println!("register|ready");
}

159
src/parsers/entry.rs Normal file
View file

@ -0,0 +1,159 @@
use super::{parse_data_structure, parse_delimiter, parse_string_parameter};
use crate::Event;
use crate::FilterPhase;
use crate::SubSystem;
use crate::TimeVal;
use nom::branch::alt;
use nom::bytes::streaming::tag;
use nom::character::streaming::digit1;
use nom::combinator::map_res;
use nom::IResult;
pub struct ReportEntry {
pub version: String,
pub timestamp: TimeVal,
pub subsystem: SubSystem,
pub event: Event,
pub session_id: String,
}
pub struct FilterEntry {
pub version: String,
pub timestamp: TimeVal,
pub subsystem: SubSystem,
pub phase: FilterPhase,
pub session_id: String,
pub token: String,
}
pub struct DataLineEntry {
pub session_id: String,
pub token: String,
}
pub(crate) enum EntryOption {
Report(ReportEntry),
Filter(FilterEntry),
DataLine(DataLineEntry),
}
pub(crate) fn parse_entry(input: &[u8]) -> IResult<&[u8], EntryOption> {
let (input, entry) = alt((
parse_report_entry_meta,
alt((parse_filter_entry_meta, parse_data_line_entry_meta)),
))(input)?;
Ok((input, entry))
}
fn parse_report_entry_meta(input: &[u8]) -> IResult<&[u8], EntryOption> {
let (input, _) = tag("report")(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, entry) = parse_report_entry(input)?;
Ok((input, EntryOption::Report(entry)))
}
fn parse_filter_entry_meta(input: &[u8]) -> IResult<&[u8], EntryOption> {
let (input, _) = tag("filter")(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, entry) = parse_filter_entry(input)?;
Ok((input, EntryOption::Filter(entry)))
}
fn parse_data_line_entry_meta(input: &[u8]) -> IResult<&[u8], EntryOption> {
let (input, _) = tag("filter-dataline")(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, data_line) = parse_data_line_entry(input)?;
Ok((input, EntryOption::DataLine(data_line)))
}
fn parse_report_entry(input: &[u8]) -> IResult<&[u8], ReportEntry> {
let (input, version) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, timestamp) = parse_timestamp(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, subsystem) = parse_data_structure::<SubSystem>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, event) = parse_data_structure::<Event>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, session_id) = parse_string_parameter(input)?;
let entry = ReportEntry {
version,
timestamp,
subsystem,
event,
session_id,
};
Ok((input, entry))
}
fn parse_filter_entry(input: &[u8]) -> IResult<&[u8], FilterEntry> {
let (input, version) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, timestamp) = parse_timestamp(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, subsystem) = parse_data_structure::<SubSystem>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, phase) = parse_data_structure::<FilterPhase>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, session_id) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, token) = parse_string_parameter(input)?;
let entry = FilterEntry {
version,
timestamp,
subsystem,
phase,
session_id,
token,
};
Ok((input, entry))
}
fn parse_data_line_entry(input: &[u8]) -> IResult<&[u8], DataLineEntry> {
let (input, session_id) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, token) = parse_string_parameter(input)?;
let entry = DataLineEntry { session_id, token };
Ok((input, entry))
}
fn parse_timestamp(input: &[u8]) -> IResult<&[u8], TimeVal> {
let (input, sec) = map_res(digit1, |s| String::from_utf8_lossy(s).parse::<i64>())(input)?;
let (input, _) = tag(".")(input)?;
let (input, usec) = map_res(digit1, |s| {
format!("{:0<6}", String::from_utf8_lossy(s)).parse::<i64>()
})(input)?;
let timestamp = TimeVal { sec, usec };
Ok((input, timestamp))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_report_link_connect() {
let input = b"report|0.5|1576146008.06099|smtp-in|link-connect|7641df9771b4ed00|mail.openbsd.org|pass|199.185.178.25:33174|45.77.67.80:25";
let res = parse_entry(input);
assert!(res.is_ok());
let (_, res) = res.unwrap();
let res = match res {
EntryOption::Report(r) => r,
_ => {
assert!(false);
return;
}
};
assert_eq!(res.version, String::from("0.5"));
assert_eq!(
res.timestamp,
TimeVal {
sec: 1576146008,
usec: 60990
}
);
assert_eq!(res.subsystem, SubSystem::SmtpIn);
assert_eq!(res.event, Event::LinkConnect);
assert_eq!(res.session_id, String::from("7641df9771b4ed00"));
}
}

122
src/parsers/handshake.rs Normal file
View file

@ -0,0 +1,122 @@
use super::{
parse_data_structure, parse_delimiter, parse_eol, parse_string_parameter, parse_usize,
};
use crate::SubSystem;
use nom::bytes::streaming::tag;
use nom::IResult;
#[derive(Debug)]
pub(crate) struct Handshake {
pub(crate) smtpd_version: String,
pub(crate) smtp_session_timeout: usize,
pub(crate) subsystem: SubSystem,
}
pub(crate) fn parse_handshake(input: &[u8]) -> IResult<&[u8], Handshake> {
let (input, smtpd_version) = parse_smtpd_version(input)?;
let (input, smtp_session_timeout) = parse_smtp_session_timeout(input)?;
let (input, subsystem) = parse_subsystem(input)?;
let (input, _) = parse_ready(input)?;
let handshake = Handshake {
smtpd_version,
smtp_session_timeout,
subsystem,
};
Ok((input, handshake))
}
fn parse_smtpd_version(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_config_initial(input)?;
let (input, _) = tag("smtpd-version")(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, version) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, version))
}
fn parse_smtp_session_timeout(input: &[u8]) -> IResult<&[u8], usize> {
let (input, _) = parse_config_initial(input)?;
let (input, _) = tag("smtp-session-timeout")(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, timeout) = parse_usize(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, timeout))
}
fn parse_subsystem(input: &[u8]) -> IResult<&[u8], SubSystem> {
let (input, _) = parse_config_initial(input)?;
let (input, _) = tag("subsystem")(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, subsystem) = parse_data_structure::<SubSystem>(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, subsystem))
}
fn parse_ready(input: &[u8]) -> IResult<&[u8], ()> {
let (input, _) = parse_config_initial(input)?;
let (input, _) = tag("ready")(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, ()))
}
fn parse_config_initial(input: &[u8]) -> IResult<&[u8], ()> {
let (input, _) = tag("config")(input)?;
let (input, _) = parse_delimiter(input)?;
Ok((input, ()))
}
#[cfg(test)]
mod tests {
use super::parse_handshake;
use crate::SubSystem;
#[test]
fn test_valid_handshake_nl() {
let input = b"config|smtpd-version|6.6.1\nconfig|smtp-session-timeout|300\nconfig|subsystem|smtp-in\nconfig|ready\n";
let r = parse_handshake(input);
assert!(r.is_ok());
let (r, h) = r.unwrap();
assert_eq!(r, b"");
assert_eq!(h.smtpd_version, "6.6.1");
assert_eq!(h.smtp_session_timeout, 300);
assert_eq!(h.subsystem, SubSystem::SmtpIn);
}
#[test]
fn test_valid_handshake_crnl() {
let input = b"config|smtpd-version|6.6.1\r\nconfig|smtp-session-timeout|300\r\nconfig|subsystem|smtp-in\r\nconfig|ready\r\n";
let r = parse_handshake(input);
assert!(r.is_ok());
let (r, h) = r.unwrap();
assert_eq!(r, b"");
assert_eq!(h.smtpd_version, "6.6.1");
assert_eq!(h.smtp_session_timeout, 300);
assert_eq!(h.subsystem, SubSystem::SmtpIn);
}
#[test]
fn test_valid_handshake_over() {
let input = b"config|smtpd-version|6.6.1\nconfig|smtp-session-timeout|300\nconfig|subsystem|smtp-in\nconfig|ready\nplop";
let r = parse_handshake(input);
assert!(r.is_ok());
let (r, h) = r.unwrap();
assert_eq!(r, b"plop");
assert_eq!(h.smtpd_version, "6.6.1");
assert_eq!(h.smtp_session_timeout, 300);
assert_eq!(h.subsystem, SubSystem::SmtpIn);
}
#[test]
fn test_invalid_handshakes() {
let test_vectors = vec![
"config|smtpd-version|6.6.1\nconfig|smtp-session-timeout|\nconfig|subsystem|smtp-in\nconfig|ready\n",
"config|smtp-session-timeout|300\nconfig|smtpd-version|6.6.1\nconfig|subsystem|smtp-in\nconfig|ready\n",
"config|smtpd-version|6.6.1\nconfig|smtp-session-timeout|300\nconfig|subsystem|smtp-in\nconfig|ready",
"config|smtpd-version|6.6.1\nconfig|smtp-session-timeout|300\nconfig|subsystem|smtp-in\nconfig|ready\r",
];
for input in test_vectors {
let r = parse_handshake(input.as_bytes());
assert!(r.is_err());
}
}
}

66
src/parsers/mod.rs Normal file
View file

@ -0,0 +1,66 @@
pub(crate) mod entry;
pub(crate) mod handshake;
pub(crate) mod parameters;
use nom::branch::alt;
use nom::bytes::streaming::{tag, take_while1};
use nom::combinator::map_res;
use nom::IResult;
use std::str::FromStr;
fn is_body_char(c: u8) -> bool {
!(c as char).is_control()
}
fn is_parameter_char(c: u8) -> bool {
is_body_char(c) && (c as char) != '|'
}
fn parse_string_parameter(input: &[u8]) -> IResult<&[u8], String> {
let (input, s) = take_while1(is_parameter_char)(input)?;
Ok((input, String::from_utf8(s.to_vec()).unwrap()))
}
fn parse_data_structure<T>(input: &[u8]) -> IResult<&[u8], T>
where
T: FromStr,
{
map_res(take_while1(is_parameter_char), |s: &[u8]| {
T::from_str(&String::from_utf8_lossy(s))
})(input)
}
fn parse_delimiter(input: &[u8]) -> IResult<&[u8], &[u8]> {
tag("|")(input)
}
fn parse_eol(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((tag("\r\n"), tag("\n")))(input)
}
fn parse_usize(input: &[u8]) -> IResult<&[u8], usize> {
map_res(take_while1(|c| (c as char).is_ascii_digit()), |s| {
usize::from_str_radix(&String::from_utf8_lossy(s), 10)
})(input)
}
#[cfg(test)]
mod tests {
use super::is_parameter_char;
#[test]
fn test_valid_parameter_char() {
let char_lst = "a0.:-_/";
for c in char_lst.bytes() {
assert!(is_parameter_char(c));
}
}
#[test]
fn test_invalid_parameter_char() {
let char_lst = "|\n";
for c in char_lst.bytes() {
assert!(!is_parameter_char(c));
}
}
}

317
src/parsers/parameters.rs Normal file
View file

@ -0,0 +1,317 @@
use super::{
is_parameter_char, parse_data_structure, parse_delimiter, parse_eol, parse_string_parameter,
parse_usize,
};
use crate::{Address, AuthResult, FilterKind, FilterPhase, MailResult, Method};
use nom::branch::alt;
use nom::bytes::streaming::{tag, take_while1};
use nom::combinator::{map_res, opt};
use nom::IResult;
use std::net::SocketAddr;
use std::path::PathBuf;
pub(crate) fn parse_filter_auth(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, s) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, s))
}
pub(crate) fn parse_filter_connect(
input: &[u8],
) -> IResult<&[u8], (String, String, Address, Address)> {
let (input, _) = parse_delimiter(input)?;
let (input, rdns) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, fcrdns) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, src) = parse_address(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, dest) = parse_address(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (rdns, fcrdns, src, dest)))
}
pub(crate) fn parse_filter_ehlo(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, s) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, s))
}
pub(crate) fn parse_filter_helo(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, s) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, s))
}
pub(crate) fn parse_filter_mail_from(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, s) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, s))
}
pub(crate) fn parse_filter_rcpt_to(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, s) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, s))
}
pub(crate) fn parse_filter_starttls(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, s) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, s))
}
pub(crate) fn parse_report_link_auth(input: &[u8]) -> IResult<&[u8], (String, AuthResult)> {
let (input, _) = parse_delimiter(input)?;
let (input, username) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, result) = parse_data_structure::<AuthResult>(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (username, result)))
}
pub(crate) fn parse_report_link_connect(
input: &[u8],
) -> IResult<&[u8], (String, String, Address, Address)> {
let (input, _) = parse_delimiter(input)?;
let (input, rdns) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, fcrdns) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, src) = parse_address(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, dest) = parse_address(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (rdns, fcrdns, src, dest)))
}
pub(crate) fn parse_report_link_greeting(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, hostname) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, hostname))
}
pub(crate) fn parse_report_link_identify(input: &[u8]) -> IResult<&[u8], (Method, String)> {
let (input, _) = parse_delimiter(input)?;
let (input, method) = parse_data_structure::<Method>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, identity) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (method, identity)))
}
pub(crate) fn parse_report_link_tls(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, tls_string) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, tls_string))
}
pub(crate) fn parse_report_tx_begin(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, id) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, id))
}
pub(crate) fn parse_report_tx_mail(input: &[u8]) -> IResult<&[u8], (String, MailResult, String)> {
let (input, _) = parse_delimiter(input)?;
let (input, id) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, result) = parse_data_structure::<MailResult>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, addr) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (id, result, addr)))
}
pub(crate) fn parse_report_tx_reset(input: &[u8]) -> IResult<&[u8], Option<String>> {
let (input, id) = opt(parse_tx_reset_opt)(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, id))
}
fn parse_tx_reset_opt(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, id) = parse_string_parameter(input)?;
Ok((input, id))
}
pub(crate) fn parse_report_tx_rcpt(input: &[u8]) -> IResult<&[u8], (String, MailResult, String)> {
let (input, _) = parse_delimiter(input)?;
let (input, id) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, result) = parse_data_structure::<MailResult>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, addr) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (id, result, addr)))
}
pub(crate) fn parse_report_tx_envelope(input: &[u8]) -> IResult<&[u8], (String, String)> {
let (input, _) = parse_delimiter(input)?;
let (input, msg) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, env) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (msg, env)))
}
pub(crate) fn parse_report_tx_data(input: &[u8]) -> IResult<&[u8], (String, MailResult)> {
let (input, _) = parse_delimiter(input)?;
let (input, id) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, result) = parse_data_structure::<MailResult>(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (id, result)))
}
pub(crate) fn parse_report_tx_commit(input: &[u8]) -> IResult<&[u8], (String, usize)> {
let (input, _) = parse_delimiter(input)?;
let (input, id) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, s) = parse_usize(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (id, s)))
}
pub(crate) fn parse_report_tx_rollback(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, id) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, id))
}
pub(crate) fn parse_report_protocol_client(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, cmd) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, cmd))
}
pub(crate) fn parse_report_protocol_server(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
let (input, res) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, res))
}
pub(crate) fn parse_report_filter_response(
input: &[u8],
) -> IResult<&[u8], (FilterPhase, String, Option<String>)> {
let (input, _) = parse_delimiter(input)?;
let (input, phase) = parse_data_structure::<FilterPhase>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, res) = parse_string_parameter(input)?;
let (input, param) = opt(parse_filter_response_opt)(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (phase, res, param)))
}
fn parse_filter_response_opt(input: &[u8]) -> IResult<&[u8], String> {
let (input, _) = parse_delimiter(input)?;
parse_string_parameter(input)
}
pub(crate) fn parse_report_filter_report(
input: &[u8],
) -> IResult<&[u8], (FilterKind, String, String)> {
let (input, _) = parse_delimiter(input)?;
let (input, kind) = parse_data_structure::<FilterKind>(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, name) = parse_string_parameter(input)?;
let (input, _) = parse_delimiter(input)?;
let (input, message) = parse_string_parameter(input)?;
let (input, _) = parse_eol(input)?;
Ok((input, (kind, name, message)))
}
fn parse_address(input: &[u8]) -> IResult<&[u8], Address> {
alt((parse_unix_socket, parse_socketaddr))(input)
}
fn parse_socketaddr(input: &[u8]) -> IResult<&[u8], Address> {
map_res(
take_while1(is_parameter_char),
|s: &[u8]| -> Result<Address, String> {
let s = String::from_utf8(s.to_vec()).map_err(|e| e.to_string())?;
let addr = s.parse::<SocketAddr>().map_err(|e| e.to_string())?;
Ok(Address::Ip(addr))
},
)(input)
}
fn parse_unix_socket(input: &[u8]) -> IResult<&[u8], Address> {
let (input, _) = tag("unix:")(input)?;
map_res(
take_while1(is_parameter_char),
|s: &[u8]| -> Result<Address, String> {
let s = String::from_utf8(s.to_vec()).map_err(|e| e.to_string())?;
let addr = s.parse::<PathBuf>().map_err(|e| e.to_string())?;
Ok(Address::UnixSocket(addr))
},
)(input)
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::Path;
#[test]
fn test_ipv4_port() {
let res = parse_address(b"199.185.178.25:33174|");
assert!(res.is_ok());
let (i, addr) = res.unwrap();
assert_eq!(i, b"|");
match addr {
Address::Ip(addr) => {
assert!(addr.is_ipv4());
assert_eq!(addr.port(), 33174);
assert_eq!(addr.ip(), IpAddr::V4(Ipv4Addr::new(199, 185, 178, 25)));
}
Address::UnixSocket(_) => assert!(false),
};
}
#[test]
fn test_ipv6_port() {
let res = parse_address(b"[2001:db8::42]:33174\n");
assert!(res.is_ok());
let (i, addr) = res.unwrap();
assert_eq!(i, b"\n");
match addr {
Address::Ip(addr) => {
assert!(addr.is_ipv6());
assert_eq!(addr.port(), 33174);
assert_eq!(
addr.ip(),
IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x42))
);
}
Address::UnixSocket(_) => assert!(false),
};
}
#[test]
fn test_unix_socket() {
let res = parse_address(b"unix:/var/something.sock|");
assert!(res.is_ok());
let (i, addr) = res.unwrap();
assert_eq!(i, b"|");
match addr {
Address::UnixSocket(addr) => {
assert_eq!(addr, Path::new("/var/something.sock").to_path_buf());
}
Address::Ip(_) => assert!(false),
};
}
}

168
src/process.rs Normal file
View file

@ -0,0 +1,168 @@
use crate::parsers::entry::{parse_entry, EntryOption};
use crate::parsers::parameters::{
parse_filter_auth, parse_filter_connect, parse_filter_ehlo, parse_filter_helo,
parse_filter_mail_from, parse_filter_rcpt_to, parse_filter_starttls,
parse_report_filter_report, parse_report_filter_response, parse_report_link_auth,
parse_report_link_connect, parse_report_link_greeting, parse_report_link_identify,
parse_report_link_tls, parse_report_protocol_client, parse_report_protocol_server,
parse_report_tx_begin, parse_report_tx_commit, parse_report_tx_data, parse_report_tx_envelope,
parse_report_tx_mail, parse_report_tx_rcpt, parse_report_tx_reset, parse_report_tx_rollback,
};
use crate::{Event, Filter, FilterPhase};
macro_rules! handle_reports {
($obj: ident, $r: ident, $input: ident) => {
match $r.event {
Event::LinkAuth => {
let (_, (username, result)) =
parse_report_link_auth($input).map_err(|e| e.to_string())?;
$obj.on_report_link_auth(&$r, &username, result);
}
Event::LinkConnect => {
let (_, (rdns, fcrdns, src, dest)) =
parse_report_link_connect($input).map_err(|e| e.to_string())?;
$obj.on_report_link_connect(&$r, &rdns, &fcrdns, &src, &dest);
}
Event::LinkDisconnect => {
$obj.on_report_link_disconnect(&$r);
}
Event::LinkGreeting => {
let (_, hostname) =
parse_report_link_greeting($input).map_err(|e| e.to_string())?;
$obj.on_report_link_greeting(&$r, &hostname);
}
Event::LinkIdentify => {
let (_, (method, identity)) =
parse_report_link_identify($input).map_err(|e| e.to_string())?;
$obj.on_report_link_identify(&$r, method, &identity);
}
Event::LinkTls => {
let (_, s) = parse_report_link_tls($input).map_err(|e| e.to_string())?;
$obj.on_report_link_tls(&$r, &s);
}
Event::TxBegin => {
let (_, id) = parse_report_tx_begin($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_begin(&$r, &id);
}
Event::TxMail => {
let (_, (id, result, addr)) =
parse_report_tx_mail($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_mail(&$r, &id, result, &addr);
}
Event::TxReset => {
let (_, id) = parse_report_tx_reset($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_reset(&$r, &id);
}
Event::TxRcpt => {
let (_, (id, result, addr)) =
parse_report_tx_rcpt($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_rcpt(&$r, &id, result, &addr);
}
Event::TxEnvelope => {
let (_, (msg, env)) =
parse_report_tx_envelope($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_envelope(&$r, &msg, &env);
}
Event::TxData => {
let (_, (id, result)) = parse_report_tx_data($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_data(&$r, &id, result);
}
Event::TxCommit => {
let (_, (id, size)) = parse_report_tx_commit($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_commit(&$r, &id, size);
}
Event::TxRollback => {
let (_, id) = parse_report_tx_rollback($input).map_err(|e| e.to_string())?;
$obj.on_report_tx_rollback(&$r, &id);
}
Event::ProtocolClient => {
let (_, cmd) = parse_report_protocol_client($input).map_err(|e| e.to_string())?;
$obj.on_report_protocol_client(&$r, &cmd);
}
Event::ProtocolServer => {
let (_, res) = parse_report_protocol_server($input).map_err(|e| e.to_string())?;
$obj.on_report_protocol_server(&$r, &res);
}
Event::FilterResponse => {
let (_, (phase, res, param)) =
parse_report_filter_response($input).map_err(|e| e.to_string())?;
$obj.on_report_filter_response(&$r, phase, &res, &param);
}
Event::FilterReport => {
let (_, (kind, name, message)) =
parse_report_filter_report($input).map_err(|e| e.to_string())?;
$obj.on_report_filter_report(&$r, kind, &name, &message);
}
Event::Timeout => {
$obj.on_report_timeout(&$r);
}
}
};
}
macro_rules! handle_filters {
($obj: ident, $f: ident, $input: ident) => {
match $f.phase {
FilterPhase::Auth => {
let (_, auth) = parse_filter_auth($input).map_err(|e| e.to_string())?;
Some($obj.on_filter_auth(&$f, &auth))
}
FilterPhase::Commit => Some($obj.on_filter_commit(&$f)),
FilterPhase::Connect => {
let (_, (rdns, fcrdns, src, dest)) =
parse_filter_connect($input).map_err(|e| e.to_string())?;
Some($obj.on_filter_connect(&$f, &rdns, &fcrdns, &src, &dest))
}
FilterPhase::Data => Some($obj.on_filter_data(&$f)),
FilterPhase::DataLine => None,
FilterPhase::Ehlo => {
let (_, identity) = parse_filter_ehlo($input).map_err(|e| e.to_string())?;
Some($obj.on_filter_ehlo(&$f, &identity))
}
FilterPhase::Helo => {
let (_, identity) = parse_filter_helo($input).map_err(|e| e.to_string())?;
Some($obj.on_filter_helo(&$f, &identity))
}
FilterPhase::MailFrom => {
let (_, address) = parse_filter_mail_from($input).map_err(|e| e.to_string())?;
Some($obj.on_filter_mail_from(&$f, &address))
}
FilterPhase::RcptTo => {
let (_, address) = parse_filter_rcpt_to($input).map_err(|e| e.to_string())?;
Some($obj.on_filter_rcpt_to(&$f, &address))
}
FilterPhase::StartTls => {
let (_, tls_str) = parse_filter_starttls($input).map_err(|e| e.to_string())?;
Some($obj.on_filter_starttls(&$f, &tls_str))
}
}
};
}
macro_rules! handle_data_line {
($obj: ident, $f: ident, $input: ident) => {{
// TODO
}};
}
pub(crate) fn line<T>(user_object: &mut T, input: &[u8]) -> Result<(), String>
where
T: Filter,
{
let (input, entry) = parse_entry(input).map_err(|e| e.to_string())?;
match entry {
EntryOption::Report(r) => handle_reports!(user_object, r, input),
EntryOption::Filter(f) => {
if let Some(answer) = handle_filters!(user_object, f, input) {
println!(
"filter-result|{}|{}|{}",
f.session_id,
f.token,
answer.to_string()
);
};
}
EntryOption::DataLine(l) => handle_data_line!(user_object, l, input),
};
Ok(())
}