Compare commits
74 Commits
0.13.20
...
800a097903
| Author | SHA1 | Date | |
|---|---|---|---|
|
800a097903
|
|||
|
1ccdc65d30
|
|||
|
df0a236f81
|
|||
|
e385d873ec
|
|||
|
73a75a32df
|
|||
|
b8e5901d97
|
|||
|
62ce288524
|
|||
|
731e62ee7e
|
|||
|
f50bfeea92
|
|||
|
8d00fa0afd
|
|||
|
9f520df82b
|
|||
|
41982c2f73
|
|||
|
6166a3ca36
|
|||
|
efedcd3ae4
|
|||
|
8fd5bdf5a6
|
|||
|
b946469da5
|
|||
|
06384c72fb
|
|||
|
9aeadd8f8f
|
|||
|
5b666d6858
|
|||
|
b875aa1058
|
|||
|
cc53dab035
|
|||
|
232629f4d3
|
|||
|
ff4ff825bd
|
|||
|
5eb71e90a3
|
|||
|
a0138be79e
|
|||
|
150fa22f35
|
|||
|
f104598164
|
|||
|
722679247a
|
|||
|
4db4160019
|
|||
|
928dce0234
|
|||
|
1fffd3df52
|
|||
|
a14b8fb9d7
|
|||
|
dd39aeff02
|
|||
|
fbacfecce8
|
|||
|
579ff65b67
|
|||
|
334433536b
|
|||
|
e9058803d3
|
|||
|
71d4d6ba05
|
|||
|
821f5d09e9
|
|||
|
a4a556a5b6
|
|||
|
e2c03842a3
|
|||
|
0fd66bff38
|
|||
|
0c4923016e
|
|||
|
e0c985f7ff
|
|||
|
4c81516742
|
|||
|
98c4d94f6d
|
|||
|
da190f713c
|
|||
|
10b7f7706b
|
|||
|
b1a4a1a2b9
|
|||
|
a693ced9d9
|
|||
|
1003c82d23
|
|||
|
baa75a2619
|
|||
|
d6d9c2088e
|
|||
|
ea2efdf5b9
|
|||
|
6c558654f3
|
|||
|
8699d04ccc
|
|||
|
18dfd20937
|
|||
|
42010596de
|
|||
|
0ddfa6e474
|
|||
|
326c8f77d1
|
|||
|
72ef8d00bc
|
|||
|
851f729ebd
|
|||
|
e253cdf79c
|
|||
|
d89707a47c
|
|||
|
2a75b8f820
|
|||
|
bda7c074b0
|
|||
|
2f805cc942
|
|||
|
70bec49127
|
|||
|
eae0b0352b
|
|||
|
25eb08eb84
|
|||
|
6c882f54cb
|
|||
|
cf96a13419
|
|||
|
1f59a9806e
|
|||
|
c7c71c725b
|
18
Makefile
18
Makefile
@@ -16,6 +16,11 @@
|
||||
DESTDIR ?= dist
|
||||
PREFIX ?= /usr/local
|
||||
|
||||
# for conditionally compiling OS features
|
||||
OS != uname
|
||||
OS_INCLUDE != test -e include/$(OS).mk && printf 'include/$(OS).mk\n' \
|
||||
|| printf '/dev/null\n'
|
||||
|
||||
# normalized prefix
|
||||
PREFIX_N != dirname $(PREFIX)/.
|
||||
MANDIR != test $(PREFIX_N) = / && printf '/usr/share/man\n' \
|
||||
@@ -26,8 +31,8 @@ SYSEXITS != printf '\043include <sysexits.h>\n' | cpp -M - | tr ' ' '\n' \
|
||||
CC ?= cc
|
||||
RUSTC ?= rustc
|
||||
RUSTFLAGS += --extern getopt=build/o/libgetopt.rlib \
|
||||
--extern sysexits=build/o/libsysexits.rlib \
|
||||
--extern strerror=build/o/libstrerror.rlib
|
||||
--extern strerror=build/o/libstrerror.rlib \
|
||||
--extern sysexits=build/o/libsysexits.rlib
|
||||
CFLAGS += -I$(SYSEXITS)
|
||||
|
||||
# testing requires the absolute path to the bin directory set
|
||||
@@ -74,9 +79,12 @@ docs: docs/ build
|
||||
"s/X\.X\.X/$$(git describe --tags --long | cut -d'-' -f1)/g")"; \
|
||||
sed "s/$$original/$$title/g" <"$$file" >"build/$$file"; done
|
||||
|
||||
# include OS feature libraries for compilation
|
||||
include $(OS_INCLUDE)
|
||||
|
||||
.PHONY: rustlibs
|
||||
rustlibs: build/o/libsysexits.rlib build/o/libgetopt.rlib \
|
||||
build/o/libstrerror.rlib
|
||||
rustlibs: build/o/libgetopt.rlib build/o/libstrerror.rlib \
|
||||
build/o/libsysexits.rlib $(OSLIB)
|
||||
|
||||
build/o/libgetopt.rlib: build src/libgetopt.rs
|
||||
$(RUSTC) $(RUSTFLAGS) --crate-type=lib --crate-name=getopt \
|
||||
@@ -87,7 +95,7 @@ build/o/libstrerror.rlib: build src/libstrerror.rs
|
||||
src/libstrerror.rs
|
||||
|
||||
build/o/libsysexits.rlib: build/include/sysexits.h
|
||||
bindgen --default-macro-constant-type signed --use-core --formatter=none \
|
||||
bindgen --fit-macro-constant-types --default-macro-constant-type unsigned --use-core --formatter=none \
|
||||
build/include/sysexits.h | $(RUSTC) $(RUSTFLAGS) --crate-type lib -o $@ -
|
||||
|
||||
# bandage solution until bindgen(1) gets stdin support
|
||||
|
||||
6
include/FreeBSD.mk
Normal file
6
include/FreeBSD.mk
Normal file
@@ -0,0 +1,6 @@
|
||||
# Copyright (c) 2024 Emma Tebibyte <emma@tebibyte.media>
|
||||
# SPDX-License-Identifier: FSFAP
|
||||
#
|
||||
# Copying and distribution of this file, with or without modification, are
|
||||
# permitted in any medium without royalty provided the copyright notice and this
|
||||
# notice are preserved. This file is offered as-is, without any warranty.
|
||||
13
include/OpenBSD.mk
Normal file
13
include/OpenBSD.mk
Normal file
@@ -0,0 +1,13 @@
|
||||
# Copyright (c) 2024 Emma Tebibyte <emma@tebibyte.media>
|
||||
# SPDX-License-Identifier: FSFAP
|
||||
#
|
||||
# Copying and distribution of this file, with or without modification, are
|
||||
# permitted in any medium without royalty provided the copyright notice and this
|
||||
# notice are preserved. This file is offered as-is, without any warranty.
|
||||
|
||||
OSLIB = build/o/libopenbsd.rlib
|
||||
RUSTFLAGS += --extern openbsd=$(OSLIB)
|
||||
|
||||
$(OSLIB): src/libopenbsd.rs
|
||||
$(RUSTC) $(RUSTFLAGS) --crate-type=lib --crate-name=openbsd \
|
||||
-o $@ src/libopenbsd.rs
|
||||
25
src/dj.c
25
src/dj.c
@@ -26,7 +26,8 @@
|
||||
#include <string.h> /* memcpy(3), memmove(3), memset(3) */
|
||||
#include <sysexits.h> /* EX_OK, EX_OSERR, EX_USAGE */
|
||||
#include <unistd.h> /* close(2), getopt(3), lseek(2), read(2), write(2),
|
||||
* optarg, optind, STDIN_FILENO, STDOUT_FILENO */
|
||||
* pledge(2), unveil(2), optarg, optind, STDIN_FILENO,
|
||||
* STDOUT_FILENO */
|
||||
#include <sys/stat.h> /* S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR */
|
||||
|
||||
char *program_name = "dj";
|
||||
@@ -107,8 +108,10 @@ Io_write(struct Io *io) {
|
||||
}
|
||||
|
||||
static int
|
||||
oserr(char *e, int n) {
|
||||
(void)fprintf(stderr, "%s: %s: %s\n", program_name, e, strerror(n));
|
||||
oserr(char *e, int n) { /* program_name: [failing component:] error */
|
||||
(void)fprintf(stderr, "%s: ", program_name);
|
||||
if (e != NULL) { (void)fprintf(stderr, "%s: ", e); }
|
||||
(void)fprintf(stderr, "%s\n", strerror(n));
|
||||
|
||||
return EX_OSERR;
|
||||
}
|
||||
@@ -174,6 +177,12 @@ int main(int argc, char *argv[]) {
|
||||
bool retry; /* false if exits on partial reads or writes */
|
||||
struct Io io[2 /* { in, out } */];
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
if (pledge("cpath rpath stdio unveil wpath", NULL) == -1) {
|
||||
return oserr(NULL, errno);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Set defaults. */
|
||||
align = -1;
|
||||
count = -1;
|
||||
@@ -209,6 +218,12 @@ int main(int argc, char *argv[]) {
|
||||
} else {
|
||||
int fd;
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
if (unveil(optarg, i == 0 ? "r" : "wc") == -1) {
|
||||
return oserr(NULL, errno);
|
||||
}
|
||||
#endif
|
||||
|
||||
if (
|
||||
(fd = open(optarg, io[i].fl, creat_mode)) != -1
|
||||
&& (fdisstd(io[i].fd) || close(io[i].fd) == 0)
|
||||
@@ -249,6 +264,10 @@ int main(int argc, char *argv[]) {
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
if (unveil(NULL, NULL) == -1) { return oserr(NULL, errno); }
|
||||
#endif
|
||||
|
||||
assert(io->fd != STDIN_FILENO || io->fl == read_flags);
|
||||
assert(io->fd != STDOUT_FILENO || io->fl == write_flags);
|
||||
|
||||
|
||||
15
src/false.c
15
src/false.c
@@ -1,9 +1,20 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Emma Tebibyte <emma@tebibyte.media>
|
||||
* Copyright (c) 2023–2024 Emma Tebibyte <emma@tebibyte.media>
|
||||
* Copyright (c) 2024 DTB <trinity@trinity.moe>
|
||||
* SPDX-License-Identifier: CC0
|
||||
*
|
||||
* This work is marked with CC0 1.0. To view a copy of this license, visit
|
||||
* <http://creativecommons.org/publicdomain/zero/1.0>.
|
||||
*/
|
||||
|
||||
int main() { return 1; }
|
||||
#ifdef __OpenBSD__
|
||||
# include <unistd.h> /* NULL, pledge(2), unveil(2) */
|
||||
#endif
|
||||
|
||||
int main(void) {
|
||||
#ifdef __OpenBSD__
|
||||
(void)pledge(NULL, NULL);
|
||||
(void)unveil(NULL, NULL);
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
|
||||
75
src/fop.rs
75
src/fop.rs
@@ -18,8 +18,8 @@
|
||||
|
||||
use std::{
|
||||
env::args,
|
||||
io::{ Read, stdin, stdout, Write },
|
||||
process::{ Command, exit, Stdio },
|
||||
io::{ Error, Read, Write, stdin, stdout },
|
||||
process::{ Command, ExitCode, Stdio, exit },
|
||||
};
|
||||
|
||||
extern crate getopt;
|
||||
@@ -30,15 +30,38 @@ use getopt::GetOpt;
|
||||
use strerror::StrError;
|
||||
use sysexits::{ EX_DATAERR, EX_IOERR, EX_UNAVAILABLE, EX_USAGE };
|
||||
|
||||
fn main() {
|
||||
#[cfg(target_os="openbsd")] use sysexits::EX_OSERR;
|
||||
#[cfg(target_os="openbsd")] extern crate openbsd;
|
||||
#[cfg(target_os="openbsd")] use openbsd::{ Promises, pledge, unveil };
|
||||
|
||||
fn err(argv0: &String, e: Error) {
|
||||
eprintln!("{}: {}", argv0, e.strerror());
|
||||
}
|
||||
|
||||
fn usage(argv0: &String) -> u8 {
|
||||
eprintln!("Usage: {} [-d delimiter] index command [args...]", argv0);
|
||||
EX_USAGE
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv = args().collect::<Vec<String>>();
|
||||
let mut d = '\u{1E}'.to_string(); /* ASCII record separator */
|
||||
let mut optind = 1;
|
||||
|
||||
let usage = format!(
|
||||
"Usage: {} [-d delimiter] index command [args...]",
|
||||
argv[0],
|
||||
);
|
||||
#[cfg(target_os="openbsd")] {
|
||||
let promises = Promises::new("exec proc stdio unveil");
|
||||
if let Err(e) = pledge(Some(promises), None) {
|
||||
err(&argv[0], e);
|
||||
return ExitCode::from(EX_OSERR);
|
||||
}
|
||||
|
||||
if let Err(e) = unveil(None, None) {
|
||||
err(&argv[0], e);
|
||||
return ExitCode::from(EX_OSERR);
|
||||
}
|
||||
}
|
||||
|
||||
if argv.len() == 1 { return ExitCode::from(usage(&argv[0])); }
|
||||
|
||||
while let Some(opt) = argv.getopt("d:") {
|
||||
match opt.opt() {
|
||||
@@ -48,8 +71,7 @@ fn main() {
|
||||
optind = opt.ind();
|
||||
},
|
||||
_ => {
|
||||
eprintln!("{}", usage);
|
||||
exit(EX_USAGE);
|
||||
return ExitCode::from(usage(&argv[0]));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -57,7 +79,7 @@ fn main() {
|
||||
/* parse the specified index as a number we can use */
|
||||
let index = argv[optind].parse::<usize>().unwrap_or_else(|e| {
|
||||
eprintln!("{}: {}: {}", argv[0], argv[1], e);
|
||||
exit(EX_DATAERR);
|
||||
exit(EX_DATAERR.into());
|
||||
});
|
||||
|
||||
/* index of the argv[0] for the operator command */
|
||||
@@ -65,15 +87,14 @@ fn main() {
|
||||
|
||||
/* argv[0] of the operator command */
|
||||
let operator = argv.get(command_arg).unwrap_or_else(|| {
|
||||
eprintln!("{}", usage);
|
||||
exit(EX_USAGE);
|
||||
exit(usage(&argv[0]).into());
|
||||
});
|
||||
|
||||
/* read entire standard input into memory */
|
||||
let mut buf = String::new();
|
||||
if let Err(e) = stdin().read_to_string(&mut buf) {
|
||||
eprintln!("{}: {}", argv[0], e.strerror());
|
||||
exit(EX_IOERR);
|
||||
err(&argv[0], e);
|
||||
exit(EX_IOERR.into());
|
||||
};
|
||||
|
||||
/* split the buffer by the delimiter (by default, '\u{1E}') */
|
||||
@@ -93,18 +114,14 @@ fn main() {
|
||||
.stdout(Stdio::piped()) /* piped stdout to handle output ourselves */
|
||||
.spawn()
|
||||
.unwrap_or_else( |e| {
|
||||
eprintln!("{}: {}: {}", argv[0], argv[command_arg], e.strerror());
|
||||
exit(EX_UNAVAILABLE);
|
||||
err(&argv[0], e);
|
||||
exit(EX_UNAVAILABLE.into());
|
||||
});
|
||||
|
||||
/* get field we want to pipe into spawned program */
|
||||
let field = fields.get(index).unwrap_or_else(|| {
|
||||
eprintln!(
|
||||
"{}: {}: No such index in input",
|
||||
argv[0],
|
||||
index.to_string(),
|
||||
);
|
||||
exit(EX_DATAERR);
|
||||
eprintln!("{}: {}: no such index in input", argv[0], index);
|
||||
exit(EX_DATAERR.into());
|
||||
});
|
||||
|
||||
/* get the stdin of the newly spawned program and feed it the field val */
|
||||
@@ -114,8 +131,8 @@ fn main() {
|
||||
}
|
||||
|
||||
let output = spawned.wait_with_output().unwrap_or_else(|e| {
|
||||
eprintln!("{}: {}: {}", argv[0], argv[command_arg], e.strerror());
|
||||
exit(EX_IOERR);
|
||||
err(&argv[0], e);
|
||||
exit(EX_IOERR.into());
|
||||
});
|
||||
|
||||
/* get the output with which the original field will be replaced */
|
||||
@@ -131,8 +148,8 @@ fn main() {
|
||||
|
||||
/* convert the output of the program to UTF-8 */
|
||||
let new_field = String::from_utf8(replace).unwrap_or_else(|e| {
|
||||
eprintln!("{}: {}: {}", argv[0], argv[command_arg], e);
|
||||
exit(EX_IOERR);
|
||||
eprintln!("{}: {}", argv[0], e);
|
||||
exit(EX_IOERR.into());
|
||||
});
|
||||
|
||||
/* store the new field in the old fields vector */
|
||||
@@ -142,7 +159,9 @@ fn main() {
|
||||
stdout().write_all(
|
||||
fields.join(&d.to_string()).as_bytes()
|
||||
).unwrap_or_else(|e| {
|
||||
eprintln!("{}: {}", argv[0], e.strerror());
|
||||
exit(EX_IOERR);
|
||||
err(&argv[0], e);
|
||||
exit(EX_IOERR.into());
|
||||
});
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
81
src/hru.rs
81
src/hru.rs
@@ -19,7 +19,7 @@
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
env::args,
|
||||
io::{ stdin, stdout, Write },
|
||||
io::{ Write, stdin, stdout },
|
||||
process::{ ExitCode, exit },
|
||||
};
|
||||
|
||||
@@ -29,6 +29,10 @@ extern crate sysexits;
|
||||
use strerror::StrError;
|
||||
use sysexits::{ EX_DATAERR, EX_IOERR, EX_SOFTWARE, EX_USAGE };
|
||||
|
||||
#[cfg(target_os="openbsd")] use sysexits::EX_OSERR;
|
||||
#[cfg(target_os="openbsd")] extern crate openbsd;
|
||||
#[cfg(target_os="openbsd")] use openbsd::{ Promises, pledge, unveil };
|
||||
|
||||
/* list of SI prefixes */
|
||||
const LIST: [(u32, &str); 10] = [
|
||||
(3, "k"), /* kilo */
|
||||
@@ -43,6 +47,16 @@ const LIST: [(u32, &str); 10] = [
|
||||
(30, "Q"), /* quetta */
|
||||
];
|
||||
|
||||
fn err(argv0: &String, message: String, code: Option<u8>) -> ExitCode {
|
||||
eprintln!("{}: {}", argv0, message);
|
||||
ExitCode::from(code.unwrap_or(1 /* unknown error */))
|
||||
}
|
||||
|
||||
fn usage(argv0: &String) -> ExitCode {
|
||||
eprintln!("Usage: {}", argv0);
|
||||
ExitCode::from(EX_USAGE)
|
||||
}
|
||||
|
||||
fn convert(input: u128) -> Result<(f64, (u32, &'static str)), String> {
|
||||
/* preserve decimal places in output by casting to a float */
|
||||
let mut out = (input as f64, (0_u32, ""));
|
||||
@@ -76,44 +90,49 @@ fn convert(input: u128) -> Result<(f64, (u32, &'static str)), String> {
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv = args().collect::<Vec<String>>();
|
||||
if let Some(_) = argv.get(1) {
|
||||
eprintln!("Usage: {}", argv[0]);
|
||||
return ExitCode::from(EX_USAGE as u8);
|
||||
|
||||
if let Some(_) = argv.get(1) { return usage(&argv[0]); }
|
||||
|
||||
#[cfg(target_os="openbsd")] {
|
||||
let promises = Promises::new("stdio unveil");
|
||||
if let Err(e) = pledge(Some(promises), Some(Promises::default())) {
|
||||
return err(&argv[0], e.strerror(), Some(EX_OSERR));
|
||||
}
|
||||
|
||||
if let Err(e) = unveil(None, None) {
|
||||
return err(&argv[0], e.strerror(), Some(EX_OSERR));
|
||||
}
|
||||
}
|
||||
|
||||
let mut buf = String::new();
|
||||
|
||||
while let Ok(_) = stdin().read_line(&mut buf) {
|
||||
if buf.is_empty() { return ExitCode::SUCCESS; }
|
||||
if let Err(e) = stdin().read_line(&mut buf) {
|
||||
return err(&argv[0], e.strerror(), Some(EX_IOERR));
|
||||
}
|
||||
|
||||
let n: u128 = match buf.trim().parse() {
|
||||
Ok(f) => {
|
||||
buf.clear();
|
||||
f
|
||||
},
|
||||
Err(err) => {
|
||||
eprintln!("{}: {}", argv[0], err);
|
||||
return ExitCode::from(EX_DATAERR as u8);
|
||||
},
|
||||
};
|
||||
if buf.is_empty() { return ExitCode::SUCCESS; }
|
||||
|
||||
let (number, prefix) = match convert(n) {
|
||||
Ok(x) => x,
|
||||
Err(err) => {
|
||||
eprintln!("{}: {}", argv[0], err);
|
||||
return ExitCode::from(EX_SOFTWARE as u8);
|
||||
},
|
||||
};
|
||||
let n: u128 = match buf.trim().parse() {
|
||||
Ok(f) => {
|
||||
buf.clear();
|
||||
f
|
||||
},
|
||||
Err(e) => return err(&argv[0], e.to_string(), Some(EX_DATAERR)),
|
||||
};
|
||||
|
||||
let si_prefix = format!("{}B", prefix.1);
|
||||
let (number, prefix) = convert(n).unwrap_or_else(|e| {
|
||||
let _ = err(&argv[0], e.to_string(), None);
|
||||
exit(EX_SOFTWARE.into());
|
||||
});
|
||||
|
||||
/* round output number to one decimal place */
|
||||
let out = ((number * 10.0).round() / 10.0).to_string();
|
||||
let si_prefix = prefix.1.to_owned() + "B";
|
||||
|
||||
stdout().write_all(format!("{} {}\n", out, si_prefix).as_bytes())
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("{}: {}", argv[0], e.strerror());
|
||||
exit(EX_IOERR);
|
||||
});
|
||||
/* round output number to one decimal place */
|
||||
let rounded = (number * 10.0).round() / 10.0;
|
||||
let out = rounded.to_string() + " " + &si_prefix + &'\n'.to_string();
|
||||
|
||||
if let Err(e) = stdout().write_all(out.as_bytes()) {
|
||||
return err(&argv[0], e.strerror(), Some(EX_IOERR));
|
||||
}
|
||||
|
||||
ExitCode::SUCCESS
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/*
|
||||
* Copyright (c) 2023–2024 DTB <trinity@trinity.moe>
|
||||
* Copyright (c) 2024 Emma Tebibyte <emma@tebibyte.media>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
@@ -22,18 +23,41 @@ use std::{
|
||||
};
|
||||
|
||||
extern crate getopt;
|
||||
use getopt::GetOpt;
|
||||
|
||||
extern crate sysexits;
|
||||
use sysexits::EX_USAGE;
|
||||
|
||||
fn usage(s: &str) -> ExitCode {
|
||||
eprintln!("Usage: {} [-egl] integer integer...", s);
|
||||
ExitCode::from(EX_USAGE as u8)
|
||||
use getopt::GetOpt;
|
||||
use sysexits::{ EX_DATAERR, EX_USAGE };
|
||||
|
||||
#[cfg(target_os="openbsd")] use sysexits::EX_OSERR;
|
||||
#[cfg(target_os="openbsd")] extern crate openbsd;
|
||||
#[cfg(target_os="openbsd")] extern crate strerror;
|
||||
#[cfg(target_os="openbsd")] use openbsd::{ Promises, pledge, unveil };
|
||||
#[cfg(target_os="openbsd")] use strerror::StrError;
|
||||
|
||||
fn err(argv0: &String, e: String, code: u8) -> ExitCode {
|
||||
eprintln!("{}: {}", argv0, e);
|
||||
ExitCode::from(code)
|
||||
}
|
||||
|
||||
fn usage(argv0: &str) -> ExitCode {
|
||||
eprintln!("Usage: {} [-egl] integer integer...", argv0);
|
||||
ExitCode::from(EX_USAGE)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv = args().collect::<Vec<String>>();
|
||||
|
||||
#[cfg(target_os="openbsd")] {
|
||||
let promises = Promises::new("stdio unveil");
|
||||
if let Err(e) = pledge(Some(promises), Some(Promises::default())) {
|
||||
return err(&argv[0], e.strerror(), EX_OSERR);
|
||||
}
|
||||
|
||||
if let Err(e) = unveil(None, None) {
|
||||
return err(&argv[0], e.strerror(), EX_OSERR);
|
||||
}
|
||||
}
|
||||
|
||||
let mut e = false; /* args can be == */
|
||||
let mut g = false; /* args can be > */
|
||||
let mut l = false; /* args can be < */
|
||||
@@ -46,11 +70,13 @@ fn main() -> ExitCode {
|
||||
Ok("e") => e = true,
|
||||
Ok("g") => g = true,
|
||||
Ok("l") => l = true,
|
||||
_ => { return usage(&argv[0]); },
|
||||
_ => return usage(&argv[0]),
|
||||
}
|
||||
optind = opt.ind();
|
||||
}
|
||||
|
||||
if !e & !g & !l { return usage(&argv[0]); }
|
||||
|
||||
if argv.len() - optind < 2 /* see usage */ { return usage(&argv[0]); }
|
||||
|
||||
let mut prev: Option<usize> = None; /* no previous operand */
|
||||
@@ -59,9 +85,9 @@ fn main() -> ExitCode {
|
||||
for arg in argv.iter().skip(optind) { /* iterate operands */
|
||||
match arg.parse::<usize>() { /* parse current operand */
|
||||
Ok(n) => currn = n,
|
||||
_ => {
|
||||
eprintln!("{}: {}: Invalid integer", &argv[0], arg);
|
||||
return ExitCode::from(EX_USAGE as u8);
|
||||
Err(e) => {
|
||||
let error = arg.to_owned() + ": " + &e.to_string();
|
||||
return err(&argv[0], error, EX_DATAERR);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
101
src/libopenbsd.rs
Normal file
101
src/libopenbsd.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Emma Tebibyte <emma@tebibyte.media>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU Affero General Public License as published by the Free
|
||||
* Software Foundation, either version 3 of the License, or (at your option) any
|
||||
* later version.
|
||||
*
|
||||
* This program 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 Affero General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see https://www.gnu.org/licenses/.
|
||||
*/
|
||||
|
||||
use std::{
|
||||
ffi::{ CString, c_char },
|
||||
io::Error,
|
||||
ptr::null,
|
||||
};
|
||||
|
||||
mod openbsd {
|
||||
use std::ffi::{ c_char, c_int };
|
||||
extern "C" {
|
||||
pub fn pledge(arg1: *const c_char, arg2: *const c_char) -> c_int;
|
||||
|
||||
pub fn unveil(arg1: *const c_char, arg2: *const c_char) -> c_int;
|
||||
|
||||
pub fn __errno() -> *mut c_int;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Promises(*const c_char);
|
||||
|
||||
impl Promises {
|
||||
pub fn new(promises: &str) -> Self {
|
||||
let p = CString::new(promises).unwrap();
|
||||
|
||||
Promises(p.into_raw() as *const c_char)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Promises {
|
||||
fn default() -> Self { Promises::new("") }
|
||||
}
|
||||
|
||||
pub fn pledge(
|
||||
promises: Option<Promises>, execpromises: Option<Promises>
|
||||
) -> Result<(), Error> {
|
||||
/* From pledge(2):
|
||||
*
|
||||
* Passing NULL to promises or execpromises specifies to not change
|
||||
* the current value. */
|
||||
let arg1 = promises.unwrap_or(Promises(null())).0;
|
||||
let arg2 = execpromises.unwrap_or(Promises(null())).0;
|
||||
|
||||
unsafe {
|
||||
match openbsd::pledge(arg1, arg2) {
|
||||
-1 => Err(Error::from_raw_os_error(*openbsd::__errno())),
|
||||
0 => Ok(()),
|
||||
_ => panic!(), /* unreachable */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UnveilPerms(CString);
|
||||
|
||||
impl UnveilPerms {
|
||||
pub fn new(permissions: Vec<char>) -> Self {
|
||||
if permissions.is_empty() {
|
||||
return UnveilPerms(CString::new("").unwrap());
|
||||
}
|
||||
|
||||
UnveilPerms(
|
||||
CString::new(permissions.iter().collect::<String>()).unwrap()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unveil(
|
||||
path: Option<&str>,
|
||||
permissions: Option<UnveilPerms>,
|
||||
) -> Result<(), Error> {
|
||||
let path_c = path.map(CString::new).map(Result::unwrap);
|
||||
let arg1 = path_c.map(|p| p.into_raw() as *const c_char).unwrap_or(null());
|
||||
|
||||
let arg2 = permissions
|
||||
.map(|p| p.0.into_raw() as *const c_char)
|
||||
.unwrap_or(null());
|
||||
|
||||
unsafe {
|
||||
match openbsd::unveil(arg1, arg2) {
|
||||
-1 => Err(Error::from_raw_os_error(*openbsd::__errno())),
|
||||
0 => Ok(()),
|
||||
_ => panic!(), /* unreachable */
|
||||
}
|
||||
}
|
||||
}
|
||||
84
src/mm.rs
84
src/mm.rs
@@ -20,9 +20,9 @@
|
||||
use std::{
|
||||
env::args,
|
||||
fs::File,
|
||||
io::{ stdin, stdout, stderr, BufWriter, Read, Write },
|
||||
io::{ Error, BufWriter, Read, Write, stderr, stdin, stdout },
|
||||
os::fd::{ AsRawFd, FromRawFd },
|
||||
process::{ exit, ExitCode },
|
||||
process::{ ExitCode, exit},
|
||||
};
|
||||
|
||||
extern crate getopt;
|
||||
@@ -33,13 +33,39 @@ use getopt::GetOpt;
|
||||
use strerror::StrError;
|
||||
use sysexits::{ EX_IOERR, EX_USAGE };
|
||||
|
||||
#[cfg(target_os="openbsd")] use sysexits::EX_OSERR;
|
||||
#[cfg(target_os="openbsd")] extern crate openbsd;
|
||||
#[cfg(target_os="openbsd")]
|
||||
use openbsd::{
|
||||
Promises,
|
||||
UnveilPerms,
|
||||
pledge,
|
||||
unveil,
|
||||
};
|
||||
|
||||
use ArgMode::*;
|
||||
|
||||
enum ArgMode { In, Out }
|
||||
|
||||
fn err(argv0: &String, e: Error, code: Option<u8>) -> ExitCode {
|
||||
eprintln!("{}: {}", argv0, e.strerror());
|
||||
ExitCode::from(code.unwrap_or(1 /* unknown error */))
|
||||
}
|
||||
|
||||
fn usage(argv0: &String) -> ExitCode {
|
||||
eprintln!("Usage: {} [-aetu] [-i input] [-o output]", argv0);
|
||||
ExitCode::from(EX_USAGE)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv = args().collect::<Vec<_>>();
|
||||
let usage = format!("Usage: {} [-aetu] [-i input] [-o output]", argv[0]);
|
||||
|
||||
#[cfg(target_os="openbsd")] {
|
||||
let promises = Promises::new("cpath rpath stdio unveil wpath");
|
||||
if let Err(e) = pledge(Some(promises), Some(Promises::default())) {
|
||||
return err(&argv[0], e, Some(EX_OSERR));
|
||||
}
|
||||
}
|
||||
|
||||
let mut a = false; /* append to the file */
|
||||
let mut e = false; /* use stderr as an output */
|
||||
@@ -62,13 +88,12 @@ fn main() -> ExitCode {
|
||||
mode = Some(In); /* latest argument == -i */
|
||||
},
|
||||
Ok("o") => { /* add output */
|
||||
let output = opt.arg().unwrap();
|
||||
let output = opt.arg().unwrap();
|
||||
outs.push(output);
|
||||
mode = Some(Out); /* latest argument == -o */
|
||||
},
|
||||
Err(_) | Ok(_) => {
|
||||
eprintln!("{}", usage);
|
||||
return ExitCode::from(EX_USAGE as u8);
|
||||
return usage(&argv[0]);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -86,9 +111,32 @@ fn main() -> ExitCode {
|
||||
Out => outs.push(arg.to_string()),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
eprintln!("{}", usage);
|
||||
return ExitCode::from(EX_USAGE as u8);
|
||||
}
|
||||
|
||||
#[cfg(target_os="openbsd")] {
|
||||
for input in &ins {
|
||||
let perms = UnveilPerms::new(vec!['r']);
|
||||
|
||||
if let Err(e) = unveil(Some(&input), Some(perms)) {
|
||||
return err(&argv[0], e, Some(EX_OSERR));
|
||||
}
|
||||
}
|
||||
|
||||
for output in &outs {
|
||||
let perms = UnveilPerms::new(vec!['c', 'w']);
|
||||
|
||||
if let Err(e) = unveil(Some(&output), Some(perms)) {
|
||||
return err(&argv[0], e, Some(EX_OSERR));
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = unveil(None, None) {
|
||||
return err(&argv[0], e, Some(EX_OSERR));
|
||||
}
|
||||
}
|
||||
|
||||
if ins.is_empty() && outs.is_empty() && argv.len() > optind {
|
||||
return usage(&argv[0]);
|
||||
}
|
||||
|
||||
/* use stdin if no inputs are specified */
|
||||
@@ -108,8 +156,8 @@ fn main() -> ExitCode {
|
||||
match File::open(file) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("{}: {}: {}", argv[0], file, e.strerror());
|
||||
exit(EX_IOERR);
|
||||
let _ = err(&(argv[0].clone() + ": " + file), e, None);
|
||||
exit(EX_IOERR.into());
|
||||
},
|
||||
}
|
||||
}).collect::<Vec<_>>();
|
||||
@@ -135,8 +183,8 @@ fn main() -> ExitCode {
|
||||
match options {
|
||||
Ok(f) => return f,
|
||||
Err(e) => {
|
||||
eprintln!("{}: {}: {}", argv[0], file, e.strerror());
|
||||
exit(EX_IOERR);
|
||||
let _ = err(&(argv[0].clone() + ": " + file), e, None);
|
||||
exit(EX_IOERR.into());
|
||||
},
|
||||
};
|
||||
}).collect::<Vec<_>>();
|
||||
@@ -160,21 +208,19 @@ fn main() -> ExitCode {
|
||||
for file in inputs {
|
||||
for byte in file.bytes().map(|b| {
|
||||
b.unwrap_or_else(|e| {
|
||||
eprintln!("{}: {}", argv[0], e.strerror());
|
||||
exit(EX_IOERR);
|
||||
let _ = err(&argv[0], e, None);
|
||||
exit(EX_IOERR.into());
|
||||
})
|
||||
}) {
|
||||
for out in &mut outputs {
|
||||
if let Err(e) = out.write(&[byte]) {
|
||||
eprintln!("{}: {}", argv[0], e.strerror());
|
||||
return ExitCode::from(EX_IOERR as u8);
|
||||
return err(&argv[0], e, Some(EX_IOERR));
|
||||
}
|
||||
|
||||
if u {
|
||||
/* immediately flush the output for -u */
|
||||
if let Err(e) = out.flush() {
|
||||
eprintln!("{}: {}", argv[0], e.strerror());
|
||||
return ExitCode::from(EX_IOERR as u8);
|
||||
return err(&argv[0], e, Some(EX_IOERR));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
11
src/npc.c
11
src/npc.c
@@ -19,8 +19,8 @@
|
||||
|
||||
#include <stdio.h> /* fprintf(3), fputs(3), getc(3), perror(3), putc(3), stdin,
|
||||
* stdout, EOF */
|
||||
#include <sysexits.h> /* EX_IOERR, EX_OK, EX_USAGE */
|
||||
#include <unistd.h> /* getopt(3) */
|
||||
#include <sysexits.h> /* EX_IOERR, EX_OK, EX_OSERR, EX_USAGE */
|
||||
#include <unistd.h> /* NULL, getopt(3), pledge(2), unveil(2) */
|
||||
|
||||
char *program_name = "npc";
|
||||
|
||||
@@ -43,6 +43,13 @@ int main(int argc, char *argv[]) {
|
||||
char showend = 0; /* print a dollar sign before each newline */
|
||||
char showtab = 0; /* prints tab characters in caret notation */
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
if (pledge("stdio unveil", NULL) == -1 || unveil(NULL, NULL)) {
|
||||
perror(argv[0] == NULL ? program_name : argv[0]);
|
||||
return EX_OSERR;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (argc > 0) {
|
||||
program_name = argv[0];
|
||||
|
||||
|
||||
184
src/rpn.rs
184
src/rpn.rs
@@ -46,7 +46,7 @@ use std::{
|
||||
collections::VecDeque,
|
||||
env::args,
|
||||
fmt::{ self, Display, Formatter },
|
||||
io::stdin,
|
||||
io::{ Error, Write, stdin, stdout },
|
||||
process::ExitCode,
|
||||
};
|
||||
|
||||
@@ -54,7 +54,13 @@ use CalcType::*;
|
||||
|
||||
extern crate sysexits;
|
||||
|
||||
use sysexits::EX_DATAERR;
|
||||
use sysexits::{ EX_DATAERR, EX_IOERR };
|
||||
|
||||
#[cfg(target_os="openbsd")] use sysexits::EX_OSERR;
|
||||
#[cfg(target_os="openbsd")] extern crate strerror;
|
||||
#[cfg(target_os="openbsd")] extern crate openbsd;
|
||||
#[cfg(target_os="openbsd")] use strerror::StrError;
|
||||
#[cfg(target_os="openbsd")] use openbsd::{ Promises, pledge, unveil };
|
||||
|
||||
#[derive(Clone, PartialEq, PartialOrd, Debug)]
|
||||
/* enum CalcType is a type containing operations used in the calculator */
|
||||
@@ -114,12 +120,46 @@ impl Display for CalcType {
|
||||
#[derive(Debug, Clone)]
|
||||
struct EvaluationError {
|
||||
message: String,
|
||||
code: i32,
|
||||
code: u8,
|
||||
}
|
||||
|
||||
/* I’m no math nerd but I want the highest possible approximation of 0.9
|
||||
* repeating and it seems this can give it to me */
|
||||
const PRECISION_MOD: f64 = 0.9 + f64::EPSILON * 100.0;
|
||||
impl StrError for EvaluationError {
|
||||
fn strerror(&self) -> String {
|
||||
self.message.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn err<T: StrError>(argv0: &String, e: &T, code: Option<u8>) -> ExitCode {
|
||||
eprintln!("{}: {}", argv0, e.strerror());
|
||||
ExitCode::from(code.unwrap_or(1 /* unknown error */))
|
||||
}
|
||||
|
||||
fn operate(
|
||||
mut stack: VecDeque<f64>,
|
||||
op: CalcType,
|
||||
) -> Result<VecDeque<f64>, EvaluationError> {
|
||||
let vals = (stack.pop_back(), stack.pop_back());
|
||||
|
||||
if let (Some(x), Some(y)) = vals {
|
||||
match op {
|
||||
Add => stack.push_back(y + x),
|
||||
Subtract => stack.push_back(y - x),
|
||||
Multiply => stack.push_back(y * x),
|
||||
Divide => stack.push_back(y / x),
|
||||
Power => stack.push_back(y.powf(x)),
|
||||
Floor => stack.push_back((y / x).floor()),
|
||||
Modulo => stack.push_back(y % x),
|
||||
_ => {},
|
||||
};
|
||||
} else {
|
||||
return Err(EvaluationError {
|
||||
message: format!("{}: unexpected operation", op),
|
||||
code: EX_DATAERR,
|
||||
})
|
||||
}
|
||||
|
||||
Ok(stack)
|
||||
}
|
||||
|
||||
fn eval(
|
||||
input: &str,
|
||||
@@ -139,6 +179,7 @@ fn eval(
|
||||
.rev()
|
||||
.map(|t| CalcType::from(t))
|
||||
.collect();
|
||||
|
||||
let mut ops: VecDeque<CalcType> = VecDeque::new();
|
||||
|
||||
while let Some(n) = toks.pop_back() {
|
||||
@@ -146,36 +187,15 @@ fn eval(
|
||||
Val(v) => stack.push_back(v),
|
||||
Invalid(i) => {
|
||||
return Err(EvaluationError {
|
||||
message: format!("{}: Invalid token", i),
|
||||
message: format!("{}: invalid token", i),
|
||||
code: EX_DATAERR,
|
||||
})
|
||||
},
|
||||
op => {
|
||||
ops.push_back(op.clone());
|
||||
oper = true;
|
||||
|
||||
let vals = (
|
||||
stack.pop_back(),
|
||||
stack.pop_back(),
|
||||
);
|
||||
|
||||
if let (Some(x), Some(y)) = vals {
|
||||
match op {
|
||||
Add => stack.push_back(y + x),
|
||||
Subtract => stack.push_back(y - x),
|
||||
Multiply => stack.push_back(y * x),
|
||||
Divide => stack.push_back(y / x),
|
||||
Power => stack.push_back(y.powf(x)),
|
||||
Floor => stack.push_back((y / x).floor()),
|
||||
Modulo => stack.push_back(y % x),
|
||||
_ => {},
|
||||
};
|
||||
} else {
|
||||
return Err(EvaluationError {
|
||||
message: format!("{}: Unexpected operation", op),
|
||||
code: EX_DATAERR,
|
||||
})
|
||||
}
|
||||
oper = true; /* this is an operation */
|
||||
return operate(stack, op).map(|s| (s, oper));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -184,42 +204,46 @@ fn eval(
|
||||
}
|
||||
|
||||
/* Round a float to the given precision level */
|
||||
fn round_precise(value: &f64, precision: usize) -> f64 {
|
||||
let multiplier = 10_f64.powi(precision as i32);
|
||||
fn round_precise(value: &f64) -> f64 {
|
||||
/* Set floating-point precision for correcting rounding errors based on
|
||||
* machine epsilon */
|
||||
let precision = (-f64::EPSILON.log10()).floor() as i32;
|
||||
let multiplier = 10_f64.powi(precision);
|
||||
|
||||
(value * multiplier).round() / multiplier
|
||||
}
|
||||
|
||||
/* print the stack and let the caller know if evaluation should continue */
|
||||
fn unstack(stack: VecDeque<f64>, op: bool) -> Result<bool, Error> {
|
||||
if let Some(val) = stack.iter().last() {
|
||||
if !op { return Ok(true); }
|
||||
|
||||
let out = round_precise(val).to_string() + &'\n'.to_string();
|
||||
|
||||
return stdout().write_all(out.as_bytes()).map(|_| true);
|
||||
} else {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv = args().collect::<Vec<String>>();
|
||||
|
||||
#[cfg(target_os="openbsd")] {
|
||||
let promises = Promises::new("stdio unveil");
|
||||
if let Err(e) = pledge(Some(promises), Some(Promises::default())) {
|
||||
return err(&argv[0], &e, Some(EX_OSERR));
|
||||
}
|
||||
|
||||
if let Err(e) = unveil(None, None) {
|
||||
return err(&argv[0], &e, Some(EX_OSERR));
|
||||
}
|
||||
}
|
||||
|
||||
let mut stack = VecDeque::new();
|
||||
let mut buf = String::new();
|
||||
/* Set floating-point precision for correcting rounding errors based on
|
||||
* machine epsilon */
|
||||
let precision = (-f64::EPSILON.log10() * PRECISION_MOD).ceil() as usize;
|
||||
|
||||
if argv.get(1).is_none() { /* read from stdin */
|
||||
while let Ok(_) = stdin().read_line(&mut buf) {
|
||||
match eval(&buf.trim(), stack) {
|
||||
Ok(s) => {
|
||||
buf.clear();
|
||||
stack = s.0.clone();
|
||||
|
||||
let val = match stack.iter().last() {
|
||||
Some(v) => v,
|
||||
None => break,
|
||||
};
|
||||
|
||||
if s.1 == false { continue; }
|
||||
|
||||
println!("{}", round_precise(val, precision).to_string());
|
||||
},
|
||||
Err(err) => {
|
||||
eprintln!("{}: {}", argv[0], err.message);
|
||||
return ExitCode::from(err.code as u8);
|
||||
},
|
||||
};
|
||||
}
|
||||
} else { /* read from argv */
|
||||
if argv.get(1).is_some() { /* read expressions from argv */
|
||||
/* join argv into an owned String joined by spaces minus argv[0] */
|
||||
let input = argv
|
||||
.iter()
|
||||
@@ -230,20 +254,44 @@ fn main() -> ExitCode {
|
||||
|
||||
match eval(&input, stack) {
|
||||
Ok(s) => {
|
||||
stack = s.0.clone();
|
||||
/* we can ignore the return value of unstack() because we are
|
||||
* not continually evaluating from stdin */
|
||||
if let Err(e) = unstack(s.0.clone(), s.1.clone()) {
|
||||
return err(&argv[0], &e, Some(EX_IOERR));
|
||||
}
|
||||
|
||||
let val = match stack.iter().last() {
|
||||
Some(v) => v,
|
||||
None => return ExitCode::SUCCESS,
|
||||
};
|
||||
|
||||
println!("{}", round_precise(val, precision).to_string())
|
||||
return ExitCode::SUCCESS;
|
||||
},
|
||||
Err(err) => {
|
||||
eprintln!("{}: {}", argv[0], err.message);
|
||||
return ExitCode::from(err.code as u8);
|
||||
Err(e) => {
|
||||
return err(&argv[0], &e, Some(e.code));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/* else, read from stdin */
|
||||
loop { /* take input until EOF */
|
||||
if let Err(e) = stdin().read_line(&mut buf) {
|
||||
return err(&argv[0], &e, Some(EX_IOERR));
|
||||
}
|
||||
|
||||
match eval(&buf.trim(), stack) {
|
||||
Ok(s) => {
|
||||
buf.clear();
|
||||
stack = s.0.clone(); /* out with the old, in with the new */
|
||||
|
||||
match unstack(s.0, s.1) {
|
||||
Ok(b) if b => continue,
|
||||
Ok(_) => break,
|
||||
Err(e) => {
|
||||
return err(&argv[0], &e, Some(EX_IOERR))
|
||||
},
|
||||
};
|
||||
},
|
||||
Err(e) => {
|
||||
return err(&argv[0], &e, Some(e.code));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
34
src/scrut.c
34
src/scrut.c
@@ -17,18 +17,21 @@
|
||||
* along with this program. If not, see https://www.gnu.org/licenses/.
|
||||
*/
|
||||
|
||||
#include <assert.h> /* assert(3) */
|
||||
#include <stdio.h> /* fprintf(3), stderr, NULL */
|
||||
#include <stdlib.h> /* EXIT_FAILURE, EXIT_SUCCESS */
|
||||
#include <string.h> /* memset(3), strchr(3) */
|
||||
#include <sysexits.h> /* EX_USAGE */
|
||||
#include <unistd.h> /* access(3), getopt(3), F_OK, R_OK, W_OK, X_OK */
|
||||
#include <sysexits.h> /* EX_OSERR, EX_USAGE */
|
||||
#include <unistd.h> /* access(3), getopt(3), pledge(2), unveil(2), F_OK, R_OK,
|
||||
* W_OK, X_OK */
|
||||
#include <sys/stat.h> /* lstat(3), stat struct, S_ISBLK, S_ISCHR, S_ISDIR,
|
||||
* S_ISFIFO, S_ISGID, S_ISREG, S_ISLNK, S_ISSOCK,
|
||||
* S_ISUID, S_ISVTX */
|
||||
|
||||
char *program_name = "scrut";
|
||||
#define OPTS "bcdefgkprsuwxLS"
|
||||
static char *opts = OPTS;
|
||||
/* this is an array so main:sel's size can be known at compile time */
|
||||
static char opts[] = OPTS;
|
||||
|
||||
static int
|
||||
usage(char *argv0) {
|
||||
@@ -40,7 +43,16 @@ usage(char *argv0) {
|
||||
int main(int argc, char *argv[]) {
|
||||
char sel[(sizeof opts) / (sizeof *opts)];
|
||||
|
||||
if (argc < 2) { return usage(argv[0] == NULL ? program_name : argv[0]); }
|
||||
program_name = argv[0] == NULL ? program_name : argv[0];
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
if (pledge("rpath stdio unveil", NULL) == -1) {
|
||||
perror(program_name);
|
||||
return EX_OSERR;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (argc < 2) { return usage(program_name); }
|
||||
|
||||
{ /* option parsing */
|
||||
char *p;
|
||||
@@ -48,7 +60,10 @@ int main(int argc, char *argv[]) {
|
||||
memset(sel, '\0', sizeof sel);
|
||||
for (int c; (c = getopt(argc, argv, opts)) != -1;) {
|
||||
if ((p = strchr(opts, c)) == NULL) { return usage(argv[0]); }
|
||||
else { sel[p - opts] = c; }
|
||||
else {
|
||||
assert(p - opts < sizeof sel / sizeof *sel); /* bounds check */
|
||||
sel[p - opts] = c;
|
||||
}
|
||||
}
|
||||
|
||||
/* straighten out selections; permute out nulls */
|
||||
@@ -63,9 +78,16 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
if (optind == argc) { return usage(argv[0]); }
|
||||
|
||||
for (argv += optind ; *argv != NULL; ++argv) {
|
||||
for (argv += optind ; *argv != NULL; argv = &argv[1]) {
|
||||
struct stat buf;
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
if (unveil(*argv, "r") == -1) {
|
||||
perror(program_name);
|
||||
return EX_OSERR;
|
||||
}
|
||||
#endif
|
||||
|
||||
if(access(*argv, F_OK) != 0 || lstat(*argv, &buf) == -1) {
|
||||
return EXIT_FAILURE; /* doesn't exist or isn't stattable */
|
||||
}
|
||||
|
||||
18
src/str.c
18
src/str.c
@@ -19,10 +19,14 @@
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stddef.h> /* NULL */
|
||||
#include <stdio.h> /* fprintf(3) */
|
||||
#include <stdio.h> /* fprintf(3), perror(3) */
|
||||
#include <stdlib.h> /* size_t, EXIT_FAILURE */
|
||||
#include <string.h> /* strcmp(3) */
|
||||
#include <sysexits.h> /* EX_USAGE */
|
||||
#include <sysexits.h> /* EX_OSERR, EX_USAGE */
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
# include <unistd.h> /* pledge(2), unveil(2) */
|
||||
#endif
|
||||
|
||||
char *program_name = "str";
|
||||
|
||||
@@ -55,8 +59,16 @@ usage(char *argv0) {
|
||||
int main(int argc, char *argv[]) {
|
||||
size_t ctype; // selected from ctypes.h; index of ctype
|
||||
int retval; // initially fail but becomes success on the first valid char
|
||||
program_name = argv[0] == NULL ? program_name : argv[0];
|
||||
|
||||
if (argc < 3) { return usage(argv[0] == NULL ? program_name : argv[0]); }
|
||||
#ifdef __OpenBSD__
|
||||
if (pledge("stdio unveil", NULL) == -1 || unveil(NULL, NULL) == -1) {
|
||||
perror(program_name);
|
||||
return EX_OSERR;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (argc < 3) { return usage(program_name); }
|
||||
|
||||
for ( /* iterate ctypes */
|
||||
ctype = 0;
|
||||
|
||||
18
src/strcmp.c
18
src/strcmp.c
@@ -16,13 +16,25 @@
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see https://www.gnu.org/licenses/.
|
||||
*/
|
||||
#include <stdio.h> /* fprintf(3), stderr */
|
||||
#include <sysexits.h> /* EX_OK, EX_USAGE */
|
||||
#include <stdio.h> /* fprintf(3), perror(3), stderr */
|
||||
#include <sysexits.h> /* EX_OK, EX_OSERR, EX_USAGE */
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
# include <unistd.h> /* pledge(2), unveil(2) */
|
||||
#endif
|
||||
|
||||
char *program_name = "strcmp";
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
int i;
|
||||
unsigned int i;
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
if (pledge("stdio unveil", NULL) == -1 || unveil(NULL, NULL) == -1) {
|
||||
perror(argv[0] == NULL ? program_name : argv[0]);
|
||||
|
||||
return EX_OSERR;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (argc < 3) {
|
||||
(void)fprintf(
|
||||
|
||||
32
src/swab.rs
32
src/swab.rs
@@ -32,23 +32,33 @@ use getopt::GetOpt;
|
||||
use sysexits::{ EX_IOERR, EX_OK, EX_OSERR, EX_USAGE };
|
||||
use strerror::StrError;
|
||||
|
||||
fn oserr(argv0: &str, e: Error) -> ExitCode {
|
||||
eprintln!("{}: {}", argv0, e.strerror());
|
||||
ExitCode::from(EX_OSERR as u8)
|
||||
}
|
||||
#[cfg(target_os="openbsd")] extern crate openbsd;
|
||||
#[cfg(target_os="openbsd")] use openbsd::{ Promises, pledge, unveil };
|
||||
|
||||
fn ioerr(argv0: &str, e: Error) -> ExitCode {
|
||||
fn err(argv0: &str, e: Error, code: u8) -> ExitCode {
|
||||
eprintln!("{}: {}", argv0, e.strerror());
|
||||
ExitCode::from(EX_IOERR as u8)
|
||||
ExitCode::from(code)
|
||||
}
|
||||
|
||||
fn usage(s: &str) -> ExitCode {
|
||||
eprintln!("Usage: {} [-w word_size]", s);
|
||||
ExitCode::from(EX_USAGE as u8)
|
||||
ExitCode::from(EX_USAGE)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv = args().collect::<Vec<String>>();
|
||||
|
||||
#[cfg(target_os="openbsd")] {
|
||||
let promises = Promises::new("stdio unveil");
|
||||
if let Err(e) = pledge(Some(promises), Some(Promises::default())) {
|
||||
return err(&argv[0], e, EX_OSERR);
|
||||
}
|
||||
|
||||
if let Err(e) = unveil(None, None) {
|
||||
return err(&argv[0], e, EX_OSERR);
|
||||
}
|
||||
}
|
||||
|
||||
let mut buf: Vec<u8> = Vec::new(); // holds the sequence getting swabbed
|
||||
let mut input = stdin();
|
||||
let mut output = stdout().lock();
|
||||
@@ -76,22 +86,22 @@ fn main() -> ExitCode {
|
||||
|
||||
loop {
|
||||
match input.read(&mut buf) {
|
||||
Ok(0) => break ExitCode::from(EX_OK as u8), // read nothing; bye
|
||||
Ok(0) => break ExitCode::from(EX_OK), // read nothing; bye
|
||||
Ok(v) if v == wordsize => { // read full block; swab
|
||||
let (left, right) = buf.split_at(v/2);
|
||||
|
||||
if let Err(e) = output.write(&right)
|
||||
.and_then(|_| output.write(&left)) {
|
||||
break ioerr(&argv[0], e);
|
||||
break err(&argv[0], e, EX_IOERR);
|
||||
}
|
||||
|
||||
},
|
||||
Ok(v) => { // partial read; partially write
|
||||
if let Err(e) = output.write(&buf[..v]) {
|
||||
break ioerr(&argv[0], e);
|
||||
break err(&argv[0], e, EX_IOERR);
|
||||
}
|
||||
},
|
||||
Err(e) => break oserr(&argv[0], e)
|
||||
Err(e) => break err(&argv[0], e, EX_OSERR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
14
src/true.c
14
src/true.c
@@ -1,9 +1,19 @@
|
||||
/*
|
||||
* Copyright (c) 2023 Emma Tebibyte <emma@tebibyte.media>
|
||||
* Copyright (c) 2023–2024 Emma Tebibyte <emma@tebibyte.media>
|
||||
* Copyright (c) 2024 DTB <trinity@trinity.moe>
|
||||
* SPDX-License-Identifier: CC0
|
||||
*
|
||||
* This work is marked with CC0 1.0. To view a copy of this license, visit
|
||||
* <http://creativecommons.org/publicdomain/zero/1.0>.
|
||||
*/
|
||||
|
||||
int main() {}
|
||||
#ifdef __OpenBSD__
|
||||
# include <unistd.h> /* NULL, pledge(2), unveil(2) */
|
||||
#endif
|
||||
|
||||
int main(void) {
|
||||
#ifdef __OpenBSD__
|
||||
(void)pledge(NULL, NULL);
|
||||
(void)unveil(NULL, NULL);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ dj_tests: dj_help dj_full dj_null # dj_skip_stdin
|
||||
dj_full: $(BIN)/dj /dev/full
|
||||
case "$$(uname)" in \
|
||||
Linux) \
|
||||
$(BIN)/dj -Hi /dev/zero -o /dev/full 2>&1 \
|
||||
! $(BIN)/dj -Hi /dev/zero -o /dev/full 2>&1 \
|
||||
| tee /dev/stderr \
|
||||
| xargs -I out test '1+0 > 0+0; 1024 > 0' = out \
|
||||
;; \
|
||||
|
||||
@@ -24,6 +24,7 @@ fop_fail: $(BIN)/fop
|
||||
! printf 'test\n' | $(BIN)/fop 1 cat
|
||||
! printf 'test\n' | $(BIN)/fop 'test' cat
|
||||
! printf 'test\n' | $(BIN)/fop -d'test' cat
|
||||
! $(BIN)/fop
|
||||
|
||||
.PHONY: fop_functionality
|
||||
fop_functionality: $(BIN)/fop
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
# notice are preserved. This file is offered as-is, without any warranty.
|
||||
|
||||
.PHONY: intcmp_tests
|
||||
intcmp_tests: intcmp_help intcmp_e intcmp_g intcmp_l intcmp_combined
|
||||
intcmp_tests: intcmp_help intcmp_none intcmp_e intcmp_g intcmp_l intcmp_combined
|
||||
|
||||
.PHONY: intcmp_help
|
||||
intcmp_help: $(BIN)/intcmp
|
||||
@@ -31,6 +31,10 @@ intcmp_help: $(BIN)/intcmp
|
||||
# the invocation. If this test failed, intcmp(1) would be confusing -l for -g,
|
||||
# so that would be a good place to start looking for bugs.
|
||||
|
||||
.PHONY: intcmp_none
|
||||
intcmp_none: $(BIN)/intcmp
|
||||
! $(BIN)/intcmp 1 2
|
||||
|
||||
.PHONY: intcmp_e
|
||||
intcmp_e: $(BIN)/intcmp
|
||||
$(BIN)/intcmp -e 3 3 3 # ==
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
# Copyright (c) 2024 E$(NAME)a Tebibyte <e$(NAME)a@tebibyte.media>
|
||||
# Copyright (c) 2024 Emma Tebibyte <emma@tebibyte.media>
|
||||
# SPDX-License-Identifier: FSFAP
|
||||
#
|
||||
# Copying and distribution of this file, with or without modification, are
|
||||
# permitted in any medium without royalty provided the copyright notice and this
|
||||
# notice are preserved. This file is offered as-is, without any warranty.
|
||||
|
||||
NAME = mm
|
||||
TARGET = $(NAME)_tests
|
||||
BINARY = $(BIN)/$(NAME)
|
||||
|
||||
.PHONY: mm_tests
|
||||
mm_tests: mm_args mm_help mm_stderr
|
||||
mm_tests: mm_args mm_help mm_stderr mm_remaining mm_remaining_options
|
||||
|
||||
.PHONY: mm_none
|
||||
mm_none: $(BIN)/mm
|
||||
test "$$(printf 'meow\n' | $(BIN)/mm)" = meow
|
||||
|
||||
.PHONY: mm_args
|
||||
# mm(1) will error if positional arguments are given without -i or -o
|
||||
@@ -24,4 +24,17 @@ mm_help: $(BIN)/mm
|
||||
.PHONY: mm_stderr
|
||||
# check if stderr is empty upon specifying -e
|
||||
mm_stderr: $(BIN)/mm
|
||||
! test "$$(printf 'test\n' | $(BIN)/mm -e 2>&1 >/dev/null)" = "test"
|
||||
test "$$(printf 'test\n' | $(BIN)/mm -e 2>&1 >/dev/null )" = "test"
|
||||
|
||||
.PHONY: mm_remaining
|
||||
# check to make sure remaining arguments are used
|
||||
mm_remaining: $(BIN)/mm
|
||||
test "$$($(BIN)/mm -i README COPYING)" = "$$(cat README COPYING)"
|
||||
$(BIN)/mm -i README -o /tmp/mm_test0 /tmp/mm_test1
|
||||
diff /tmp/mm_test0 /tmp/mm_test1
|
||||
|
||||
.PHONY: mm_remaining_options
|
||||
# check to make sure mm -i with trailing arguments interprets -o as one
|
||||
mm_remaining_options:
|
||||
! $(BIN)/mm -i README COPYING -o - 2>&1 | cut -d: -f2 \
|
||||
| xargs test " -o" =
|
||||
|
||||
@@ -32,11 +32,29 @@ npc_ascii: npc_ascii_controls npc_ascii_symbols npc_ascii_uppers # \
|
||||
.PHONY: npc_ascii_controls
|
||||
# (control characters)
|
||||
npc_ascii_controls:
|
||||
# The following test prints the bytes 0x00 (inclusive) through 0x20
|
||||
# (exclusive) and pipes them through npc(1). npc(1) should then replace all
|
||||
# non-printing, non-space (in the isspace(3p) sense) characters with their
|
||||
# graphical carat-char counterparts (see the npc(1) man page). The head(1p)
|
||||
# invocation then strips off everything past the first line (or past the
|
||||
# first newline byte, 0x0A) and xargs(1p) is used to test(1p) the output
|
||||
# against the known good answer.
|
||||
|
||||
# Immediately before that newline, 0x09 is printed - in ASCII, the
|
||||
# horizontal tab. If xargs' -I option is used, tr(1p) should used to delete
|
||||
# that tab. If the tab is left as part of input, OpenBSD's xargs(1)
|
||||
# implementation has been observed to strip it along with the other
|
||||
# trailing whitespace (the newline), but Busybox's and GNU's xargs(1)
|
||||
# implementations have been observed to leave the tab in. All three
|
||||
# implementations strip off the trailing tab if `-I` is not used. The POSIX
|
||||
# specification for `-I` is ambiguous as to which behavior is correct.
|
||||
# This comment is the result of much bewilderment and debugging.
|
||||
|
||||
# ASCII 0x00 to 0x0a (before the newline, due to xargs(1p) issues)
|
||||
awk 'BEGIN{ for (i = 0; i < 32; ++i) printf("%c", i); }' \
|
||||
| $(BIN)/npc \
|
||||
| head -n 1 \
|
||||
| xargs -I out test "^@^A^B^C^D^E^F^G^H" = out
|
||||
| xargs test "^@^A^B^C^D^E^F^G^H" =
|
||||
|
||||
# ASCII 0x0a (otherwise the head|tail sequence won't work) to 0x1f
|
||||
awk 'BEGIN{ for (i = 0; i < 32; ++i) printf("%c", i); print }' \
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# notice are preserved. This file is offered as-is, without any warranty.
|
||||
|
||||
.PHONY: rpn_tests
|
||||
rpn_tests: rpn_help rpn_add
|
||||
rpn_tests: rpn_help rpn_add rpn_sub rpn_mul rpn_div rpn_mod rpn_flr rpn_stdin
|
||||
|
||||
.PHONY: rpn_help
|
||||
rpn_help: $(BIN)/rpn
|
||||
@@ -20,7 +20,7 @@ rpn_add: $(BIN)/rpn
|
||||
.PHONY: rpn_sub
|
||||
rpn_sub: $(BIN)/rpn
|
||||
test "$$($(BIN)/rpn 23 5 -)" -eq 18
|
||||
test "$$($(BIN)/rpn 0.3 0.1)" = 0.2
|
||||
test "$$($(BIN)/rpn 0.3 0.1 -)" = 0.2
|
||||
|
||||
.PHONY: rpn_mul
|
||||
rpn_mul: $(BIN)/rpn
|
||||
@@ -30,7 +30,7 @@ rpn_mul: $(BIN)/rpn
|
||||
.PHONY: rpn_div
|
||||
rpn_div: $(BIN)/rpn
|
||||
test "$$($(BIN)/rpn 12 5 /)" = 2.4
|
||||
test "$$($(BIN)/rpn 3 0 /)" -eq inf
|
||||
test "$$($(BIN)/rpn 3 0 /)" = inf
|
||||
|
||||
.PHONY: rpn_mod
|
||||
rpn_mod: $(BIN)/rpn
|
||||
@@ -41,3 +41,8 @@ rpn_mod: $(BIN)/rpn
|
||||
rpn_flr: $(BIN)/rpn
|
||||
test "$$($(BIN)/rpn 12 5 //)" -eq 2
|
||||
test "$$($(BIN)/rpn 9 4 //)" -eq 2
|
||||
|
||||
# done last because all operations have been tested
|
||||
.PHONY: rpn_stdin
|
||||
rpn_stdin: $(BIN)/rpn
|
||||
test "$$(printf '1\n2\n+\n3\n-\n' | $(BIN)/rpn | tail -n1)" -eq 0
|
||||
|
||||
Reference in New Issue
Block a user