1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use async_macros::{join, ready};
use async_process::{Command, Stdio};
use async_std::io;
use log::*;
use samotop_core::common::Result;
use std::task::{Context, Poll};
use std::{future::Future, pin::Pin};

#[pin_project::pin_project]
pub struct SMime<'a> {
    #[pin]
    input: Option<Pin<Box<dyn io::Write + Sync + Send>>>,
    #[pin]
    copy: Pin<Box<dyn Future<Output = io::Result<()>> + Sync + Send + 'a>>,
}

impl<'a> SMime<'a> {
    pub fn encrypt_and_sign<W: io::Write + Sync + Send + 'a>(
        target: W,
        my_key: &str,
        my_cert: &str,
        her_cert: &str,
        their_certs: Vec<&str>,
    ) -> Result<Self> {
        Self::seal(target, my_key, my_cert, her_cert, their_certs, false)
    }
    pub fn sign_and_encrypt<W: io::Write + Sync + Send + 'a>(
        target: W,
        my_key: &str,
        my_cert: &str,
        her_cert: &str,
        their_certs: Vec<&str>,
    ) -> Result<Self> {
        Self::seal(target, my_key, my_cert, her_cert, their_certs, true)
    }
    pub fn decrypt_and_verify<W: io::Write + Sync + Send + 'a>(
        target: W,
        her_key: &str,
    ) -> Result<Self> {
        Self::open(target, her_key, true)
    }
    pub fn verify_and_decrypt<W: io::Write + Sync + Send + 'a>(
        target: W,
        her_key: &str,
    ) -> Result<Self> {
        Self::open(target, her_key, false)
    }
    fn seal<W: io::Write + Sync + Send + 'a>(
        target: W,
        my_key: &str,
        my_cert: &str,
        her_cert: &str,
        their_certs: Vec<&str>,
        sign_first: bool,
    ) -> Result<Self> {
        let mut sign = Command::new("openssl")
            .arg("smime")
            .arg("-stream")
            .arg("-sign")
            .arg("-inkey")
            .arg(my_key)
            .arg("-signer")
            .arg(my_cert)
            .kill_on_drop(true)
            .reap_on_drop(true)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;

        let mut encrypt = Command::new("openssl");
        encrypt
            .arg("smime")
            .arg("-stream")
            .arg("-encrypt")
            .arg(her_cert);

        for crt in their_certs {
            encrypt.arg(crt);
        }

        let mut encrypt = encrypt
            .kill_on_drop(true)
            .reap_on_drop(true)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;

        let sign_in = sign.stdin.take().expect("sign input");
        let sign_out = sign.stdout.take().expect("sign output");
        let encrypt_in = encrypt.stdin.take().expect("encrypt input");
        let encrypt_out = encrypt.stdout.take().expect("encrypt output");

        let (input, cp1, cp2) = if sign_first {
            (
                sign_in,
                CopyAndClose::new(sign_out, encrypt_in),
                CopyAndClose::new(encrypt_out, target),
            )
        } else {
            (
                encrypt_in,
                CopyAndClose::new(encrypt_out, sign_in),
                CopyAndClose::new(sign_out, target),
            )
        };

        let copy = async move {
            let (res1, res2) = join!(cp1, cp2).await;
            res1?;
            res2?;
            trace!("sign: {:?}", sign.status().await?);
            trace!("encrypt: {:?}", encrypt.status().await?);
            Ok(())
        };
        let writer = SMime {
            input: Some(Box::pin(input)),
            copy: Box::pin(copy),
        };

        Ok(writer)
    }

    fn open<W: io::Write + Sync + Send + 'a>(
        target: W,
        her_key: &str,
        sign_first: bool,
    ) -> Result<Self> {
        let mut verify = Command::new("openssl")
            .arg("smime")
            .arg("-stream")
            .arg("-verify")
            .arg("-noverify")
            .kill_on_drop(true)
            .reap_on_drop(true)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;

        let mut decrypt = Command::new("openssl")
            .arg("smime")
            .arg("-stream")
            .arg("-decrypt")
            .arg("-inkey")
            .arg(her_key)
            .kill_on_drop(true)
            .reap_on_drop(true)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;

        let verify_in = verify.stdin.take().expect("verify input");
        let verify_out = verify.stdout.take().expect("verify output");
        let decrypt_in = decrypt.stdin.take().expect("decrypt input");
        let decrypt_out = decrypt.stdout.take().expect("decrypt output");

        let (input, cp1, cp2) = if sign_first {
            (
                decrypt_in,
                CopyAndClose::new(decrypt_out, verify_in),
                CopyAndClose::new(verify_out, target),
            )
        } else {
            (
                verify_in,
                CopyAndClose::new(verify_out, decrypt_in),
                CopyAndClose::new(decrypt_out, target),
            )
        };

        let copy = async move {
            let (res1, res2) = join!(cp1, cp2).await;
            res1?;
            res2?;
            trace!("verify: {:?}", verify.status().await?);
            trace!("decrypt: {:?}", decrypt.status().await?);
            Ok(())
        };
        let writer = SMime {
            input: Some(Box::pin(input)),
            copy: Box::pin(copy),
        };

        Ok(writer)
    }
}

