aboutsummaryrefslogtreecommitdiff
path: root/var/clipboard.rs
blob: 9d7ba2142a388c580412be8294d594f5f2d81eee (plain)
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
// clipboard.rs

// Copyright (C) 2020 The Nitrocli Developers
// SPDX-License-Identifier: GPL-3.0-or-later

use std::ffi;
use std::fmt;
use std::io::Write as _;
use std::os::unix::ffi::OsStrExt as _;
use std::process;
use std::str;
use std::thread;
use std::time;

use anyhow::Context as _;
use structopt::StructOpt as _;

#[derive(Clone, Copy, Debug, PartialEq, structopt::StructOpt)]
enum Selection {
  Primary,
  Secondary,
  Clipboard,
}

impl fmt::Display for Selection {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let s = match self {
      Self::Primary => "primary",
      Self::Secondary => "secondary",
      Self::Clipboard => "clipboard",
    };
    fmt::Display::fmt(s, f)
  }
}

impl str::FromStr for Selection {
  type Err = anyhow::Error;

  fn from_str(s: &str) -> Result<Selection, Self::Err> {
    match s {
      "primary" => Ok(Self::Primary),
      "secondary" => Ok(Self::Secondary),
      "clipboard" => Ok(Self::Clipboard),
      _ => Err(anyhow::anyhow!("Unexpected selection type: {}", s)),
    }
  }
}

/// Parse a duration from a string.
fn parse_duration(s: &str) -> Result<time::Duration, anyhow::Error> {
  let durations = [
    ("ms", 1),
    ("sec", 1000),
    ("s", 1000),
    ("min", 60000),
    ("m", 60000),
  ];

  for (suffix, multiplier) in &durations {
    if s.ends_with(suffix) {
      if let Ok(count) = u64::from_str_radix(&s[..s.len() - suffix.len()], 10) {
        return Ok(time::Duration::from_millis(count * multiplier));
      }
    }
  }

  anyhow::bail!("invalid duration provided: {}", s)
}

fn copy(selection: Selection, content: &[u8]) -> anyhow::Result<()> {
  let mut clip = process::Command::new("xclip")
    .stdin(process::Stdio::piped())
    .stdout(process::Stdio::null())
    .stderr(process::Stdio::null())
    .args(&["-selection", &selection.to_string()])
    .spawn()
    .context("Failed to execute xclip")?;

  let stdin = clip.stdin.as_mut().unwrap();
  stdin
    .write_all(content)
    .context("Failed to write to stdin")?;

  let output = clip.wait().context("Failed to wait for xclip for finish")?;
  anyhow::ensure!(output.success(), "xclip failed");
  Ok(())
}

/// Retrieve the current clipboard contents.
fn clipboard(selection: Selection) -> anyhow::Result<Vec<u8>> {
  let output = process::Command::new("xclip")
    .args(&["-out", "-selection", &selection.to_string()])
    .output()
    .context("Failed to execute xclip")?;

  anyhow::ensure!(
    output.status.success(),
    "xclip failed: {}",
    String::from_utf8_lossy(&output.stderr)
  );
  Ok(output.stdout)
}

/// Access Nitrokey OTP slots by name
#[derive(Debug, structopt::StructOpt)]
#[structopt()]
struct Args {
  /// The "selection" to use (see xclip(1)).
  #[structopt(short, long, default_value = "clipboard")]
  selection: Selection,
  /// Revert the contents of the clipboard to the previous value after
  /// this time.
  #[structopt(short, long, parse(try_from_str = parse_duration))]
  revert_after: Option<time::Duration>,
  /// The data to copy to the clipboard.
  #[structopt(name = "data")]
  data: ffi::OsString,
}

/// Revert clipboard contents after a while.
fn revert_contents(
  delay: time::Duration,
  selection: Selection,
  expected: &[u8],
  previous: &[u8],
) -> anyhow::Result<()> {
  let pid = unsafe { libc::fork() };
  if pid == 0 {
    // We are in the child. Sleep for the provided delay and then revert
    // the clipboard contents.
    thread::sleep(delay);
    // We potentially suffer from A-B-A as well as TOCTOU problems here.
    // But who's checking...
    let content = clipboard(selection).context("Failed to save clipboard contents")?;
    if content == expected {
      copy(selection, previous).context("Failed to restore original xclip content")?;
    }
    Ok(())
  } else if pid < 0 {
    // TODO: Could provide errno or whatever describes the failure.
    anyhow::bail!("Failed to fork")
  } else {
    debug_assert!(pid > 0);
    // We are in the parent. There is nothing to do but to exit.
    Ok(())
  }
}

fn main() -> anyhow::Result<()> {
  let args = Args::from_args();

  let revert = if let Some(revert_after) = args.revert_after {
    let content = match clipboard(args.selection) {
      Ok(content) => content,
      // If the clipboard/selection is "empty" xclip reports this
      // nonsense and fails. We have no other way to detect it than
      // pattern matching on its output, but we definitely want to
      // handle this case gracefully.
      Err(err) if err.to_string().contains("target STRING not available") => Vec::new(),
      e => e.context("Failed to save clipboard contents")?,
    };
    Some((revert_after, content))
  } else {
    None
  };

  copy(args.selection, args.data.as_bytes()).context("Failed to modify clipboard contents")?;

  if let Some((revert_after, previous)) = revert {
    revert_contents(
      revert_after,
      args.selection,
      args.data.as_bytes(),
      &previous,
    )
    .context("Failed to revert clipboard contents")?;
  }
  Ok(())
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn duration_parsing() {
    assert_eq!(
      parse_duration("1ms").unwrap(),
      time::Duration::from_millis(1)
    );
    assert_eq!(
      parse_duration("500ms").unwrap(),
      time::Duration::from_millis(500)
    );
    assert_eq!(parse_duration("1s").unwrap(), time::Duration::from_secs(1));
    assert_eq!(
      parse_duration("1sec").unwrap(),
      time::Duration::from_secs(1)
    );
    assert_eq!(
      parse_duration("13s").unwrap(),
      time::Duration::from_secs(13)
    );
    assert_eq!(
      parse_duration("13sec").unwrap(),
      time::Duration::from_secs(13)
    );
    assert_eq!(
      parse_duration("1m").unwrap(),
      time::Duration::from_secs(1 * 60)
    );
    assert_eq!(
      parse_duration("1min").unwrap(),
      time::Duration::from_secs(1 * 60)
    );
    assert_eq!(
      parse_duration("13m").unwrap(),
      time::Duration::from_secs(13 * 60)
    );
    assert_eq!(
      parse_duration("13min").unwrap(),
      time::Duration::from_secs(13 * 60)
    );
  }
}