Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Crash & Logs Improvement #155

Merged
merged 2 commits into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ sha256 = "1.1.4"
pathdiff = "0.2.1"
libssh-rs = { version = "0.2.0", features = ["vendored"] }
libssh-rs-sys = "0.2.0"
flate2 = "1.0"

[dependencies.tauri]
version = "1.4.0"
Expand Down
84 changes: 81 additions & 3 deletions src-tauri/src/conn_pool/connection.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use std::fmt::{Debug, Formatter};
use std::io::{Read, Write};
use std::ops::{Deref, DerefMut};
use std::sync::Mutex;
use std::time::Duration;

use libssh_rs::{AuthStatus, Session, SshKey, SshOption};
use tauri::regex::Regex;
use uuid::Uuid;

use crate::conn_pool::DeviceConnection;
use crate::conn_pool::{DeviceConnection, DeviceConnectionUserInfo, Id};
use crate::device_manager::Device;
use crate::error::Error;

Expand Down Expand Up @@ -58,6 +60,7 @@ impl DeviceConnection {
let connection = DeviceConnection {
id: Uuid::new_v4(),
device: device.clone(),
user: DeviceConnectionUserInfo::new(&session)?,
session,
last_ok: Mutex::new(true),
};
Expand Down Expand Up @@ -109,8 +112,83 @@ impl Drop for DeviceConnection {
impl Debug for DeviceConnection {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"DeviceConnection {{ id={}, device.name={} }}",
self.id, self.device.name
"DeviceConnection {{ id={}, device.name={}, user={:?} }}",
self.id, self.device.name, self.user,
))
}
}

impl DeviceConnectionUserInfo {
fn new(session: &Session) -> Result<Option<DeviceConnectionUserInfo>, Error> {
let ch = session.new_channel()?;
ch.open_session()?;
ch.request_exec("id")?;
let mut buf = String::new();
ch.stdout().read_to_string(&mut buf)?;
let exit_code = ch.get_exit_status().unwrap_or(0);
ch.close()?;
if exit_code != 0 {
return Err(Error::Message {
message: format!("id command failed with exit code {}", exit_code),
});
}
return Ok(DeviceConnectionUserInfo::parse(&buf));
}

fn parse(s: &str) -> Option<DeviceConnectionUserInfo> {
let mut uid: Option<Id> = None;
let mut gid: Option<Id> = None;
let mut groups: Vec<Id> = Vec::new();
for seg in s.split_ascii_whitespace() {
let Some((k, v)) = seg.split_once('=') else {
continue;
};
match k {
"uid" => {
uid = Id::parse(v);
}
"gid" => {
gid = Id::parse(v);
}
"groups" => {
for group in v.split(',') {
if let Some(id) = Id::parse(group) {
groups.push(id);
}
}
}
_ => {}
}
}
let (Some(uid), Some(gid)) = (uid, gid) else {
return None;
};
return Some(DeviceConnectionUserInfo { uid, gid, groups });
}
}

impl Debug for Id {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(name) = &self.name {
f.write_fmt(format_args!("{}({})", self.id, name))
} else {
f.write_fmt(format_args!("{}", self.id))
}
}
}
impl Id {
fn parse(s: &str) -> Option<Self> {
let regex = Regex::new("(\\d+)(\\(\\w+\\))?").unwrap();
let Some(caps) = regex.captures(s) else {
return None;
};
return Some(Self {
id: u32::from_str_radix(caps.get(1).unwrap().as_str(), 10).unwrap(),
name: caps.get(2).map(|s| {
s.as_str()
.trim_matches(|c| c == '(' || c == ')')
.to_string()
}),
});
}
}
15 changes: 14 additions & 1 deletion src-tauri/src/conn_pool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,24 @@ pub mod pool;

pub struct DeviceConnection {
id: Uuid,
device: Device,
pub device: Device,
pub user: Option<DeviceConnectionUserInfo>,
session: Session,
last_ok: Mutex<bool>,
}

#[derive(Debug)]
pub struct DeviceConnectionUserInfo {
pub uid: Id,
pub gid: Id,
pub groups: Vec<Id>,
}

