├── rust-toolchain ├── .gitignore ├── src ├── lib.rs ├── syntax.rs ├── reply.rs ├── codecs.rs ├── bin │ └── smtpbis-server │ │ └── main.rs └── server.rs ├── README.md ├── Cargo.toml ├── data ├── testcert.pem └── testcert.key └── LICENSE /rust-toolchain: -------------------------------------------------------------------------------- 1 | stable 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(rust_2018_idioms)] 2 | 3 | mod codecs; 4 | mod reply; 5 | mod server; 6 | mod syntax; 7 | 8 | pub use codecs::{LineCodec, LineError}; 9 | pub use reply::*; 10 | pub use server::*; 11 | pub use syntax::*; 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # smtpbis 2 | 3 | [![crates.io](http://meritbadge.herokuapp.com/smtpbis)](https://crates.io/crates/smtpbis) 4 | 5 | Extensible SMTP server library 6 | 7 | Built on top of [rustyknife] and [tokio] for native performance. 8 | 9 | The ESMTP extensions that affect the socket layer are directly 10 | implemented in the base server. Extensions such as DSN that merely 11 | attributes are implemented via the Handler interface. 12 | 13 | Features: 14 | * SMTPUTF8 support 15 | * CHUNKING support 16 | * Pluggable STARTTLS support 17 | 18 | [rustyknife]: https://crates.io/crates/rustyknife 19 | [tokio]: https://tokio.rs/ 20 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "smtpbis" 3 | version = "0.1.8" 4 | authors = ["Jonathan Bastien-Filiatrault "] 5 | edition = "2018" 6 | description = "Asynchronous ESMTP service library." 7 | license = "GPL-3.0+" 8 | categories = ["email", "network-programming"] 9 | readme = "README.md" 10 | homepage = "https://github.com/zerospam/smtpbis" 11 | repository = "https://github.com/zerospam/smtpbis.git" 12 | 13 | [dependencies] 14 | rustyknife = {version="0.2", features=["quoted-string-rfc2047"]} 15 | tokio = {version="1.0", features=["signal", "io-util", "sync", "net", "rt-multi-thread"]} 16 | tokio-util = {version="0.7", features=["codec"]} 17 | bytes = "1.0" 18 | futures = "0.3" 19 | futures-util = "0.3" 20 | tokio-rustls = "0.24" 21 | async-trait = "0.1.10" 22 | rustls-pemfile = "1.0.3" 23 | anyhow = "1.0.75" 24 | -------------------------------------------------------------------------------- /src/syntax.rs: -------------------------------------------------------------------------------- 1 | use rustyknife::nom::branch::alt; 2 | use rustyknife::nom::combinator::map; 3 | 4 | use rustyknife::rfc5321::{ 5 | bdat_command, command as base_command, starttls_command, Command as BaseCommand, UTF8Policy, 6 | }; 7 | use rustyknife::xforward::{command as xforward_command, Param as XforwardParam}; 8 | use rustyknife::NomResult; 9 | 10 | #[derive(Debug)] 11 | pub enum Command { 12 | Base(BaseCommand), 13 | Ext(Ext), 14 | } 15 | 16 | #[derive(Debug)] 17 | pub enum Ext { 18 | STARTTLS, 19 | BDAT(u64, bool), 20 | XFORWARD(Vec), 21 | } 22 | 23 | pub fn command(input: &[u8]) -> NomResult<'_, Command> { 24 | alt(( 25 | map(base_command::

