1
//! Utilities
2

            
3
use std::fs::{self, File};
4
use std::io::{self, BufReader, BufWriter, Read as _, Write as _};
5
use std::str::FromStr;
6

            
7
use anyhow::anyhow;
8

            
9
use super::*;
10

            
11
define_derive_deftly! {
12
    /// Define `fn new`
13
    ///
14
    /// # Field attributes
15
    ///
16
    ///  * `#[deftly(new(arg))]`: this field should be an argument to `new`.
17
    ///    If not specified, `Default` is used.
18
    //
19
    // TODO enhance documentation and promote somewhere?
20
    // tor_netdoc::Constructor is not suitable because all the fields would have to be pub(crate)
21
    // derive_more::Constructor is not suitable because it can't Default fields
22
    New beta_deftly:
23

            
24
    ${defcond ARG fmeta(new(arg))}
25

            
26
    $impl {
27
        $/// Make a new `$tname`
28
        $tvis fn new(
29
            $(
30
                ${when ARG}
31
                $fname: $ftype,
32
            )
33
1
        ) -> Self {
34
            $tname {
35
                $(
36
                    $fname
37
                    ${if not(ARG) {
38
                        : Default::default()
39
                    }},
40
                )
41
            }
42
        }
43
    }
44
}
45

            
46
/// Command line filename argument, allowing `-` for stdin/stdout
47
///
48
/// Doesn't implement `Display`; for content error reporting prefer
49
/// [`Reading::description`].
50
//
51
// TODO move this somewhere deeper in the stack (tor-basic-utils even maybe?)
52
// and replace open-coding in eg crates/arti/src/subcommands/hsc.rs display_service_discovery_key
53
// If we do that:
54
//   - consider whether we should preserve file permissions
55
//   - see the comment about leftover `.tmp` files in `write`, below
56
//   - fix the locking problem (see the two TODO locking/hang)
57
//   - consider whether to keep the unconditional setting of retain_unknown_values in parse2
58
#[derive(Debug, Clone)]
59
pub(super) enum FilenameOrStdio {
60
    /// Filename
61
    Path(String),
62
    /// `-`
63
    Stdio,
64
}
65

            
66
/// Output file currently being read from
67
///
68
/// See [`FilenameOrStdio::start_reading`].
69
#[derive(Educe)]
70
#[educe(Debug)]
71
pub(super) struct Reading {
72
    /// Actual open-file
73
    #[educe(Debug(ignore))]
74
    handle: io::BufReader<Box<dyn io::Read>>,
75
    /// Description (for error messages), already quoted
76
    description: String,
77
}
78

            
79
/// Input file completely read into memory
80
///
81
/// Thin wrapper around `String`.
82
///
83
/// But, also provides a [`.description()`](EntireInput::description)
84
/// for use in error reporting.
85
///
86
/// See [`FilenameOrStdio::read_entire`].
87
#[derive(Educe, derive_more::Deref)]
88
#[educe(Debug)]
89
pub(super) struct EntireInput {
90
    /// File data
91
    #[educe(Debug(ignore))] // too verbose
92
    #[deref(forward)]
93
    data: String,
94
    /// Description (for error messages), already quoted
95
    description: String,
96
}
97

            
98
/// Output file currently being written to
99
///
100
/// See [`FilenameOrStdio::start_writing`].
101
#[derive(Educe)]
102
#[educe(Debug)]
103
pub(super) struct Writing {
104
    /// Actual open-file
105
    #[educe(Debug(ignore))]
106
    handle: io::BufWriter<Box<dyn io::Write>>,
107
    /// Filenames
108
    files: Option<WritingFiles>,
109
}
110

            
111
/// Filenames when writing an output file
112
#[derive(Debug)]
113
struct WritingFiles {
114
    /// The `.tmp` file
115
    tmp: String,
116
    /// The main file
117
    main: String,
118
}
119

            
120
impl FromStr for FilenameOrStdio {
121
    type Err = anyhow::Error;
122
5
    fn from_str(s: &str) -> Result<Self, Self::Err> {
123
5
        match s {
124
            "" => Err(anyhow!("empty filename")),
125
            "-" => Ok(FilenameOrStdio::Stdio),
126
5
            other => Ok(FilenameOrStdio::Path(other.to_owned())),
127
        }
128
5
    }
129
}
130

            
131
impl FilenameOrStdio {
132
    /// Write the output file, with write-to-`.tmp`-and-rename
133
    ///
134
    /// `writer` should generate the actual output.
135
    /// It shouldn't fail other than for write errors.
136
    ///
137
    /// Makes no attempt to preserve file permissions.
138
    ///
139
    /// ### `.tmp` file cleanup
140
    ///
141
    /// If this fails, we can leave a `.tmp` file lying about.  This is fine for
142
    /// the C Tor Arti consensus method plugin.
143
    ///
144
    /// If we promote this code we might want to make an effort to clean up leftover `.tmp`
145
    /// files.  Note however that it is not possible to make that cleanup reliable.
146
    /// Therefore whatever invokes us will need to be able to clean up such garbage, anyway.
147
    /// It might be better to rely entirely on that, avoiding the situation where
148
    /// a caller fails to have any cleanup functionality and very occasionally
149
    /// `.tmp` files get left over anyway (and *this* code unjustifiably gets the blame).
150
    pub(super) fn write<W>(&self, writer: W) -> Result<(), CliError>
151
    where
152
        W: FnOnce(&mut dyn io::Write) -> io::Result<()>,
153
    {
154
        let mut w = self.start_writing()?;
155
        w.append_with(writer)?;
156
        w.finish()
157
    }
158

            
159
    /// Start writing the output file, with write-to-`.tmp`-and-rename
160
    /// in the case of the file being on the file system (i.e. no stdout).
161
    ///
162
    /// Returns a [`Writing`], which implements `io::Write` -
163
    /// but usually it's better to use [`Writing::append_with`]
164
    /// since that automatically converts errors to a nice `CliError`.
165
    ///
166
    /// When the output is complete, you *must* call [`Writing::finish`]
167
    /// to install the output file.
168
    ///
169
    /// If `Writing` is dropped, we leave the `.tmp` file lying about.
170
    /// See [`FilenameOrStdio::write`] for more information.
171
    ///
172
    /// Makes no attempt to preserve file permissions.
173
2
    pub(super) fn start_writing(&self) -> Result<Writing, CliError> {
174
2
        match self {
175
            FilenameOrStdio::Stdio => {
176
                //
177
                Ok(Writing {
178
                    // TODO locking/hang
179
                    //
180
                    // If multiple `FilenameOrStdio`s referring to stdin/stdout are
181
                    // used simultaneously (rather than sequentially), this will hang.
182
                    //
183
                    // Eg, `compute-mds --mds-out - --meta-out -` will hang.
184
                    //
185
                    // Unfortunately there is no `.try_lock()`.  We could have a private
186
                    // global lock to detect this situation.  That seems overkill for
187
                    // the dirauth plugin, but ought to be done before these routines
188
                    // are promoted to general utilities.
189
                    handle: BufWriter::new(Box::new(io::stdout().lock())),
190
                    files: None,
191
                })
192
            }
193
            FilenameOrStdio::Path(main) => {
194
2
                let tmp = format!("{main}.tmp");
195
2
                let f = File::create(&tmp)
196
                    .with_context(|| format!("create {tmp:?}"))
197
2
                    .map_err(convert_output_error)?;
198
2
                Ok(Writing {
199
2
                    handle: BufWriter::new(Box::new(f)),
200
2
                    files: Some(WritingFiles {
201
2
                        tmp,
202
2
                        main: main.clone(),
203
2
                    }),
204
2
                })
205
            }
206
        }
207
2
    }
208

            
209
    /// Start reading this input file
210
3
    pub(super) fn start_reading(&self) -> Result<Reading, CliError> {
211
        let (handle, description);
212
3
        match self {
213
            FilenameOrStdio::Stdio => {
214
                // TODO locking/hang, see above
215
                handle = Box::new(io::stdin().lock()) as _;
216
                description = "<stdin>".into();
217
            }
218
            FilenameOrStdio::Path(path) => {
219
3
                handle = Box::new(
220
3
                    File::open(path)
221
                        .with_context(|| format!("open input file {path:?}"))
222
3
                        .map_err(CliError::OperationalError)?,
223
                ) as _;
224
3
                description = format!("{path:?}");
225
            }
226
        }
227
3
        let handle = BufReader::new(handle);
228
3
        Ok(Reading {
229
3
            handle,
230
3
            description,
231
3
        })
232
3
    }
233

            
234
    /// Read the input file
235
3
    pub(super) fn read_entire(&self) -> Result<EntireInput, CliError> {
236
3
        let i = self.start_reading()?;
237
3
        let description = i.description().to_owned();
238
3
        let data = i.read_entire_string()?;
239
3
        Ok(EntireInput { data, description })
240
3
    }
241
}
242

            
243
impl io::Read for Reading {
244
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
245
        self.handle.read(buf)
246
    }