pub struct Id {
pub id: u32,
pub name: Option<String>,
}

pub type ManagedDeviceConnection = PooledConnection<DeviceConnectionManager>;

pub struct DeviceConnectionPool {
Expand Down
18 changes: 15 additions & 3 deletions src-tauri/src/plugins/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ use std::fs::File;
use std::io::{copy, Read, Write};
use std::path::Path;

use flate2::read::GzDecoder;
use tauri::plugin::{Builder, TauriPlugin};
use tauri::{AppHandle, Manager, Runtime};
use uuid::Uuid;

use crate::device_manager::Device;
use crate::error::Error;
use crate::remote_files::serve;
use crate::remote_files::FileItem;
use crate::remote_files::{FileItem, PermInfo};
use crate::session_manager::SessionManager;

#[tauri::command]
Expand All @@ -28,10 +29,11 @@ async fn ls<R: Runtime>(
return sessions.with_session(device, |session| {
let sftp = session.sftp()?;
let entries = sftp.read_dir(&path)?;
let user = session.user.as_ref();
return Ok(entries
.iter()
.filter(|entry| entry.name() != Some(".") && entry.name() != Some(".."))
.map(|entry| entry.into())
.map(|entry| FileItem::new(entry, None, user.map(|u| PermInfo::from(entry, &u))))
.collect());
});
})
Expand All @@ -44,14 +46,24 @@ async fn read<R: Runtime>(
app: AppHandle<R>,
device: Device,
path: String,
encoding: Option<String>,
) -> Result<Vec<u8>, Error> {
return tokio::task::spawn_blocking(move || {
let sessions = app.state::<SessionManager>();
return sessions.with_session(device, |session| {
let sftp = session.sftp()?;
let mut file = sftp.open(&path, 0 /*O_RDONLY*/, 0)?;
let mut buf = Vec::<u8>::new();
file.read_to_end(&mut buf)?;
if let Some(encoding) = &encoding {
if encoding == "gzip" {
let mut decoder = GzDecoder::new(&mut file);
decoder.read_to_end(&mut buf)?;
} else {
return Err(Error::new(format!("Unsupported encoding {}", encoding)));
}
} else {
file.read_to_end(&mut buf)?;
}
return Ok(buf);
});
})
Expand Down
8 changes: 8 additions & 0 deletions src-tauri/src/remote_files/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,18 @@ pub struct FileItem {
size: usize,
mtime: f64,
link: Option<LinkInfo>,
access: Option<PermInfo>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct LinkInfo {
target: Option<String>,
broken: Option<bool>,
}

#[derive(Serialize, Clone, Debug)]
pub struct PermInfo {
read: bool,
write: bool,
execute: bool,
}
39 changes: 37 additions & 2 deletions src-tauri/src/remote_files/sftp.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
use std::time::UNIX_EPOCH;

use crate::conn_pool::DeviceConnectionUserInfo;
use libssh_rs::{FileType, Metadata};

use crate::remote_files::FileItem;
use crate::remote_files::{FileItem, LinkInfo, PermInfo};

impl From<&Metadata> for FileItem {
fn from(stat: &Metadata) -> Self {
return FileItem::new(stat, None, None);
}
}

impl FileItem {
pub(crate) fn new(stat: &Metadata, link: Option<LinkInfo>, access: Option<PermInfo>) -> Self {
return FileItem {
filename: String::from(stat.name().unwrap()),
r#type: format!(
Expand All @@ -22,7 +29,35 @@ impl From<&Metadata> for FileItem {
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs_f64(),
link: None,
link,
access,
};
}
}

impl PermInfo {
pub fn from(stat: &Metadata, user: &DeviceConnectionUserInfo) -> Self {
let perms = stat.permissions().unwrap_or(0);
if user.uid.id == stat.uid().unwrap_or(0) {
return PermInfo {
read: (perms & 0o400) != 0,
write: (perms & 0o200) != 0,
execute: (perms & 0o100) != 0,
};
}
for group in &user.groups {
if group.id == stat.gid().unwrap_or(0) {
return PermInfo {
read: (perms & 0o040) != 0,
write: (perms & 0o020) != 0,
execute: (perms & 0o010) != 0,
};
}
}
return PermInfo {
read: (perms & 0o004) != 0,
write: (perms & 0o002) != 0,
execute: (perms & 0o001) != 0,
};
}
}
Expand Down
43 changes: 18 additions & 25 deletions src/app/core/services/device-manager.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import {Injectable, NgZone} from "@angular/core";
import {BehaviorSubject, from, Observable, Subject} from "rxjs";
import {CrashReportEntry, Device, DeviceLike, FileSession, NewDevice, StorageInfo} from '../../types';
import {CrashReportEntry, Device, DeviceLike, FileItem, FileSession, NewDevice, StorageInfo} from '../../types';
import {BackendClient} from "./backend-client";
import {FileSessionImpl} from "./file.session";
import {HomebrewChannelConfiguration, SystemInfo} from "../../types/luna-apis";
import {basename} from "@tauri-apps/api/path";
import {LunaResponseError, RemoteLunaService} from "./remote-luna.service";
import {RemoteCommandService} from "./remote-command.service";
import {Buffer} from "buffer";
import {RemoteFileService} from "./remote-file.service";
import {DevModeService} from "./dev-mode.service";

Expand Down Expand Up @@ -77,20 +75,9 @@ export class DeviceManagerService extends BackendClient {
}

async listCrashReports(device: Device): Promise<CrashReport[]> {
return this.cmd.exec(device, 'find /tmp/faultmanager/crash/ -name \'*.gz\' -print0', 'utf-8')
.catch((e) => {
if (e.data) {
throw new Error(e.data);
} else {
throw e;
}
})
.then(output => output.split('\0').filter(l => l.length))
.then(list => Promise.all(list.map(l => CrashReport.obtain(this, device, l))));
}

async zcat(device: Device, path: string): Promise<Buffer> {
return await this.cmd.exec(device, `xargs -0 zcat`, 'buffer', path);
const dir = '/tmp/faultmanager/crash/';
return this.file.ls(device, dir)
.then(list => list.map(l => CrashReport.obtain(this.file, device, dir, l)));
}

async extendDevMode(device: Device): Promise<any> {
Expand Down Expand Up @@ -156,18 +143,24 @@ export class DeviceManagerService extends BackendClient {

export class CrashReport implements CrashReportEntry {

constructor(public device: Device, public path: string, public title: string, public summary: string,
public saveName: string, public content: Observable<string>) {
constructor(public device: Device, public dir: string, public file: FileItem, public title: string,
public summary: string, public saveName: string, public content: Observable<string>) {
}

get path(): string {
return `${this.dir}/${this.file.filename}`;
}

static async obtain(dm: DeviceManagerService, device: Device, path: string) {
const {title, summary, saveName} = await CrashReport.parseTitle(path);
const content = from(dm.zcat(device, path).then(content => content.toString('utf-8').trim()));
return new CrashReport(device, path, title, summary, saveName, content);
static obtain(fs: RemoteFileService, device: Device, dir: string, info: FileItem) {
const {title, summary, saveName} = CrashReport.parseTitle(info.filename);
const path = `${dir}/${info.filename}`;
const content = from(fs.read(device, path, 'gzip', 'utf-8')
.then(s => s.trim()));
return new CrashReport(device, dir, info, title, summary, saveName, content);
}

private static async parseTitle(path: string): Promise<{ title: string, summary: string; saveName: string; }> {
const name = (await basename(path)).replace(/[\x00-\x1f]/g, '/').replace(/.gz$/, '');
private static parseTitle(filename: string): { title: string, summary: string; saveName: string; } {
const name = filename.replace(/[\x00-\x1f]/g, '/').replace(/.gz$/, '');
let appDirIdx = -1, appDirPrefix = '';
for (const prefix of ['/usr/palm/applications/', '/var/palm/jail/']) {
appDirIdx = name.indexOf(prefix);
Expand Down
Loading
Loading