use crate::api::SessionFormat;
use crate::crypto::CryptoUtils;
use crate::error::{OpenteleError, Result};
use crate::qt_compat::{QByteArray, QDataStream, QDataStreamWriter};
use crate::td::auth::{AuthKey, AuthKeyType, AUTH_KEY_LEN};
use crate::td::storage::{FileWriteDescriptor, Storage};
use rand::RngCore;
use std::collections::HashSet;
use std::fmt;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use zeroize::Zeroize;
const DEFAULT_KEY_FILE: &str = "data";
const APP_VERSION: u32 = 5_001_000;
const MAX_ACCOUNTS: usize = 100;
const MTP_AUTHORIZATION_BLOCK_ID: i32 = 75;
pub struct TDesktop {
base_path: PathBuf,
key_file: String,
passcode: String,
local_key: Option<AuthKey>,
accounts: Vec<Account>,
}
impl fmt::Debug for TDesktop {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("TDesktop")
.field("base_path", &self.base_path)
.field("key_file", &self.key_file)
.field("passcode", &"[REDACTED]")
.field("local_key", &self.local_key)
.field("accounts", &self.accounts)
.finish()
}
}
impl Drop for TDesktop {
fn drop(&mut self) {
self.passcode.zeroize();
}
}
#[derive(Debug, Clone)]
pub struct Account {
index: u32,
active: bool,
auth_key: Option<AuthKey>,
user_id: u64,
main_dc: u32,
}
impl Account {
pub fn index(&self) -> u32 {
self.index
}
pub fn is_active(&self) -> bool {
self.active
}
pub fn user_id(&self) -> u64 {
self.user_id
}
pub fn main_dc(&self) -> u32 {
self.main_dc
}
}
struct LoadedAuthorization {
auth_key: AuthKey,
user_id: u64,
main_dc: u32,
}
impl TDesktop {
pub fn new<P: AsRef<Path>>(base_path: P) -> Result<Self> {
Ok(Self {
base_path: base_path.as_ref().to_path_buf(),
key_file: DEFAULT_KEY_FILE.to_string(),
passcode: String::new(),
local_key: None,
accounts: Vec::new(),
})
}
pub fn with_passcode(mut self, passcode: impl Into<String>) -> Self {
self.passcode = passcode.into();
self
}
pub fn base_path(&self) -> &Path {
&self.base_path
}
pub fn accounts(&self) -> &[Account] {
&self.accounts
}
pub fn load_tdata(&mut self) -> Result<()> {
let key_file_name = format!("key_{}", self.key_file);
let (payload, _) = Storage::read_tdf_file(&self.base_path, &key_file_name)?;
let mut stream = QDataStream::new(Cursor::new(payload));
let salt = stream.read_qbytearray()?;
let key_encrypted = stream.read_qbytearray()?;
let info_encrypted = stream.read_qbytearray()?;
if salt.is_null || salt.data.len() != 32 {
return Err(OpenteleError::InvalidTData(format!(
"local-key salt must contain 32 bytes, got {}",
salt.data.len()
)));
}
let passcode_key = AuthKey::new(
CryptoUtils::derive_local_key(self.passcode.as_bytes(), &salt.data)?,
AuthKeyType::Local,
0,
)?;
let key_inner_data = Storage::decrypt_local(&key_encrypted.data, &passcode_key)?;
if key_inner_data.len() != AUTH_KEY_LEN {
return Err(OpenteleError::InvalidTData(format!(
"local key must contain {AUTH_KEY_LEN} bytes, got {}",
key_inner_data.len()
)));
}
let local_key = AuthKey::new(key_inner_data, AuthKeyType::Local, 0)?;
let info_inner_data = Storage::decrypt_local(&info_encrypted.data, &local_key)?;
let mut info_stream = QDataStream::new(Cursor::new(info_inner_data));
let count = info_stream.read_i32()?;
if count <= 0 || count as usize > MAX_ACCOUNTS {
return Err(OpenteleError::InvalidTData(format!(
"account count must be between 1 and {MAX_ACCOUNTS}, got {count}"
)));
}
let mut accounts = Vec::with_capacity(count as usize);
let mut seen = HashSet::with_capacity(count as usize);
for _ in 0..count {
let index = info_stream.read_i32()?;
if index < 0 || !seen.insert(index) {
return Err(OpenteleError::InvalidTData(format!(
"invalid or duplicate account index: {index}"
)));
}
accounts.push(Account {
index: index as u32,
active: false,
auth_key: None,
user_id: 0,
main_dc: 0,
});
}
let active_index = info_stream.read_i32()?;
let mut found_active = false;
for account in &mut accounts {
if account.index == active_index as u32 && active_index >= 0 {
account.active = true;
found_active = true;
}
}
if !found_active {
return Err(OpenteleError::InvalidTData(format!(
"active account index {active_index} is not in the account list"
)));
}
self.local_key = Some(local_key);
self.accounts = accounts;
Ok(())
}
pub fn load_auth_key(&self, account_index: u32) -> Result<(AuthKey, u32)> {
let loaded = self.load_authorization(account_index)?;
Ok((loaded.auth_key, loaded.main_dc))
}
fn load_authorization(&self, account_index: u32) -> Result<LoadedAuthorization> {
if !self
.accounts
.iter()
.any(|account| account.index == account_index)
{
return Err(OpenteleError::InvalidArgument(format!(
"account index {account_index} is not loaded"
)));
}
let local_key = self
.local_key
.as_ref()
.ok_or_else(|| OpenteleError::InvalidTData("local key is not loaded".into()))?;
let data_name = compose_data_name(&self.key_file, account_index)?;
let file_part = Storage::to_file_part(Storage::compute_data_name_key(&data_name));
let (payload, _) = Storage::read_tdf_file(&self.base_path, &file_part)?;
let mut stream = QDataStream::new(Cursor::new(payload));
let encrypted = stream.read_qbytearray()?;
let decrypted = Storage::decrypt_local(&encrypted.data, local_key)?;
let mut stream = QDataStream::new(Cursor::new(decrypted));
let block_id = stream.read_i32()?;
if block_id != MTP_AUTHORIZATION_BLOCK_ID {
return Err(OpenteleError::InvalidTData(format!(
"expected MTP authorization block {MTP_AUTHORIZATION_BLOCK_ID}, got {block_id}"
)));
}
let serialized = stream.read_qbytearray()?;
let mut authorization = QDataStream::new(Cursor::new(serialized.data));
let user_low = authorization.read_i32()?;
let mut main_dc = authorization.read_i32()?;
let user_id = if user_low == -1 && main_dc == -1 {
let user_id = authorization.read_u64()?;
main_dc = authorization.read_i32()?;
user_id
} else {
user_low as u32 as u64
};
validate_dc(main_dc)?;
let key_count = authorization.read_i32()?;
if key_count <= 0 || key_count as usize > MAX_ACCOUNTS {
return Err(OpenteleError::InvalidTData(format!(
"invalid authorization-key count: {key_count}"
)));
}
let mut main_key = None;
for _ in 0..key_count {
let dc_id = authorization.read_i32()?;
validate_dc(dc_id)?;
let key = authorization.read_raw_data(AUTH_KEY_LEN)?;
if dc_id == main_dc {
main_key = Some(AuthKey::new(key, AuthKeyType::ReadFromFile, dc_id as u32)?);
}
}
let auth_key = main_key.ok_or_else(|| {
OpenteleError::InvalidTData("main DC authorization key was not found".into())
})?;
Ok(LoadedAuthorization {
auth_key,
user_id,
main_dc: main_dc as u32,
})
}
pub fn export_session<P: AsRef<Path>>(
&self,
session_path: P,
format: SessionFormat,
account_index: u32,
) -> Result<()> {
let loaded = self.load_authorization(account_index)?;
match format {
SessionFormat::Telethon => crate::tl::TelethonSession::save_to_sqlite(
&loaded.auth_key,
loaded.main_dc,
dc_ipv4(loaded.main_dc)?,
443,
session_path.as_ref(),
),
SessionFormat::Grammers => crate::grammers::export_grammers_session(
session_path,
loaded.main_dc,
&loaded.auth_key,
),
}
}
pub fn import_session<P: AsRef<Path>, Q: AsRef<Path>>(
session_path: P,
format: SessionFormat,
user_id: u64,
base_path: Q,
) -> Result<Self> {
if user_id == 0 {
return Err(OpenteleError::InvalidArgument(
"Telegram user ID must be non-zero".into(),
));
}
let (auth_key_bytes, dc_id) = match format {
SessionFormat::Telethon => {
crate::tl::TelethonSession::read_telethon_session(session_path.as_ref())?
}
SessionFormat::Grammers => {
crate::grammers::read_grammers_session(session_path.as_ref())?
}
};
validate_dc(dc_id as i32)?;
let mut local_key_bytes = vec![0u8; AUTH_KEY_LEN];
rand::thread_rng().fill_bytes(&mut local_key_bytes);
let local_key = AuthKey::new(local_key_bytes, AuthKeyType::Local, 0)?;
let auth_key = AuthKey::new(auth_key_bytes, AuthKeyType::ReadFromFile, dc_id)?;
let mut tdesktop = Self::new(base_path)?;
tdesktop.local_key = Some(local_key);
tdesktop.accounts.push(Account {
index: 0,
active: true,
auth_key: Some(auth_key),
user_id,
main_dc: dc_id,
});
Ok(tdesktop)
}
pub fn save_tdata(&self) -> Result<()> {
let local_key = self
.local_key
.as_ref()
.ok_or_else(|| OpenteleError::InvalidTData("local key is missing".into()))?;
if self.accounts.is_empty() || self.accounts.len() > MAX_ACCOUNTS {
return Err(OpenteleError::InvalidTData(format!(
"account count must be between 1 and {MAX_ACCOUNTS}"
)));
}
let mut resolved = Vec::with_capacity(self.accounts.len());
for account in &self.accounts {
if let Some(auth_key) = &account.auth_key {
validate_dc(account.main_dc as i32)?;
if account.user_id == 0 || auth_key.dc_id() != account.main_dc {
return Err(OpenteleError::InvalidTData(
"account metadata and authorization key are inconsistent".into(),
));
}
resolved.push(LoadedAuthorization {
auth_key: auth_key.clone(),
user_id: account.user_id,
main_dc: account.main_dc,
});
} else {
resolved.push(self.load_authorization(account.index)?);
}
}
for (account, authorization) in self.accounts.iter().zip(&resolved) {
self.write_account(account.index, authorization, local_key)?;
}
self.write_key_file(local_key)?;
Ok(())
}
fn write_account(
&self,
account_index: u32,
authorization: &LoadedAuthorization,
local_key: &AuthKey,
) -> Result<()> {
let data_name = compose_data_name(&self.key_file, account_index)?;
let file_part = Storage::to_file_part(Storage::compute_data_name_key(&data_name));
let account_path = self.base_path.join(&file_part);
let mut map_file = FileWriteDescriptor::new("maps", &account_path)?;
map_file.write_data(&[])?;
map_file.write_data(&[])?;
map_file.write_encrypted(&[], local_key)?;
map_file.finish(APP_VERSION)?;
let mut serialized = Vec::new();
let mut stream = QDataStreamWriter::new(Cursor::new(&mut serialized));
stream.write_u64(u64::MAX)?;
stream.write_u64(authorization.user_id)?;
stream.write_u32(authorization.main_dc)?;
stream.write_i32(1)?;
stream.write_u32(authorization.auth_key.dc_id())?;
stream.write_raw_data(authorization.auth_key.as_bytes())?;
stream.write_i32(0)?;
let mut encrypted_payload = Vec::new();
let mut payload_stream = QDataStreamWriter::new(Cursor::new(&mut encrypted_payload));
payload_stream.write_i32(MTP_AUTHORIZATION_BLOCK_ID)?;
payload_stream.write_qbytearray(&QByteArray::new(serialized))?;
let mut mtp_file = FileWriteDescriptor::new(&format!("{file_part}s"), &self.base_path)?;
mtp_file.write_encrypted(&encrypted_payload, local_key)?;
mtp_file.finish(APP_VERSION)?;
Ok(())
}
fn write_key_file(&self, local_key: &AuthKey) -> Result<()> {
let mut salt = [0u8; 32];
rand::thread_rng().fill_bytes(&mut salt);
let passcode_key = Storage::create_local_key(&salt, self.passcode.as_bytes())?;
let encrypted_local_key = Storage::prepare_encrypted(local_key.as_bytes(), &passcode_key)?;
let mut info = Vec::new();
let mut stream = QDataStreamWriter::new(Cursor::new(&mut info));
stream.write_i32(self.accounts.len() as i32)?;
for account in &self.accounts {
stream.write_i32(account.index as i32)?;
}
let active = self
.accounts
.iter()
.find(|account| account.active)
.ok_or_else(|| OpenteleError::InvalidTData("no active account is set".into()))?;
stream.write_i32(active.index as i32)?;
let mut key_file =
FileWriteDescriptor::new(&format!("key_{}s", self.key_file), &self.base_path)?;
key_file.write_data(&salt)?;
key_file.write_data(&encrypted_local_key)?;
key_file.write_encrypted(&info, local_key)?;
key_file.finish(APP_VERSION)?;
Ok(())
}
}
fn compose_data_name(key_file: &str, account_index: u32) -> Result<String> {
if account_index == 0 {
Ok(key_file.to_string())
} else {
let number = account_index
.checked_add(1)
.ok_or_else(|| OpenteleError::InvalidArgument("account index is too large".into()))?;
Ok(format!("{key_file}#{number}"))
}
}
fn validate_dc(dc_id: i32) -> Result<()> {
if !(1..=5).contains(&dc_id) {
return Err(OpenteleError::InvalidTData(format!(
"Telegram data-center ID must be between 1 and 5, got {dc_id}"
)));
}
Ok(())
}
pub(crate) fn dc_ipv4(dc_id: u32) -> Result<&'static str> {
match dc_id {
1 => Ok("149.154.175.50"),
2 => Ok("149.154.167.51"),
3 => Ok("149.154.175.100"),
4 => Ok("149.154.167.91"),
5 => Ok("149.154.171.5"),
_ => Err(OpenteleError::InvalidArgument(format!(
"unsupported Telegram data-center ID: {dc_id}"
))),
}
}
pub(crate) fn dc_ipv6(dc_id: u32) -> Result<&'static str> {
match dc_id {
1 => Ok("2001:0b28:f23d:f001:0000:0000:0000:000a"),
2 => Ok("2001:067c:04e8:f002:0000:0000:0000:000a"),
3 => Ok("2001:0b28:f23d:f003:0000:0000:0000:000a"),
4 => Ok("2001:067c:04e8:f004:0000:0000:0000:000a"),
5 => Ok("2001:0b28:f23f:f005:0000:0000:0000:000a"),
_ => Err(OpenteleError::InvalidArgument(format!(
"unsupported Telegram data-center ID: {dc_id}"
))),
}
}