grammpars 0.1.0

Offline conversion between Telegram Desktop tdata, Telethon, and grammers sessions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
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;

/// A Telegram Desktop `tdata` directory.
pub struct TDesktop {
    base_path: PathBuf,
    key_file: String,
    passcode: String,
    local_key: Option<AuthKey>,
    accounts: Vec<Account>,
}

impl fmt::Debug for TDesktop {
    /// Formats desktop metadata while redacting the local passcode and key bytes.
    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 {
    /// Zeroizes the local passcode before its allocation is released.
    fn drop(&mut self) {
        self.passcode.zeroize();
    }
}

/// Metadata for an account stored in `tdata`.
#[derive(Debug, Clone)]
pub struct Account {
    index: u32,
    active: bool,
    auth_key: Option<AuthKey>,
    user_id: u64,
    main_dc: u32,
}

impl Account {
    /// Account slot index in the `tdata` directory.
    pub fn index(&self) -> u32 {
        self.index
    }

    /// Whether this is the active Telegram Desktop account.
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Telegram user ID, when already resolved from MTP authorization data.
    pub fn user_id(&self) -> u64 {
        self.user_id
    }

    /// Home Telegram data-center ID, when already resolved.
    pub fn main_dc(&self) -> u32 {
        self.main_dc
    }
}

struct LoadedAuthorization {
    auth_key: AuthKey,
    user_id: u64,
    main_dc: u32,
}

impl TDesktop {
    /// Creates a handle for a `tdata` directory without reading it.
    ///
    /// # Errors
    ///
    /// This constructor currently performs no I/O and returns no errors. The
    /// result remains wrapped to preserve a uniform construction API.
    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(),
        })
    }

    /// Sets the Telegram Desktop local passcode used for loading or saving.
    pub fn with_passcode(mut self, passcode: impl Into<String>) -> Self {
        self.passcode = passcode.into();
        self
    }

    /// Returns the directory represented by this handle.
    pub fn base_path(&self) -> &Path {
        &self.base_path
    }

    /// Returns account entries loaded from the key file.
    pub fn accounts(&self) -> &[Account] {
        &self.accounts
    }

    /// Loads and authenticates the key file and account list.
    ///
    /// # Errors
    ///
    /// Returns an error when storage files are missing or malformed, the
    /// passcode is incorrect, decryption fails, or account metadata is invalid.
    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(())
    }

    /// Loads the authorization key for an account index.
    ///
    /// # Errors
    ///
    /// Returns an error when the account is unknown, its storage file cannot be
    /// read or decrypted, or its authorization metadata is invalid.
    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))
    }

    /// Loads and validates the serialized authorization record for one account.
    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,
        })
    }

    /// Exports one account into a Telethon or grammers SQLite session.
    ///
    /// # Errors
    ///
    /// Returns an error when the account authorization cannot be loaded, the DC
    /// is unsupported, or the destination session cannot be written safely.
    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,
            ),
        }
    }

    /// Imports a SQLite session into an in-memory Telegram Desktop account.
    ///
    /// # Errors
    ///
    /// Returns an error for a zero user ID, an unreadable or unsupported session,
    /// an invalid DC, or malformed authorization key material.
    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)
    }

    /// Writes a Telegram Desktop-compatible `tdata` directory.
    ///
    /// # Errors
    ///
    /// Returns an error for missing or inconsistent account data, an unsupported
    /// DC, encryption failure, or an I/O failure while replacing storage files.
    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(())
    }

    /// Writes the map and MTP authorization files for one account.
    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(())
    }

    /// Writes the passcode protected local key and account index file.
    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(())
    }
}

/// Produces Telegram Desktop's logical data name for an account slot.
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}"))
    }
}

/// Validates that a data center identifier belongs to a production Telegram DC.
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(())
}

/// Returns the production IPv4 address for a Telegram data center.
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}"
        ))),
    }
}

/// Returns the production IPv6 address for a Telegram data center.
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}"
        ))),
    }
}