navid/veins / 83508482911f348af86cb892949a35bdce0d6b2f949b4a0faab7cba9a499fb82 / veinsrs/src/protocol/wire.rs

wire.rs

← veinsrs/src/protocol · 7634 bytes · raw · download

use std::io::{Read, Write};

use crate::error::{Error, Result};
use crate::object::MAX_OBJECT_BODY;
use crate::object::id::Id;

pub const MAX_FRAME: usize = 16 * 1024 * 1024;

pub mod kind {
    pub const HELLO: u8 = 1;
    pub const HELLO_OK: u8 = 2;
    pub const AUTH: u8 = 3;
    pub const AUTH_OK: u8 = 4;
    pub const WHOAMI: u8 = 5;
    pub const WHOAMI_OK: u8 = 6;
    pub const LIST_REFS: u8 = 7;
    pub const REFS: u8 = 8;
    pub const NEGOTIATE: u8 = 9;
    pub const NEGOTIATE_OK: u8 = 10;
    pub const FETCH_SKELETON: u8 = 11;
    pub const GET_CHUNKS: u8 = 12;
    pub const HAVE_QUERY: u8 = 13;
    pub const HAVE_BITMAP: u8 = 14;
    pub const PUT_RECORDS: u8 = 15;
    pub const UPDATE_REFS: u8 = 16;
    pub const UPDATE_REFS_OK: u8 = 17;
    pub const RECORDS: u8 = 18;
    pub const END: u8 = 19;
    pub const ERROR: u8 = 20;
}

pub mod error_code {
    pub const UNSUPPORTED_VERSION: u8 = 1;
    pub const BAD_FRAME: u8 = 2;
    pub const NOT_FOUND: u8 = 3;
    pub const HASH_MISMATCH: u8 = 4;
    pub const NON_CANONICAL: u8 = 5;
    pub const MISSING_CLOSURE: u8 = 6;
    pub const REF_CONFLICT: u8 = 7;
    pub const REJECTED: u8 = 8;
    pub const INTERNAL: u8 = 9;
    pub const UNAUTHENTICATED: u8 = 10;
    pub const FORBIDDEN: u8 = 11;
    pub const AUTH_FAILED: u8 = 12;
    pub const QUOTA: u8 = 13;
    pub const TOO_LARGE: u8 = 14;
}

pub struct Frame {
    pub kind: u8,
    pub request_id: u32,
    pub payload: Vec<u8>,
}

pub struct Stream {
    reader: Box<dyn Read + Send>,
    writer: Box<dyn Write + Send>,
    child: Option<std::process::Child>,
}

impl Stream {
    pub fn stdio() -> Self {
        Self {
            reader: Box::new(std::io::stdin()),
            writer: Box::new(std::io::stdout()),
            child: None,
        }
    }

    pub fn spawn(arguments: &[String]) -> Result<Self> {
        let executable = std::env::current_exe().map_err(Error::from)?;
        let mut child = std::process::Command::new(executable)
            .args(arguments)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::inherit())
            .spawn()
            .map_err(Error::from)?;
        let stdin = child
            .stdin
            .take()
            .ok_or_else(|| Error::new("cannot open child stdin"))?;
        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| Error::new("cannot open child stdout"))?;
        Ok(Self {
            reader: Box::new(stdout),
            writer: Box::new(stdin),
            child: Some(child),
        })
    }

    fn read_exact(&mut self, buffer: &mut [u8]) -> bool {
        let mut done = 0;
        while done < buffer.len() {
            match self.reader.read(&mut buffer[done..]) {
                Ok(0) => return false,
                Ok(count) => done += count,
                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(_) => return false,
            }
        }
        true
    }

    pub fn read_frame(&mut self) -> Option<Frame> {
        let mut head = [0u8; 4];
        if !self.read_exact(&mut head) {
            return None;
        }
        let length = u32::from_be_bytes(head) as usize;
        if !(5..=MAX_FRAME).contains(&length) {
            return None;
        }
        let mut body = vec![0u8; length];
        if !self.read_exact(&mut body) {
            return None;
        }
        Some(Frame {
            kind: body[0],
            request_id: u32::from_be_bytes([body[1], body[2], body[3], body[4]]),
            payload: body[5..].to_vec(),
        })
    }

    pub fn write_frame(&mut self, kind: u8, request_id: u32, payload: &[u8]) -> bool {
        if payload.len() > MAX_FRAME - 5 {
            return false;
        }
        let length = 5 + payload.len();
        let mut head = Vec::with_capacity(9 + payload.len());
        head.extend_from_slice(&(length as u32).to_be_bytes());
        head.push(kind);
        head.extend_from_slice(&request_id.to_be_bytes());
        head.extend_from_slice(payload);
        self.writer.write_all(&head).is_ok() && self.writer.flush().is_ok()
    }

    pub fn write_simple(&mut self, kind: u8, request_id: u32) -> bool {
        self.write_frame(kind, request_id, &[])
    }

    pub fn write_error(&mut self, request_id: u32, code: u8, message: &str) -> bool {
        let mut payload = Vec::with_capacity(message.len() + 8);
        payload.push(code);
        crate::encoding::Writer::varint_into(&mut payload, message.len() as u64);
        payload.extend_from_slice(message.as_bytes());
        self.write_frame(kind::ERROR, request_id, &payload)
    }
}

