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:
parent
fc072743ad
commit
a6d4dd21c1
48 changed files with 1723 additions and 1493 deletions
|
@ -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"
|
|
@ -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.
|
|
@ -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.
|
|
@ -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]);
|
||||
}
|
|
@ -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]);
|
||||
}
|
|
@ -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]);
|
||||
}
|
|
@ -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
|
|
@ -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
|
|
@ -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
|
|
@ -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))
|
||||
}
|
|
@ -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))
|
||||
}
|
||||
}
|
|
@ -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
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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;
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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) {}
|
||||
}
|
|
@ -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};
|
|
@ -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(())
|
||||
}
|
||||
}
|
|
@ -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);
|
Reference in a new issue