impl<'a> io::Write for SMime<'a> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.project();
        trace!("poll_write {}", buf.len());
        if let Some(i) = this.input.as_pin_mut() {
            trace!("poll_write input");
            let written = ready!(i.poll_write(cx, buf))?;
            Poll::Ready(Ok(written))
        } else {
            Poll::Ready(Err(io::ErrorKind::NotConnected.into()))
        }
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let mut this = self.project();
        trace!("poll_flush");
        if let Some(i) = this.input.as_mut().as_pin_mut() {
            trace!("poll_flush input");
            ready!(i.poll_flush(cx))?;
        }
        trace!("flush poll copy...");
        if let Poll::Ready(copied) = this.copy.poll(cx) {
            // Copy is not meant to be ready.
            // It will finish when input is closed.
            // But we are moving it forward by polling here.
            warn!("flush poll copy => {:?}", copied);
        } else {
            trace!("flush poll copy => not ready");
        }
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let mut this = self.project();
        trace!("poll_close");
        if let Some(i) = this.input.as_mut().as_pin_mut() {
            trace!("poll_close input");
            ready!(i.poll_close(cx))?;
            // must drop input to finish processing
            this.input.set(None);
            trace!("closed input");
        }

        trace!("close poll copy...");
        let copied = ready!(this.copy.poll(cx))?;
        trace!("close poll copy => {:?}", copied);

        Poll::Ready(Ok(()))
    }
}

#[pin_project::pin_project]
struct CopyAndClose<R, W> {
    #[pin]
    reader: R,
    #[pin]
    writer: W,
    amt: u64,
}

impl<R, W> CopyAndClose<io::BufReader<R>, W>
where
    R: io::Read,
    W: io::Write,
{
    pub fn new(reader: R, writer: W) -> Self {
        CopyAndClose {
            reader: io::BufReader::new(reader),
            writer,
            amt: 0,
        }
    }
}

impl<R, W> async_std::future::Future for CopyAndClose<R, W>
where
    R: io::BufRead,
    W: io::Write,
{
    type Output = io::Result<u64>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();
        loop {
            trace!("copy poll_fill_buf...");
            let buffer = ready!(this.reader.as_mut().poll_fill_buf(cx))?;
            trace!("copy poll_fill_buf => {}", buffer.len());
            if buffer.is_empty() {
                trace!("copy poll_close...");
                ready!(this.writer.as_mut().poll_close(cx))?;
                return Poll::Ready(Ok(*this.amt));
            }

            trace!("copy poll_write...");
            let i = ready!(this.writer.as_mut().poll_write(cx, buffer))?;
            trace!("copy poll_write => {}", i);
            if i == 0 {
                return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
            }
            *this.amt += i as u64;
            this.reader.as_mut().consume(i);
        }
    }
}