mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
tools: rngit, rnx, and the rsg helpers build on Windows
This commit is contained in:
1 parent
21a22cbd2d
commit
2aee96ea4f
17 files changed
+305
-103
No files matched your search
Generated
+1
@@ -1881,6 +1881,7 @@ dependencies = [
|
||||
"base64",
|
||||
"clap",
|
||||
"hex",
|
||||
"libc",
|
||||
"nix 0.29.0",
|
||||
"rmpv",
|
||||
"rns-identity",
|
||||
|
||||
@@ -344,6 +344,17 @@
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "libc",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(windows)",
|
||||
"requirement": "^0.2",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -23,6 +23,9 @@ hex = { workspace = true }
|
||||
rns-wire = { workspace = true, features = ["std"] }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
|
||||
@@ -159,24 +159,15 @@ fn first_chars(text: &str, n: usize) -> String {
|
||||
|
||||
/// `time.strftime(fmt, time.localtime(ts))` for the two formats used here.
|
||||
fn strftime(ts: i64, seconds: bool) -> String {
|
||||
let time = ts as nix::libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<nix::libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_r is reentrant.
|
||||
if unsafe { nix::libc::localtime_r(&time, tm.as_mut_ptr()) }.is_null() {
|
||||
let Some(tm) = crate::platform::localtime(ts) else {
|
||||
return String::new();
|
||||
}
|
||||
// SAFETY: localtime_r filled `tm` when it returned non-null.
|
||||
let tm = unsafe { tm.assume_init() };
|
||||
};
|
||||
let mut out = format!(
|
||||
"{:04}-{:02}-{:02} {:02}:{:02}",
|
||||
tm.tm_year + 1900,
|
||||
tm.tm_mon + 1,
|
||||
tm.tm_mday,
|
||||
tm.tm_hour,
|
||||
tm.tm_min
|
||||
tm.year, tm.month, tm.day, tm.hour, tm.minute
|
||||
);
|
||||
if seconds {
|
||||
out.push_str(&format!(":{:02}", tm.tm_sec));
|
||||
out.push_str(&format!(":{:02}", tm.second));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -142,24 +142,15 @@ fn timestamp(value: Option<&Value>) -> f64 {
|
||||
|
||||
/// `time.strftime("%Y-%m-%d %H:%M[:%S]", time.localtime(ts))`.
|
||||
fn strftime(ts: f64, seconds: bool) -> String {
|
||||
let time = ts.floor() as nix::libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<nix::libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_r is reentrant.
|
||||
if unsafe { nix::libc::localtime_r(&time, tm.as_mut_ptr()) }.is_null() {
|
||||
let Some(tm) = crate::platform::localtime(ts.floor() as i64) else {
|
||||
return String::new();
|
||||
}
|
||||
// SAFETY: localtime_r filled `tm` when it returned non-null.
|
||||
let tm = unsafe { tm.assume_init() };
|
||||
};
|
||||
let mut out = format!(
|
||||
"{:04}-{:02}-{:02} {:02}:{:02}",
|
||||
tm.tm_year + 1900,
|
||||
tm.tm_mon + 1,
|
||||
tm.tm_mday,
|
||||
tm.tm_hour,
|
||||
tm.tm_min
|
||||
tm.year, tm.month, tm.day, tm.hour, tm.minute
|
||||
);
|
||||
if seconds {
|
||||
out.push_str(&format!(":{:02}", tm.tm_sec));
|
||||
out.push_str(&format!(":{:02}", tm.second));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -211,10 +202,7 @@ fn run_editor(
|
||||
.status()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !status.success() {
|
||||
let code = status.code().unwrap_or_else(|| {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
-status.signal().unwrap_or(0)
|
||||
});
|
||||
let code = crate::platform::return_code(status);
|
||||
let _ = writeln!(out, "Editor exited with error code {code}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return Ok(None);
|
||||
|
||||
@@ -6,6 +6,7 @@ pub mod highlight;
|
||||
pub mod md2micron;
|
||||
pub mod media;
|
||||
pub mod pages;
|
||||
mod platform;
|
||||
pub mod remote_helper;
|
||||
pub mod server;
|
||||
pub mod util;
|
||||
@@ -85,6 +85,7 @@ static WINNER: Mutex<Option<&'static str>> = Mutex::new(None);
|
||||
static NO_BACKEND_LOGGED: Mutex<bool> = Mutex::new(false);
|
||||
|
||||
/// `shutil.which`: an executable file of that name on `PATH`.
|
||||
#[cfg(unix)]
|
||||
pub fn which(tool: &str) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
@@ -96,6 +97,27 @@ pub fn which(tool: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// `shutil.which` on Windows: a file of that name on `PATH`, tried with each
|
||||
/// `PATHEXT` extension unless it already ends in one.
|
||||
#[cfg(not(unix))]
|
||||
pub fn which(tool: &str) -> bool {
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
};
|
||||
let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
|
||||
let extensions: Vec<&str> = pathext.split(';').filter(|e| !e.is_empty()).collect();
|
||||
let lower = tool.to_ascii_lowercase();
|
||||
let names: Vec<String> = if extensions
|
||||
.iter()
|
||||
.any(|e| lower.ends_with(&e.to_ascii_lowercase()))
|
||||
{
|
||||
vec![tool.to_string()]
|
||||
} else {
|
||||
extensions.iter().map(|e| format!("{tool}{e}")).collect()
|
||||
};
|
||||
std::env::split_paths(&path).any(|dir| names.iter().any(|name| dir.join(name).is_file()))
|
||||
}
|
||||
|
||||
/// `_selected_backend` for a forced name, a tool lookup and the previous
|
||||
/// winner. A forced name whose tool is absent selects nothing.
|
||||
pub fn select_backend(
|
||||
|
||||
@@ -356,10 +356,9 @@ impl PageNode {
|
||||
|
||||
/// `get_template`: `<templates>/<name>.mu`, run when executable.
|
||||
fn get_template(&self, name: &str) -> Option<String> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = self.templates_dir.join(format!("{name}.mu"));
|
||||
let meta = std::fs::metadata(&path).ok().filter(|m| m.is_file())?;
|
||||
if meta.permissions().mode() & 0o111 != 0 {
|
||||
if crate::platform::mode_executable(&meta) {
|
||||
let argv = [path.to_string_lossy().into_owned()];
|
||||
let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
|
||||
let output = std::process::Command::new(argv[0])
|
||||
@@ -724,34 +723,17 @@ pub(crate) fn prettysize(size: u64) -> String {
|
||||
rns_tools::format::prettysize(size as f64, "B")
|
||||
}
|
||||
|
||||
/// Local broken-down time, as `time.localtime`.
|
||||
fn local_tm(ts: f64) -> Option<nix::libc::tm> {
|
||||
let time = ts.floor() as nix::libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<nix::libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_r is reentrant.
|
||||
if unsafe { nix::libc::localtime_r(&time, tm.as_mut_ptr()) }.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: localtime_r filled `tm` when it returned non-null.
|
||||
Some(unsafe { tm.assume_init() })
|
||||
}
|
||||
|
||||
/// `time.strftime` with `%Y-%m-%d`, then `%H:%M` and `:%S` as asked.
|
||||
pub(crate) fn local_time(ts: f64, minutes: bool, seconds: bool) -> String {
|
||||
let Some(tm) = local_tm(ts) else {
|
||||
let Some(tm) = crate::platform::localtime(ts.floor() as i64) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut out = format!(
|
||||
"{:04}-{:02}-{:02}",
|
||||
tm.tm_year + 1900,
|
||||
tm.tm_mon + 1,
|
||||
tm.tm_mday
|
||||
);
|
||||
let mut out = format!("{:04}-{:02}-{:02}", tm.year, tm.month, tm.day);
|
||||
if minutes {
|
||||
out.push_str(&format!(" {:02}:{:02}", tm.tm_hour, tm.tm_min));
|
||||
out.push_str(&format!(" {:02}:{:02}", tm.hour, tm.minute));
|
||||
}
|
||||
if seconds {
|
||||
out.push_str(&format!(":{:02}", tm.tm_sec));
|
||||
out.push_str(&format!(":{:02}", tm.second));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
//! The Unix calls rngit makes, and what other platforms do in their place.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// `os.access(path, os.X_OK)`. Windows has no execute permission (upstream's
|
||||
/// check passes for any file there and the run then fails), so nothing is
|
||||
/// treated as executable and permission files and templates are read as text.
|
||||
pub(crate) fn executable(path: &Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Any execute bit in `meta`'s mode; never on platforms without one.
|
||||
pub(crate) fn mode_executable(meta: &std::fs::Metadata) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode() & 0o111 != 0
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = meta;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.makedirs(path, mode=0o755)`; the mode applies only on Unix, as in Python.
|
||||
pub(crate) fn create_dir_all_755(path: &Path) -> std::io::Result<()> {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
builder.mode(0o755);
|
||||
}
|
||||
builder.create(path)
|
||||
}
|
||||
|
||||
/// Copy the symbolic link `from` as a link at `to`, as `copytree(symlinks=True)`.
|
||||
/// Windows needs the link's kind, which follows what `from` names (a file
|
||||
/// link when it names nothing).
|
||||
pub(crate) fn copy_symlink(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
let target = std::fs::read_link(from)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(target, to)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if std::fs::metadata(from).is_ok_and(|m| m.is_dir()) {
|
||||
std::os::windows::fs::symlink_dir(target, to)
|
||||
} else {
|
||||
std::os::windows::fs::symlink_file(target, to)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A finished process's return code as Python reports it: negative for the
|
||||
/// signal that ended it on Unix.
|
||||
pub(crate) fn return_code(status: std::process::ExitStatus) -> i32 {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
status
|
||||
.code()
|
||||
.unwrap_or_else(|| -status.signal().unwrap_or(0))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
status.code().unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Broken-down local time, as `time.localtime`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct LocalTime {
|
||||
pub year: i32,
|
||||
/// 1 to 12.
|
||||
pub month: i32,
|
||||
pub day: i32,
|
||||
pub hour: i32,
|
||||
pub minute: i32,
|
||||
pub second: i32,
|
||||
}
|
||||
|
||||
/// `time.localtime(secs)`; `None` where the C library refuses the time.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn localtime(secs: i64) -> Option<LocalTime> {
|
||||
let time = secs as nix::libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<nix::libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_r is reentrant.
|
||||
if unsafe { nix::libc::localtime_r(&time, tm.as_mut_ptr()) }.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: localtime_r filled `tm` when it returned non-null.
|
||||
let tm = unsafe { tm.assume_init() };
|
||||
Some(LocalTime {
|
||||
year: tm.tm_year + 1900,
|
||||
month: tm.tm_mon + 1,
|
||||
day: tm.tm_mday,
|
||||
hour: tm.tm_hour,
|
||||
minute: tm.tm_min,
|
||||
second: tm.tm_sec,
|
||||
})
|
||||
}
|
||||
|
||||
/// `time.localtime(secs)` through the C runtime's `localtime_s`.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn localtime(secs: i64) -> Option<LocalTime> {
|
||||
let time = secs as libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_s writes only `tm`.
|
||||
if unsafe { libc::localtime_s(tm.as_mut_ptr(), &time) } != 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: localtime_s filled `tm` when it returned zero.
|
||||
let tm = unsafe { tm.assume_init() };
|
||||
Some(LocalTime {
|
||||
year: tm.tm_year + 1900,
|
||||
month: tm.tm_mon + 1,
|
||||
day: tm.tm_mday,
|
||||
hour: tm.tm_hour,
|
||||
minute: tm.tm_min,
|
||||
second: tm.tm_sec,
|
||||
})
|
||||
}
|
||||
|
||||
/// `time.mktime` of local midnight on `year-month-day`, a day past the month's
|
||||
/// end rolling over as C's `mktime` does.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn local_midnight(year: i32, month: i32, day: i32) -> i64 {
|
||||
// SAFETY: an all-zero `tm` is a valid value of the C struct.
|
||||
let mut tm: nix::libc::tm = unsafe { std::mem::zeroed() };
|
||||
tm.tm_year = year - 1900;
|
||||
tm.tm_mon = month - 1;
|
||||
tm.tm_mday = day;
|
||||
tm.tm_isdst = -1;
|
||||
// SAFETY: `tm` is initialised; mktime reads and normalises it in place.
|
||||
let secs = unsafe { nix::libc::mktime(&mut tm) };
|
||||
secs as i64
|
||||
}
|
||||
|
||||
/// `time.mktime` of local midnight on `year-month-day`: the Windows C runtime
|
||||
/// offers no `mktime` binding here, so the time is found from `localtime`,
|
||||
/// correcting once for an offset that differs at the result.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn local_midnight(year: i32, month: i32, day: i32) -> i64 {
|
||||
let wall = days_from_civil(i64::from(year), i64::from(month), i64::from(day)) * 86_400;
|
||||
let offset = |secs: i64| {
|
||||
localtime(secs).map_or(0, |t| {
|
||||
days_from_civil(i64::from(t.year), i64::from(t.month), i64::from(t.day)) * 86_400
|
||||
+ i64::from(t.hour) * 3600
|
||||
+ i64::from(t.minute) * 60
|
||||
+ i64::from(t.second)
|
||||
- secs
|
||||
})
|
||||
};
|
||||
let first = wall - offset(wall);
|
||||
wall - offset(first)
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 of a proleptic Gregorian date; linear in `day`.
|
||||
#[cfg(windows)]
|
||||
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
|
||||
let year = if month <= 2 { year - 1 } else { year };
|
||||
let era = year.div_euclid(400);
|
||||
let yoe = year - era * 400;
|
||||
let mp = (month + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + day - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe - 719_468
|
||||
}
|
||||
@@ -36,11 +36,13 @@ const LS_REMOTE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const SIZE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// What a stopped fetch gets to drop its lock files before it is killed.
|
||||
#[cfg(unix)]
|
||||
const STOP_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Process groups of the fetches in flight.
|
||||
#[cfg(unix)]
|
||||
static FETCHES: Mutex<Vec<nix::libc::pid_t>> = Mutex::new(Vec::new());
|
||||
|
||||
/// What a clone handler makes: a fork or a mirror.
|
||||
@@ -115,22 +117,27 @@ fn lossy(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn signal_group(pgid: nix::libc::pid_t, signal: nix::libc::c_int) {
|
||||
// SAFETY: killpg takes two integers and touches no memory of this process.
|
||||
unsafe { nix::libc::killpg(pgid, signal) };
|
||||
}
|
||||
|
||||
/// Stop the fetches in flight. They run in their own process groups, so a
|
||||
/// terminal interrupt of the node does not reach them.
|
||||
/// terminal interrupt of the node does not reach them. On Windows they share
|
||||
/// the node's console, so its interrupt reaches them directly.
|
||||
pub fn stop_fetches() {
|
||||
#[cfg(unix)]
|
||||
for pgid in FETCHES.lock().unwrap_or_else(|e| e.into_inner()).iter() {
|
||||
signal_group(*pgid, nix::libc::SIGTERM);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fetch's process group, listed in `FETCHES` while it runs.
|
||||
#[cfg(unix)]
|
||||
struct FetchGroup(nix::libc::pid_t);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl FetchGroup {
|
||||
fn new(child: &std::process::Child) -> Self {
|
||||
let pgid = child.id() as nix::libc::pid_t;
|
||||
@@ -150,6 +157,7 @@ impl FetchGroup {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for FetchGroup {
|
||||
fn drop(&mut self) {
|
||||
FETCHES
|
||||
@@ -159,6 +167,23 @@ impl Drop for FetchGroup {
|
||||
}
|
||||
}
|
||||
|
||||
/// Without process groups or signals, a stopped fetch is terminated at once;
|
||||
/// git may leave its lock files behind.
|
||||
#[cfg(not(unix))]
|
||||
struct FetchGroup;
|
||||
|
||||
#[cfg(not(unix))]
|
||||
impl FetchGroup {
|
||||
fn new(_child: &std::process::Child) -> Self {
|
||||
FetchGroup
|
||||
}
|
||||
|
||||
fn stop(&self, child: &mut std::process::Child) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of the files under `path`; what vanishes during the walk counts as nothing.
|
||||
fn dir_size(path: &Path) -> u64 {
|
||||
let mut total = 0;
|
||||
@@ -217,19 +242,20 @@ fn fetch_all(
|
||||
source: &str,
|
||||
limits: FetchLimits,
|
||||
) -> std::io::Result<Fetched> {
|
||||
use std::os::unix::process::CommandExt;
|
||||
let packs_before = pack_files(repo_path);
|
||||
let size_before = dir_size(repo_path);
|
||||
let grown = || dir_size(repo_path).saturating_sub(size_before);
|
||||
let mut child = Command::new("git")
|
||||
let mut command = Command::new("git");
|
||||
command
|
||||
.args(["fetch", source, "+refs/*:refs/*"])
|
||||
.current_dir(repo_path)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
// Its own group, so the transport helpers it starts are stopped with it.
|
||||
.process_group(0)
|
||||
.spawn()?;
|
||||
.stderr(Stdio::piped());
|
||||
// Its own group, so the transport helpers it starts are stopped with it.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::process::CommandExt::process_group(&mut command, 0);
|
||||
let mut child = command.spawn()?;
|
||||
let group = FetchGroup::new(&child);
|
||||
let mut stderr = child.stderr.take().expect("piped");
|
||||
let reader = std::thread::spawn(move || {
|
||||
@@ -492,7 +518,7 @@ pub fn sync_mirrors(repos: &RwLock<Repositories>, mirror_interval: i64, sync_loc
|
||||
fn move_dir(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
match std::fs::rename(from, to) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.raw_os_error() == Some(nix::libc::EXDEV) => {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
|
||||
copy_dir(from, to)?;
|
||||
std::fs::remove_dir_all(from)
|
||||
}
|
||||
@@ -508,7 +534,7 @@ fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
let target = to.join(entry.file_name());
|
||||
let kind = entry.file_type()?;
|
||||
if kind.is_symlink() {
|
||||
std::os::unix::fs::symlink(std::fs::read_link(entry.path())?, &target)?;
|
||||
crate::platform::copy_symlink(&entry.path(), &target)?;
|
||||
} else if kind.is_dir() {
|
||||
copy_dir(&entry.path(), &target)?;
|
||||
} else {
|
||||
@@ -662,14 +688,7 @@ fn clone_into(
|
||||
let tmpdir = tempfile::TempDir::new().map_err(|e| e.to_string())?;
|
||||
tracing::debug!("Created temporary directory {}", tmpdir.path().display());
|
||||
let temp_path = tmpdir.path().join(repo);
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
std::fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o755)
|
||||
.create(&temp_path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
crate::platform::create_dir_all_755(&temp_path).map_err(|e| e.to_string())?;
|
||||
let run = |args: &[&str]| git(Some(&temp_path), args).map_err(|e| e.to_string());
|
||||
|
||||
let result = run(&["init", "--bare"])?;
|
||||
|
||||
@@ -653,12 +653,7 @@ pub fn handle_create(
|
||||
);
|
||||
}
|
||||
};
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
if let Err(e) = std::fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o755)
|
||||
.create(&repository_path)
|
||||
{
|
||||
if let Err(e) = crate::platform::create_dir_all_755(&repository_path) {
|
||||
tracing::error!(
|
||||
"Error while creating repository {group}/{repo} for {}: {e}",
|
||||
identity_text(identity)
|
||||
|
||||
@@ -266,7 +266,7 @@ pub fn load_allowed_permissions(
|
||||
if !path.is_file() {
|
||||
return Ok((Permissions::default(), false));
|
||||
}
|
||||
let executable = nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok();
|
||||
let executable = crate::platform::executable(path);
|
||||
let (raw, dynamic) = if executable {
|
||||
let output = std::process::Command::new(path)
|
||||
.stdin(std::process::Stdio::inherit())
|
||||
|
||||
@@ -93,7 +93,7 @@ fn read_allowed(path: &Path, what: &str) -> Vec<u8> {
|
||||
/// The file part of the `set` step: refuse an executable resolver, then
|
||||
/// write through `<path>.tmp` and a rename. `Ok(None)` was written.
|
||||
fn write_allowed(path: &Path, content: &str) -> Option<Vec<u8>> {
|
||||
if nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok() {
|
||||
if crate::platform::executable(path) {
|
||||
return Some(status(
|
||||
RES_DISALLOWED,
|
||||
"Executable permission resolvers can only be modified node-side",
|
||||
|
||||
@@ -506,20 +506,10 @@ fn now_secs() -> i64 {
|
||||
|
||||
/// Local calendar time, as Python's `time.localtime`: year, month, day.
|
||||
fn local_date(secs: i64) -> (i64, i64, i64) {
|
||||
let time = secs as nix::libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<nix::libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_r is reentrant.
|
||||
let result = unsafe { nix::libc::localtime_r(&time, tm.as_mut_ptr()) };
|
||||
if result.is_null() {
|
||||
return (1970, 1, 1);
|
||||
match crate::platform::localtime(secs) {
|
||||
Some(t) => (i64::from(t.year), i64::from(t.month), i64::from(t.day)),
|
||||
None => (1970, 1, 1),
|
||||
}
|
||||
// SAFETY: localtime_r filled `tm` when it returned non-null.
|
||||
let tm = unsafe { tm.assume_init() };
|
||||
(
|
||||
i64::from(tm.tm_year) + 1900,
|
||||
i64::from(tm.tm_mon) + 1,
|
||||
i64::from(tm.tm_mday),
|
||||
)
|
||||
}
|
||||
|
||||
/// `_get_day` (`server.py`): `%Y-%m-%d` in local time.
|
||||
@@ -542,7 +532,7 @@ fn local_midnight(day: &str) -> Option<i64> {
|
||||
let mut parts = day.split('-');
|
||||
let field = |p: Option<&str>, max: usize| {
|
||||
p.filter(|s| !s.is_empty() && s.len() <= max && s.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|s| s.parse::<nix::libc::c_int>().ok())
|
||||
.and_then(|s| s.parse::<i32>().ok())
|
||||
};
|
||||
let year = field(parts.next(), 4)?;
|
||||
let month = field(parts.next(), 2).filter(|m| (1..=12).contains(m))?;
|
||||
@@ -550,13 +540,5 @@ fn local_midnight(day: &str) -> Option<i64> {
|
||||
if parts.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: an all-zero `tm` is a valid value of the C struct.
|
||||
let mut tm: nix::libc::tm = unsafe { std::mem::zeroed() };
|
||||
tm.tm_year = year - 1900;
|
||||
tm.tm_mon = month - 1;
|
||||
tm.tm_mday = mday;
|
||||
tm.tm_isdst = -1;
|
||||
// SAFETY: `tm` is initialised; mktime reads and normalises it in place.
|
||||
let secs = unsafe { nix::libc::mktime(&mut tm) };
|
||||
Some(secs as i64)
|
||||
Some(crate::platform::local_midnight(year, month, mday))
|
||||
}
|
||||
@@ -8082,6 +8082,7 @@ async fn resolve_discovery_inputs(
|
||||
config.interface_type.as_str(),
|
||||
"BackboneInterface" | "TCPServerInterface"
|
||||
) {
|
||||
#[cfg_attr(not(unix), allow(unused_mut))]
|
||||
let mut reachable_on = sanitize(config.reachable_on.as_deref()?);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -8112,6 +8113,7 @@ async fn resolve_discovery_inputs(
|
||||
/// (Discovery.py).
|
||||
// Plain comparisons let NaN through, as upstream's do.
|
||||
#[allow(clippy::manual_range_contains)]
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
fn parse_discovery_location(output: &str) -> Result<(f64, f64, f64), String> {
|
||||
let output = output.replace(' ', "");
|
||||
let parts: Vec<&str> = output.split(',').collect();
|
||||
|
||||
@@ -233,12 +233,16 @@ pub async fn execute(request: &CommandRequest) -> CommandResult {
|
||||
Err(_) => {
|
||||
killed = true;
|
||||
tracing::info!(target: crate::NOTICE_TARGET, "Command [{}] timed out and is being killed...", request.command);
|
||||
// `Popen.terminate`: SIGTERM, or TerminateProcess on Windows.
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = child.id() {
|
||||
// SAFETY: signals the child this task still owns.
|
||||
unsafe {
|
||||
nix::libc::kill(pid as i32, nix::libc::SIGTERM);
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = child.start_kill();
|
||||
child.wait().await
|
||||
}
|
||||
},
|
||||
@@ -254,8 +258,14 @@ pub async fn execute(request: &CommandRequest) -> CommandResult {
|
||||
.filter(|_| !killed)
|
||||
.and_then(|t| (now() < started + t).then(now));
|
||||
let retcode = status.ok().and_then(|s| {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
s.code().or_else(|| s.signal().map(|n| -n)).map(i64::from)
|
||||
#[cfg(unix)]
|
||||
let code = {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
s.code().or_else(|| s.signal().map(|n| -n))
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let code = s.code();
|
||||
code.map(i64::from)
|
||||
});
|
||||
CommandResult {
|
||||
executed: true,
|
||||
|
||||
@@ -175,6 +175,7 @@ pub fn py_fromhex(text: &str) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
|
||||
/// Python `str(OSError)` for a failed file operation.
|
||||
#[cfg(unix)]
|
||||
pub fn py_os_error(error: &std::io::Error, path: &str) -> String {
|
||||
match error.raw_os_error() {
|
||||
Some(code) => format!(
|
||||
@@ -186,6 +187,21 @@ pub fn py_os_error(error: &std::io::Error, path: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `str(OSError)` for a failed file operation, with the system's own
|
||||
/// message where Unix has a `strerror` table, as `rnodeconf-rs` prints it.
|
||||
#[cfg(not(unix))]
|
||||
pub fn py_os_error(error: &std::io::Error, path: &str) -> String {
|
||||
let text = error.to_string();
|
||||
match error.raw_os_error() {
|
||||
Some(code) => format!(
|
||||
"[Errno {code}] {}: {}",
|
||||
text.split(" (os error").next().unwrap_or(&text),
|
||||
py_str_repr(path)
|
||||
),
|
||||
None => text,
|
||||
}
|
||||
}
|
||||
|
||||
/// Text of the `UnicodeDecodeError` CPython raises for `data.decode("utf-8")`.
|
||||
pub fn py_utf8_error(data: &[u8]) -> Option<String> {
|
||||
let err = std::str::from_utf8(data).err()?;
|
||||
|
||||
Reference in new issue
Block a user