, Command::Base), 26 | map(starttls_command, |_| Command::Ext(Ext::STARTTLS)), 27 | map(bdat_command, |(size, last)| { 28 | Command::Ext(Ext::BDAT(size, last)) 29 | }), 30 | map(xforward_command, |params| { 31 | Command::Ext(Ext::XFORWARD(params)) 32 | }), 33 | ))(input) 34 | } 35 | -------------------------------------------------------------------------------- /data/testcert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIEPTCCAqWgAwIBAgIIXeEi3DA2UhIwDQYJKoZIhvcNAQELBQAwHjEcMBoGA1UE 3 | AxMTaW52YWxpZC5leGFtcGxlLmNvbTAeFw0xOTExMjkxMzUzMzRaFw0yOTExMjYx 4 | MzUzMzhaMB4xHDAaBgNVBAMTE2ludmFsaWQuZXhhbXBsZS5jb20wggGiMA0GCSqG 5 | SIb3DQEBAQUAA4IBjwAwggGKAoIBgQCpux2PNpBF3J1x23gp+KUnHrkqLZTgGMyy 6 | D1G7n1/j7aIJbtotjW4LDARCYGaMTDvbm6MMqpqLfKWAdYHy5kAsw3GbTFRaG1cz 7 | X0T1yBs46zQrQKxG+2xhkQMawEW3Oh5j2F12nPaTJAgiYUy5E+do3Z94NbyOOKt2 8 | J7NB902ipFy71vsQA39axOLqXi/Nskr2pAa6D3/VAHl95yNYvXStKQ7Ld1WvFNg8 9 | GDhcotgdBs5L9QgrAjIG4/46RlLgVtwbCPVtgHJy0f8MDghT7ggG1t+igJ2ME2Ct 10 | LY4khFxJAHrwAhT4gP2O+2eEgJ8E/bEfmq1ufXpe7VmN7NfDtWe7nXi7IHPE5C1b 11 | sN+z1+VERrjsvAFR7Do8szeakWs3d4fTucJnq0P0RAkNU0L0HkMFDisnMAeNVqax 12 | IqkBClxuenErci27EEdibglKbleVlI/YeX7BVZZ908LNr/fwmLg6rdmpKNbnqOs/ 13 | FbXl2vLCCbj0oKbn7QL95nqxl+x5sxkCAwEAAaN/MH0wDAYDVR0TAQH/BAIwADAd 14 | BgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwHgYDVR0RBBcwFYITaW52YWxp 15 | ZC5leGFtcGxlLmNvbTAPBgNVHQ8BAf8EBQMDB6AAMB0GA1UdDgQWBBQMp0heYu4A 16 | rRp+fPbMVrJEp/MANTANBgkqhkiG9w0BAQsFAAOCAYEAfHey6pDUNDI2fE5/oe6E 17 | TeDk1/ZfTDUg64z2njPYCMJmxdudyQUh6USTtwfBkkMGa5ygR29BoFY/632Qtprv 18 | 7OPVvNIPDSaMjTMJocDh5FE9ULFPmHzd5UYX1kPP5/uQvOckjcOlQ3nBM8ehqkmG 19 | dJoErMFaBs7+e5dQ6yfcpXpcKDf3BKI42QGlt7n9m1PZP475zr6Lfp63q/6gyTlQ 20 | ItZm8BfKBaz7dLl/WSLQZAVfgWvemw42O2F9IPu/5/ScZnZ9J9efw+5f4Ype5oRr 21 | 45qdhBJnobX8bLgooyqdmjsC59r8QunyejlHym8eIfgYM0b1LQOR5KqxnAr9sVHi 22 | e89/7e5lpAU0NsTwzrkFsZA/8i6H3SRSimVKpBnmndIEfGMvhnH1XN0t05L95CRT 23 | RHHM82p2xveD+JRQG4B67nJKt+jYoi2EoCp33FNHI4Wttc0Zj6IvwVaqRHJ2gEJS 24 | tm//EJpuKW8wDx3dr/Ijjuc6wyZY++0C+cHuwE9NIYAZ 25 | -----END CERTIFICATE----- 26 | -------------------------------------------------------------------------------- /data/testcert.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIG5AIBAAKCAYEAqbsdjzaQRdydcdt4KfilJx65Ki2U4BjMsg9Ru59f4+2iCW7a 3 | LY1uCwwEQmBmjEw725ujDKqai3ylgHWB8uZALMNxm0xUWhtXM19E9cgbOOs0K0Cs 4 | RvtsYZEDGsBFtzoeY9hddpz2kyQIImFMuRPnaN2feDW8jjirdiezQfdNoqRcu9b7 5 | EAN/WsTi6l4vzbJK9qQGug9/1QB5fecjWL10rSkOy3dVrxTYPBg4XKLYHQbOS/UI 6 | KwIyBuP+OkZS4FbcGwj1bYByctH/DA4IU+4IBtbfooCdjBNgrS2OJIRcSQB68AIU 7 | +ID9jvtnhICfBP2xH5qtbn16Xu1ZjezXw7Vnu514uyBzxOQtW7Dfs9flREa47LwB 8 | Uew6PLM3mpFrN3eH07nCZ6tD9EQJDVNC9B5DBQ4rJzAHjVamsSKpAQpcbnpxK3It 9 | uxBHYm4JSm5XlZSP2Hl+wVWWfdPCza/38Ji4Oq3ZqSjW56jrPxW15drywgm49KCm 10 | 5+0C/eZ6sZfsebMZAgMBAAECggGAdQW2lqQXCqPVxcd8bOuq6nLrVWJB79QJZYbc 11 | YlC660pO2tQcByYoxeMOGLmgWoDBEGOZIkWJ8jwJW60o4FDR1EsYS+tviQSqtZes 12 | 0wyZgD/iIyQe4327tvUlP89rAa5Hf62QmxQTiVVhalrNbBmGBi4vIdFi5Ge8B+XN 13 | WODqHQXXjgbl6J+QsgNnNBGmQdr4hl6G6MeA6lm+agjvvOI6zJyvP6dSYzkq8Rv9 14 | 2BjKihDEMWiKriSAW3HcOU99GoGndedQgPb9LDANXhcaWrw+Lj1eKmXRehTD33tf 15 | bUGWJcOZCpW+ZQ/0cFZgpjmHBu0xJIl5R+SLa/Hf/amy7Ij43nGpXoGpFYUkn5a1 16 | UKRKPJ8fcT/1WYK1ViNa7b9jMRCG9+JY3dECU9lTxnuxEG/YqhOg3N+UOvUe7UBh 17 | CHF84ncDWHuUDWf2JWnE3vpxqOJcSfAn0+lb0rMIy41u5TFEVFrg5HIfJvLKhd91 18 | k10mDxDegrXj2dUCraDrQdiw9NA1AoHBAMR6CYVge35cRTRT86/9PLNw8vOS/e9c 19 | 4nXxAP9SR8OBItXiPaBppvQeBPGU+ivDQuidjhupYnTr+liR/VUW7Iby/U0odzjQ 20 | +/qEMydr9UyUwNOU/SMQC2SLr6M3qQeBXXiFdvGdsBL2e7wn2SekSVDCv1HyMDy0 21 | a1Empiq/EV8IqAFlf7rmPIiKZrW/fWuc6xSE11SkYcjc+zzFeUXZA8qayItbuoju 22 | PyZKx8FJ+YzhZzZCK2XKmQihcgKKCq1W5wKBwQDdJselNKkKZsVzYApaQwT/snnN 23 | pyCOWWVtaNnmNJfpDJDgPvCUbBCAuv1CH1XeGAATvsjqWxpRtmHm9je0GMyZ2y3T 24 | sb8rtSG/7gNX7p7nmlT3c3+d43J4RBRmFq2f1JRhQk6k78JA+WLTf5KXHk4zkJ8E 25 | 0CYb60SOh/67BFjEA2dvgSfZyQ+tFJnp8s6zWL1Yxu2kw3kohqYf2KyIOMaTVI9M 26 | euCAU5WEA6PsrT+BUg3zk/2ngttBTHCDSx9hZf8CgcBraFeaHWOFcYW3lIlsVSEA 27 | 66c1Ns8xMnLujODBs0Zd/1N+315XOkq1u09yjcGxeN4z8iXEw3V6e6JxFuYJxS1q 28 | nJ2St6NtYPnPOsQIMgF4av167UDxEQ1ZWu+aZ4w0+SiTAUtDzLN7ullsQ9B31lzq 29 | FHyonKB4Hx1n0JwYVDl33XCSytzn3IONFTQO+W7kDHWK0xAwSmjWeM+zqjSg1YE4 30 | GiO142B3CN9m3IyVAw60UGivBb9Zt0avrCp6buJlXlMCgcEAyYrj+01ImLAcVg86 31 | oBPf5F903dTnuJMD+nfJzSA1KTBIf/UcL0dkqsy+rZn9GVBqEZSXaezoyXsbMe9F 32 | yJ2pKLY0x25/uId0YIO7DFHtA0kFEhZyQSPdWHlC1d7pEHYdW52gKnROZgRg6jqj 33 | D5GQ1zF/mlVPxbXdXr/Vh/5oHwqzI01jUfkIjkXuFuUvNwcyWEvCm5uBOUus7ez7 34 | H5IOdopjpeF947VI12yx4anp7CMpj8hZLGX3B0VwbFb0HEFlAoHBAJcKr69GNbjG 35 | mZCrr/MWK8LyYtAamRwsp1y5olYeLoc7LK2C9mucsMd/MzTWUOjrxZCqgBo1YAp0 36 | oUNDLL23Ec08mD7W4l0oOcfA8cb9smHMk2C8/Cf36EJht+bwhCUllIGl0BrihJX8 37 | A2RkGWkLWz7GIJOK2Yh1qV2BQCT2nm6xG6qmUQOk97yRlbdtDOFWVTf55Tpsnhok 38 | 8k5vWxxtBetxHiBBnfbumwbaZMmHbHlWG+lBCwKnpk/HR5M6Bdo7kA== 39 | -----END RSA PRIVATE KEY----- 40 | -------------------------------------------------------------------------------- /src/reply.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::fmt::Display; 3 | 4 | pub struct Reply { 5 | code: u16, 6 | ecode: Option, 7 | text: Cow<'static, str>, 8 | } 9 | 10 | impl Reply { 11 | pub fn new_checked>>( 12 | code: u16, 13 | ecode: Option, 14 | text: S, 15 | ) -> Option { 16 | let text = text.into(); 17 | if !(200..600).contains(&code) || text.contains('\r') { 18 | return None; 19 | } 20 | Some(Reply { code, ecode, text }) 21 | } 22 | 23 | pub fn new>>( 24 | code: u16, 25 | ecode: Option, 26 | text: S, 27 | ) -> Self { 28 | Self::new_checked(code, ecode, text).expect("Invalid code or CR in reply text.") 29 | } 30 | 31 | pub fn ok() -> Self { 32 | Self::new(250, None, "OK") 33 | } 34 | 35 | pub fn bad_sequence() -> Self { 36 | Self::new(503, None, "Bad sequence of commands") 37 | } 38 | 39 | pub fn no_mail_transaction() -> Self { 40 | Self::new(503, None, "No mail transaction in progress") 41 | } 42 | 43 | pub fn no_valid_recipients() -> Self { 44 | Self::new(554, None, "No valid recipients") 45 | } 46 | 47 | pub fn syntax_error() -> Self { 48 | Self::new(500, None, "Syntax error") 49 | } 50 | 51 | pub fn not_implemented() -> Self { 52 | Self::new(502, None, "Command not implemented") 53 | } 54 | 55 | pub fn data_ok() -> Self { 56 | Self::new(354, None, "OK, send data") 57 | } 58 | 59 | /// Used when we cannot read all mail data, such as with an 60 | /// oversized message. 61 | pub fn data_abort() -> Self { 62 | Self::new(450, None, "Data abort") 63 | } 64 | 65 | pub fn is_error(&self) -> bool { 66 | matches!( 67 | ReplyCategory::from(self), 68 | ReplyCategory::TempError | ReplyCategory::PermError 69 | ) 70 | } 71 | } 72 | 73 | pub(crate) trait ReplyDefault { 74 | fn with_default(self, default: Reply) -> Result; 75 | } 76 | 77 | impl ReplyDefault for Option { 78 | fn with_default(self, default: Reply) -> Result { 79 | let expected_category = ReplyCategory::from(&default); 80 | let reply = self.unwrap_or(default); 81 | let category = ReplyCategory::from(&reply); 82 | 83 | if category == expected_category { 84 | Ok(reply) 85 | } else { 86 | Err(reply) 87 | } 88 | } 89 | } 90 | 91 | #[derive(Clone, Copy, Debug, PartialEq)] 92 | enum ReplyCategory { 93 | Success, 94 | Intermediate, 95 | TempError, 96 | PermError, 97 | } 98 | 99 | impl From<&Reply> for ReplyCategory { 100 | fn from(input: &Reply) -> Self { 101 | // Caveat: 552 on reply to RCPT is considered temporary. 102 | 103 | match input.code { 104 | 200..=299 => Self::Success, 105 | 300..=399 => Self::Intermediate, 106 | 400..=499 => Self::TempError, 107 | 500..=599 => Self::PermError, 108 | _ => unreachable!(), 109 | } 110 | } 111 | } 112 | 113 | impl Display for Reply { 114 | fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { 115 | let mut lines_iter = self.text.lines().peekable(); 116 | 117 | loop { 118 | let line = match (lines_iter.next(), lines_iter.peek()) { 119 | (Some(line), Some(_)) => { 120 | write!(fmt, "{}-", self.code)?; 121 | line 122 | } 123 | (Some(line), None) => { 124 | write!(fmt, "{} ", self.code)?; 125 | line 126 | } 127 | (None, _) => break, 128 | }; 129 | 130 | if let Some(ecode) = &self.ecode { 131 | write!(fmt, "{} ", ecode)?; 132 | } 133 | 134 | writeln!(fmt, "{}\r", line)?; 135 | } 136 | 137 | Ok(()) 138 | } 139 | } 140 | 141 | pub struct EnhancedCode(pub u8, pub u16, pub u16); 142 | 143 | impl Display for EnhancedCode { 144 | fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { 145 | write!(fmt, "{}.{}.{}", self.0, self.1, self.2) 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/codecs.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryInto; 2 | use std::error::Error; 3 | use std::fmt::{Display, Write}; 4 | 5 | use bytes::BytesMut; 6 | use tokio_util::codec::{Decoder, Encoder}; 7 | 8 | use crate::Reply; 9 | 10 | const DEFAULT_LINE_LENGTH: usize = 2048; 11 | const DEFAULT_MAX_CHUNK_SIZE: u64 = 1024 * 1024; 12 | 13 | #[derive(Clone, Debug)] 14 | pub struct LineCodec { 15 | max_length: usize, 16 | /// Max chunk that is buffered at once. If a BDAT is larger than 17 | /// this, it will be split into chunks of this size. 18 | max_chunk_size: u64, 19 | valid: bool, 20 | state: State, 21 | } 22 | 23 | #[derive(Debug)] 24 | pub enum LineError { 25 | LineTooLong, 26 | IO(std::io::Error), 27 | ChunkingDone, 28 | DataAbort, 29 | } 30 | 31 | #[derive(Clone, Debug)] 32 | enum State { 33 | Text { next_index: usize }, 34 | Chunk(u64), 35 | } 36 | 37 | impl LineCodec { 38 | fn new(max_length: Option, max_chunk_size: Option) -> Self { 39 | Self { 40 | max_length: max_length.unwrap_or(DEFAULT_LINE_LENGTH), 41 | max_chunk_size: max_chunk_size.unwrap_or(DEFAULT_MAX_CHUNK_SIZE), 42 | state: State::Text { next_index: 0 }, 43 | valid: true, 44 | } 45 | } 46 | 47 | fn decode_text( 48 | &mut self, 49 | buf: &mut BytesMut, 50 | next_index: usize, 51 | ) -> Result, LineError> { 52 | let read_to = std::cmp::min(self.max_length.saturating_add(1), buf.len()); 53 | 54 | let crlf_offset = buf[next_index..read_to] 55 | .windows(2) 56 | .position(|x| x == b"\r\n") 57 | .map(|i| i + next_index + 2); 58 | 59 | match crlf_offset { 60 | Some(offset) => { 61 | self.state = State::Text { next_index: 0 }; 62 | 63 | Ok(Some(buf.split_to(offset))) 64 | } 65 | None => { 66 | if buf.len() > self.max_length { 67 | self.valid = false; 68 | Err(LineError::LineTooLong) 69 | } else { 70 | self.state = State::Text { 71 | next_index: buf.len().saturating_sub(1), 72 | }; 73 | Ok(None) 74 | } 75 | } 76 | } 77 | } 78 | 79 | fn decode_binary( 80 | &mut self, 81 | buf: &mut BytesMut, 82 | bytes_remaining: u64, 83 | ) -> Result, LineError> { 84 | if bytes_remaining == 0 { 85 | self.state = State::Text { next_index: 0 }; 86 | return Err(LineError::ChunkingDone); 87 | } 88 | 89 | // FIXME: too many conversions to be clear. 90 | let wanted_chunk: u64 = std::cmp::min(self.max_chunk_size, bytes_remaining); 91 | let buf_len: u64 = buf.len().try_into().unwrap(); 92 | 93 | if buf_len >= wanted_chunk { 94 | let chunk_size: usize = wanted_chunk.try_into().unwrap_or(std::usize::MAX); 95 | let chunk_size_u64: u64 = chunk_size.try_into().unwrap(); 96 | 97 | self.state = State::Chunk(bytes_remaining - chunk_size_u64); 98 | Ok(Some(buf.split_to(chunk_size))) 99 | } else { 100 | Ok(None) 101 | } 102 | } 103 | 104 | pub(crate) fn chunking_mode(&mut self, chunk_size: u64) { 105 | self.state = match self.state { 106 | State::Text { .. } => State::Chunk(chunk_size), 107 | State::Chunk(..) => panic!("Invalid chunking state"), 108 | } 109 | } 110 | } 111 | 112 | impl Default for LineCodec { 113 | fn default() -> Self { 114 | Self::new(None, None) 115 | } 116 | } 117 | 118 | impl Decoder for LineCodec { 119 | type Error = LineError; 120 | type Item = BytesMut; 121 | 122 | fn decode(&mut self, buf: &mut BytesMut) -> Result, Self::Error> { 123 | if !self.valid { 124 | return Err(LineError::LineTooLong); 125 | } 126 | 127 | match self.state { 128 | State::Text { next_index } => self.decode_text(buf, next_index), 129 | State::Chunk(remaining) => self.decode_binary(buf, remaining), 130 | } 131 | } 132 | } 133 | 134 | impl Encoder for LineCodec { 135 | type Error = LineError; 136 | 137 | fn encode(&mut self, reply: Reply, buf: &mut BytesMut) -> Result<(), Self::Error> { 138 | write!(buf, "{}", reply) 139 | .map_err(|_| LineError::from(std::io::Error::from(std::io::ErrorKind::Other))) 140 | } 141 | } 142 | 143 | impl From for LineError { 144 | fn from(err: std::io::Error) -> Self { 145 | Self::IO(err) 146 | } 147 | } 148 | 149 | impl Error for LineError {} 150 | 151 | impl Display for LineError { 152 | fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { 153 | write!(fmt, "{:?}", self) 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/bin/smtpbis-server/main.rs: -------------------------------------------------------------------------------- 1 | #![warn(rust_2018_idioms)] 2 | 3 | use std::io::Cursor; 4 | use std::net::SocketAddr; 5 | use std::sync::Arc; 6 | 7 | use async_trait::async_trait; 8 | use bytes::BytesMut; 9 | 10 | use futures_util::future::{select, Either}; 11 | use futures_util::future::{FutureExt, TryFutureExt}; 12 | use futures_util::pin_mut; 13 | use futures_util::stream::Stream; 14 | use futures_util::stream::TryStreamExt; 15 | 16 | use tokio::io::AsyncWriteExt; 17 | use tokio::net::{TcpListener, TcpStream}; 18 | use tokio::runtime::Runtime; 19 | use tokio::sync::oneshot::Receiver; 20 | 21 | use rustls_pemfile::rsa_private_keys; 22 | use tokio_rustls::rustls::{Certificate, PrivateKey, ServerConfig, ServerConnection}; 23 | use tokio_rustls::TlsAcceptor; 24 | 25 | use rustyknife::rfc5321::{ForwardPath, Param, Path, ReversePath}; 26 | use rustyknife::types::{Domain, DomainPart}; 27 | use smtpbis::{ 28 | smtp_server, Config, EhloKeywords, Handler, LineError, LoopExit, Reply, ServerError, 29 | ShutdownSignal, 30 | }; 31 | 32 | const CERT: &[u8] = include_bytes!("../../../data/testcert.pem"); 33 | const KEY: &[u8] = include_bytes!("../../../data/testcert.key"); 34 | 35 | struct DummyHandler { 36 | tls_config: Arc, 37 | addr: SocketAddr, 38 | helo: Option, 39 | mail: Option, 40 | rcpt: Vec, 41 | body: Vec, 42 | } 43 | 44 | impl DummyHandler { 45 | async fn tls_started(&self, conn: &ServerConnection) { 46 | println!( 47 | "TLS started: {:?}/{:?}", 48 | conn.protocol_version().unwrap(), 49 | conn.negotiated_cipher_suite().unwrap(), 50 | ); 51 | } 52 | } 53 | 54 | #[async_trait] 55 | impl Handler for DummyHandler { 56 | type TlsConfig = Arc; 57 | 58 | async fn tls_request(&mut self) -> Option { 59 | Some(self.tls_config.clone()) 60 | } 61 | 62 | async fn ehlo( 63 | &mut self, 64 | domain: DomainPart, 65 | mut initial_keywords: EhloKeywords, 66 | ) -> Result<(String, EhloKeywords), Reply> { 67 | initial_keywords.insert("DSN".into(), None); 68 | initial_keywords.insert("8BITMIME".into(), None); 69 | initial_keywords.insert("SIZE".into(), Some("73400320".into())); 70 | 71 | let greet = format!("hello {} from {}", domain, self.addr); 72 | self.helo = Some(domain); 73 | self.reset_tx(); 74 | 75 | Ok((greet, initial_keywords)) 76 | } 77 | 78 | async fn helo(&mut self, domain: Domain) -> Option { 79 | self.helo = Some(DomainPart::Domain(domain)); 80 | self.reset_tx(); 81 | 82 | None 83 | } 84 | 85 | async fn mail(&mut self, path: ReversePath, _params: Vec) -> Option { 86 | println!("Handler MAIL: {:?}", path); 87 | 88 | self.mail = Some(path); 89 | None 90 | } 91 | 92 | async fn rcpt(&mut self, path: ForwardPath, _params: Vec) -> Option { 93 | println!("Handler RCPT: {:?}", path); 94 | if let ForwardPath::Path(Path(mbox, _)) = &path { 95 | if let DomainPart::Domain(domain) = mbox.domain_part() { 96 | if domain.starts_with('z') { 97 | return Some(Reply::new(550, None, "I don't like zeds")); 98 | } 99 | } 100 | }; 101 | self.rcpt.push(path); 102 | None 103 | } 104 | 105 | async fn data_start(&mut self) -> Option { 106 | println!("Handler DATA start"); 107 | None 108 | } 109 | 110 | async fn data(&mut self, stream: &mut S) -> Result, ServerError> 111 | where 112 | S: Stream> + Unpin + Send, 113 | { 114 | println!("Handler DATA read"); 115 | let mut nb_lines: usize = 0; 116 | self.body.clear(); 117 | 118 | while let Some(line) = stream.try_next().await? { 119 | self.body.extend(line); 120 | nb_lines += 1; 121 | } 122 | 123 | println!("got {} body lines", nb_lines); 124 | let reply_txt = format!("Received {} bytes in {} lines.", self.body.len(), nb_lines); 125 | self.reset_tx(); 126 | 127 | Ok(Some(Reply::new(250, None, reply_txt))) 128 | } 129 | 130 | async fn bdat( 131 | &mut self, 132 | stream: &mut S, 133 | _size: u64, 134 | last: bool, 135 | ) -> Result, ServerError> 136 | where 137 | S: Stream> + Unpin + Send, 138 | { 139 | while let Some(chunk) = stream.try_next().await? { 140 | self.body.extend(chunk) 141 | } 142 | if last { 143 | self.reset_tx(); 144 | } 145 | 146 | Ok(None) 147 | } 148 | 149 | async fn rset(&mut self) { 150 | self.reset_tx(); 151 | } 152 | } 153 | 154 | impl DummyHandler { 155 | fn reset_tx(&mut self) { 156 | println!("Reset!"); 157 | self.mail = None; 158 | self.rcpt.clear(); 159 | self.body.clear(); 160 | } 161 | } 162 | 163 | fn main() -> Result<(), Box> { 164 | let rt = Runtime::new()?; 165 | 166 | rt.block_on(async { 167 | let (listen_shutdown_tx, listen_shutdown_rx) = tokio::sync::oneshot::channel(); 168 | tokio::spawn(listen_loop(listen_shutdown_rx)); 169 | 170 | tokio::signal::ctrl_c().await.unwrap(); 171 | listen_shutdown_tx.send(()).unwrap(); 172 | println!("Waiting for tasks to finish..."); 173 | // FIXME: actually wait on tasks here. 174 | }); 175 | 176 | Ok(()) 177 | } 178 | 179 | async fn listen_loop(mut shutdown: Receiver<()>) { 180 | let listener = TcpListener::bind("127.0.0.1:2525").await.unwrap(); 181 | 182 | let certs = rustls_pemfile::certs(&mut Cursor::new(CERT)) 183 | .unwrap() 184 | .into_iter() 185 | .map(Certificate) 186 | .collect(); 187 | let key = PrivateKey( 188 | rsa_private_keys(&mut Cursor::new(KEY)) 189 | .unwrap() 190 | .into_iter() 191 | .next() 192 | .unwrap(), 193 | ); 194 | 195 | let tls_config = ServerConfig::builder() 196 | .with_safe_defaults() 197 | .with_no_client_auth() 198 | .with_single_cert(certs, key) 199 | .unwrap(); 200 | 201 | let tls_config = Arc::new(tls_config); 202 | 203 | let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); 204 | let shutdown_rx = shutdown_rx.map_err(|_| ()).shared(); 205 | 206 | loop { 207 | let accept = listener.accept(); 208 | pin_mut!(accept); 209 | 210 | match select(accept, &mut shutdown).await { 211 | Either::Left((listen_res, _)) => { 212 | let (socket, addr) = listen_res.unwrap(); 213 | let mut shutdown_rx = shutdown_rx.clone(); 214 | let tls_config = tls_config.clone(); 215 | 216 | tokio::spawn(async move { 217 | let smtp_res = serve_smtp(socket, addr, tls_config, &mut shutdown_rx).await; 218 | println!("SMTP task done: {:?}", smtp_res); 219 | }) 220 | } 221 | Either::Right(..) => { 222 | println!("socket listening loop stopping"); 223 | shutdown_tx.send(()).unwrap(); 224 | break; 225 | } 226 | }; 227 | } 228 | } 229 | 230 | async fn serve_smtp( 231 | mut socket: TcpStream, 232 | addr: SocketAddr, 233 | tls_config: Arc, 234 | shutdown: &mut ShutdownSignal, 235 | ) -> Result<(), Box> { 236 | let mut handler = DummyHandler { 237 | addr, 238 | tls_config, 239 | helo: None, 240 | mail: None, 241 | rcpt: Vec::new(), 242 | body: Vec::new(), 243 | }; 244 | 245 | let mut config = Config::default(); 246 | match smtp_server(&mut socket, &mut handler, &config, shutdown, true).await { 247 | Ok(LoopExit::Done) => println!("Server done"), 248 | Ok(LoopExit::STARTTLS(tls_config)) => { 249 | let acceptor = TlsAcceptor::from(tls_config); 250 | let mut tls_socket = acceptor.accept(socket).await?; 251 | config.enable_starttls = false; 252 | handler.tls_started(tls_socket.get_ref().1).await; 253 | match smtp_server(&mut tls_socket, &mut handler, &config, shutdown, false).await { 254 | Ok(_) => println!("TLS Server done"), 255 | Err(e) => println!("TLS Top level error: {:?}", e), 256 | } 257 | tls_socket.shutdown().await?; 258 | } 259 | Err(e) => println!("Top level error: {:?}", e), 260 | } 261 | 262 | Ok(()) 263 | } 264 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | use std::collections::BTreeMap; 2 | use std::fmt::Write; 3 | use std::sync::{ 4 | atomic::{AtomicBool, Ordering}, 5 | Arc, 6 | }; 7 | 8 | use async_trait::async_trait; 9 | use bytes::{Buf, BytesMut}; 10 | 11 | use futures::future::ready; 12 | use futures::Sink; 13 | use futures_util::future::{select, Either, FusedFuture}; 14 | use futures_util::sink::SinkExt; 15 | use futures_util::stream::{Stream, StreamExt}; 16 | 17 | use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; 18 | use tokio_util::codec::{Framed, FramedParts}; 19 | 20 | use crate::reply::ReplyDefault; 21 | use crate::{command, Command, Command::Base, Command::*}; 22 | use crate::{LineCodec, LineError, Reply}; 23 | 24 | use rustyknife::behaviour::{Intl, Legacy}; 25 | use rustyknife::rfc5321::Command::*; 26 | use rustyknife::rfc5321::{ForwardPath, Param, ReversePath}; 27 | use rustyknife::types::{Domain, DomainPart}; 28 | 29 | pub type EhloKeywords = BTreeMap>; 30 | pub type ShutdownSignal = dyn FusedFuture> + Send + Unpin; 31 | 32 | #[async_trait] 33 | pub trait Handler: Send { 34 | type TlsConfig; 35 | 36 | async fn tls_request(&mut self) -> Option { 37 | None 38 | } 39 | 40 | async fn ehlo( 41 | &mut self, 42 | domain: DomainPart, 43 | initial_keywords: EhloKeywords, 44 | ) -> Result<(String, EhloKeywords), Reply>; 45 | async fn helo(&mut self, domain: Domain) -> Option; 46 | async fn rset(&mut self); 47 | 48 | async fn mail(&mut self, path: ReversePath, params: Vec) -> Option; 49 | async fn rcpt(&mut self, path: ForwardPath, params: Vec) -> Option; 50 | 51 | async fn data_start(&mut self) -> Option { 52 | None 53 | } 54 | async fn data(&mut self, stream: &mut S) -> Result, ServerError> 55 | where 56 | S: Stream> + Unpin + Send; 57 | async fn bdat( 58 | &mut self, 59 | stream: &mut S, 60 | size: u64, 61 | last: bool, 62 | ) -> Result, ServerError> 63 | where 64 | S: Stream> + Unpin + Send; 65 | 66 | async fn unhandled_command(&mut self, _command: Command) -> Option { 67 | None 68 | } 69 | } 70 | 71 | pub struct Config { 72 | pub enable_smtputf8: bool, 73 | pub enable_chunking: bool, 74 | pub enable_starttls: bool, 75 | } 76 | 77 | impl Default for Config { 78 | fn default() -> Self { 79 | Config { 80 | enable_smtputf8: true, 81 | enable_chunking: true, 82 | enable_starttls: true, 83 | } 84 | } 85 | } 86 | 87 | pub async fn smtp_server( 88 | socket: &mut S, 89 | handler: &mut H, 90 | config: &Config, 91 | shutdown: &mut ShutdownSignal, 92 | banner: bool, 93 | ) -> Result, ServerError> 94 | where 95 | S: AsyncRead + AsyncWrite + Unpin + Send, 96 | H: Handler, 97 | { 98 | let terminated = shutdown.is_terminated(); 99 | let mut server = InnerServer { 100 | handler, 101 | config, 102 | state: State::Initial, 103 | shutdown, 104 | shutdown_on_idle: terminated, 105 | }; 106 | 107 | let res = server.serve(socket, banner).await; 108 | socket.flush().await?; 109 | Ok(res?) 110 | } 111 | 112 | pub enum LoopExit { 113 | Done, 114 | STARTTLS(H::TlsConfig), 115 | } 116 | 117 | #[derive(Debug, PartialEq)] 118 | enum State { 119 | Initial, 120 | MAIL, 121 | RCPT, 122 | BDAT, 123 | BDATFAIL, 124 | } 125 | 126 | struct InnerServer<'a, H> { 127 | handler: &'a mut H, 128 | config: &'a Config, 129 | state: State, 130 | shutdown: &'a mut ShutdownSignal, 131 | shutdown_on_idle: bool, 132 | } 133 | 134 | impl<'a, H> InnerServer<'a, H> 135 | where 136 | H: Handler, 137 | { 138 | async fn serve( 139 | &mut self, 140 | base_socket: &mut S, 141 | banner: bool, 142 | ) -> Result, ServerError> 143 | where 144 | S: AsyncRead + AsyncWrite + Unpin + Send, 145 | { 146 | let mut socket = Framed::new(base_socket, LineCodec::default()); 147 | 148 | if banner { 149 | socket 150 | .send(Reply::new(220, None, "localhost ESMTP smtpbis 0.1.0")) 151 | .await?; 152 | } 153 | 154 | loop { 155 | let cmd = match self.read_command(&mut socket).await { 156 | Ok(cmd) => cmd, 157 | Err(ServerError::SyntaxError(_)) => { 158 | socket.send(Reply::syntax_error()).await?; 159 | continue; 160 | } 161 | Err(ServerError::Shutdown) => { 162 | socket.send(Reply::new(421, None, "Shutting down")).await?; 163 | return Ok(LoopExit::Done); 164 | } 165 | Err(e) => return Err(e), 166 | }; 167 | 168 | match self.dispatch_command(&mut socket, cmd).await? { 169 | Some(LoopExit::STARTTLS(tls_config)) => { 170 | socket.flush().await?; 171 | let FramedParts { io, read_buf, .. } = socket.into_parts(); 172 | // Absolutely do not allow pipelining past a 173 | // STARTTLS command. 174 | if !read_buf.is_empty() { 175 | return Err(ServerError::Pipelining); 176 | } 177 | let tls_reply = Reply::new(220, None, "starting TLS").to_string(); 178 | 179 | io.write_all(tls_reply.as_bytes()).await?; 180 | return Ok(LoopExit::STARTTLS(tls_config)); 181 | } 182 | Some(LoopExit::Done) => { 183 | return Ok(LoopExit::Done); 184 | } 185 | None => {} 186 | } 187 | } 188 | } 189 | 190 | fn shutdown_check(&self) -> Result<(), ServerError> { 191 | match (self.shutdown_on_idle, &self.state) { 192 | (true, State::Initial) | (true, State::BDATFAIL) => Err(ServerError::Shutdown), 193 | _ => Ok(()), 194 | } 195 | } 196 | 197 | async fn read_command(&mut self, reader: &mut S) -> Result 198 | where 199 | S: Stream> + Unpin, 200 | S: Sink, 201 | ServerError: From<>::Error>, 202 | { 203 | self.shutdown_check()?; 204 | 205 | let line = if self.shutdown.is_terminated() { 206 | reader.next().await 207 | } else { 208 | match select(reader.next(), &mut self.shutdown).await { 209 | Either::Left((cmd, _)) => cmd, 210 | Either::Right((_, cmd_fut)) => { 211 | self.shutdown_on_idle = true; 212 | self.shutdown_check()?; 213 | cmd_fut.await 214 | } 215 | } 216 | } 217 | .ok_or(ServerError::EOF)??; 218 | 219 | let parse_res = if self.config.enable_smtputf8 { 220 | command::(&line) 221 | } else { 222 | command::(&line) 223 | }; 224 | 225 | match parse_res { 226 | Err(_) => Err(ServerError::SyntaxError(line)), 227 | Ok((rem, _)) if !rem.is_empty() => Err(ServerError::SyntaxError(line)), 228 | Ok((_, cmd)) => Ok(cmd), 229 | } 230 | } 231 | 232 | async fn dispatch_command( 233 | &mut self, 234 | socket: &mut Framed<&mut S, LineCodec>, 235 | command: Command, 236 | ) -> Result>, ServerError> 237 | where 238 | S: AsyncRead + AsyncWrite + Unpin + Send, 239 | { 240 | match command { 241 | Base(EHLO(domain)) => { 242 | socket.send(self.do_ehlo(domain).await?).await?; 243 | } 244 | Base(HELO(domain)) => { 245 | socket.send(self.do_helo(domain).await?).await?; 246 | } 247 | Base(MAIL(path, params)) => { 248 | socket.send(self.do_mail(path, params).await?).await?; 249 | } 250 | Base(RCPT(path, params)) => { 251 | socket.send(self.do_rcpt(path, params).await?).await?; 252 | } 253 | Base(DATA) => { 254 | let reply = self.do_data(socket).await?; 255 | socket.send(reply).await?; 256 | } 257 | Base(QUIT) => { 258 | socket.send(Reply::new(221, None, "bye")).await?; 259 | return Ok(Some(LoopExit::Done)); 260 | } 261 | Base(RSET) => { 262 | self.state = State::Initial; 263 | self.handler.rset().await; 264 | socket.send(Reply::ok()).await?; 265 | } 266 | Ext(crate::Ext::STARTTLS) if self.config.enable_starttls => { 267 | if let Some(tls_config) = self.handler.tls_request().await { 268 | return Ok(Some(LoopExit::STARTTLS(tls_config))); 269 | } else { 270 | socket.send(Reply::not_implemented()).await?; 271 | } 272 | } 273 | Ext(crate::Ext::BDAT(size, last)) if self.config.enable_chunking => { 274 | let reply = self.do_bdat(socket, size, last).await?; 275 | socket.send(reply).await?; 276 | } 277 | _ => { 278 | let reply = self 279 | .handler 280 | .unhandled_command(command) 281 | .await 282 | .unwrap_or_else(Reply::not_implemented); 283 | socket.send(reply).await?; 284 | } 285 | } 286 | Ok(None) 287 | } 288 | 289 | async fn do_ehlo(&mut self, domain: DomainPart) -> Result { 290 | let mut initial_keywords = EhloKeywords::new(); 291 | for kw in ["PIPELINING", "ENHANCEDSTATUSCODES"].as_ref() { 292 | initial_keywords.insert((*kw).into(), None); 293 | } 294 | if self.config.enable_smtputf8 { 295 | initial_keywords.insert("8BITMIME".into(), None); 296 | initial_keywords.insert("SMTPUTF8".into(), None); 297 | } 298 | if self.config.enable_chunking { 299 | initial_keywords.insert("CHUNKING".into(), None); 300 | } 301 | if self.config.enable_starttls { 302 | initial_keywords.insert("STARTTLS".into(), None); 303 | } 304 | 305 | match self.handler.ehlo(domain, initial_keywords).await { 306 | Err(reply) => Ok(reply), 307 | Ok((greeting, keywords)) => { 308 | assert!(!greeting.contains('\r') && !greeting.contains('\n')); 309 | let mut reply_text = format!("{}\n", greeting); 310 | 311 | for (kw, value) in keywords { 312 | match value { 313 | Some(value) => writeln!(reply_text, "{} {}", kw, value).unwrap(), 314 | None => writeln!(reply_text, "{}", kw).unwrap(), 315 | } 316 | } 317 | self.state = State::Initial; 318 | Ok(Reply::new(250, None, reply_text)) 319 | } 320 | } 321 | } 322 | 323 | async fn do_helo(&mut self, domain: Domain) -> Result { 324 | Ok( 325 | match self.handler.helo(domain).await.with_default(Reply::ok()) { 326 | Ok(reply) => { 327 | self.state = State::Initial; 328 | reply 329 | } 330 | Err(reply) => reply, 331 | }, 332 | ) 333 | } 334 | 335 | async fn do_mail( 336 | &mut self, 337 | path: ReversePath, 338 | params: Vec, 339 | ) -> Result { 340 | Ok(match self.state { 341 | State::Initial => match self 342 | .handler 343 | .mail(path, params) 344 | .await 345 | .with_default(Reply::ok()) 346 | { 347 | Ok(reply) => { 348 | self.state = State::MAIL; 349 | reply 350 | } 351 | Err(reply) => reply, 352 | }, 353 | _ => Reply::bad_sequence(), 354 | }) 355 | } 356 | 357 | async fn do_rcpt( 358 | &mut self, 359 | path: ForwardPath, 360 | params: Vec, 361 | ) -> Result { 362 | Ok(match self.state { 363 | State::MAIL | State::RCPT => match self 364 | .handler 365 | .rcpt(path, params) 366 | .await 367 | .with_default(Reply::ok()) 368 | { 369 | Ok(reply) => { 370 | self.state = State::RCPT; 371 | reply 372 | } 373 | Err(reply) => reply, 374 | }, 375 | _ => Reply::bad_sequence(), 376 | }) 377 | } 378 | 379 | async fn do_data(&mut self, socket: &mut S) -> Result 380 | where 381 | S: Stream> + Unpin + Send, 382 | S: Sink, 383 | ServerError: From<>::Error>, 384 | { 385 | Ok(match self.state { 386 | State::RCPT => match self 387 | .handler 388 | .data_start() 389 | .await 390 | .with_default(Reply::data_ok()) 391 | { 392 | Ok(reply) => { 393 | socket.send(reply).await?; 394 | 395 | let mut body_stream = read_body_data(socket).fuse(); 396 | let mut reply = self 397 | .handler 398 | .data(&mut body_stream) 399 | .await? 400 | .unwrap_or_else(Reply::ok); 401 | 402 | if !body_stream.is_done() { 403 | drop(body_stream); 404 | // The handler MUST signal an error. 405 | if !reply.is_error() { 406 | reply = Reply::data_abort(); 407 | } 408 | 409 | socket.send(reply).await?; 410 | 411 | return Err(ServerError::DataAbort); 412 | } 413 | 414 | self.state = State::Initial; 415 | reply 416 | } 417 | Err(reply) => reply, 418 | }, 419 | State::Initial => Reply::no_mail_transaction(), 420 | State::MAIL => Reply::no_valid_recipients(), 421 | State::BDAT | State::BDATFAIL => { 422 | Reply::new(503, None, "BDAT may not be mixed with DATA") 423 | } 424 | }) 425 | } 426 | 427 | async fn do_bdat( 428 | &mut self, 429 | socket: &mut Framed, 430 | chunk_size: u64, 431 | last: bool, 432 | ) -> Result 433 | where 434 | Framed: Stream> 435 | + Sink 436 | + Send 437 | + Unpin, 438 | { 439 | Ok(match self.state { 440 | State::RCPT | State::BDAT => { 441 | let mut body_stream = read_body_bdat(socket, chunk_size).fuse(); 442 | 443 | let reply = self 444 | .handler 445 | .bdat(&mut body_stream, chunk_size, last) 446 | .await?; 447 | 448 | if !body_stream.is_done() { 449 | let mut reply = reply.unwrap_or_else(Reply::ok); 450 | 451 | drop(body_stream); 452 | // The handler MUST signal an error. 453 | if !reply.is_error() { 454 | reply = Reply::data_abort(); 455 | } 456 | 457 | socket.send(reply).await?; 458 | 459 | return Err(ServerError::DataAbort); 460 | } 461 | 462 | match reply.with_default(Reply::ok()) { 463 | Ok(reply) => { 464 | if last { 465 | self.state = State::Initial 466 | } else { 467 | self.state = State::BDAT 468 | } 469 | reply 470 | } 471 | Err(reply) => { 472 | self.state = State::BDATFAIL; 473 | reply 474 | } 475 | } 476 | } 477 | State::MAIL => Reply::no_valid_recipients(), 478 | _ => Reply::no_mail_transaction(), 479 | }) 480 | } 481 | } 482 | 483 | #[derive(Debug)] 484 | pub enum ServerError { 485 | EOF, 486 | Framing(LineError), 487 | SyntaxError(BytesMut), 488 | IO(std::io::Error), 489 | Pipelining, 490 | DataAbort, 491 | Shutdown, 492 | } 493 | 494 | impl From for ServerError { 495 | fn from(source: LineError) -> Self { 496 | match source { 497 | LineError::IO(e) => Self::IO(e), 498 | _ => Self::Framing(source), 499 | } 500 | } 501 | } 502 | 503 | impl From for ServerError { 504 | fn from(err: std::io::Error) -> Self { 505 | Self::IO(err) 506 | } 507 | } 508 | 509 | fn read_body_data(source: &mut S) -> impl Stream> + '_ 510 | where 511 | S: Stream> + Unpin, 512 | { 513 | let gen_abort = Arc::new(AtomicBool::new(true)); 514 | let gen_abort2 = gen_abort.clone(); 515 | 516 | let abort = futures::stream::once(ready(Err(LineError::DataAbort))) 517 | .filter(move |_| ready(gen_abort.load(Ordering::SeqCst))); 518 | 519 | source 520 | .take_while(move |res| { 521 | ready( 522 | res.as_ref() 523 | .map(|line| { 524 | if line.as_ref() == b".\r\n" { 525 | gen_abort2.store(false, Ordering::SeqCst); 526 | false 527 | } else { 528 | true 529 | } 530 | }) 531 | .unwrap_or(true), 532 | ) 533 | }) 534 | .map(|res| { 535 | res.map(|mut line| { 536 | if line.starts_with(b".") { 537 | line.advance(1); 538 | } 539 | line 540 | }) 541 | }) 542 | .chain(abort) 543 | } 544 | 545 | fn read_body_bdat( 546 | socket: &mut Framed, 547 | size: u64, 548 | ) -> impl Stream> + '_ 549 | where 550 | Framed: Stream> + Unpin, 551 | { 552 | let gen_abort = Arc::new(AtomicBool::new(true)); 553 | let gen_abort2 = gen_abort.clone(); 554 | 555 | let abort = futures::stream::once(ready(Err(LineError::DataAbort))) 556 | .filter(move |_| ready(gen_abort.load(Ordering::SeqCst))); 557 | 558 | socket.codec_mut().chunking_mode(size); 559 | 560 | socket 561 | .take_while(move |chunk| { 562 | let more = match chunk { 563 | Err(LineError::ChunkingDone) => { 564 | gen_abort2.store(false, Ordering::SeqCst); 565 | false 566 | } 567 | _ => true, 568 | }; 569 | 570 | ready(more) 571 | }) 572 | .chain(abort) 573 | } 574 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------