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

messages.rs

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

use crate::encoding::{Reader, Writer};
use crate::error::{Error, Result};
use crate::object::id::Id;

pub const PROTOCOL_VERSION: u16 = 1;

pub struct Hello {
    pub min_version: u16,
    pub max_version: u16,
    pub capabilities: Vec<String>,
    pub repo: String,
    pub client_nonce: Vec<u8>,
}

pub struct HelloOk {
    pub version: u16,
    pub capabilities: Vec<String>,
    pub server_nonce: Vec<u8>,
    pub auth_required: u8,
}

pub struct Auth {
    pub public_key: Vec<u8>,
    pub signature: Vec<u8>,
}

pub struct AuthOk {
    pub role: u8,
    pub fingerprint: Vec<u8>,
}

pub struct RefInfo {
    pub name: String,
    pub target: Id,
    pub change_id: String,
    pub kind: u8,
}

pub struct Negotiate {
    pub wants: Vec<Id>,
    pub haves: Vec<Id>,
}

#[derive(Clone)]
pub struct UpdateRef {
    pub name: String,
    pub expected: Option<Id>,
    pub target: Option<Id>,
}

fn put_u16(writer: &mut Writer, value: u16) {
    writer.u8((value >> 8) as u8);
    writer.u8(value as u8);
}

fn read_u16(reader: &mut Reader<'_>) -> Result<u16> {
    let high = reader.u8()?;
    let low = reader.u8()?;
    Ok(u16::from_be_bytes([high, low]))
}

fn encode_string_list(items: &[String]) -> Vec<u8> {
    let mut writer = Writer::with_capacity(128);
    writer.varint(items.len() as u64);
    for item in items {
        writer.bytes(item.as_bytes());
    }
    writer.into_vec()
}

fn decode_string_list(reader: &mut Reader<'_>, maximum: usize) -> Result<Vec<String>> {
    let count = reader.varint()?;
    let count = usize::try_from(count).map_err(|_| Error::new("string list overflow"))?;
    if count > maximum {
        return Err(Error::new("string list limit exceeded"));
    }
    let mut output = Vec::with_capacity(count);
    for _ in 0..count {
        let value = reader.bytes(4096)?;
        output.push(String::from_utf8_lossy(value).into_owned());
    }
    Ok(output)
}

pub fn encode_hello(hello: &Hello) -> Vec<u8> {
    let mut writer = Writer::with_capacity(128);
    put_u16(&mut writer, hello.min_version);
    put_u16(&mut writer, hello.max_version);
    writer.raw(&encode_string_list(&hello.capabilities));
    writer.bytes(hello.repo.as_bytes());
    writer.bytes(&hello.client_nonce);
    writer.into_vec()
}

pub fn decode_hello(data: &[u8]) -> Option<Hello> {
    let mut reader = Reader::new(data);
    let min_version = read_u16(&mut reader).ok()?;
    let max_version = read_u16(&mut reader).ok()?;
    let capabilities = decode_string_list(&mut reader, 64).ok()?;
    let repo = reader.bytes(4096).ok()?;
    let nonce = reader.bytes(64).ok()?;
    reader.finish().ok()?;
    Some(Hello {
        min_version,
        max_version,
        capabilities,
        repo: String::from_utf8_lossy(repo).into_owned(),
        client_nonce: nonce.to_vec(),
    })
}

pub fn encode_hello_ok(hello: &HelloOk) -> Vec<u8> {
    let mut writer = Writer::with_capacity(128);
    put_u16(&mut writer, hello.version);
    writer.raw(&encode_string_list(&hello.capabilities));
    writer.bytes(&hello.server_nonce);
    writer.u8(hello.auth_required);
    writer.into_vec()
}

pub fn decode_hello_ok(data: &[u8]) -> Option<HelloOk> {
    let mut reader = Reader::new(data);
    let version = read_u16(&mut reader).ok()?;
    let capabilities = decode_string_list(&mut reader, 64).ok()?;
    let nonce = reader.bytes(64).ok()?;
    let auth_required = reader.u8().ok()?;
    reader.finish().ok()?;
    Some(HelloOk {
        version,
        capabilities,
        server_nonce: nonce.to_vec(),
        auth_required,
    })
}

pub fn encode_auth(auth: &Auth) -> Vec<u8> {
    let mut writer = Writer::with_capacity(128);
    writer.bytes(&auth.public_key);
    writer.bytes(&auth.signature);
    writer.into_vec()
}