247
}
248

            
249
impl io::BufRead for Reading {
250
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
251
        self.handle.fill_buf()
252
    }
253
    #[allow(clippy::semicolon_if_nothing_returned)] // more consistent without the ;
254
    fn consume(&mut self, n: usize) {
255
        self.handle.consume(n)
256
    }
257
}
258

            
259
impl Reading {
260
    /// Reads the whole file into memory as a `String`
261
    ///
262
    /// Non-UTF-8 input is treated as an operational error, just like an io error.
263
3
    pub(crate) fn read_entire_string(mut self) -> Result<String, CliError> {
264
3
        let mut s = String::new();
265
3
        self.handle
266
3
            .read_to_string(&mut s)
267
3
            .map_err(self.handle_read_error())?;
268
3
        Ok(s)
269
3
    }
270

            
271
    /// Provide a human-readable description of what this is (eg for error reporting)
272
3
    pub(crate) fn description(&self) -> &str {
273
3
        &self.description
274
3
    }
275

            
276
    /// Returns an error handler for IO errors from this input file
277
3
    pub(crate) fn handle_read_error(&self) -> impl FnOnce(io::Error) -> CliError {
278
3
        let m = format!("error reading {}", self.description);
279
        move |e| CliError::OperationalError(anyhow::Error::from(e).context(m))
280
3
    }
281
}
282

            
283
impl EntireInput {
284
    /// Provide a human-readable description of what this is (eg for error reporting)
285
3
    pub(crate) fn description(&self) -> &str {
286
3
        &self.description
287
3
    }
288

            
289
    /// Return a `parse2::ParseInput` for this input file
290
3
    pub(crate) fn netdoc_parse2(&self) -> parse2::ParseInput {
291
3
        parse2::ParseInput::new(&**self, self.description()).retain_unknown_values()
292
3
    }
293
}
294

            
295
impl io::Write for Writing {
296
10
    fn write(&mut self, b: &[u8]) -> io::Result<usize> {
297
10
        self.handle.write(b)
298
10
    }
299
2
    fn flush(&mut self) -> io::Result<()> {
300
2
        self.handle.flush()
301
2
    }
302
}
303

            
304
impl Writing {
305
    /// Write to an output file, with a `dyn io::Write`, handling errors
306
    ///
307
    /// Calls `writer(self)` but converts the error into a nice `CliError`
308
10
    pub(super) fn append_with<W>(&mut self, writer: W) -> Result<(), CliError>
309
10
    where
310
10
        W: FnOnce(&mut dyn io::Write) -> io::Result<()>,
311
    {
312
10
        writer(self).map_err(self.handle_write_error())
313
10
    }
314

            
315
    /// Finish writing and install the output file
316
2
    pub(super) fn finish(mut self) -> Result<(), CliError> {
317
2
        self.flush().map_err(self.handle_write_error())?;
318

            
319
2
        if let Some(WritingFiles { main, tmp }) = &self.files {
320
2
            fs::rename(tmp, main)
321
                .with_context(|| format!("install {tmp:?} as {main:?}"))
322
2
                .map_err(convert_output_error)?;
323
        }
324

            
325
2
        Ok(())
326
2
    }
327

            
328
    /// Helper to handle errors from `io::Write::write` and `flush`
329
12
    fn handle_write_error(&self) -> impl FnOnce(io::Error) -> CliError {
330
12
        let msg = self
331
12
            .files
332
12
            .as_ref()
333
12
            .map(|files| format!("write to {:?}", files.tmp))
334
            .unwrap_or_else(|| "write to stdout".into());
335
        move |e| convert_output_error(anyhow::Error::from(e).context(msg))
336
12
    }
337

            
338
    /// Write some netdoc(s)
339
5
    pub(super) fn write_netdocs<'d, D: NetdocEncodable + ?Sized + 'd>(
340
5
        &mut self,
341
5
        doc: impl IntoIterator<Item = &'d D>,
342
5
    ) -> Result<(), CliError> {
343
5
        let doc = encode_netdoc_unsigned(doc)?;
344
5
        self.append_with(|w| write!(w, "{doc}"))
345
5
    }
346
}
347

            
348
/// Helper to convert an error encountered while writing to CliError
349
fn convert_output_error(e: anyhow::Error) -> CliError {
350
    CliError::OperationalError(e.context("write output"))
351
}
352

            
353
/// A network document, but possibly preceded by C Tor `@`-annotation(s)
354
///
355
/// Parsing adapter wrapper.
356
///
357
/// Implements `NetdocParseable`: discards any annotations,
358
/// and then parses `D`.
359
pub(crate) struct CTorAnnotated<D>(pub(crate) D);
360

            
361
impl<D: NetdocParseable> NetdocParseable for CTorAnnotated<D> {
362
    fn doctype_for_error() -> &'static str {
363
        D::doctype_for_error()
364
    }
365
    fn is_intro_item_keyword(kw: tor_netdoc::parse2::KeywordRef<'_>) -> bool {
366
        D::is_intro_item_keyword(kw)
367
    }
368
    fn is_structural_keyword(
369
        kw: tor_netdoc::parse2::KeywordRef<'_>,
370
    ) -> Option<parse2::IsStructural> {
371
        D::is_structural_keyword(kw)
372
    }
373
5
    fn from_items(
374
5
        input: &mut parse2::ItemStream<'_>,
375
5
        stop_at: tor_netdoc::stop_at!(),
376
5
    ) -> Result<Self, parse2::ErrorProblem> {
377
5
        input.with_inner_lines_mut(|lines| {
378
6
            while let Some(peeked) = lines.peek() {
379
6
                let line = lines.peeked_line(&peeked);
380
6
                if !line.starts_with('@') {
381
5
                    break;
382
1
                }
383
1
                let _: &str = lines.next().expect("just peeked");
384
            }
385
5
        });
386
5
        D::from_items(input, stop_at).map(CTorAnnotated)
387
5
    }
388
}