grammpars 0.1.0

Offline conversion between Telegram Desktop tdata, Telethon, and grammers sessions
Documentation
//! grammers SQLite session support.

use crate::error::{OpenteleError, Result};
use crate::td::auth::{AuthKey, AUTH_KEY_LEN};
use crate::td::tdesktop::{dc_ipv4, dc_ipv6};
use crate::utils::{replace_file, temporary_sibling};
use rusqlite::{params, Connection};
use std::path::Path;

const GRAMMERS_SCHEMA_VERSION: i64 = 1;

/// Creates or atomically replaces a grammers SQLite session.
///
/// # Errors
///
/// Returns an error for an unsupported DC, an invalid output path, a SQLite
/// failure, an I/O failure, or a failed atomic replacement.
pub fn export_grammers_session<P: AsRef<Path>>(
    path: P,
    main_dc: u32,
    auth_key: &AuthKey,
) -> Result<()> {
    let ipv4 = dc_ipv4(main_dc)?;
    let ipv6 = dc_ipv6(main_dc)?;
    let destination = path.as_ref();
    let temporary = temporary_sibling(destination)?;
    let result = (|| -> Result<()> {
        let mut db = Connection::open(&temporary)?;
        let tx = db.transaction()?;
        tx.execute_batch(
            "CREATE TABLE dc_home (
                 dc_id INTEGER NOT NULL,
                 PRIMARY KEY(dc_id)
             );
             CREATE TABLE dc_option (
                 dc_id INTEGER NOT NULL,
                 ipv4 TEXT NOT NULL,
                 ipv6 TEXT NOT NULL,
                 auth_key BLOB,
                 PRIMARY KEY(dc_id)
             );
             CREATE TABLE peer_info (
                 peer_id INTEGER NOT NULL,
                 hash INTEGER,
                 subtype INTEGER,
                 PRIMARY KEY(peer_id)
             );
             CREATE TABLE update_state (
                 pts INTEGER NOT NULL,
                 qts INTEGER NOT NULL,
                 date INTEGER NOT NULL,
                 seq INTEGER NOT NULL
             );
             CREATE TABLE channel_state (
                 peer_id INTEGER NOT NULL,
                 pts INTEGER NOT NULL,
                 PRIMARY KEY(peer_id)
             );",
        )?;
        tx.pragma_update(None, "user_version", GRAMMERS_SCHEMA_VERSION)?;
        tx.execute("INSERT INTO dc_home (dc_id) VALUES (?1)", [main_dc])?;
        tx.execute(
            "INSERT INTO dc_option (dc_id, ipv4, ipv6, auth_key)
             VALUES (?1, ?2, ?3, ?4)",
            params![main_dc, ipv4, ipv6, auth_key.as_bytes()],
        )?;
        tx.commit()?;
        drop(db);
        replace_file(&temporary, destination)?;
        Ok(())
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&temporary);
    }
    result
}

/// Reads and validates the home authorization key from a grammers session.
///
/// # Errors
///
/// Returns an error when the file is missing, SQLite cannot read it, the schema
/// is unsupported, the home DC is invalid, or the key is not 256 bytes.
pub fn read_grammers_session(session_path: &Path) -> Result<(Vec<u8>, u32)> {
    if !session_path.is_file() {
        return Err(OpenteleError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("session file {} does not exist", session_path.display()),
        )));
    }
    let conn = Connection::open(session_path)?;
    let schema_version: i64 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
    if schema_version != GRAMMERS_SCHEMA_VERSION {
        return Err(OpenteleError::Unsupported(format!(
            "grammers schema version {schema_version}; expected {GRAMMERS_SCHEMA_VERSION}"
        )));
    }
    let (dc_id, auth_key): (i64, Vec<u8>) = conn
        .query_row(
            "SELECT h.dc_id, o.auth_key
             FROM dc_home h JOIN dc_option o ON o.dc_id = h.dc_id
             LIMIT 1",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .map_err(|error| match error {
            rusqlite::Error::QueryReturnedNoRows => {
                OpenteleError::InvalidTData("grammers session contains no home auth key".into())
            }
            other => other.into(),
        })?;
    let dc_id = u32::try_from(dc_id)
        .map_err(|_| OpenteleError::InvalidTData("grammers DC ID is negative".into()))?;
    dc_ipv4(dc_id)?;
    if auth_key.len() != AUTH_KEY_LEN {
        return Err(OpenteleError::InvalidTData(format!(
            "grammers auth key must contain {AUTH_KEY_LEN} bytes, got {}",
            auth_key.len()
        )));
    }
    Ok((auth_key, dc_id))
}