1use rand::Rng;
22
23use crate::error::E2eError;
24
25pub const ID_DECRYPTED_MESSAGE: u32 = 0x91cc4674;
29
30pub const ID_DECRYPTED_MESSAGE_OLD: u32 = 0x36b091de;
32
33pub const ID_DECRYPTED_MESSAGE_SERVICE: u32 = 0x73164160;
35
36pub const ID_DECRYPTED_MESSAGE_SERVICE8: u32 = 0xaa48327d;
38
39pub const ID_DECRYPTED_MESSAGE_LAYER: u32 = 0x1be31789;
41
42pub const ID_ACTION_NOTIFY_LAYER: u32 = 0xf3048883;
44
45pub const ID_ACTION_REQUEST_KEY: u32 = 0xf3c9611b;
47
48pub const ID_ACTION_ACCEPT_KEY: u32 = 0x6fe1735b;
50
51pub const ID_ACTION_ABORT_KEY: u32 = 0xdd05ec6b;
53
54pub const ID_ACTION_COMMIT_KEY: u32 = 0xec2e0b9b;
56
57pub const ID_ACTION_NOOP: u32 = 0xa82fdd63;
59
60pub const ID_ACTION_SET_TTL: u32 = 0xa1733aec;
62
63pub const ID_ACTION_RESEND: u32 = 0x511110b0;
65
66pub const ID_ACTION_READ_MESSAGES: u32 = 0x0c4f40be;
68
69pub const ID_ACTION_DELETE_MESSAGES: u32 = 0x65614304;
71
72pub const ID_ACTION_SCREENSHOT_MESSAGES: u32 = 0x8ac1f475;
74
75pub const ID_ACTION_FLUSH_HISTORY: u32 = 0x6719e45c;
77
78pub const ID_ACTION_TYPING: u32 = 0xccb27641;
80
81pub const ID_MEDIA_EMPTY: u32 = 0x089f5c4a;
83
84pub const ID_MEDIA_VENUE: u32 = 0x8a0df56f;
86
87pub const ID_MEDIA_PHOTO: u32 = 0xf1fa8d78;
89
90pub const ID_MEDIA_PHOTO_OLD: u32 = 0x32798a8c;
92
93pub const ID_MEDIA_DOCUMENT: u32 = 0x6abd9782;
95
96pub const ID_MEDIA_DOCUMENT_OLD: u32 = 0xb095434b;
98
99pub const ID_MEDIA_GEO: u32 = 0x35480a59;
101
102pub const ID_MEDIA_CONTACT: u32 = 0x588a0a97;
104
105pub const ID_MEDIA_AUDIO_L8: u32 = 0x6080758f;
107
108pub const ID_MEDIA_AUDIO_L17: u32 = 0x57e0a9cb;
110
111pub const ID_MEDIA_VIDEO_L8: u32 = 0x4cee6ef3;
113
114pub const ID_MEDIA_VIDEO_L17: u32 = 0x524a415d;
116
117pub const ID_MEDIA_VIDEO_L45: u32 = 0x970c8c0e;
119
120pub const ID_ATTR_IMAGE_SIZE: u32 = 0x6c37c15c;
122
123pub const ID_ATTR_ANIMATED: u32 = 0x11b58939;
125
126pub const ID_ATTR_STICKER: u32 = 0x3a556302;
128
129pub const ID_ATTR_VIDEO: u32 = 0x0ef02ce6;
131
132pub const ID_ATTR_AUDIO: u32 = 0x9852f9c6;
134
135pub const ID_ATTR_FILENAME: u32 = 0x15590068;
137
138const TL_VECTOR: u32 = 0x1cb5c415;
140
141#[derive(Debug, Clone)]
143pub enum DecryptedAction {
144 NotifyLayer {
146 layer: i32,
148 },
149 RequestKey {
151 exchange_id: i64,
153 g_a: Vec<u8>,
155 },
156 AcceptKey {
158 exchange_id: i64,
160 g_b: Vec<u8>,
162 key_fingerprint: i64,
164 },
165 AbortKey {
167 exchange_id: i64,
169 },
170 CommitKey {
172 exchange_id: i64,
174 key_fingerprint: i64,
176 },
177 Noop,
179 SetTtl {
181 ttl_seconds: i32,
183 },
184 Resend {
186 start_seq_no: i32,
188 end_seq_no: i32,
190 },
191 ReadMessages {
193 random_ids: Vec<i64>,
195 },
196 DeleteMessages {
198 random_ids: Vec<i64>,
200 },
201 ScreenshotMessages {
203 random_ids: Vec<i64>,
205 },
206 FlushHistory,
208 Typing {
210 action_ctor: u32,
212 },
213 Unknown {
215 ctor: u32,
217 },
218}
219
220#[derive(Debug, Clone)]
222pub enum DocumentAttribute {
223 ImageSize {
225 w: i32,
227 h: i32,
229 },
230 Animated,
232 Sticker {
234 alt: String,
236 },
237 Video {
239 duration: i32,
241 w: i32,
243 h: i32,
245 },
246 Audio {
248 duration: i32,
250 title: Option<String>,
252 performer: Option<String>,
254 },
255 FileName {
257 file_name: String,
259 },
260 Unknown {
262 ctor: u32,
264 },
265}
266
267#[derive(Debug, Clone)]
272pub enum DecryptedMedia {
273 Empty,
275 Photo {
277 thumb: Vec<u8>,
279 thumb_w: i32,
281 thumb_h: i32,
283 w: i32,
285 h: i32,
287 size: i32,
289 key: Vec<u8>,
291 iv: Vec<u8>,
293 caption: String,
295 },
296 Document {
298 thumb: Vec<u8>,
300 thumb_w: i32,
302 thumb_h: i32,
304 mime_type: String,
306 size: i64,
308 key: Vec<u8>,
310 iv: Vec<u8>,
312 attributes: Vec<DocumentAttribute>,
314 caption: String,
316 },
317 GeoPoint {
319 lat: f64,
321 long: f64,
323 },
324 Contact {
326 phone_number: String,
328 first_name: String,
330 last_name: String,
332 user_id: i32,
334 },
335 Unknown {
337 ctor: u32,
339 },
340}
341
342#[derive(Debug, Clone)]
344pub enum DecryptedMessage {
345 Text {
347 random_id: i64,
349 ttl: i32,
351 message: String,
353 media: DecryptedMedia,
355 },
356 Service {
358 random_id: i64,
360 action: DecryptedAction,
362 },
363 Unknown {
366 ctor: u32,
368 raw: Vec<u8>,
370 },
371}
372
373#[derive(Debug, Clone)]
375pub struct DecryptedMessageLayer {
376 pub random_bytes: Vec<u8>,
378 pub layer: i32,
380 pub in_seq_no: i32,
382 pub out_seq_no: i32,
384 pub message: DecryptedMessage,
386}
387
388fn write_u32(buf: &mut Vec<u8>, v: u32) {
389 buf.extend_from_slice(&v.to_le_bytes());
390}
391fn write_i32(buf: &mut Vec<u8>, v: i32) {
392 buf.extend_from_slice(&v.to_le_bytes());
393}
394fn write_i64(buf: &mut Vec<u8>, v: i64) {
395 buf.extend_from_slice(&v.to_le_bytes());
396}
397
398fn write_bytes(buf: &mut Vec<u8>, data: &[u8]) {
399 let len = data.len();
400 if len < 254 {
401 buf.push(len as u8);
402 buf.extend_from_slice(data);
403 let pad = (4 - (1 + len) % 4) % 4;
404 for _ in 0..pad {
405 buf.push(0);
406 }
407 } else {
408 buf.push(0xfe);
409 buf.push((len & 0xff) as u8);
410 buf.push(((len >> 8) & 0xff) as u8);
411 buf.push(((len >> 16) & 0xff) as u8);
412 buf.extend_from_slice(data);
413 let pad = (4 - (4 + len) % 4) % 4;
414 for _ in 0..pad {
415 buf.push(0);
416 }
417 }
418}
419
420fn write_string(buf: &mut Vec<u8>, s: &str) {
421 write_bytes(buf, s.as_bytes());
422}
423
424fn need(data: &[u8], offset: usize, n: usize) -> Result<(), E2eError> {
425 if offset + n > data.len() {
426 Err(E2eError::TlDeserializationFailed)
427 } else {
428 Ok(())
429 }
430}
431
432fn read_u32(data: &[u8], offset: &mut usize) -> Result<u32, E2eError> {
433 need(data, *offset, 4)?;
434 let mut b = [0u8; 4];
435 b.copy_from_slice(&data[*offset..*offset + 4]);
436 *offset += 4;
437 Ok(u32::from_le_bytes(b))
438}
439
440fn read_i32(data: &[u8], offset: &mut usize) -> Result<i32, E2eError> {
441 Ok(read_u32(data, offset)? as i32)
442}
443
444fn read_i64(data: &[u8], offset: &mut usize) -> Result<i64, E2eError> {
445 need(data, *offset, 8)?;
446 let mut b = [0u8; 8];
447 b.copy_from_slice(&data[*offset..*offset + 8]);
448 *offset += 8;
449 Ok(i64::from_le_bytes(b))
450}
451
452fn read_f64(data: &[u8], offset: &mut usize) -> Result<f64, E2eError> {
453 need(data, *offset, 8)?;
454 let mut b = [0u8; 8];
455 b.copy_from_slice(&data[*offset..*offset + 8]);
456 *offset += 8;
457 Ok(f64::from_le_bytes(b))
458}
459
460fn read_bytes(data: &[u8], offset: &mut usize) -> Result<Vec<u8>, E2eError> {
461 need(data, *offset, 1)?;
462 let first = data[*offset];
463 if first < 254 {
464 let len = first as usize;
465 *offset += 1;
466 need(data, *offset, len)?;
467 let out = data[*offset..*offset + len].to_vec();
468 *offset += len;
469 let pad = (4 - (1 + len) % 4) % 4;
470 *offset += pad;
471 Ok(out)
472 } else if first == 0xfe {
473 need(data, *offset, 4)?;
474 let len = (data[*offset + 1] as usize)
475 | ((data[*offset + 2] as usize) << 8)
476 | ((data[*offset + 3] as usize) << 16);
477 *offset += 4;
478 need(data, *offset, len)?;
479 let out = data[*offset..*offset + len].to_vec();
480 *offset += len;
481 let pad = (4 - (4 + len) % 4) % 4;
482 *offset += pad;
483 Ok(out)
484 } else {
485 Err(E2eError::TlDeserializationFailed)
486 }
487}
488
489fn read_string(data: &[u8], offset: &mut usize) -> Result<String, E2eError> {
490 String::from_utf8(read_bytes(data, offset)?).map_err(|_| E2eError::TlDeserializationFailed)
491}
492
493fn read_vector_long(data: &[u8], offset: &mut usize) -> Result<Vec<i64>, E2eError> {
495 if read_u32(data, offset)? != TL_VECTOR {
496 return Err(E2eError::TlDeserializationFailed);
497 }
498 let count = read_i32(data, offset)?;
499 if !(0..=65536).contains(&count) {
500 return Err(E2eError::TlDeserializationFailed);
501 }
502 let mut out = Vec::with_capacity(count as usize);
503 for _ in 0..count {
504 out.push(read_i64(data, offset)?);
505 }
506 Ok(out)
507}
508
509fn serialize_doc_attr(buf: &mut Vec<u8>, attr: &DocumentAttribute) {
510 match attr {
511 DocumentAttribute::ImageSize { w, h } => {
512 write_u32(buf, ID_ATTR_IMAGE_SIZE);
513 write_i32(buf, *w);
514 write_i32(buf, *h);
515 }
516 DocumentAttribute::Animated => {
517 write_u32(buf, ID_ATTR_ANIMATED);
518 }
519 DocumentAttribute::Sticker { alt } => {
520 write_u32(buf, ID_ATTR_STICKER);
522 write_string(buf, alt);
523 write_u32(buf, 0xffb62b95); }
525 DocumentAttribute::Video { duration, w, h } => {
526 write_u32(buf, ID_ATTR_VIDEO);
527 write_u32(buf, 0u32); write_i32(buf, *duration);
529 write_i32(buf, *w);
530 write_i32(buf, *h);
531 }
532 DocumentAttribute::Audio {
533 duration,
534 title,
535 performer,
536 } => {
537 write_u32(buf, ID_ATTR_AUDIO);
538 let mut flags: u32 = 0;
539 if title.is_some() {
540 flags |= 1;
541 }
542 if performer.is_some() {
543 flags |= 2;
544 }
545 write_u32(buf, flags);
546 write_i32(buf, *duration);
547 if let Some(t) = title {
548 write_string(buf, t);
549 }
550 if let Some(p) = performer {
551 write_string(buf, p);
552 }
553 }
554 DocumentAttribute::FileName { file_name } => {
555 write_u32(buf, ID_ATTR_FILENAME);
556 write_string(buf, file_name);
557 }
558 DocumentAttribute::Unknown { .. } => {
559 }
561 }
562}
563
564fn deserialize_doc_attr(data: &[u8], offset: &mut usize) -> Result<DocumentAttribute, E2eError> {
565 let ctor = read_u32(data, offset)?;
566 match ctor {
567 ID_ATTR_IMAGE_SIZE => Ok(DocumentAttribute::ImageSize {
568 w: read_i32(data, offset)?,
569 h: read_i32(data, offset)?,
570 }),
571 ID_ATTR_ANIMATED => Ok(DocumentAttribute::Animated),
572 0xfb0a5727 => Ok(DocumentAttribute::Sticker { alt: String::new() }),
574 ID_ATTR_STICKER => {
575 let alt = read_string(data, offset)?;
577 let set_ctor = read_u32(data, offset)?;
579 match set_ctor {
580 0xffb62b95 => {} 0x861cc8a0 => {
582 let _ = read_string(data, offset);
583 } _ => {}
585 }
586 Ok(DocumentAttribute::Sticker { alt })
587 }
588 ID_ATTR_VIDEO => {
589 let _flags = read_u32(data, offset)?;
590 let duration = read_i32(data, offset)?;
591 let w = read_i32(data, offset)?;
592 let h = read_i32(data, offset)?;
593 Ok(DocumentAttribute::Video { duration, w, h })
594 }
595 ID_ATTR_AUDIO => {
596 let flags = read_u32(data, offset)?;
597 let duration = read_i32(data, offset)?;
598 let title = if flags & (1 << 0) != 0 {
599 Some(read_string(data, offset)?)
600 } else {
601 None
602 };
603 let performer = if flags & (1 << 1) != 0 {
604 Some(read_string(data, offset)?)
605 } else {
606 None
607 };
608 if flags & (1 << 2) != 0 {
610 let _ = read_bytes(data, offset)?;
611 }
612 Ok(DocumentAttribute::Audio {
613 duration,
614 title,
615 performer,
616 })
617 }
618 ID_ATTR_FILENAME => Ok(DocumentAttribute::FileName {
619 file_name: read_string(data, offset)?,
620 }),
621 _ => Ok(DocumentAttribute::Unknown { ctor }),
622 }
623}
624
625pub fn serialize_media(buf: &mut Vec<u8>, media: &DecryptedMedia) {
627 match media {
628 DecryptedMedia::Empty => {
629 write_u32(buf, ID_MEDIA_EMPTY);
630 }
631 DecryptedMedia::Photo {
632 thumb,
633 thumb_w,
634 thumb_h,
635 w,
636 h,
637 size,
638 key,
639 iv,
640 caption,
641 } => {
642 write_u32(buf, ID_MEDIA_PHOTO);
643 write_bytes(buf, thumb);
644 write_i32(buf, *thumb_w);
645 write_i32(buf, *thumb_h);
646 write_i32(buf, *w);
647 write_i32(buf, *h);
648 write_i32(buf, *size);
649 write_bytes(buf, key);
650 write_bytes(buf, iv);
651 write_string(buf, caption);
652 }
653 DecryptedMedia::Document {
654 thumb,
655 thumb_w,
656 thumb_h,
657 mime_type,
658 size,
659 key,
660 iv,
661 attributes,
662 caption,
663 } => {
664 write_u32(buf, ID_MEDIA_DOCUMENT);
665 write_bytes(buf, thumb);
666 write_i32(buf, *thumb_w);
667 write_i32(buf, *thumb_h);
668 write_string(buf, mime_type);
669 write_i64(buf, *size);
670 write_bytes(buf, key);
671 write_bytes(buf, iv);
672 write_u32(buf, TL_VECTOR);
673 write_i32(buf, attributes.len() as i32);
674 for attr in attributes {
675 serialize_doc_attr(buf, attr);
676 }
677 write_string(buf, caption);
678 }
679 DecryptedMedia::GeoPoint { lat, long } => {
680 write_u32(buf, ID_MEDIA_GEO);
681 buf.extend_from_slice(&lat.to_le_bytes());
682 buf.extend_from_slice(&long.to_le_bytes());
683 }
684 DecryptedMedia::Contact {
685 phone_number,
686 first_name,
687 last_name,
688 user_id,
689 } => {
690 write_u32(buf, ID_MEDIA_CONTACT);
691 write_string(buf, phone_number);
692 write_string(buf, first_name);
693 write_string(buf, last_name);
694 write_i32(buf, *user_id);
695 }
696 DecryptedMedia::Unknown { .. } => {
697 write_u32(buf, ID_MEDIA_EMPTY);
698 }
699 }
700}
701
702pub fn deserialize_media(data: &[u8], offset: &mut usize) -> Result<DecryptedMedia, E2eError> {
704 if *offset + 4 > data.len() {
705 return Ok(DecryptedMedia::Empty);
706 }
707 let ctor = read_u32(data, offset)?;
708 match ctor {
709 ID_MEDIA_EMPTY => Ok(DecryptedMedia::Empty),
710
711 ID_MEDIA_PHOTO => {
712 let thumb = read_bytes(data, offset)?;
713 let thumb_w = read_i32(data, offset)?;
714 let thumb_h = read_i32(data, offset)?;
715 let w = read_i32(data, offset)?;
716 let h = read_i32(data, offset)?;
717 let size = read_i32(data, offset)?;
718 let key = read_bytes(data, offset)?;
719 let iv = read_bytes(data, offset)?;
720 let caption = read_string(data, offset).unwrap_or_default();
721 Ok(DecryptedMedia::Photo {
722 thumb,
723 thumb_w,
724 thumb_h,
725 w,
726 h,
727 size,
728 key,
729 iv,
730 caption,
731 })
732 }
733
734 ID_MEDIA_PHOTO_OLD => {
735 let thumb = read_bytes(data, offset)?;
737 let thumb_w = read_i32(data, offset)?;
738 let thumb_h = read_i32(data, offset)?;
739 let w = read_i32(data, offset)?;
740 let h = read_i32(data, offset)?;
741 let size = read_i32(data, offset)?;
742 let key = read_bytes(data, offset)?;
743 let iv = read_bytes(data, offset)?;
744 Ok(DecryptedMedia::Photo {
745 thumb,
746 thumb_w,
747 thumb_h,
748 w,
749 h,
750 size,
751 key,
752 iv,
753 caption: String::new(),
754 })
755 }
756
757 ID_MEDIA_DOCUMENT => {
758 let thumb = read_bytes(data, offset)?;
759 let thumb_w = read_i32(data, offset)?;
760 let thumb_h = read_i32(data, offset)?;
761 let mime_type = read_string(data, offset)?;
762 let size = read_i64(data, offset)?;
763 let key = read_bytes(data, offset)?;
764 let iv = read_bytes(data, offset)?;
765 let attributes = if *offset + 4 <= data.len() {
766 let vec_ctor = read_u32(data, offset)?;
767 if vec_ctor == TL_VECTOR {
768 let count = read_i32(data, offset)?.clamp(0, 64) as usize;
769 let mut attrs = Vec::with_capacity(count);
770 for _ in 0..count {
771 match deserialize_doc_attr(data, offset) {
772 Ok(a) => attrs.push(a),
773 Err(_) => break,
774 }
775 }
776 attrs
777 } else {
778 Vec::new()
779 }
780 } else {
781 Vec::new()
782 };
783 let caption = read_string(data, offset).unwrap_or_default();
784 Ok(DecryptedMedia::Document {
785 thumb,
786 thumb_w,
787 thumb_h,
788 mime_type,
789 size,
790 key,
791 iv,
792 attributes,
793 caption,
794 })
795 }
796
797 ID_MEDIA_DOCUMENT_OLD => {
798 let thumb = read_bytes(data, offset)?;
800 let thumb_w = read_i32(data, offset)?;
801 let thumb_h = read_i32(data, offset)?;
802 let _file_name = read_string(data, offset)?; let mime_type = read_string(data, offset)?;
804 let size = read_i32(data, offset)? as i64;
805 let key = read_bytes(data, offset)?;
806 let iv = read_bytes(data, offset)?;
807 Ok(DecryptedMedia::Document {
808 thumb,
809 thumb_w,
810 thumb_h,
811 mime_type,
812 size,
813 key,
814 iv,
815 attributes: Vec::new(),
816 caption: String::new(),
817 })
818 }
819
820 0x7afe8ae2 => {
823 let thumb = read_bytes(data, offset)?;
824 let thumb_w = read_i32(data, offset)?;
825 let thumb_h = read_i32(data, offset)?;
826 let mime_type = read_string(data, offset)?;
827 let size = read_i32(data, offset)? as i64;
828 let key = read_bytes(data, offset)?;
829 let iv = read_bytes(data, offset)?;
830 let attributes = if *offset + 4 <= data.len() {
831 let vec_ctor = read_u32(data, offset)?;
832 if vec_ctor == TL_VECTOR {
833 let count = read_i32(data, offset)?.clamp(0, 64) as usize;
834 let mut attrs = Vec::with_capacity(count);
835 for _ in 0..count {
836 match deserialize_doc_attr(data, offset) {
837 Ok(a) => attrs.push(a),
838 Err(_) => break,
839 }
840 }
841 attrs
842 } else {
843 Vec::new()
844 }
845 } else {
846 Vec::new()
847 };
848 let caption = read_string(data, offset).unwrap_or_default();
849 Ok(DecryptedMedia::Document {
850 thumb,
851 thumb_w,
852 thumb_h,
853 mime_type,
854 size,
855 key,
856 iv,
857 attributes,
858 caption,
859 })
860 }
861
862 ID_MEDIA_GEO => {
863 let lat = read_f64(data, offset)?;
864 let long = read_f64(data, offset)?;
865 Ok(DecryptedMedia::GeoPoint { lat, long })
866 }
867
868 ID_MEDIA_CONTACT => {
869 let phone_number = read_string(data, offset)?;
870 let first_name = read_string(data, offset)?;
871 let last_name = read_string(data, offset)?;
872 let user_id = read_i32(data, offset)?;
873 Ok(DecryptedMedia::Contact {
874 phone_number,
875 first_name,
876 last_name,
877 user_id,
878 })
879 }
880
881 ID_MEDIA_AUDIO_L8 | ID_MEDIA_AUDIO_L17 | ID_MEDIA_VIDEO_L8 | ID_MEDIA_VIDEO_L17
883 | ID_MEDIA_VIDEO_L45 => Ok(DecryptedMedia::Unknown { ctor }),
884
885 ID_MEDIA_VENUE => Ok(DecryptedMedia::Unknown { ctor }),
887
888 _ => Ok(DecryptedMedia::Unknown { ctor }),
889 }
890}
891
892fn serialize_action(buf: &mut Vec<u8>, action: &DecryptedAction) {
893 match action {
894 DecryptedAction::NotifyLayer { layer } => {
895 write_u32(buf, ID_ACTION_NOTIFY_LAYER);
896 write_i32(buf, *layer);
897 }
898 DecryptedAction::RequestKey { exchange_id, g_a } => {
899 write_u32(buf, ID_ACTION_REQUEST_KEY);
900 write_i64(buf, *exchange_id);
901 write_bytes(buf, g_a);
902 }
903 DecryptedAction::AcceptKey {
904 exchange_id,
905 g_b,
906 key_fingerprint,
907 } => {
908 write_u32(buf, ID_ACTION_ACCEPT_KEY);
909 write_i64(buf, *exchange_id);
910 write_bytes(buf, g_b);
911 write_i64(buf, *key_fingerprint);
912 }
913 DecryptedAction::AbortKey { exchange_id } => {
914 write_u32(buf, ID_ACTION_ABORT_KEY);
915 write_i64(buf, *exchange_id);
916 }
917 DecryptedAction::CommitKey {
918 exchange_id,
919 key_fingerprint,
920 } => {
921 write_u32(buf, ID_ACTION_COMMIT_KEY);
922 write_i64(buf, *exchange_id);
923 write_i64(buf, *key_fingerprint);
924 }
925 DecryptedAction::Noop => {
926 write_u32(buf, ID_ACTION_NOOP);
927 }
928 DecryptedAction::SetTtl { ttl_seconds } => {
929 write_u32(buf, ID_ACTION_SET_TTL);
930 write_i32(buf, *ttl_seconds);
931 }
932 DecryptedAction::Resend {
933 start_seq_no,
934 end_seq_no,
935 } => {
936 write_u32(buf, ID_ACTION_RESEND);
937 write_i32(buf, *start_seq_no);
938 write_i32(buf, *end_seq_no);
939 }
940 DecryptedAction::ReadMessages { .. }
942 | DecryptedAction::DeleteMessages { .. }
943 | DecryptedAction::ScreenshotMessages { .. }
944 | DecryptedAction::FlushHistory
945 | DecryptedAction::Typing { .. }
946 | DecryptedAction::Unknown { .. } => {}
947 }
948}
949
950fn deserialize_action(data: &[u8], offset: &mut usize) -> Result<DecryptedAction, E2eError> {
951 let ctor = read_u32(data, offset)?;
952 match ctor {
953 ID_ACTION_NOTIFY_LAYER => Ok(DecryptedAction::NotifyLayer {
954 layer: read_i32(data, offset)?,
955 }),
956 ID_ACTION_REQUEST_KEY => Ok(DecryptedAction::RequestKey {
957 exchange_id: read_i64(data, offset)?,
958 g_a: read_bytes(data, offset)?,
959 }),
960 ID_ACTION_ACCEPT_KEY => Ok(DecryptedAction::AcceptKey {
961 exchange_id: read_i64(data, offset)?,
962 g_b: read_bytes(data, offset)?,
963 key_fingerprint: read_i64(data, offset)?,
964 }),
965 ID_ACTION_ABORT_KEY => Ok(DecryptedAction::AbortKey {
966 exchange_id: read_i64(data, offset)?,
967 }),
968 ID_ACTION_COMMIT_KEY => Ok(DecryptedAction::CommitKey {
969 exchange_id: read_i64(data, offset)?,
970 key_fingerprint: read_i64(data, offset)?,
971 }),
972 ID_ACTION_NOOP => Ok(DecryptedAction::Noop),
973 ID_ACTION_SET_TTL => Ok(DecryptedAction::SetTtl {
974 ttl_seconds: read_i32(data, offset)?,
975 }),
976 ID_ACTION_RESEND => Ok(DecryptedAction::Resend {
977 start_seq_no: read_i32(data, offset)?,
978 end_seq_no: read_i32(data, offset)?,
979 }),
980 ID_ACTION_READ_MESSAGES => Ok(DecryptedAction::ReadMessages {
981 random_ids: read_vector_long(data, offset)?,
982 }),
983 ID_ACTION_DELETE_MESSAGES => Ok(DecryptedAction::DeleteMessages {
984 random_ids: read_vector_long(data, offset)?,
985 }),
986 ID_ACTION_SCREENSHOT_MESSAGES => Ok(DecryptedAction::ScreenshotMessages {
987 random_ids: read_vector_long(data, offset)?,
988 }),
989 ID_ACTION_FLUSH_HISTORY => Ok(DecryptedAction::FlushHistory),
990 ID_ACTION_TYPING => Ok(DecryptedAction::Typing {
991 action_ctor: read_u32(data, offset)?,
992 }),
993 _ => Ok(DecryptedAction::Unknown { ctor }),
994 }
995}
996
997fn serialize_message(buf: &mut Vec<u8>, msg: &DecryptedMessage) {
998 match msg {
999 DecryptedMessage::Text {
1000 random_id,
1001 ttl,
1002 message,
1003 media,
1004 } => {
1005 write_u32(buf, ID_DECRYPTED_MESSAGE);
1006 let has_media = !matches!(media, DecryptedMedia::Empty);
1009 let flags: u32 = if has_media { 1 << 9 } else { 0 };
1010 write_u32(buf, flags);
1011 write_i64(buf, *random_id);
1012 write_i32(buf, *ttl);
1013 write_string(buf, message);
1014 if has_media {
1015 serialize_media(buf, media);
1016 }
1017 }
1018 DecryptedMessage::Service { random_id, action } => {
1019 write_u32(buf, ID_DECRYPTED_MESSAGE_SERVICE);
1020 write_i64(buf, *random_id);
1021 serialize_action(buf, action);
1022 }
1023 DecryptedMessage::Unknown { .. } => {
1024 }
1026 }
1027}
1028
1029fn deserialize_message(data: &[u8], offset: &mut usize) -> Result<DecryptedMessage, E2eError> {
1030 let ctor = read_u32(data, offset)?;
1031 match ctor {
1032 ID_DECRYPTED_MESSAGE => {
1033 let flags = read_u32(data, offset)?;
1034 let random_id = read_i64(data, offset)?;
1035 let ttl = read_i32(data, offset)?;
1036 let message = read_string(data, offset)?;
1037 let media = if flags & (1 << 9) != 0 {
1039 deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty)
1040 } else {
1041 DecryptedMedia::Empty
1042 };
1043 Ok(DecryptedMessage::Text {
1044 random_id,
1045 ttl,
1046 message,
1047 media,
1048 })
1049 }
1050 ID_DECRYPTED_MESSAGE_OLD => {
1051 let flags = read_u32(data, offset)?;
1053 let random_id = read_i64(data, offset)?;
1054 let ttl = read_i32(data, offset)?;
1055 let message = read_string(data, offset)?;
1056 let media = if flags & (1 << 9) != 0 {
1057 deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty)
1058 } else {
1059 DecryptedMedia::Empty
1060 };
1061 Ok(DecryptedMessage::Text {
1062 random_id,
1063 ttl,
1064 message,
1065 media,
1066 })
1067 }
1068 0x1f814f1f => {
1070 let random_id = read_i64(data, offset)?;
1071 let _random_bytes = read_bytes(data, offset)?;
1072 let message = read_string(data, offset)?;
1073 let media = deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty);
1074 Ok(DecryptedMessage::Text {
1075 random_id,
1076 ttl: 0,
1077 message,
1078 media,
1079 })
1080 }
1081 0x204d3878 => {
1083 let random_id = read_i64(data, offset)?;
1084 let ttl = read_i32(data, offset)?;
1085 let message = read_string(data, offset)?;
1086 let media = deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty);
1087 Ok(DecryptedMessage::Text {
1088 random_id,
1089 ttl,
1090 message,
1091 media,
1092 })
1093 }
1094 ID_DECRYPTED_MESSAGE_SERVICE => {
1095 let random_id = read_i64(data, offset)?;
1096 let action = deserialize_action(data, offset)?;
1097 Ok(DecryptedMessage::Service { random_id, action })
1098 }
1099 ID_DECRYPTED_MESSAGE_SERVICE8 => {
1101 let random_id = read_i64(data, offset)?;
1102 let _random_bytes = read_bytes(data, offset)?;
1103 let action = deserialize_action(data, offset)?;
1104 Ok(DecryptedMessage::Service { random_id, action })
1105 }
1106 _ => {
1107 let raw = data[*offset..].to_vec();
1108 *offset = data.len();
1109 Ok(DecryptedMessage::Unknown { ctor, raw })
1110 }
1111 }
1112}
1113
1114pub fn serialize_message_layer(layer: &DecryptedMessageLayer) -> Result<Vec<u8>, E2eError> {
1116 let mut buf = Vec::new();
1117 write_u32(&mut buf, ID_DECRYPTED_MESSAGE_LAYER);
1118 write_bytes(&mut buf, &layer.random_bytes);
1119 write_i32(&mut buf, layer.layer);
1120 write_i32(&mut buf, layer.in_seq_no);
1121 write_i32(&mut buf, layer.out_seq_no);
1122 serialize_message(&mut buf, &layer.message);
1123 Ok(buf)
1124}
1125
1126pub fn deserialize_message_layer(data: &[u8]) -> Result<DecryptedMessageLayer, E2eError> {
1128 let mut offset = 0usize;
1129 if read_u32(data, &mut offset)? != ID_DECRYPTED_MESSAGE_LAYER {
1130 return Err(E2eError::TlDeserializationFailed);
1131 }
1132 let random_bytes = read_bytes(data, &mut offset)?;
1133 let layer = read_i32(data, &mut offset)?;
1134 let in_seq_no = read_i32(data, &mut offset)?;
1135 let out_seq_no = read_i32(data, &mut offset)?;
1136 let message = deserialize_message(data, &mut offset)?;
1137 Ok(DecryptedMessageLayer {
1138 random_bytes,
1139 layer,
1140 in_seq_no,
1141 out_seq_no,
1142 message,
1143 })
1144}
1145
1146pub fn serialize_layer8_service(
1150 random_id: i64,
1151 action: &DecryptedAction,
1152) -> Result<Vec<u8>, E2eError> {
1153 let mut buf = Vec::new();
1154 write_u32(&mut buf, ID_DECRYPTED_MESSAGE_SERVICE8);
1155 write_i64(&mut buf, random_id);
1156 let mut rb = [0u8; 15];
1157 rand::rng().fill_bytes(&mut rb);
1158 write_bytes(&mut buf, &rb);
1159 serialize_action(&mut buf, action);
1160 Ok(buf)
1161}
1162
1163pub fn make_random_bytes() -> Vec<u8> {
1167 let extra = (rand::random::<u8>() % 3) as usize * 4;
1168 let mut rb = vec![0u8; 15 + extra];
1169 rand::rng().fill_bytes(&mut rb);
1170 rb
1171}