impl Drop for Stream {
    fn drop(&mut self) {
        if let Some(child) = &mut self.child {
            let _ = child.kill();
            let _ = child.wait();
        }
    }
}

pub fn read_error(payload: &[u8]) -> u8 {
    payload.first().copied().unwrap_or(error_code::INTERNAL)
}

pub fn error_message(payload: &[u8]) -> String {
    if payload.len() < 2 {
        return String::new();
    }
    let mut reader = crate::encoding::Reader::new(&payload[1..]);
    match reader.bytes(4096) {
        Ok(value) => String::from_utf8_lossy(value).into_owned(),
        Err(_) => String::new(),
    }
}

pub fn error_code_name(code: u8) -> &'static str {
    match code {
        error_code::UNSUPPORTED_VERSION => "unsupported protocol version",
        error_code::BAD_FRAME => "bad frame",
        error_code::NOT_FOUND => "object not found",
        error_code::HASH_MISMATCH => "hash mismatch",
        error_code::NON_CANONICAL => "non-canonical object",
        error_code::MISSING_CLOSURE => "missing object closure",
        error_code::REF_CONFLICT => "ref conflict",
        error_code::REJECTED => "request rejected",
        error_code::INTERNAL => "server internal error",
        error_code::UNAUTHENTICATED => "authentication required",
        error_code::FORBIDDEN => "permission denied",
        error_code::AUTH_FAILED => "authentication failed",
        error_code::QUOTA => "storage quota exceeded",
        error_code::TOO_LARGE => "push too large",
        _ => "unknown server error",
    }
}

pub struct IncomingRecord {
    pub id: Id,
    pub kind: u8,
    pub body: Vec<u8>,
}

pub fn parse_record(data: &[u8]) -> Option<IncomingRecord> {
    if data.len() < 35 {
        return None;
    }
    let mut reader = crate::encoding::Reader::new(data);
    let id = reader.id().ok()?;
    let kind = reader.u8().ok()?;
    let compression = reader.u8().ok()?;
    let raw_len = reader.varint().ok()?;
    let stored_len = reader.varint().ok()?;
    if raw_len == 0 || raw_len > MAX_OBJECT_BODY as u64 || stored_len > MAX_FRAME as u64 {
        return None;
    }
    let stored = reader.raw(stored_len as usize).ok()?;
    reader.finish().ok()?;
    if compression == 0 {
        if stored.len() as u64 != raw_len {
            return None;
        }
        return Some(IncomingRecord {
            id,
            kind,
            body: stored.to_vec(),
        });
    }
    let body = zstd::bulk::decompress(stored, raw_len as usize).ok()?;
    if body.len() as u64 != raw_len {
        return None;
    }
    Some(IncomingRecord { id, kind, body })
}

pub fn make_record(id: Id, kind: u8, body: &[u8]) -> Vec<u8> {
    let mut writer = crate::encoding::Writer::with_capacity(body.len() + 64);
    writer.id(id);
    writer.u8(kind);
    writer.u8(0);
    writer.varint(body.len() as u64);
    writer.varint(body.len() as u64);
    writer.raw(body);
    writer.into_vec()
}