forked from vysheng/tg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtproto-client.c
1830 lines (1656 loc) · 48.9 KB
/
mtproto-client.c
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of telegram-client.
Telegram-client is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
Telegram-client is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this telegram-client. If not, see <http://www.gnu.org/licenses/>.
Copyright Nikolay Durov, Andrey Lopatin 2012-2013
Copyright Vitaly Valtman 2013
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _FILE_OFFSET_BITS 64
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#ifdef __FreeBSD__
#include <sys/endian.h>
#endif
#include <sys/types.h>
#include <netdb.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/sha.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include "net.h"
#include "include.h"
#include "queries.h"
#include "loop.h"
#include "interface.h"
#include "structures.h"
#include "binlog.h"
#if defined(__FreeBSD__)
#define __builtin_bswap32(x) bswap32(x)
#endif
#define sha1 SHA1
#include "mtproto-common.h"
#define MAX_NET_RES (1L << 16)
extern int log_level;
int verbosity;
int auth_success;
enum dc_state c_state;
char nonce[256];
char new_nonce[256];
char server_nonce[256];
extern int binlog_enabled;
extern int disable_auto_accept;
extern int allow_weak_random;
int total_packets_sent;
long long total_data_sent;
int rpc_execute (struct connection *c, int op, int len);
int rpc_becomes_ready (struct connection *c);
int rpc_close (struct connection *c);
struct connection_methods auth_methods = {
.execute = rpc_execute,
.ready = rpc_becomes_ready,
.close = rpc_close
};
long long precise_time;
double get_utime (int clock_id) {
struct timespec T;
my_clock_gettime (clock_id, &T);
double res = T.tv_sec + (double) T.tv_nsec * 1e-9;
if (clock_id == CLOCK_REALTIME) {
precise_time = (long long) (res * (1LL << 32));
}
return res;
}
void secure_random (void *s, int l) {
if (RAND_bytes (s, l) < 0) {
if (allow_weak_random) {
RAND_pseudo_bytes (s, l);
} else {
assert (0 && "End of random. If you want, you can start with -w");
}
}
}
#define STATS_BUFF_SIZE (64 << 10)
int stats_buff_len;
char stats_buff[STATS_BUFF_SIZE];
#define MAX_RESPONSE_SIZE (1L << 24)
char Response[MAX_RESPONSE_SIZE];
int Response_len;
/*
*
* STATE MACHINE
*
*/
char *rsa_public_key_name = "tg.pub";
RSA *pubKey;
long long pk_fingerprint;
static int rsa_load_public_key (const char *public_key_name) {
pubKey = NULL;
FILE *f = fopen (public_key_name, "r");
if (f == NULL) {
logprintf ( "Couldn't open public key file: %s\n", public_key_name);
return -1;
}
pubKey = PEM_read_RSAPublicKey (f, NULL, NULL, NULL);
fclose (f);
if (pubKey == NULL) {
logprintf ( "PEM_read_RSAPublicKey returns NULL.\n");
return -1;
}
return 0;
}
int auth_work_start (struct connection *c);
/*
*
* UNAUTHORIZED (DH KEY EXCHANGE) PROTOCOL PART
*
*/
BIGNUM dh_prime, dh_g, g_a, dh_power, auth_key_num;
char s_power [256];
struct {
long long auth_key_id;
long long out_msg_id;
int msg_len;
} unenc_msg_header;
#define ENCRYPT_BUFFER_INTS 16384
int encrypt_buffer[ENCRYPT_BUFFER_INTS];
#define DECRYPT_BUFFER_INTS 16384
int decrypt_buffer[ENCRYPT_BUFFER_INTS];
int encrypt_packet_buffer (void) {
return pad_rsa_encrypt ((char *) packet_buffer, (packet_ptr - packet_buffer) * 4, (char *) encrypt_buffer, ENCRYPT_BUFFER_INTS * 4, pubKey->n, pubKey->e);
}
int encrypt_packet_buffer_aes_unauth (const char server_nonce[16], const char hidden_client_nonce[32]) {
init_aes_unauth (server_nonce, hidden_client_nonce, AES_ENCRYPT);
return pad_aes_encrypt ((char *) packet_buffer, (packet_ptr - packet_buffer) * 4, (char *) encrypt_buffer, ENCRYPT_BUFFER_INTS * 4);
}
int rpc_send_packet (struct connection *c) {
int len = (packet_ptr - packet_buffer) * 4;
c->out_packet_num ++;
long long next_msg_id = (long long) ((1LL << 32) * get_utime (CLOCK_REALTIME)) & -4;
if (next_msg_id <= unenc_msg_header.out_msg_id) {
unenc_msg_header.out_msg_id += 4;
} else {
unenc_msg_header.out_msg_id = next_msg_id;
}
unenc_msg_header.msg_len = len;
int total_len = len + 20;
assert (total_len > 0 && !(total_len & 0xfc000003));
total_len >>= 2;
if (total_len < 0x7f) {
assert (write_out (c, &total_len, 1) == 1);
} else {
total_len = (total_len << 8) | 0x7f;
assert (write_out (c, &total_len, 4) == 4);
}
write_out (c, &unenc_msg_header, 20);
write_out (c, packet_buffer, len);
flush_out (c);
total_packets_sent ++;
total_data_sent += total_len;
return 1;
}
int rpc_send_message (struct connection *c, void *data, int len) {
assert (len > 0 && !(len & 0xfc000003));
int total_len = len >> 2;
if (total_len < 0x7f) {
assert (write_out (c, &total_len, 1) == 1);
} else {
total_len = (total_len << 8) | 0x7f;
assert (write_out (c, &total_len, 4) == 4);
}
c->out_packet_num ++;
assert (write_out (c, data, len) == len);
flush_out (c);
total_packets_sent ++;
total_data_sent += total_len;
return 1;
}
int send_req_pq_packet (struct connection *c) {
assert (c_state == st_init);
secure_random (nonce, 16);
unenc_msg_header.out_msg_id = 0;
clear_packet ();
out_int (CODE_req_pq);
out_ints ((int *)nonce, 4);
rpc_send_packet (c);
c_state = st_reqpq_sent;
return 1;
}
unsigned long long gcd (unsigned long long a, unsigned long long b) {
return b ? gcd (b, a % b) : a;
}
//typedef unsigned int uint128_t __attribute__ ((mode(TI)));
unsigned long long what;
unsigned p1, p2;
int process_respq_answer (struct connection *c, char *packet, int len) {
int i;
if (verbosity) {
logprintf ( "process_respq_answer(), len=%d\n", len);
}
assert (len >= 76);
assert (!*(long long *) packet);
assert (*(int *) (packet + 16) == len - 20);
assert (!(len & 3));
assert (*(int *) (packet + 20) == CODE_resPQ);
assert (!memcmp (packet + 24, nonce, 16));
memcpy (server_nonce, packet + 40, 16);
char *from = packet + 56;
int clen = *from++;
assert (clen <= 8);
what = 0;
for (i = 0; i < clen; i++) {
what = (what << 8) + (unsigned char)*from++;
}
while (((unsigned long)from) & 3) ++from;
p1 = 0, p2 = 0;
if (verbosity >= 2) {
logprintf ( "%lld received\n", what);
}
int it = 0;
unsigned long long g = 0;
for (i = 0; i < 3 || it < 1000; i++) {
int q = ((lrand48() & 15) + 17) % what;
unsigned long long x = (long long)lrand48 () % (what - 1) + 1, y = x;
int lim = 1 << (i + 18);
int j;
for (j = 1; j < lim; j++) {
++it;
unsigned long long a = x, b = x, c = q;
while (b) {
if (b & 1) {
c += a;
if (c >= what) {
c -= what;
}
}
a += a;
if (a >= what) {
a -= what;
}
b >>= 1;
}
x = c;
unsigned long long z = x < y ? what + x - y : x - y;
g = gcd (z, what);
if (g != 1) {
break;
}
if (!(j & (j - 1))) {
y = x;
}
}
if (g > 1 && g < what) break;
}
assert (g > 1 && g < what);
p1 = g;
p2 = what / g;
if (p1 > p2) {
unsigned t = p1; p1 = p2; p2 = t;
}
if (verbosity) {
logprintf ( "p1 = %d, p2 = %d, %d iterations\n", p1, p2, it);
}
/// ++p1; ///
assert (*(int *) (from) == CODE_vector);
int fingerprints_num = *(int *)(from + 4);
assert (fingerprints_num >= 1 && fingerprints_num <= 64 && len == fingerprints_num * 8 + 8 + (from - packet));
long long *fingerprints = (long long *) (from + 8);
for (i = 0; i < fingerprints_num; i++) {
if (fingerprints[i] == pk_fingerprint) {
//logprintf ( "found our public key at position %d\n", i);
break;
}
}
if (i == fingerprints_num) {
logprintf ( "fatal: don't have any matching keys (%016llx expected)\n", pk_fingerprint);
exit (2);
}
// create inner part (P_Q_inner_data)
clear_packet ();
packet_ptr += 5;
out_int (CODE_p_q_inner_data);
out_cstring (packet + 57, clen);
//out_int (0x0f01); // pq=15
if (p1 < 256) {
clen = 1;
} else if (p1 < 65536) {
clen = 2;
} else if (p1 < 16777216) {
clen = 3;
} else {
clen = 4;
}
p1 = __builtin_bswap32 (p1);
out_cstring ((char *)&p1 + 4 - clen, clen);
p1 = __builtin_bswap32 (p1);
if (p2 < 256) {
clen = 1;
} else if (p2 < 65536) {
clen = 2;
} else if (p2 < 16777216) {
clen = 3;
} else {
clen = 4;
}
p2 = __builtin_bswap32 (p2);
out_cstring ((char *)&p2 + 4 - clen, clen);
p2 = __builtin_bswap32 (p2);
//out_int (0x0301); // p=3
//out_int (0x0501); // q=5
out_ints ((int *) nonce, 4);
out_ints ((int *) server_nonce, 4);
secure_random (new_nonce, 32);
out_ints ((int *) new_nonce, 8);
sha1 ((unsigned char *) (packet_buffer + 5), (packet_ptr - packet_buffer - 5) * 4, (unsigned char *) packet_buffer);
int l = encrypt_packet_buffer ();
clear_packet ();
out_int (CODE_req_DH_params);
out_ints ((int *) nonce, 4);
out_ints ((int *) server_nonce, 4);
//out_int (0x0301); // p=3
//out_int (0x0501); // q=5
if (p1 < 256) {
clen = 1;
} else if (p1 < 65536) {
clen = 2;
} else if (p1 < 16777216) {
clen = 3;
} else {
clen = 4;
}
p1 = __builtin_bswap32 (p1);
out_cstring ((char *)&p1 + 4 - clen, clen);
p1 = __builtin_bswap32 (p1);
if (p2 < 256) {
clen = 1;
} else if (p2 < 65536) {
clen = 2;
} else if (p2 < 16777216) {
clen = 3;
} else {
clen = 4;
}
p2 = __builtin_bswap32 (p2);
out_cstring ((char *)&p2 + 4 - clen, clen);
p2 = __builtin_bswap32 (p2);
out_long (pk_fingerprint);
out_cstring ((char *) encrypt_buffer, l);
c_state = st_reqdh_sent;
return rpc_send_packet (c);
}
int check_prime (BIGNUM *p) {
int r = BN_is_prime (p, BN_prime_checks, 0, BN_ctx, 0);
ensure (r >= 0);
return r;
}
int check_DH_params (BIGNUM *p, int g) {
if (g < 2 || g > 7) { return -1; }
BIGNUM t;
BN_init (&t);
BN_init (&dh_g);
ensure (BN_set_word (&dh_g, 4 * g));
ensure (BN_mod (&t, p, &dh_g, BN_ctx));
int x = BN_get_word (&t);
assert (x >= 0 && x < 4 * g);
BN_free (&dh_g);
switch (g) {
case 2:
if (x != 7) { return -1; }
break;
case 3:
if (x % 3 != 2 ) { return -1; }
break;
case 4:
break;
case 5:
if (x % 5 != 1 && x % 5 != 4) { return -1; }
break;
case 6:
if (x != 19 && x != 23) { return -1; }
break;
case 7:
if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { return -1; }
break;
}
if (!check_prime (p)) { return -1; }
BIGNUM b;
BN_init (&b);
ensure (BN_set_word (&b, 2));
ensure (BN_div (&t, 0, p, &b, BN_ctx));
if (!check_prime (&t)) { return -1; }
BN_free (&b);
BN_free (&t);
return 0;
}
int check_g (unsigned char p[256], BIGNUM *g) {
static unsigned char s[256];
memset (s, 0, 256);
assert (BN_num_bytes (g) <= 256);
BN_bn2bin (g, s);
int ok = 0;
int i;
for (i = 0; i < 64; i++) {
if (s[i]) {
ok = 1;
break;
}
}
if (!ok) { return -1; }
ok = 0;
for (i = 0; i < 64; i++) {
if (s[255 - i]) {
ok = 1;
break;
}
}
if (!ok) { return -1; }
ok = 0;
for (i = 0; i < 64; i++) {
if (s[i] < p[i]) {
ok = 1;
break;
} else if (s[i] > p[i]) {
logprintf ("i = %d (%d %d)\n", i, (int)s[i], (int)p[i]);
return -1;
}
}
if (!ok) { return -1; }
return 0;
}
int check_g_bn (BIGNUM *p, BIGNUM *g) {
static unsigned char s[256];
memset (s, 0, 256);
assert (BN_num_bytes (p) <= 256);
BN_bn2bin (p, s);
return check_g (s, g);
}
int process_dh_answer (struct connection *c, char *packet, int len) {
if (verbosity) {
logprintf ( "process_dh_answer(), len=%d\n", len);
}
if (len < 116) {
logprintf ( "%u * %u = %llu", p1, p2, what);
}
assert (len >= 116);
assert (!*(long long *) packet);
assert (*(int *) (packet + 16) == len - 20);
assert (!(len & 3));
assert (*(int *) (packet + 20) == (int)CODE_server_DH_params_ok);
assert (!memcmp (packet + 24, nonce, 16));
assert (!memcmp (packet + 40, server_nonce, 16));
init_aes_unauth (server_nonce, new_nonce, AES_DECRYPT);
in_ptr = (int *)(packet + 56);
in_end = (int *)(packet + len);
int l = prefetch_strlen ();
assert (l > 0);
l = pad_aes_decrypt (fetch_str (l), l, (char *) decrypt_buffer, DECRYPT_BUFFER_INTS * 4 - 16);
assert (in_ptr == in_end);
assert (l >= 60);
assert (decrypt_buffer[5] == (int)CODE_server_DH_inner_data);
assert (!memcmp (decrypt_buffer + 6, nonce, 16));
assert (!memcmp (decrypt_buffer + 10, server_nonce, 16));
int g = decrypt_buffer[14];
in_ptr = decrypt_buffer + 15;
in_end = decrypt_buffer + (l >> 2);
BN_init (&dh_prime);
BN_init (&g_a);
assert (fetch_bignum (&dh_prime) > 0);
assert (fetch_bignum (&g_a) > 0);
assert (check_g_bn (&dh_prime, &g_a) >= 0);
int server_time = *in_ptr++;
assert (in_ptr <= in_end);
assert (check_DH_params (&dh_prime, g) >= 0);
static char sha1_buffer[20];
sha1 ((unsigned char *) decrypt_buffer + 20, (in_ptr - decrypt_buffer - 5) * 4, (unsigned char *) sha1_buffer);
assert (!memcmp (decrypt_buffer, sha1_buffer, 20));
assert ((char *) in_end - (char *) in_ptr < 16);
GET_DC(c)->server_time_delta = server_time - time (0);
GET_DC(c)->server_time_udelta = server_time - get_utime (CLOCK_MONOTONIC);
//logprintf ( "server time is %d, delta = %d\n", server_time, server_time_delta);
// Build set_client_DH_params answer
clear_packet ();
packet_ptr += 5;
out_int (CODE_client_DH_inner_data);
out_ints ((int *) nonce, 4);
out_ints ((int *) server_nonce, 4);
out_long (0LL);
BN_init (&dh_g);
ensure (BN_set_word (&dh_g, g));
secure_random (s_power, 256);
BIGNUM *dh_power = BN_bin2bn ((unsigned char *)s_power, 256, 0);
ensure_ptr (dh_power);
BIGNUM *y = BN_new ();
ensure_ptr (y);
ensure (BN_mod_exp (y, &dh_g, dh_power, &dh_prime, BN_ctx));
out_bignum (y);
BN_free (y);
BN_init (&auth_key_num);
ensure (BN_mod_exp (&auth_key_num, &g_a, dh_power, &dh_prime, BN_ctx));
l = BN_num_bytes (&auth_key_num);
assert (l >= 250 && l <= 256);
assert (BN_bn2bin (&auth_key_num, (unsigned char *)GET_DC(c)->auth_key));
memset (GET_DC(c)->auth_key + l, 0, 256 - l);
BN_free (dh_power);
BN_free (&auth_key_num);
BN_free (&dh_g);
BN_free (&g_a);
BN_free (&dh_prime);
//hexdump (auth_key, auth_key + 256);
sha1 ((unsigned char *) (packet_buffer + 5), (packet_ptr - packet_buffer - 5) * 4, (unsigned char *) packet_buffer);
//hexdump ((char *)packet_buffer, (char *)packet_ptr);
l = encrypt_packet_buffer_aes_unauth (server_nonce, new_nonce);
clear_packet ();
out_int (CODE_set_client_DH_params);
out_ints ((int *) nonce, 4);
out_ints ((int *) server_nonce, 4);
out_cstring ((char *) encrypt_buffer, l);
c_state = st_client_dh_sent;
return rpc_send_packet (c);
}
int process_auth_complete (struct connection *c UU, char *packet, int len) {
if (verbosity) {
logprintf ( "process_dh_answer(), len=%d\n", len);
}
assert (len == 72);
assert (!*(long long *) packet);
assert (*(int *) (packet + 16) == len - 20);
assert (!(len & 3));
assert (*(int *) (packet + 20) == CODE_dh_gen_ok);
assert (!memcmp (packet + 24, nonce, 16));
assert (!memcmp (packet + 40, server_nonce, 16));
static unsigned char tmp[44], sha1_buffer[20];
memcpy (tmp, new_nonce, 32);
tmp[32] = 1;
//GET_DC(c)->auth_key_id = *(long long *)(sha1_buffer + 12);
bl_do_set_auth_key_id (GET_DC(c)->id, (unsigned char *)GET_DC(c)->auth_key);
sha1 ((unsigned char *)GET_DC(c)->auth_key, 256, sha1_buffer);
memcpy (tmp + 33, sha1_buffer, 8);
sha1 (tmp, 41, sha1_buffer);
assert (!memcmp (packet + 56, sha1_buffer + 4, 16));
GET_DC(c)->server_salt = *(long long *)server_nonce ^ *(long long *)new_nonce;
if (verbosity >= 3) {
logprintf ( "auth_key_id=%016llx\n", GET_DC(c)->auth_key_id);
}
//kprintf ("OK\n");
//c->status = conn_error;
//sleep (1);
c_state = st_authorized;
//return 1;
if (verbosity) {
logprintf ( "Auth success\n");
}
auth_success ++;
GET_DC(c)->flags |= 1;
write_auth_file ();
return 1;
}
/*
*
* AUTHORIZED (MAIN) PROTOCOL PART
*
*/
struct encrypted_message enc_msg;
long long client_last_msg_id, server_last_msg_id;
double get_server_time (struct dc *DC) {
if (!DC->server_time_udelta) {
DC->server_time_udelta = get_utime (CLOCK_REALTIME) - get_utime (CLOCK_MONOTONIC);
}
return get_utime (CLOCK_MONOTONIC) + DC->server_time_udelta;
}
long long generate_next_msg_id (struct dc *DC) {
long long next_id = (long long) (get_server_time (DC) * (1LL << 32)) & -4;
if (next_id <= client_last_msg_id) {
next_id = client_last_msg_id += 4;
} else {
client_last_msg_id = next_id;
}
return next_id;
}
void init_enc_msg (struct session *S, int useful) {
struct dc *DC = S->dc;
assert (DC->auth_key_id);
enc_msg.auth_key_id = DC->auth_key_id;
// assert (DC->server_salt);
enc_msg.server_salt = DC->server_salt;
if (!S->session_id) {
secure_random (&S->session_id, 8);
}
enc_msg.session_id = S->session_id;
//enc_msg.auth_key_id2 = auth_key_id;
enc_msg.msg_id = generate_next_msg_id (DC);
//enc_msg.msg_id -= 0x10000000LL * (lrand48 () & 15);
//kprintf ("message id %016llx\n", enc_msg.msg_id);
enc_msg.seq_no = S->seq_no;
if (useful) {
enc_msg.seq_no |= 1;
}
S->seq_no += 2;
};
int aes_encrypt_message (struct dc *DC, struct encrypted_message *enc) {
unsigned char sha1_buffer[20];
const int MINSZ = offsetof (struct encrypted_message, message);
const int UNENCSZ = offsetof (struct encrypted_message, server_salt);
int enc_len = (MINSZ - UNENCSZ) + enc->msg_len;
assert (enc->msg_len >= 0 && enc->msg_len <= MAX_MESSAGE_INTS * 4 - 16 && !(enc->msg_len & 3));
sha1 ((unsigned char *) &enc->server_salt, enc_len, sha1_buffer);
//printf ("enc_len is %d\n", enc_len);
if (verbosity >= 2) {
logprintf ( "sending message with sha1 %08x\n", *(int *)sha1_buffer);
}
memcpy (enc->msg_key, sha1_buffer + 4, 16);
init_aes_auth (DC->auth_key, enc->msg_key, AES_ENCRYPT);
//hexdump ((char *)enc, (char *)enc + enc_len + 24);
return pad_aes_encrypt ((char *) &enc->server_salt, enc_len, (char *) &enc->server_salt, MAX_MESSAGE_INTS * 4 + (MINSZ - UNENCSZ));
}
long long encrypt_send_message (struct connection *c, int *msg, int msg_ints, int useful) {
struct dc *DC = GET_DC(c);
struct session *S = c->session;
assert (S);
const int UNENCSZ = offsetof (struct encrypted_message, server_salt);
if (msg_ints <= 0 || msg_ints > MAX_MESSAGE_INTS - 4) {
return -1;
}
if (msg) {
memcpy (enc_msg.message, msg, msg_ints * 4);
enc_msg.msg_len = msg_ints * 4;
} else {
if ((enc_msg.msg_len & 0x80000003) || enc_msg.msg_len > MAX_MESSAGE_INTS * 4 - 16) {
return -1;
}
}
init_enc_msg (S, useful);
//hexdump ((char *)msg, (char *)msg + (msg_ints * 4));
int l = aes_encrypt_message (DC, &enc_msg);
//hexdump ((char *)&enc_msg, (char *)&enc_msg + l + 24);
assert (l > 0);
rpc_send_message (c, &enc_msg, l + UNENCSZ);
return client_last_msg_id;
}
int longpoll_count, good_messages;
int auth_work_start (struct connection *c UU) {
return 1;
}
void rpc_execute_answer (struct connection *c, long long msg_id UU);
int unread_messages;
int our_id;
int pts;
int qts;
int last_date;
int seq;
void fetch_pts (void) {
int p = fetch_int ();
if (p <= pts) { return; }
if (p != pts + 1) {
if (pts) {
//logprintf ("Hole in pts p = %d, pts = %d\n", p, pts);
// get difference should be here
pts = p;
} else {
pts = p;
}
} else {
pts ++;
}
bl_do_set_pts (pts);
}
void fetch_qts (void) {
int p = fetch_int ();
if (p <= qts) { return; }
if (p != qts + 1) {
if (qts) {
//logprintf ("Hole in qts\n");
// get difference should be here
qts = p;
} else {
qts = p;
}
} else {
qts ++;
}
bl_do_set_qts (qts);
}
void fetch_date (void) {
int p = fetch_int ();
if (p > last_date) {
last_date = p;
bl_do_set_date (last_date);
}
}
void fetch_seq (void) {
int x = fetch_int ();
if (x > seq + 1) {
logprintf ("Hole in seq: seq = %d, x = %d\n", seq, x);
//do_get_difference ();
//seq = x;
} else if (x == seq + 1) {
seq = x;
bl_do_set_seq (seq);
}
}
void work_update_binlog (void) {
unsigned op = fetch_int ();
switch (op) {
case CODE_update_user_name:
{
peer_id_t user_id = MK_USER (fetch_int ());
peer_t *UC = user_chat_get (user_id);
if (UC) {
struct user *U = &UC->user;
if (U->first_name) { tfree_str (U->first_name); }
if (U->last_name) { tfree_str (U->last_name); }
if (U->print_name) { tfree_str (U->print_name); }
U->first_name = fetch_str_dup ();
U->last_name = fetch_str_dup ();
U->print_name = create_print_name (U->id, U->first_name, U->last_name, 0, 0);
} else {
fetch_skip_str ();
fetch_skip_str ();
}
}
break;
case CODE_update_user_photo:
{
peer_id_t user_id = MK_USER (fetch_int ());
peer_t *UC = user_chat_get (user_id);
fetch_date ();
if (UC) {
struct user *U = &UC->user;
unsigned y = fetch_int ();
if (y == CODE_user_profile_photo_empty) {
U->photo_id = 0;
U->photo_big.dc = -2;
U->photo_small.dc = -2;
} else {
assert (y == CODE_user_profile_photo);
U->photo_id = fetch_long ();
fetch_file_location (&U->photo_small);
fetch_file_location (&U->photo_big);
}
} else {
struct file_location t;
unsigned y = fetch_int ();
if (y == CODE_user_profile_photo_empty) {
} else {
assert (y == CODE_user_profile_photo);
fetch_long (); // photo_id
fetch_file_location (&t);
fetch_file_location (&t);
}
}
fetch_bool ();
}
break;
default:
assert (0);
}
}
void work_update (struct connection *c UU, long long msg_id UU) {
unsigned op = fetch_int ();
switch (op) {
case CODE_update_new_message:
{
struct message *M = fetch_alloc_message ();
assert (M);
fetch_pts ();
unread_messages ++;
print_message (M);
update_prompt ();
break;
};
case CODE_update_message_i_d:
{
int id = fetch_int (); // id
int new = fetch_long (); // random_id
struct message *M = message_get (new);
if (M) {
bl_do_set_msg_id (M, id);
}
}
break;
case CODE_update_read_messages:
{
assert (fetch_int () == (int)CODE_vector);
int n = fetch_int ();
int i;
for (i = 0; i < n; i++) {
int id = fetch_int ();
struct message *M = message_get (id);
if (M) {
bl_do_set_unread (M, 0);
}
}
fetch_pts ();
if (log_level >= 1) {
print_start ();
push_color (COLOR_YELLOW);
print_date (time (0));
printf (" %d messages marked as read\n", n);
pop_color ();
print_end ();
}
}
break;
case CODE_update_user_typing:
{
peer_id_t id = MK_USER (fetch_int ());
peer_t *U = user_chat_get (id);
if (log_level >= 2) {
print_start ();
push_color (COLOR_YELLOW);
print_date (time (0));
printf (" User ");
print_user_name (id, U);
printf (" is typing....\n");
pop_color ();
print_end ();
}
}
break;
case CODE_update_chat_user_typing:
{
peer_id_t chat_id = MK_CHAT (fetch_int ());
peer_id_t id = MK_USER (fetch_int ());
peer_t *C = user_chat_get (chat_id);
peer_t *U = user_chat_get (id);
if (log_level >= 2) {
print_start ();
push_color (COLOR_YELLOW);
print_date (time (0));
printf (" User ");
print_user_name (id, U);
printf (" is typing in chat ");
print_chat_name (chat_id, C);
printf ("....\n");
pop_color ();
print_end ();
}
}
break;
case CODE_update_user_status:
{
peer_id_t user_id = MK_USER (fetch_int ());
peer_t *U = user_chat_get (user_id);
if (U) {
fetch_user_status (&U->user.status);
if (log_level >= 3) {
print_start ();
push_color (COLOR_YELLOW);
print_date (time (0));
printf (" User ");
print_user_name (user_id, U);
printf (" is now ");
printf ("%s\n", (U->user.status.online > 0) ? "online" : "offline");
pop_color ();
print_end ();
}
} else {
struct user_status t;
fetch_user_status (&t);
}
}
break;
case CODE_update_user_name:
{
peer_id_t user_id = MK_USER (fetch_int ());
peer_t *UC = user_chat_get (user_id);
if (UC && (UC->flags & FLAG_CREATED)) {