pub fn decode_auth(data: &[u8]) -> Option<Auth> {
    let mut reader = Reader::new(data);
    let public_key = reader.bytes(64).ok()?;
    let signature = reader.bytes(128).ok()?;
    reader.finish().ok()?;
    Some(Auth {
        public_key: public_key.to_vec(),
        signature: signature.to_vec(),
    })
}

pub fn encode_auth_ok(auth: &AuthOk) -> Vec<u8> {
    let mut writer = Writer::with_capacity(64);
    writer.u8(auth.role);
    writer.bytes(&auth.fingerprint);
    writer.into_vec()
}

pub fn decode_auth_ok(data: &[u8]) -> Option<AuthOk> {
    let mut reader = Reader::new(data);
    let role = reader.u8().ok()?;
    let fingerprint = reader.bytes(64).ok()?;
    reader.finish().ok()?;
    Some(AuthOk {
        role,
        fingerprint: fingerprint.to_vec(),
    })
}

pub fn encode_refs(refs: &[RefInfo]) -> Vec<u8> {
    let mut writer = Writer::with_capacity(256);
    writer.varint(refs.len() as u64);
    for reference in refs {
        writer.bytes(reference.name.as_bytes());
        writer.id(reference.target);
        writer.bytes(reference.change_id.as_bytes());
        writer.u8(reference.kind);
    }
    writer.into_vec()
}

pub fn decode_refs(data: &[u8]) -> Option<Vec<RefInfo>> {
    let mut reader = Reader::new(data);
    let count = reader.varint().ok()?;
    let count = usize::try_from(count).ok()?;
    if count > 1_000_000 {
        return None;
    }
    let mut output = Vec::with_capacity(count);
    for _ in 0..count {
        let name = reader.bytes(4096).ok()?;
        let target = reader.id().ok()?;
        let change = reader.bytes(64).ok()?;
        let kind = reader.u8().ok()?;
        output.push(RefInfo {
            name: String::from_utf8_lossy(name).into_owned(),
            target,
            change_id: String::from_utf8_lossy(change).into_owned(),
            kind,
        });
    }
    reader.finish().ok()?;
    Some(output)
}

pub fn encode_ids(ids: &[Id]) -> Vec<u8> {
    let mut writer = Writer::with_capacity(ids.len() * 32 + 8);
    writer.varint(ids.len() as u64);
    for id in ids {
        writer.id(*id);
    }
    writer.into_vec()
}

pub fn decode_ids(data: &[u8], maximum: usize) -> Option<Vec<Id>> {
    let mut reader = Reader::new(data);
    let count = reader.varint().ok()?;
    let count = usize::try_from(count).ok()?;
    if count > maximum {
        return None;
    }
    let mut output = Vec::with_capacity(count);
    for _ in 0..count {
        output.push(reader.id().ok()?);
    }
    reader.finish().ok()?;
    Some(output)
}

pub fn encode_negotiate(wants: &[Id], haves: &[Id]) -> Vec<u8> {
    let mut writer = Writer::with_capacity(256);
    writer.raw(&encode_ids(wants));
    writer.raw(&encode_ids(haves));
    writer.into_vec()
}

pub fn decode_negotiate(data: &[u8]) -> Option<Negotiate> {
    let mut reader = Reader::new(data);
    let count = reader.varint().ok()?;
    let count = usize::try_from(count).ok()?;
    if count > 1_000_000 {
        return None;
    }
    let mut wants = Vec::with_capacity(count);
    for _ in 0..count {
        wants.push(reader.id().ok()?);
    }
    let count = reader.varint().ok()?;
    let count = usize::try_from(count).ok()?;
    if count > 1_000_000 {
        return None;
    }
    let mut haves = Vec::with_capacity(count);
    for _ in 0..count {
        haves.push(reader.id().ok()?);
    }
    reader.finish().ok()?;
    Some(Negotiate { wants, haves })
}

pub fn encode_negotiate_ok(known: &[u8], enough: u8) -> Vec<u8> {
    let mut writer = Writer::with_capacity(known.len() + 16);
    writer.u8(enough);
    writer.varint(known.len() as u64);
    writer.raw(known);
    writer.into_vec()
}

