use super::*;
pub fn validate_store_identifier(ident: &str) -> io::Result<()> {
let all_allowed: bool = ident.bytes().all(|byte: u8| {
byte.is_ascii_alphanumeric()
|| byte == ASCII_HYPHEN
|| byte == ASCII_UNDERSCORE
|| byte == ASCII_DOT
});
if ident.is_empty()
|| ident == "."
|| ident == ".."
|| ident.contains("..")
|| ident.contains('/')
|| ident.contains('\\')
|| !all_allowed
{
return Err(Error::new(
ErrorKind::InvalidInput,
format!("{ERR_INVALID_STORE_IDENT}: `{ident}`"),
));
}
Ok(())
}
#[must_use]
pub fn resolve_proxy_base_url(
configured_proxy_base: &str,
fwd_proto: Option<&str>,
fwd_host: Option<&str>,
fwd_prefix: Option<&str>,
) -> Option<String> {
let explicit: &str = configured_proxy_base.trim().trim_end_matches('/');
if !explicit.is_empty() {
return Some(explicit.to_string());
}
let clean_prefix: String = fwd_prefix
.map(|prefix_raw: &str| {
let trimmed: &str = prefix_raw.trim().trim_end_matches('/');
if trimmed.is_empty() {
String::new()
} else if trimmed.starts_with('/') {
trimmed.to_string()
} else {
format!("/{trimmed}")
}
})
.unwrap_or_default();
if let Some(host_raw) = fwd_host {
let host: &str = host_raw
.split(',')
.next()
.unwrap_or("")
.trim()
.trim_end_matches('/');
if !host.is_empty() {
let proto: &str = fwd_proto
.and_then(|proto_raw: &str| proto_raw.split(',').next())
.map(str::trim)
.filter(|proto_val: &&str| !proto_val.is_empty())
.unwrap_or("http");
return Some(format!("{proto}://{host}{clean_prefix}"));
}
}
if !clean_prefix.is_empty() {
return Some(clean_prefix);
}
None
}
#[cfg(feature = "update-server")]
pub(crate) fn apply_update_cors_headers(ctx: &mut Context) {
let _: &mut Response = ctx
.get_mut_response()
.set_header(UPDATE_HDR_CORS_ORIGIN, UPDATE_VAL_CORS_ANY)
.set_header(UPDATE_HDR_CORS_METHODS, UPDATE_VAL_CORS_METHODS)
.set_header(UPDATE_HDR_CORS_HEADERS, UPDATE_VAL_CORS_HEADERS)
.set_header(UPDATE_HDR_CORS_EXPOSE, UPDATE_VAL_CORS_EXPOSE);
}
#[must_use]
pub fn sse_topic_for_channel(project: &str, channel: &str) -> String {
format!("{project}:{channel}")
}
#[must_use]
pub fn parse_http_byte_range(header: Option<&str>, total_len: usize) -> ByteRangeSpec {
let Some(raw) = header else {
return ByteRangeSpec::Full;
};
let trimmed: &str = raw.trim();
let Some(spec) = trimmed.strip_prefix(RANGE_BYTES_PREFIX) else {
return ByteRangeSpec::Invalid;
};
if spec.contains(',') || total_len == 0 {
return ByteRangeSpec::Invalid;
}
let Some((start_str, end_str)) = spec.split_once('-') else {
return ByteRangeSpec::Invalid;
};
let start_trimmed: &str = start_str.trim();
let end_trimmed: &str = end_str.trim();
if start_trimmed.is_empty() {
let Ok(suffix_len) = end_trimmed.parse::<usize>() else {
return ByteRangeSpec::Invalid;
};
if suffix_len == 0 {
return ByteRangeSpec::Invalid;
}
let start: usize = total_len.saturating_sub(suffix_len);
return ByteRangeSpec::Slice {
start,
end: total_len - 1,
};
}
let Ok(start) = start_trimmed.parse::<usize>() else {
return ByteRangeSpec::Invalid;
};
if start >= total_len {
return ByteRangeSpec::Invalid;
}
let end: usize = if end_trimmed.is_empty() {
total_len - 1
} else {
let Ok(parsed_end) = end_trimmed.parse::<usize>() else {
return ByteRangeSpec::Invalid;
};
parsed_end.min(total_len - 1)
};
if end < start {
return ByteRangeSpec::Invalid;
}
ByteRangeSpec::Slice { start, end }
}
pub(crate) fn atomic_write_synced(target: &Path, bytes: &[u8]) -> io::Result<()> {
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
let seq: u64 = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
let pid: u32 = process::id();
let file_name: String = target
.file_name()
.map(|file_name_os: &OsStr| file_name_os.to_string_lossy().into_owned())
.unwrap_or_else(|| "tmp".to_string());
let tmp_path: PathBuf = target.with_file_name(format!(".{file_name}.tmp.{pid}.{seq}"));
{
let mut file: File = OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_path)?;
file.write_all(bytes)?;
file.sync_all()?;
}
fs::rename(&tmp_path, target)?;
#[cfg(unix)]
if let Some(parent) = target.parent()
&& let Ok(dir) = File::open(parent)
{
let _: io::Result<()> = dir.sync_all();
}
Ok(())
}
#[must_use]
pub(crate) fn current_unix_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed: Duration| elapsed.as_secs())
.unwrap_or(0)
}
#[cfg(feature = "update-server")]
#[must_use]
pub(crate) fn parse_delivery_mode_token(raw: Option<&str>) -> DeliveryChannelMode {
match raw.map(str::trim) {
Some(tok) if tok.eq_ignore_ascii_case(MODE_TOKEN_DATA) => {
DeliveryChannelMode::DeclarativeData
}
_ => DeliveryChannelMode::WasmComponent,
}
}
#[cfg(feature = "update-server")]
pub fn register_update_routes(server: &mut Server, state: Arc<UpdateServerState>) {
let slot: &RwLock<Option<Arc<UpdateServerState>>> =
DEFAULT_UPDATE_SERVER_STATE.get_or_init(|| RwLock::new(None));
if let Ok(mut guard) = slot.write() {
*guard = Some(state);
}
let _: &mut Server = server
.route::<ManifestRouteHook>(UPDATE_ROUTE_MANIFEST)
.route::<BlobRouteHook>(UPDATE_ROUTE_BLOB)
.route::<EventsRouteHook>(UPDATE_ROUTE_EVENTS)
.route::<HealthRouteHook>(UPDATE_ROUTE_HEALTHZ);
}
#[cfg(feature = "update-server")]
pub fn start_update_server(config: UpdateServerConfig) -> io::Result<UpdateServerHandle> {
let mut store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
store.set_max_artifact_bytes(config.get_max_artifact_bytes());
store.init_layout()?;
let sse_config: SseConfig = SseConfig::default()
.with_heartbeat_ms(config.get_heartbeat_ms())
.with_retry_ms(config.get_retry_ms())
.with_replay_capacity(config.get_replay_capacity());
let state: Arc<UpdateServerState> = Arc::new(
UpdateServerState::new(store, sse_config).with_proxy_base(config.get_proxy_base().clone()),
);
state.sync_store_events_to_sse();
let runtime_ref: runtime::Runtime = runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()?;
let max_attempts: usize = if config.get_port() == 0 { 8 } else { 1 };
let mut last_err: Option<Error> = None;
let mut bound_pair: Option<(SocketAddr, ServerControlHook)> = None;
for _ in 0..max_attempts {
let candidate_addr: SocketAddr = resolve_bind_addr(config.get_host(), config.get_port())?;
register_server_state_for_addr(candidate_addr, Arc::clone(&state));
let mut server_cfg: ServerConfig = ServerConfig::default();
server_cfg.set_address(candidate_addr.to_string());
let mut server: Server = Server::from(server_cfg);
register_update_routes(&mut server, Arc::clone(&state));
match runtime_ref.block_on(async move { server.run().await }) {
Ok(control) => {
bound_pair = Some((candidate_addr, control));
break;
}
Err(err) => {
unregister_server_state_for_addr(candidate_addr);
last_err = Some(Error::other(err.to_string()));
}
}
}
let (resolved_addr, control): (SocketAddr, ServerControlHook) = match bound_pair {
Some(pair) => pair,
None => {
return Err(last_err.unwrap_or_else(|| Error::from(ErrorKind::AddrInUse)));
}
};
let watcher_state: Arc<UpdateServerState> = Arc::clone(&state);
let poll_ms: u64 = config.get_watch_poll_ms().max(20);
let _: task::JoinHandle<()> = runtime_ref.spawn(async move {
run_pointer_watcher_task(watcher_state, poll_ms).await;
});
Ok(UpdateServerHandle {
address: resolved_addr,
state,
control: Some(control),
runtime: Some(runtime_ref),
})
}
#[cfg(feature = "update-server")]
pub fn run_update_server_blocking(config: UpdateServerConfig) -> io::Result<UpdateServerReport> {
let once: bool = config.get_once();
let mut handle: UpdateServerHandle = start_update_server(config)?;
let report: UpdateServerReport = handle.report(once);
if once {
handle.shutdown();
return Ok(report);
}
eprintln!(
"[euv-update] serving store={} url={} manifest={} blobs={} events={}",
report.get_store_root(),
report.get_url(),
report.get_manifest_route(),
report.get_blob_route(),
report.get_events_route()
);
while handle.is_running() {
thread::sleep(Duration::from_millis(250));
}
handle.shutdown();
Ok(report)
}
#[cfg(not(feature = "update-server"))]
pub fn run_update_server_blocking(_config: UpdateServerConfig) -> io::Result<UpdateServerReport> {
Err(Error::new(
ErrorKind::Unsupported,
ERR_UPDATE_SERVER_FEATURE_DISABLED,
))
}
#[cfg(feature = "update-server")]
fn resolve_bind_addr(host: &str, port: u16) -> io::Result<SocketAddr> {
if port != 0 {
let raw: String = format!("{host}:{port}");
return raw
.parse::<SocketAddr>()
.map_err(|err: AddrParseError| Error::new(ErrorKind::InvalidInput, err.to_string()));
}
let probe: TcpListener = TcpListener::bind(format!("{host}:0"))?;
let addr: SocketAddr = probe.local_addr()?;
drop(probe);
Ok(addr)
}
#[cfg(feature = "update-server")]
pub(crate) fn register_server_state_for_addr(addr: SocketAddr, state: Arc<UpdateServerState>) {
let map: &RwLock<HashMap<SocketAddr, Arc<UpdateServerState>>> =
UPDATE_SERVER_REGISTRY.get_or_init(|| RwLock::new(HashMap::new()));
if let Ok(mut guard) = map.write() {
let _: Option<Arc<UpdateServerState>> = guard.insert(addr, state);
}
}
#[cfg(feature = "update-server")]
pub(crate) fn unregister_server_state_for_addr(addr: SocketAddr) {
if let Some(map) = UPDATE_SERVER_REGISTRY.get()
&& let Ok(mut guard) = map.write()
{
let _: Option<Arc<UpdateServerState>> = guard.remove(&addr);
}
}
#[cfg(feature = "update-server")]
pub(crate) fn resolve_server_state(stream: &Stream) -> Option<Arc<UpdateServerState>> {
if let Ok(local_addr) = stream.get_local_addr()
&& let Some(map) = UPDATE_SERVER_REGISTRY.get()
&& let Ok(guard) = map.read()
&& let Some(found) = guard.get(&local_addr)
{
return Some(Arc::clone(found));
}
DEFAULT_UPDATE_SERVER_STATE
.get()
.and_then(|lock: &RwLock<Option<Arc<UpdateServerState>>>| lock.read().ok())
.and_then(|guard: RwLockReadGuard<'_, Option<Arc<UpdateServerState>>>| guard.clone())
}
#[cfg(feature = "update-server")]
async fn run_pointer_watcher_task(state: Arc<UpdateServerState>, poll_ms: u64) {
let mut ticker: Interval = interval(Duration::from_millis(poll_ms));
while state.is_running() {
let _: Instant = ticker.tick().await.into_std();
if !state.is_running() {
break;
}
state.sync_store_events_to_sse();
}
}
#[cfg(feature = "update-server")]
pub(crate) async fn serve_release_sse_stream(
stream: &mut Stream,
ctx: &mut Context,
replay_events: Vec<StoredReleaseEvent>,
mut subscription: SseSubscription,
config: &SseConfig,
) -> Result<(), SseError> {
SseStream::prepare(ctx);
apply_update_cors_headers(ctx);
let _: &mut Response = ctx
.get_mut_response()
.set_header(CACHE_CONTROL, UPDATE_SSE_CACHE_CONTROL)
.set_header(UPDATE_HDR_ACCEL_BUFFERING, UPDATE_VAL_NO_BUFFER);
let head: ResponseData = ctx.get_mut_response().build_head();
stream
.try_send(&head)
.await
.map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
let mut scratch: Vec<u8> = Vec::with_capacity(256);
if config.get_retry_ms() > 0 {
let hint: SseEvent =
SseEvent::comment_only(UPDATE_SSE_CONNECTED_COMMENT).with_retry(config.get_retry_ms());
SseStream::send_event_buffered(stream, &hint, &mut scratch).await?;
}
let mut last_sent_seq: u64 = 0;
for rec in replay_events.into_iter() {
if let Ok(json) = to_string(rec.get_event()) {
let ui_event: SseEvent = SseEvent::new(json)
.with_id(rec.get_event_id().to_string())
.with_event(SSE_EVENT_RELEASE_ACTIVATED);
SseStream::send_event_buffered(stream, &ui_event, &mut scratch).await?;
if rec.get_event_id() > last_sent_seq {
last_sent_seq = rec.get_event_id();
}
}
}
let heartbeat_ms: u64 = config.get_heartbeat_ms();
if heartbeat_ms == 0 {
loop {
match subscription.recv().await {
Ok(event) => {
let ev_seq: u64 = event
.get_id()
.as_deref()
.and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
.unwrap_or(u64::MAX);
if ev_seq <= last_sent_seq {
continue;
}
SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
if ev_seq != u64::MAX {
last_sent_seq = ev_seq;
}
}
Err(SseError::Lagged(_)) => continue,
Err(SseError::ChannelClosed) => return Ok(()),
Err(err) => return Err(err),
}
}
}
let heartbeat_frame: Vec<u8> = SseEvent::comment_only(UPDATE_SSE_HEARTBEAT_COMMENT).encode();
let mut ticker: Interval = interval(Duration::from_millis(heartbeat_ms));
ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
let _: Instant = ticker.tick().await.into_std();
loop {
select! {
_ = ticker.tick() => {
stream
.try_send(&heartbeat_frame)
.await
.map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
}
next = subscription.recv() => {
match next {
Ok(event) => {
let ev_seq: u64 = event
.get_id()
.as_deref()
.and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
.unwrap_or(u64::MAX);
if ev_seq <= last_sent_seq {
continue;
}
SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
if ev_seq != u64::MAX {
last_sent_seq = ev_seq;
}
}
Err(SseError::Lagged(_)) => continue,
Err(SseError::ChannelClosed) => return Ok(()),
Err(err) => return Err(err),
}
}
}
}
}
#[cfg(feature = "update-server")]
pub(crate) async fn send_hyperlane_bytes(
stream: &mut Stream,
ctx: &mut Context,
status_code: usize,
content_type: &str,
body: Vec<u8>,
) -> Status {
apply_update_cors_headers(ctx);
ctx.get_mut_response()
.set_status_code(status_code)
.set_header(CONTENT_TYPE, content_type)
.set_body(body);
let data: ResponseData = ctx.build_response();
if stream.try_send(&data).await.is_err() {
stream.set_closed(true);
return Status::Reject;
}
Status::Continue
}
#[must_use]
pub fn etag_matches_if_none_match(header: Option<&str>, current_etag: &str) -> bool {
let Some(raw) = header else {
return false;
};
let clean_current: &str = current_etag.trim().trim_matches('"');
if clean_current.is_empty() {
return false;
}
for token in raw.split(',') {
let trimmed: &str = token.trim();
if trimmed == "*" {
return true;
}
let without_weak: &str = trimmed
.strip_prefix(OTA_ETAG_WEAK_PREFIX)
.or_else(|| trimmed.strip_prefix(OTA_ETAG_WEAK_PREFIX_LOWER))
.unwrap_or(trimmed)
.trim();
let candidate: &str = without_weak.trim_matches('"');
if !candidate.is_empty() && constant_time_eq(candidate.as_bytes(), clean_current.as_bytes())
{
return true;
}
}
false
}
pub fn generate_signing_key_hex() -> io::Result<String> {
let mut seed_buf: Vec<u8> = Vec::with_capacity(128);
#[cfg(unix)]
{
if let Ok(mut urandom) = File::open(OTA_DEV_URANDOM) {
let mut os_bytes: [u8; 32] = [0u8; 32];
if urandom.read_exact(&mut os_bytes).is_ok() {
seed_buf.extend_from_slice(&os_bytes);
}
}
}
for round in 0..4u64 {
let hasher_builder: RandomState = RandomState::new();
let mut hasher: DefaultHasher = hasher_builder.build_hasher();
hasher.write_u64(round);
hasher.write_u32(process::id());
let nanos: u128 = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed: Duration| elapsed.as_nanos())
.unwrap_or(0);
hasher.write_u128(nanos);
let seq: u64 = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
hasher.write_u64(seq);
seed_buf.extend_from_slice(&hasher.finish().to_le_bytes());
}
let digest: [u8; 32] = sha256_bytes(&seed_buf);
let hex_key: String = sha256_hex(&digest);
Ok(hex_key)
}
pub fn generate_ota_keygen_report() -> io::Result<KeygenReport> {
let signing_key: String = generate_signing_key_hex()?;
let export_hint: String = format!("export {DEFAULT_OTA_SIGNING_KEY_ENV}={signing_key}");
Ok(KeygenReport::new(
signing_key,
DEFAULT_OTA_SIGNING_KEY_ENV.to_string(),
export_hint,
OTA_KEYGEN_BIT_LENGTH,
))
}
pub fn init_ota_store(config: &OtaInitConfig) -> io::Result<OtaInitReport> {
validate_store_identifier(config.get_project())?;
validate_store_identifier(config.get_channel())?;
let store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
store.init_layout()?;
let root: &Path = config.get_store_root();
let created_dirs: Vec<String> = vec![
root.join(STORE_DIR_STAGING).display().to_string(),
root.join(STORE_DIR_BLOBS)
.join(STORE_DIR_SHA256)
.display()
.to_string(),
root.join(STORE_DIR_RELEASES).display().to_string(),
root.join(STORE_DIR_CHANNELS).display().to_string(),
root.join(STORE_DIR_STATE)
.join(STORE_DIR_EVENTS)
.display()
.to_string(),
];
let signing_key: String = match config.try_get_signing_key() {
Some(existing) if !existing.trim().is_empty() => existing.trim().to_string(),
_ => generate_signing_key_hex()?,
};
let config_file: String = if let Some(cfg_path) = config.try_get_config_path() {
let project_cfg: OtaProjectConfig = OtaProjectConfig::new(
OTA_CONFIG_SCHEMA_V1,
config.get_project().clone(),
config.get_channel().clone(),
root.display().to_string(),
config.get_server_url().clone(),
DEFAULT_OTA_SIGNING_KEY_ENV.to_string(),
);
let encoded: String = to_string_pretty(&project_cfg)
.map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
atomic_write_synced(cfg_path, encoded.as_bytes())?;
cfg_path.display().to_string()
} else {
String::new()
};
Ok(OtaInitReport::new(
root.display().to_string(),
config.get_project().clone(),
config.get_channel().clone(),
config_file,
signing_key,
DEFAULT_OTA_SIGNING_KEY_ENV.to_string(),
created_dirs,
))
}
pub fn validate_dynamic_wasm_bytes(wasm_bytes: &[u8]) -> io::Result<DynamicWasmValidation> {
if !wasm_bytes.starts_with(WASM_BINARY_MAGIC) {
return Err(Error::new(
ErrorKind::InvalidData,
ERR_PUSH_INVALID_WASM.to_string(),
));
}
if (wasm_bytes.len() as u64) > DEFAULT_MAX_ARTIFACT_BYTES {
return Err(Error::new(
ErrorKind::InvalidData,
format!("{ERR_PUSH_INVALID_WASM}: exceeds max artifact byte budget"),
));
}
let sandbox: WasmSandboxConfig = WasmSandboxConfig::default();
let parsed: WasmParsedModule =
parse_wasm_binary(wasm_bytes, &sandbox).map_err(|err: WasmDynamicError| {
Error::new(
ErrorKind::InvalidData,
format!("{ERR_PUSH_INVALID_WASM}: {err}"),
)
})?;
let abi_out: WasmExecutionOutput = execute_wasm_export(&parsed, WASM_EXPORT_ABI, &[], &sandbox)
.map_err(|err: WasmDynamicError| {
Error::new(
ErrorKind::InvalidData,
format!("{ERR_PUSH_INVALID_WASM}: {err}"),
)
})?;
let mod_abi: u32 = abi_out.get_return_value().max(0) as u32;
if mod_abi != DYNAMIC_HOST_ABI_V1 {
return Err(Error::new(
ErrorKind::InvalidData,
format!("{ERR_PUSH_INVALID_WASM}: ABI v{mod_abi} != host v{DYNAMIC_HOST_ABI_V1}"),
));
}
if !parsed.get_exports().contains_key(WASM_EXPORT_RENDER) {
return Err(Error::new(
ErrorKind::InvalidData,
format!("{ERR_PUSH_INVALID_WASM}: missing `{WASM_EXPORT_RENDER}` export"),
));
}
let mut exports: Vec<String> = parsed.get_exports().keys().cloned().collect();
exports.sort();
Ok(DynamicWasmValidation::new(
mod_abi,
exports,
sha256_hex(wasm_bytes),
wasm_bytes.len() as u64,
))
}
pub fn build_dynamic_wasm_widget(config: &OtaBuildConfig) -> io::Result<OtaBuildReport> {
let manifest_dir: &Path = config.get_manifest_dir();
let mut cargo_args: Vec<String> = vec![
ARG_BUILD.to_string(),
ARG_TARGET.to_string(),
OTA_WASM_TARGET_TRIPLE.to_string(),
OTA_CARGO_ARG_LIB.to_string(),
];
if let Some(pkg) = config.try_get_package() {
cargo_args.push(ARG_PACKAGE.to_string());
cargo_args.push(pkg.clone());
}
if config.get_release() {
cargo_args.push(ARG_RELEASE.to_string());
}
let output: Output = Command::new(BIN_CARGO)
.args(&cargo_args)
.current_dir(manifest_dir)
.output()?;
if !output.status.success() {
let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
return Err(Error::other(format!("{OTA_ERR_BUILD_FAILED}: {stderr}")));
}
let built_wasm: PathBuf = locate_built_wasm_artifact(
manifest_dir,
config.try_get_package().as_deref(),
config.get_release(),
)?;
let wasm_bytes: Vec<u8> = fs::read(&built_wasm)?;
let validated: DynamicWasmValidation = validate_dynamic_wasm_bytes(&wasm_bytes)?;
let out_path: PathBuf = match config.try_get_out_path() {
Some(explicit) => explicit.clone(),
None => {
let file_name: String = built_wasm
.file_name()
.map(|os_name: &OsStr| os_name.to_string_lossy().into_owned())
.unwrap_or_else(|| OTA_DEFAULT_WIDGET_FILENAME.to_string());
manifest_dir.join(OTA_BUILD_OUT_SUBDIR).join(file_name)
}
};
atomic_write_synced(&out_path, &wasm_bytes)?;
let pushed: Option<PublishReport> = if config.get_push() {
let signing_key: String = match config.try_get_signing_key() {
Some(key) if !key.trim().is_empty() => key.trim().to_string(),
_ => match env::var(DEFAULT_OTA_SIGNING_KEY_ENV) {
Ok(key) if !key.trim().is_empty() => key,
_ => {
return Err(Error::new(
ErrorKind::InvalidInput,
OTA_ERR_PUSH_KEY_MISSING.to_string(),
));
}
},
};
let mut store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
let _: &mut UpdateStore = store.set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES);
let pub_report: PublishReport = store.publish_artifact_direct(
config.get_project(),
config.get_channel(),
config.try_get_route().as_deref(),
config.try_get_slot().as_deref(),
&wasm_bytes,
signing_key.as_bytes(),
)?;
Some(pub_report)
} else {
None
};
let mut report: OtaBuildReport = OtaBuildReport::new(
out_path.display().to_string(),
validated.get_sha256().clone(),
validated.get_size_bytes(),
validated.get_abi_version(),
validated.get_exports().clone(),
);
let _: &mut OtaBuildReport = report.set_pushed(pushed);
Ok(report)
}
fn locate_built_wasm_artifact(
manifest_dir: &Path,
package: Option<&str>,
release: bool,
) -> io::Result<PathBuf> {
let target_root: PathBuf = match env::var(OTA_ENV_CARGO_TARGET_DIR) {
Ok(dir) if !dir.trim().is_empty() => PathBuf::from(dir),
_ => manifest_dir.join(OTA_DIR_TARGET),
};
let profile_dir: &str = if release {
OTA_DIR_RELEASE
} else {
OTA_DIR_DEBUG
};
let wasm_dir: PathBuf = target_root.join(OTA_WASM_TARGET_TRIPLE).join(profile_dir);
if let Some(pkg) = package {
let normalized: String = pkg.replace('-', "_");
let direct: PathBuf = wasm_dir.join(format!("{normalized}.{OTA_EXT_WASM}"));
if direct.is_file() {
return Ok(direct);
}
}
if wasm_dir.is_dir() {
let mut candidates: Vec<(SystemTime, PathBuf)> = Vec::new();
for entry_res in fs::read_dir(&wasm_dir)? {
let entry: DirEntry = entry_res?;
let path: PathBuf = entry.path();
let is_wasm_file: bool = path.is_file()
&& path
.extension()
.and_then(|ext_os: &OsStr| ext_os.to_str())
.is_some_and(|ext: &str| ext.eq_ignore_ascii_case(OTA_EXT_WASM));
if is_wasm_file {
let modified: SystemTime = entry
.metadata()
.ok()
.and_then(|meta: Metadata| meta.modified().ok())
.unwrap_or(UNIX_EPOCH);
candidates.push((modified, path));
}
}
candidates.sort_by_key(|entry: &(SystemTime, PathBuf)| cmp::Reverse(entry.0));
if let Some((_, newest)) = candidates.into_iter().next() {
return Ok(newest);
}
}
Err(Error::new(
ErrorKind::NotFound,
format!("{OTA_ERR_WASM_NOT_FOUND} in {}", wasm_dir.display()),
))
}
#[must_use]
pub fn detect_lan_ip_addresses() -> Vec<String> {
let mut detected: BTreeSet<String> = BTreeSet::new();
for probe in [OTA_LAN_PROBE_PRIMARY, OTA_LAN_PROBE_FALLBACK] {
if let Ok(socket) = UdpSocket::bind(OTA_LAN_BIND_ANY)
&& socket.connect(probe).is_ok()
&& let Ok(local_addr) = socket.local_addr()
&& let IpAddr::V4(ipv4) = local_addr.ip()
&& !ipv4.is_loopback()
&& !ipv4.is_unspecified()
{
let _: bool = detected.insert(ipv4.to_string());
}
}
detected.into_iter().collect()
}
#[cfg(feature = "update-server")]
pub fn run_ota_dev_blocking(config: OtaDevConfig) -> io::Result<OtaDevReport> {
validate_store_identifier(config.get_project())?;
validate_store_identifier(config.get_channel())?;
let signing_key: String = if config.get_signing_key().trim().is_empty() {
generate_signing_key_hex()?
} else {
config.get_signing_key().clone()
};
let mut store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
let _: &mut UpdateStore = store.set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES);
store.init_layout()?;
let initial_release: Option<PublishReport> =
if let Some(watch_path) = config.try_get_watch_path() {
if watch_path.exists() {
Some(push_watched_ota_source(
&store,
watch_path,
(config.get_project(), config.get_channel()),
(
config.try_get_route().as_deref(),
config.try_get_slot().as_deref(),
),
config.try_get_package().as_deref(),
signing_key.as_bytes(),
)?)
} else {
None
}
} else {
None
};
let mut srv_cfg: UpdateServerConfig = UpdateServerConfig::default();
let _: &mut UpdateServerConfig = srv_cfg
.set_store_root(config.get_store_root().clone())
.set_host(config.get_host().clone())
.set_port(config.get_port())
.set_proxy_base(config.get_proxy_base().clone())
.set_heartbeat_ms(config.get_heartbeat_ms())
.set_watch_poll_ms(config.get_poll_ms().clamp(25, 2000))
.set_once(false);
let mut handle: UpdateServerHandle = start_update_server(srv_cfg)?;
let bound_port: u16 = handle.address().port();
let local_url: String = if config.get_host() == OTA_HOST_ALL_INTERFACES {
format!("http://{OTA_HOST_LOCALHOST}:{bound_port}")
} else {
handle.url()
};
let manifest_path: String = format!(
"{OTA_PATH_V1_PROJECTS_PREFIX}{}/{OTA_PATH_SEG_CHANNELS}/{}/{OTA_PATH_SEG_MANIFEST}",
config.get_project(),
config.get_channel()
);
let events_path: String = format!(
"{OTA_PATH_V1_PROJECTS_PREFIX}{}/{OTA_PATH_SEG_CHANNELS}/{}/{OTA_PATH_SEG_EVENTS}",
config.get_project(),
config.get_channel()
);
let lan_urls: Vec<String> = detect_lan_ip_addresses()
.into_iter()
.map(|lan_ip: String| format!("http://{lan_ip}:{bound_port}{manifest_path}"))
.collect();
let manifest_url: String = format!("{local_url}{manifest_path}");
let events_url: String = format!("{local_url}{events_path}");
let health_url: String = format!("{local_url}{UPDATE_ROUTE_HEALTHZ}");
let mut report: OtaDevReport = OtaDevReport::default();
let _: &mut OtaDevReport = report
.set_store_root(config.get_store_root().display().to_string())
.set_local_url(local_url.clone())
.set_lan_urls(lan_urls.clone())
.set_manifest_url(manifest_url.clone())
.set_events_url(events_url.clone())
.set_health_url(health_url.clone())
.set_project(config.get_project().clone())
.set_channel(config.get_channel().clone())
.set_initial_release(initial_release)
.set_once(config.get_once());
if config.get_once() {
handle.shutdown();
return Ok(report);
}
eprintln!(
"[euv-update-dev] local={local_url} manifest={manifest_url} events={events_url} health={health_url}"
);
for lan_manifest in lan_urls.iter() {
eprintln!("[euv-update-dev] lan={lan_manifest}");
}
let poll_delay: Duration = Duration::from_millis(config.get_poll_ms().clamp(50, 5000));
let mut prev_stamp: String = config
.try_get_watch_path()
.as_deref()
.map(compute_watch_fingerprint)
.unwrap_or_default();
while handle.is_running() {
thread::sleep(poll_delay);
if let Some(watch_path) = config.try_get_watch_path()
&& watch_path.exists()
{
let next_stamp: String = compute_watch_fingerprint(watch_path);
if next_stamp != prev_stamp {
prev_stamp = next_stamp;
match push_watched_ota_source(
&store,
watch_path,
(config.get_project(), config.get_channel()),
(
config.try_get_route().as_deref(),
config.try_get_slot().as_deref(),
),
config.try_get_package().as_deref(),
signing_key.as_bytes(),
) {
Ok(pub_rep) => {
eprintln!(
"[euv-update-dev] pushed release seq={} sha={}",
pub_rep.get_to_release(),
pub_rep.get_manifest_sha256()
);
}
Err(err) => {
eprintln!("[euv-update-dev] skipped invalid change: {err}");
}
}
}
}
}
handle.shutdown();
Ok(report)
}
#[cfg(not(feature = "update-server"))]
pub fn run_ota_dev_blocking(_config: OtaDevConfig) -> io::Result<OtaDevReport> {
Err(Error::new(
ErrorKind::Unsupported,
ERR_UPDATE_SERVER_FEATURE_DISABLED,
))
}
pub fn push_watched_ota_source(
store: &UpdateStore,
watch_path: &Path,
project_channel: (&str, &str),
route_slot: (Option<&str>, Option<&str>),
package: Option<&str>,
signing_key: &[u8],
) -> io::Result<PublishReport> {
let (project, channel): (&str, &str) = project_channel;
let (route, slot): (Option<&str>, Option<&str>) = route_slot;
let is_cargo_crate: bool = watch_path.is_dir()
|| watch_path
.file_name()
.and_then(|file_os: &OsStr| file_os.to_str())
.is_some_and(|name: &str| name == OTA_CARGO_MANIFEST_FILE);
if is_cargo_crate {
let crate_dir: PathBuf = if watch_path.is_dir() {
watch_path.to_path_buf()
} else {
watch_path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."))
};
let mut build_cfg: OtaBuildConfig = OtaBuildConfig::default();
let _: &mut OtaBuildConfig = build_cfg
.set_manifest_dir(crate_dir)
.set_package(package.map(str::to_string))
.set_release(true)
.set_push(false);
let built: OtaBuildReport = build_dynamic_wasm_widget(&build_cfg)?;
let wasm_bytes: Vec<u8> = fs::read(built.get_wasm_path())?;
return store.publish_artifact_direct(
project,
channel,
route,
slot,
&wasm_bytes,
signing_key,
);
}
let raw_bytes: Vec<u8> = fs::read(watch_path)?;
store.publish_artifact_direct(project, channel, route, slot, &raw_bytes, signing_key)
}
#[cfg(feature = "update-server")]
fn compute_watch_fingerprint(watch_path: &Path) -> String {
if watch_path.is_file() {
return fs::read(watch_path)
.map(|bytes: Vec<u8>| sha256_hex(&bytes))
.unwrap_or_default();
}
let snapshot: WatchSnapshot =
WatchSnapshot::scan(watch_path, &WATCH_EXTS_CODE).unwrap_or_default();
let mut acc: String = String::new();
for (entry_path, stamp) in snapshot.get_entries().iter() {
acc.push_str(&format!(
"{}:{}:{}\n",
entry_path.display(),
stamp.get_modified_nanos(),
stamp.get_size_bytes()
));
}
sha256_hex(acc.as_bytes())
}
pub fn verify_ota_store(config: &OtaVerifyConfig) -> io::Result<OtaVerifyReport> {
let store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
store.verify_store(config)
}
pub fn diff_ota_releases(
store_root: &Path,
project: &str,
channel: &str,
from_seq: u64,
to_seq: u64,
) -> io::Result<OtaReleaseDiff> {
let store: UpdateStore = UpdateStore::new(store_root.to_path_buf());
store.diff_releases(project, channel, from_seq, to_seq)
}
pub fn gc_ota_store(config: &OtaGcConfig) -> io::Result<OtaGcReport> {
let store: UpdateStore = UpdateStore::new(config.get_store_root().clone());
store.gc(config)
}
pub fn build_health_response(
store: &UpdateStore,
running: bool,
) -> io::Result<UpdateHealthResponse> {
let status: UpdateStoreStatus = store.status(None, None)?;
let channel_count: usize = status.get_channels().len();
let mut response: UpdateHealthResponse = UpdateHealthResponse::default();
let _: &mut UpdateHealthResponse = response
.set_status(OTA_HEALTH_STATUS_OK.to_string())
.set_store_root(status.get_store_root().clone())
.set_blob_count(status.get_blob_count())
.set_blob_total_bytes(status.get_blob_total_bytes())
.set_channel_count(channel_count)
.set_channels(status.get_channels().clone())
.set_running(running)
.set_timestamp_unix(current_unix_secs());
Ok(response)
}
#[must_use]
pub fn parse_v1_events_path(path: &str) -> Option<(String, String)> {
let rest: &str = path.strip_prefix(OTA_PATH_V1_PROJECTS_PREFIX)?;
let parts: Vec<&str> = rest.split('/').collect();
if parts.len() != 4 || parts[1] != OTA_PATH_SEG_CHANNELS || parts[3] != OTA_PATH_SEG_EVENTS {
return None;
}
let project: &str = parts[0];
let channel: &str = parts[2];
if validate_store_identifier(project).is_err() || validate_store_identifier(channel).is_err() {
return None;
}
Some((project.to_string(), channel.to_string()))
}
#[must_use]
pub fn handle_embedded_v1_ota_request(
store: &UpdateStore,
method: &str,
raw_target: &str,
if_none_match: Option<&str>,
range_header: Option<&str>,
) -> Option<EmbeddedOtaResponse> {
let (path_only, query_str): (&str, &str) = match raw_target.split_once('?') {
Some((path_part, query_part)) => (path_part, query_part),
None => (raw_target, ""),
};
if path_only == UPDATE_ROUTE_HEALTHZ {
if method.eq_ignore_ascii_case(OTA_METHOD_OPTIONS) {
return Some(EmbeddedOtaResponse::new(
204,
OTA_HTTP_STATUS_NO_CONTENT,
OTA_HTTP_MIME_JSON,
Vec::new(),
Vec::new(),
));
}
if !method.eq_ignore_ascii_case(OTA_METHOD_GET)
&& !method.eq_ignore_ascii_case(OTA_METHOD_HEAD)
{
return Some(EmbeddedOtaResponse::new(
405,
OTA_HTTP_STATUS_METHOD_NOT_ALLOWED,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
));
}
let body: Vec<u8> = build_health_response(store, true)
.ok()
.and_then(|resp: UpdateHealthResponse| to_string(&resp).ok())
.map(String::into_bytes)
.unwrap_or_else(|| OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec());
return Some(EmbeddedOtaResponse::new(
200,
OTA_HTTP_STATUS_OK,
OTA_HTTP_MIME_JSON,
vec![(
OTA_HDR_CACHE_CONTROL_TITLE.to_string(),
OTA_HTTP_CACHE_NO_CACHE.to_string(),
)],
body,
));
}
if let Some(sha_raw) = path_only.strip_prefix(OTA_PATH_V1_BLOBS_PREFIX) {
if method.eq_ignore_ascii_case(OTA_METHOD_OPTIONS) {
return Some(EmbeddedOtaResponse::new(
204,
OTA_HTTP_STATUS_NO_CONTENT,
OTA_HTTP_MIME_JSON,
Vec::new(),
Vec::new(),
));
}
if !method.eq_ignore_ascii_case(OTA_METHOD_GET)
&& !method.eq_ignore_ascii_case(OTA_METHOD_HEAD)
{
return Some(EmbeddedOtaResponse::new(
405,
OTA_HTTP_STATUS_METHOD_NOT_ALLOWED,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
));
}
if !is_valid_sha256_hex(sha_raw) {
return Some(EmbeddedOtaResponse::new(
400,
OTA_HTTP_STATUS_BAD_REQUEST,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec(),
));
}
let blob_bytes: Vec<u8> = match store.read_blob(sha_raw) {
Ok(Some(bytes)) => bytes,
Ok(None) => {
return Some(EmbeddedOtaResponse::new(
404,
OTA_HTTP_STATUS_NOT_FOUND,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_NOT_FOUND.as_bytes().to_vec(),
));
}
Err(_) => {
return Some(EmbeddedOtaResponse::new(
400,
OTA_HTTP_STATUS_BAD_REQUEST,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec(),
));
}
};
let mut headers: Vec<(String, String)> = vec![
(
OTA_HDR_CACHE_CONTROL_TITLE.to_string(),
OTA_HTTP_CACHE_IMMUTABLE.to_string(),
),
(OTA_HDR_ETAG_TITLE.to_string(), format!("\"{sha_raw}\"")),
(
OTA_HDR_ACCEPT_RANGES_TITLE.to_string(),
OTA_HTTP_RANGE_BYTES.to_string(),
),
];
if etag_matches_if_none_match(if_none_match, sha_raw) {
return Some(EmbeddedOtaResponse::new(
304,
OTA_HTTP_STATUS_NOT_MODIFIED,
OTA_HTTP_MIME_OCTET,
headers,
Vec::new(),
));
}
let total_len: usize = blob_bytes.len();
return match parse_http_byte_range(range_header, total_len) {
ByteRangeSpec::Full => Some(EmbeddedOtaResponse::new(
200,
OTA_HTTP_STATUS_OK,
OTA_HTTP_MIME_OCTET,
headers,
blob_bytes,
)),
ByteRangeSpec::Slice { start, end } => {
headers.push((
OTA_HDR_CONTENT_RANGE_TITLE.to_string(),
format!("bytes {start}-{end}/{total_len}"),
));
Some(EmbeddedOtaResponse::new(
206,
OTA_HTTP_STATUS_PARTIAL,
OTA_HTTP_MIME_OCTET,
headers,
blob_bytes[start..=end].to_vec(),
))
}
ByteRangeSpec::Invalid => {
headers.push((
OTA_HDR_CONTENT_RANGE_TITLE.to_string(),
format!("bytes */{total_len}"),
));
Some(EmbeddedOtaResponse::new(
416,
OTA_HTTP_STATUS_RANGE_INVALID,
OTA_HTTP_MIME_JSON,
headers,
OTA_HTTP_ERR_RANGE_INVALID.as_bytes().to_vec(),
))
}
};
}
if let Some(rest) = path_only.strip_prefix(OTA_PATH_V1_PROJECTS_PREFIX) {
let parts: Vec<&str> = rest.split('/').collect();
if parts.len() == 4
&& parts[1] == OTA_PATH_SEG_CHANNELS
&& parts[3] == OTA_PATH_SEG_MANIFEST
{
if method.eq_ignore_ascii_case(OTA_METHOD_OPTIONS) {
return Some(EmbeddedOtaResponse::new(
204,
OTA_HTTP_STATUS_NO_CONTENT,
OTA_HTTP_MIME_JSON,
Vec::new(),
Vec::new(),
));
}
if !method.eq_ignore_ascii_case(OTA_METHOD_GET)
&& !method.eq_ignore_ascii_case(OTA_METHOD_HEAD)
{
return Some(EmbeddedOtaResponse::new(
405,
OTA_HTTP_STATUS_METHOD_NOT_ALLOWED,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
));
}
let project: &str = parts[0];
let channel: &str = parts[2];
let query_map: BTreeMap<String, String> = parse_simple_query(query_str);
let protocol: u32 = query_map
.get(OTA_HTTP_QUERY_PROTOCOL)
.and_then(|val: &String| val.parse::<u32>().ok())
.unwrap_or(DYNAMIC_PROTOCOL_VERSION_V1);
let host_abi: u32 = query_map
.get(OTA_HTTP_QUERY_ABI)
.and_then(|val: &String| val.parse::<u32>().ok())
.unwrap_or(DYNAMIC_HOST_ABI_V1);
let mode: DeliveryChannelMode = match query_map
.get(OTA_HTTP_QUERY_MODE)
.map(|val: &String| val.trim())
{
Some(tok) if tok.eq_ignore_ascii_case(OTA_HTTP_MODE_DATA) => {
DeliveryChannelMode::DeclarativeData
}
_ => DeliveryChannelMode::WasmComponent,
};
let mut neg: ClientNegotiation = ClientNegotiation::new(protocol, host_abi, mode);
if let Some(track) = query_map.get(OTA_HTTP_QUERY_TRACK)
&& !track.is_empty()
{
neg = neg.with_preferred_track(track.clone());
}
return match store.read_compatible_manifest(project, channel, &neg) {
Ok(Ok(manifest)) => {
let etag: String = manifest.manifest_sha256().unwrap_or_default();
let headers: Vec<(String, String)> = vec![
(
OTA_HDR_CACHE_CONTROL_TITLE.to_string(),
OTA_HTTP_CACHE_NO_CACHE.to_string(),
),
(OTA_HDR_ETAG_TITLE.to_string(), format!("\"{etag}\"")),
];
if etag_matches_if_none_match(if_none_match, &etag) {
return Some(EmbeddedOtaResponse::new(
304,
OTA_HTTP_STATUS_NOT_MODIFIED,
OTA_HTTP_MIME_JSON,
headers,
Vec::new(),
));
}
let body: Vec<u8> = to_string(&manifest)
.map(String::into_bytes)
.unwrap_or_default();
Some(EmbeddedOtaResponse::new(
200,
OTA_HTTP_STATUS_OK,
OTA_HTTP_MIME_JSON,
headers,
body,
))
}
Ok(Err(reason)) => Some(EmbeddedOtaResponse::new(
409,
OTA_HTTP_STATUS_CONFLICT,
OTA_HTTP_MIME_JSON,
Vec::new(),
format!("{{\"error\":\"incompatible\",\"detail\":\"{reason}\"}}").into_bytes(),
)),
Err(err) if err.kind() == ErrorKind::NotFound => Some(EmbeddedOtaResponse::new(
404,
OTA_HTTP_STATUS_NOT_FOUND,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_NOT_FOUND.as_bytes().to_vec(),
)),
Err(_) => Some(EmbeddedOtaResponse::new(
400,
OTA_HTTP_STATUS_BAD_REQUEST,
OTA_HTTP_MIME_JSON,
Vec::new(),
OTA_HTTP_ERR_BAD_REQUEST.as_bytes().to_vec(),
)),
};
}
}
None
}
fn parse_simple_query(query: &str) -> BTreeMap<String, String> {
let mut map: BTreeMap<String, String> = BTreeMap::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
if let Some((key, val)) = pair.split_once('=') {
let _: Option<String> = map.insert(key.to_string(), val.to_string());
}
}
map
}
pub(crate) fn is_writer_lock_stale(lock_path: &Path, stale_secs: u64) -> bool {
let Ok(raw) = fs::read_to_string(lock_path) else {
return false;
};
let mut parsed_pid: Option<u32> = None;
let mut parsed_created: Option<u64> = None;
for line in raw.lines() {
let trimmed: &str = line.trim();
if let Some(pid_text) = trimmed.strip_prefix(OTA_LOCK_PID_PREFIX) {
parsed_pid = pid_text.trim().parse::<u32>().ok();
} else if let Some(ts_text) = trimmed.strip_prefix(OTA_LOCK_CREATED_PREFIX) {
parsed_created = ts_text.trim().parse::<u64>().ok();
}
}
if let Some(owner_pid) = parsed_pid
&& !is_process_alive(owner_pid)
{
return true;
}
let now_secs: u64 = current_unix_secs();
if let Some(created_secs) = parsed_created
&& now_secs.saturating_sub(created_secs) >= stale_secs
{
return true;
}
if let Ok(meta) = fs::metadata(lock_path)
&& let Ok(modified) = meta.modified()
&& let Ok(age) = SystemTime::now().duration_since(modified)
&& age.as_secs() >= stale_secs
{
return true;
}
false
}
fn is_process_alive(pid: u32) -> bool {
if pid == 0 {
return false;
}
if pid == process::id() {
return true;
}
#[cfg(unix)]
{
let proc_root: &Path = Path::new(OTA_PROC_DIR);
if proc_root.is_dir() {
return proc_root.join(pid.to_string()).exists();
}
if let Ok(out) = Command::new(OTA_KILL_BIN)
.args([OTA_KILL_SIGNAL_ZERO, &pid.to_string()])
.stdin(Stdio::null())
.output()
{
if out.status.success() {
return true;
}
let stderr_lower: String = String::from_utf8_lossy(&out.stderr).to_ascii_lowercase();
if stderr_lower.contains(OTA_ERR_NO_SUCH_PROCESS) {
return false;
}
}
true
}
#[cfg(not(unix))]
{
true
}
}
pub(crate) fn dir_total_bytes(path: &Path) -> u64 {
if path.is_file() {
return fs::metadata(path)
.map(|meta: Metadata| meta.len())
.unwrap_or(0);
}
if !path.is_dir() {
return 0;
}
let mut total: u64 = 0;
if let Ok(entries) = fs::read_dir(path) {
for entry in entries.flatten() {
total = total.saturating_add(dir_total_bytes(&entry.path()));
}
}
total
}