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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
// mailcap file handling - see RFC 1524
// Copyright (C) 2022 savoy
// mailcap is free software: you can redistribute it and/or modify
// it under the terms of the GNU Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// mailcap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with mailcap. If not, see <http://www.gnu.org/licenses/>.
//! # mailcap
//!
//! `mailcap` is a parsing library for mailcap files.
//!
//! Mailcap files are a format documented in [RFC
//! 1524](https://www.rfc-editor.org/rfc/rfc1524.html), "A User Agent Configuration
//! Mechanism For Multimedia Mail Format Information." They allow the handling of
//! MIME types by software aware of those types. For example, a mailcap line of
//! `text/html; qutebrowser '%s'; test=test -n "$DISPLAY"` would instruct the
//! software to open any HTML file with qutebrowser if you are running a graphical
//! session, with the file replacing the `'%s'`.
//!
//! `mailcap` is a parsing library that looks at either a present `$MAILCAPS` env
//! variable or cycles through the four paths where a mailcap file would be found in
//! ascending order of importance: `/usr/local/etc/mailcap`, `/usr/etc/mailcap`,
//! `/etc/mailcap`, and `$HOME/.mailcap`. It builds the mailcap from all available
//! files, with duplicate entries being squashed with newer lines, allowing
//! `$HOME/.mailcap` to be the final decider.
//!
//! The entries that make up the mailcap include only those that are relevant i.e.
//! those that have passed the `test` field (if present). With the above `text/html`
//! example, that test would fail if run through SSH, and unless another existing
//! `text/html` entry (or `text/*`) exists that doesn't require a display server, no
//! entry would exist for that mime type.
//!
//! # Usage
//!
//! ```rust
//! use mailcap::{Mailcap, MailcapError};
//!
//! fn main() -> Result<(), MailcapError> {
//! let cap = Mailcap::new()?;
//! if let Some(i) = cap.get("text/html") {
//! let command = i.viewer("/var/www/index.html");
//! assert_eq!(command, "qutebrowser '/var/www/index.html'");
//! }
//! Ok(())
//! }
//! ```
//!
//! Wildcard fallbacks are also supported.
//!
//! ```rust
//! use mailcap::{Mailcap, MailcapError};
//!
//! fn main() -> Result<(), MailcapError> {
//! let cap = Mailcap::new()?;
//! if let Some(i) = cap.get("video/avi") {
//! // if no video/avi MIME entry available
//! let mime_type = i.mime();
//! assert_eq!(mime_type, "video/*");
//! }
//! Ok(())
//! }
//! ```
use libc::system;
use std::collections::HashMap;
use std::ffi::CString;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::{env, fmt};
/// The error type for `mailcap`.
#[derive(Debug, PartialEq)]
pub enum MailcapError {
/// The mailcap line was unable to be parsed.
LineParseError,
/// The mailcap file was unable to be parsed.
FileParseError,
/// There are no valid mailcap files to parse.
NoValidFiles,
}
/// Meta representation of all available mailcap files and their combined lines.
#[derive(Default, Debug, PartialEq, Clone)]
pub struct Mailcap {
files: Vec<PathBuf>,
data: HashMap<String, Entry>,
}
/// Parsed mailcap line. Each mailcap entry consists of a number of fields, separated by
/// semi-colons. The first two fields are required, and must occur in the specified order. The
/// remaining fields are optional, and may appear in any order.
#[derive(Default, Debug, PartialEq, Clone)]
pub struct Entry {
mime_type: String,
viewer: String,
compose: Option<String>,
compose_typed: Option<String>,
edit: Option<String>,
print: Option<String>,
test: Option<String>,
description: Option<String>,
name_template: Option<String>,
needs_terminal: bool,
copious_output: bool,
textual_new_lines: bool,
}
impl fmt::Display for MailcapError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MailcapError::NoValidFiles => write!(f, "No populated mailcap found"),
MailcapError::LineParseError => write!(f, "Unable to parse mailcap lines"),
MailcapError::FileParseError => write!(f, "Unable to parse mailcap file"),
}
}
}
impl Mailcap {
/// Returns a combined mailcap from all available default files or a $MAILCAPS env.
/// The default list (in ascending order of importance) includes:
///
/// - `/usr/local/etc/mailcap`
/// - `/usr/etc/mailcap`
/// - `/etc/mailcap`
/// - `$HOME/.mailcap`
///
/// # Examples
///
/// ```rust
/// # use mailcap::{Mailcap, MailcapError};
/// # fn main() -> Result<(), MailcapError> {
/// let cap = Mailcap::new()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// If there are no available mailcap files in the default locations or no $MAILCAPS env has
/// been set, or if the files or empty or contain no valid mailcap lines, `MailcapError` will
/// be returned. The implementation is loose: as long as one file exists with at least one
/// valid mailcap line, the `Result` will be `Ok`.
pub fn new() -> Result<Mailcap, MailcapError> {
let mut files = Self::list_potential_files();
Self::check_files_exist(&mut files)?;
let mut virgin_lines: Vec<String> = vec![];
for file in &files {
match Self::get_mailcap_lines(&file) {
Ok(mut i) => virgin_lines.append(&mut i),
Err(_) => continue,
};
}
let parsed_lines = Self::parse_valid_lines(virgin_lines)?;
let data: HashMap<String, Entry> = parsed_lines
.iter()
.filter_map(|i| match Entry::from(i) {
Some(m) => Some((i[0].to_owned(), m)),
None => None,
})
.collect();
Ok(Mailcap { files, data })
}
/// Given a specific mime-type value, will lookup if there is an existing mailcap entry for
/// that type.
///
/// # Examples
///
/// ```rust
/// # use mailcap::{Mailcap, MailcapError};
/// # fn main() -> Result<(), MailcapError> {
/// let cap = Mailcap::new()?;
/// if let Some(i) = cap.get("text/html") {
/// let command = i.viewer("/var/www/index.html");
/// assert_eq!(command, "qutebrowser '/var/www/index.html'");
/// }
/// # Ok(())
/// # }
/// ```
pub fn get(&self, key: &str) -> Option<&Entry> {
match self.data.get(key) {
Some(v) => Some(v),
None => {
let mime_split: Vec<&str> = key.split("/").collect();
let mut wildcard = String::new();
if let Some(x) = mime_split.get(0) {
wildcard.push_str(x);
wildcard.push_str("/*");
};
self.data.get(&wildcard)
}
}
}
fn get_user_home() -> PathBuf {
let home = match env::var("HOME") {
Ok(i) => PathBuf::from(i),
Err(_) => PathBuf::from("."),
};
home
}
fn list_potential_files() -> Vec<PathBuf> {
let mut mailcap_files: Vec<PathBuf> = vec![];
if let Ok(paths) = env::var("MAILCAPS") {
for path in env::split_paths(&paths) {
mailcap_files.push(path)
}
};
if mailcap_files.is_empty() {
let home = Self::get_user_home();
let mut default_locations: Vec<PathBuf> = vec![
PathBuf::from("/usr/local/etc/mailcap"),
PathBuf::from("/usr/etc/mailcap"),
PathBuf::from("/etc/mailcap"),
home.join(".mailcap"),
];
mailcap_files.append(&mut default_locations)
};
mailcap_files
}
fn check_files_exist(mailcap_files: &mut Vec<PathBuf>) -> Result<(), MailcapError> {
mailcap_files.retain(|i| i.exists());
match mailcap_files.is_empty() {
true => Err(MailcapError::NoValidFiles),
false => Ok(()),
}
}
fn get_mailcap_lines(filepath: &PathBuf) -> std::io::Result<Vec<String>> {
let ignore_chars = ['#', '\n'];
let file = BufReader::new(File::open(filepath)?);
let correct_lines: Vec<String> = file
.lines()
.map(|i| i.unwrap())
.filter(|i| !i.starts_with(ignore_chars))
.filter(|i| !i.is_empty())
.collect();
Ok(correct_lines)
}
fn parse_valid_lines(all_lines: Vec<String>) -> Result<Vec<Vec<String>>, MailcapError> {
let mut lines: Vec<Vec<String>> = vec![];
for line in all_lines {
lines.push(
line.split(";")
.into_iter()
.map(|i| i.trim().to_string())
.collect::<Vec<String>>(),
);
}
match lines.is_empty() {
true => Err(MailcapError::FileParseError),
false => {
if lines.iter().all(|i| i.len() >= 2) {
Ok(lines)
} else {
Err(MailcapError::FileParseError)
}
}
}
}
}
impl Entry {
fn from(line: &Vec<String>) -> Option<Entry> {
let mut entry = Entry::default();
entry.mime_type = line[0].to_owned();
entry.viewer = line[1].to_owned();
for field in line[2..].iter() {
match Self::parse_arg(field) {
Some(("compose", v)) => entry.compose = Some(v[1..].to_string()),
Some(("composetyped", v)) => entry.compose_typed = Some(v[1..].to_string()),
Some(("edit", v)) => entry.edit = Some(v[1..].to_string()),
Some(("print", v)) => entry.print = Some(v[1..].to_string()),
Some(("test", v)) => entry.test = Some(v[1..].to_string()),
Some(("description", v)) => entry.description = Some(v[1..].to_string()),
Some(("nametemplate", v)) => entry.name_template = Some(v[1..].to_string()),
Some(("needsterminal", _)) => entry.needs_terminal = true,
Some(("copiousoutput", _)) => entry.copious_output = true,
Some(("textualnewlines", _)) => entry.textual_new_lines = true,
_ => continue,
}
}
match entry.test {
Some(ref c) => match unsafe { Self::test_entry(c) } {
Ok(()) => Some(entry),
Err(()) => None,
},
None => None,
}
}
/// The `mime_type`, which indicates the type of data this mailcap entry describes how to
/// handle. It is to be matched against the type/subtype specification in the "Content-Type"
/// header field of an Internet mail message. If the subtype is specified as "*", it is
/// intended to match all subtypes of the named `mime_type`.
pub fn mime(&self) -> &String {
&self.mime_type
}
/// The second field, `viewer`, is a specification of how the message or body part can be
/// viewed at the local site. Although the syntax of this field is fully specified, the
/// semantics of program execution are necessarily somewhat operating system dependent. UNIX
/// semantics are given in Appendix A of RFC 1524.
pub fn viewer(&self, filename: &str) -> String {
self.viewer.replace("%s", filename)
}
/// The `compose` field may be used to specify a program that can be used to compose a new body
/// or body part in the given format. Its intended use is to support mail composing agents that
/// support the composition of multiple types of mail using external composing agents. As with
/// `viewer`, the semantics of program execution are operating system dependent, with UNIX
/// semantics specified in Appendix A of RFC 1524. The result of the composing program may be
/// data that is not yet suitable for mail transport -- that is, a Content-Transfer-Encoding
/// may need to be applied to the data.
pub fn compose(&self) -> &Option<String> {
&self.compose
}
/// The `compose_typed` field is similar to the `compose` field, but is to be used when the
/// composing program needs to specify the Content-type header field to be applied to the
/// composed data. The `compose` field is simpler, and is preferred for use with existing
/// (non-mail-oriented) programs for composing data in a given format. The `compose_typed` field
/// is necessary when the Content-type information must include auxilliary parameters, and the
/// composition program must then know enough about mail formats to produce output that
/// includes the mail type information.
pub fn compose_typed(&self) -> &Option<String> {
&self.compose_typed
}
/// The `edit` field may be used to specify a program that can be used to edit a body or body
/// part in the given format. In many cases, it may be identical in content to the `compose`
/// field, and shares the operating-system dependent semantics for program execution.
pub fn edit(&self) -> &Option<String> {
&self.edit
}
/// The `print` field may be used to specify a program that can be used to print a message or
/// body part in the given format. As with `viewer`, the semantics of program execution are
/// operating system dependent, with UNIX semantics specified in Appendix A of RFC 1524.
pub fn print(&self) -> &Option<String> {
&self.print
}
/// The `test` field may be used to test some external condition (e.g., the machine
/// architecture, or the window system in use) to determine whether or not the mailcap line
/// applies. It specifies a program to be run to test some condition. The semantics of
/// execution and of the value returned by the test program are operating system dependent,
/// with UNIX semantics specified in Appendix A of RFC 1524. If the test fails, a subsequent
/// mailcap entry should be sought. Multiple test fields are not permitted -- since a test can
/// call a program, it can already be arbitrarily complex.
pub fn test(&self) -> &Option<String> {
&self.test
}
/// The `description` field simply provides a textual description, optionally quoted, that
/// describes the type of data, to be used optionally by mail readers that wish to describe the
/// data before offering to display it.
pub fn description(&self) -> &Option<String> {
&self.description
}
/// The `name_template` field gives a file name format, in which %s will be replaced by a short
/// unique string to give the name of the temporary file to be passed to the viewing command.
/// This is only expected to be relevant in environments where filename extensions are
/// meaningful, e.g., one coulld specify that a GIF file being passed to a gif viewer should
/// have a name eding in ".gif" by using "nametemplate=%s.gif".
pub fn name_template(&self) -> &Option<String> {
&self.name_template
}
/// The `needs_terminal` field indicates that the `viewer` must be run on an interactive
/// terminal. This is needed to inform window-oriented user agents that an interactive
/// terminal is needed. (The decision is not left exclusively to `viewer` because in
/// some circumstances it may not be possible for such programs to tell whether or not they are
/// on interactive terminals). The `needs_terminal` command should be assumed to apply to the
/// compose and edit commands, too, if they exist. Note that this is NOT a test -- it is a
/// requirement for the environment in which the program will be executed, and should typically
/// cause the creation of a terminal window when not executed on either a real terminal or a
/// terminal window.
pub fn needs_terminal(&self) -> &bool {
&self.needs_terminal
}
/// The `copious_output` field indicates that the output from `viewer` will be an
/// extended stream of output, and is to be interpreted as advice to the UA (User Agent
/// mail-reading program) that the output should be either paged or made scrollable. Note that
/// it is probably a mistake if `needs_terminal` and `copious_output` are both specified.
pub fn copious_output(&self) -> &bool {
&self.copious_output
}
/// The `textual_new_lines` field, if set to any non-zero value, indicates that this type of data
/// is line-oriented and that, if encoded in base64, all newlines should be converted to
/// canonical form (CRLF) before encoding, and will be in that form after decoding. In general,
/// this field is needed only if there is line-oriented data of some type other than text/* or
/// non-line-oriented data that is a subtype of text.
pub fn textual_new_lines(&self) -> &bool {
&self.textual_new_lines
}
fn parse_arg(field: &str) -> Option<(&str, &str)> {
match field.find("=") {
Some(i) => Some(field.split_at(i)),
None => Some((field, "")),
}
}
unsafe fn test_entry(test_command: &String) -> Result<(), ()> {
let c_str = CString::new(test_command.as_str()).unwrap();
match system(c_str.as_ptr()) {
0 => Ok(()),
_ => Err(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serial_test::serial;
use std::io::Write;
fn create_dummy_mailcap_line(dummy_value: Vec<String>) -> (PathBuf, Vec<String>) {
let path = PathBuf::from("/tmp/mailcap-rs.test");
let mut dummy_file = File::create(&path).unwrap();
writeln!(&mut dummy_file, "{:?}", dummy_value).unwrap();
(path, dummy_value)
}
fn dummy_mailcap() -> Mailcap {
let mut cap_data: HashMap<String, Entry> = HashMap::new();
cap_data.insert(
"text/html".to_string(),
Entry {
mime_type: "text/html".to_string(),
viewer: "qutebrowser '%s'".to_string(),
compose: None,
compose_typed: None,
edit: None,
print: None,
test: Some("test -n \"$DISPLAY\"".to_string()),
description: None,
name_template: Some("%s.html".to_string()),
needs_terminal: true,
copious_output: false,
textual_new_lines: true,
},
);
cap_data.insert(
"text/*".to_string(),
Entry {
mime_type: "text/*".to_string(),
viewer: "qutebrowser '%s'".to_string(),
compose: None,
compose_typed: None,
edit: None,
print: None,
test: Some("test -n \"$DISPLAY\"".to_string()),
description: None,
name_template: Some("%s.html".to_string()),
needs_terminal: true,
copious_output: false,
textual_new_lines: true,
},
);
Mailcap {
files: vec![PathBuf::from("/etc/mailcap")],
data: cap_data,
}
}
#[test]
#[serial]
fn mailcap_files_env() {
env::set_var("MAILCAPS", "/etc/mailcap");
let mailcaps = Mailcap::list_potential_files();
env::remove_var("MAILCAPS");
assert_eq!(mailcaps, vec![PathBuf::from("/etc/mailcap")]);
}
#[test]
#[serial]
fn mailcap_files_no_env() {
if let Ok(_) = env::var("MAILCAPS") {
env::remove_var("MAILCAPS")
}
let home = Mailcap::get_user_home();
let default_locations: Vec<PathBuf> = vec![
PathBuf::from("/usr/local/etc/mailcap"),
PathBuf::from("/usr/etc/mailcap"),
PathBuf::from("/etc/mailcap"),
home.join(".mailcap"),
];
assert_eq!(default_locations, Mailcap::list_potential_files())
}
#[test]
fn mailcap_lines() {
let home = Mailcap::get_user_home();
let local_location = home.join(".mailcap");
let correct_lines = Mailcap::get_mailcap_lines(&local_location);
match correct_lines {
Ok(i) => assert!(!i.is_empty()),
Err(e) => panic!("{}", e),
};
}
#[test]
fn mailcap_line_splitting() {
let all_lines = vec![
String::from("text/html; qutebrowser '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.html; needsterminal"),
String::from("image/*; feh -g 1280x720 --scale-down '%s'; test=test -n \"$DISPLAY\"")
];
let lines = Mailcap::parse_valid_lines(all_lines).unwrap();
assert_eq!(
vec![
vec![
"text/html",
"qutebrowser '%s'",
"test=test -n \"$DISPLAY\"",
"nametemplate=%s.html",
"needsterminal"
],
vec![
"image/*",
"feh -g 1280x720 --scale-down '%s'",
"test=test -n \"$DISPLAY\""
]
],
lines
);
}
#[test]
fn create_entry_struct() {
let line = vec![
"text/html".to_string(),
"qutebrowser '%s'".to_string(),
"test=test -n \"$DISPLAY\"".to_string(),
"nametemplate=%s.html".to_string(),
"needsterminal".to_string(),
"textualnewlines=1917".to_string(),
];
let entry = Entry::from(&line).unwrap();
assert_eq!(
Entry {
mime_type: "text/html".to_string(),
viewer: "qutebrowser '%s'".to_string(),
compose: None,
compose_typed: None,
edit: None,
print: None,
test: Some("test -n \"$DISPLAY\"".to_string()),
description: None,
name_template: Some("%s.html".to_string()),
needs_terminal: true,
copious_output: false,
textual_new_lines: true
},
entry
)
}
#[test]
#[serial]
fn create_mailcap_struct() {
let (_path, dummy_line) = create_dummy_mailcap_line(
vec!["text/html; qutebrowser '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.html; needsterminal".to_string()]
);
let dummy_line_vectorized = Mailcap::parse_valid_lines(dummy_line).unwrap();
let dummy_line = Entry::from(&dummy_line_vectorized[0]).unwrap();
env::set_var("MAILCAPS", "/tmp/mailcap-rs.test");
let mailcap = Mailcap::new().unwrap();
env::remove_var("MAILCAPS");
if let Some(i) = mailcap.data.get("text/html") {
assert_eq!(i.viewer, dummy_line.viewer)
}
}
#[test]
#[serial]
fn mailcap_with_duplicates() {
let (_path, dummy_line) = create_dummy_mailcap_line(
vec![
"text/html; qutebrowser '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.html; needsterminal".to_string(),
"text/html; firefox '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.html".to_string()]
);
let dummy_line_vectorized = Mailcap::parse_valid_lines(dummy_line).unwrap();
let dummy_line = Entry::from(&dummy_line_vectorized[1]).unwrap();
env::set_var("MAILCAPS", "/tmp/mailcap-rs.test");
let mailcap = Mailcap::new().unwrap();
env::remove_var("MAILCAPS");
if let Some(i) = mailcap.data.get("text/html") {
assert_eq!(i.viewer, dummy_line.viewer)
}
}
#[test]
fn get_mailcap_success() {
let mailcap = dummy_mailcap();
assert!(mailcap.get("text/html").is_some())
}
#[test]
fn get_mailcap_failure() {
let mailcap = dummy_mailcap();
assert!(mailcap.get("image/jpeg").is_none())
}
#[test]
fn get_mailcap_wildcard_fallback() {
let mailcap = dummy_mailcap();
// deliberate mispelling
let fallback = mailcap.get("text/hmtl").unwrap();
assert_eq!(fallback.mime_type, "text/*")
}
}