pub fn decode_negotiate_ok(data: &[u8]) -> Option<Vec<u8>> {
    let mut reader = Reader::new(data);
    reader.u8().ok()?;
    let count = reader.varint().ok()?;
    let count = usize::try_from(count).ok()?;
    if count > 1_000_000 {
        return None;
    }
    let bits = reader.raw(count).ok()?.to_vec();
    reader.finish().ok()?;
    Some(bits)
}

pub fn encode_bitmap(bits: &[u8]) -> Vec<u8> {
    let mut writer = Writer::with_capacity(bits.len() + 8);
    writer.varint(bits.len() as u64);
    writer.raw(bits);
    writer.into_vec()
}

pub fn decode_bitmap(data: &[u8]) -> Option<Vec<u8>> {
    let mut reader = Reader::new(data);
    let count = reader.varint().ok()?;
    let count = usize::try_from(count).ok()?;
    if count > 1_000_000 {
        return None;
    }
    let bits = reader.raw(count).ok()?.to_vec();
    reader.finish().ok()?;
    Some(bits)
}

pub fn encode_update_refs(updates: &[UpdateRef]) -> Vec<u8> {
    let mut writer = Writer::with_capacity(256);
    writer.varint(updates.len() as u64);
    for update in updates {
        writer.bytes(update.name.as_bytes());
        writer.opt_id(update.expected);
        writer.opt_id(update.target);
    }
    writer.into_vec()
}

pub fn decode_update_refs(data: &[u8]) -> Option<Vec<UpdateRef>> {
    let mut reader = Reader::new(data);
    let count = reader.varint().ok()?;
    let count = usize::try_from(count).ok()?;
    if count > 1_000_000 {
        return None;
    }
    let mut output = Vec::with_capacity(count);
    for _ in 0..count {
        let name = reader.bytes(4096).ok()?;
        let expected = reader.opt_id().ok()?;
        let target = reader.opt_id().ok()?;
        output.push(UpdateRef {
            name: String::from_utf8_lossy(name).into_owned(),
            expected,
            target,
        });
    }
    reader.finish().ok()?;
    Some(output)
}

pub fn auth_message(
    version: u16,
    repo: &str,
    server_nonce: &[u8],
    client_nonce: &[u8],
    binding: &[u8],
) -> Vec<u8> {
    let mut writer = Writer::with_capacity(128);
    writer.raw(b"veins-auth/1");
    writer.u8(0);
    put_u16(&mut writer, version);
    writer.bytes(repo.as_bytes());
    writer.raw(server_nonce);
    writer.raw(client_nonce);
    writer.raw(binding);
    writer.into_vec()
}

pub fn role_name(role: u8) -> &'static str {
    match role {
        2 => "write",
        1 => "read",
        _ => "anonymous",
    }
}

pub struct Url {
    pub tls: bool,
    pub ssh: bool,
    pub host: String,
    pub port: i32,
    pub path: String,
}

fn parse_authority(authority: &str, default_port: i32, strip_user: bool) -> (String, i32) {
    let authority = if strip_user {
        authority.rsplit('@').next().unwrap_or(authority)
    } else {
        authority
    };
    let mut host = authority.to_string();
    let mut port = default_port;
    if let Some((name, value)) = authority.rsplit_once(':') {
        host = name.to_string();
        if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
            port = value.parse().unwrap_or(default_port);
        }
    }
    (host, port)
}

pub fn parse_url(url: &str) -> Option<Url> {
    if let Some(path) = url.strip_prefix("file://") {
        return Some(Url {
            tls: false,
            ssh: false,
            host: String::new(),
            port: 0,
            path: path.to_string(),
        });
    }
    if let Some(rest) = url.strip_prefix("ssh://") {
        let slash = rest.find('/')?;
        let (host, port) = parse_authority(&rest[..slash], 22, true);
        return Some(Url {
            tls: false,
            ssh: true,
            host,
            port,
            path: rest[slash + 1..].to_string(),
        });
    }
    if let Some(rest) = url.strip_prefix("veins://") {
        let slash = rest.find('/')?;
        let (host, port) = parse_authority(&rest[..slash], 7419, false);
        return Some(Url {
            tls: true,
            ssh: false,
            host,
            port,
            path: rest[slash + 1..].to_string(),
        });
    }
    None
}

pub fn url_repo_name(url: &str) -> String {
    match parse_url(url) {
        Some(parsed) if parsed.tls => parsed.path,
        _ => String::new(),
    }
}