forked from TelegramMessenger/MTProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmtproto-proxy.c
2374 lines (2097 loc) · 70.9 KB
/
mtproto-proxy.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 MTProto-proxy
MTProto-proxy 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.
MTProto-Server 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 MTProto-Server. If not, see <http://www.gnu.org/licenses/>.
This program is released under the GPL with the additional exemption
that compiling, linking, and/or using OpenSSL is allowed.
You are free to remove this exemption from derived works.
Copyright 2012-2018 Nikolai Durov
2012-2014 Andrey Lopatin
2014-2018 Telegram Messenger Inc
*/
#define _FILE_OFFSET_BITS 64
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <netdb.h>
#include <ctype.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include "crc32.h"
#include "md5.h"
#include "resolver.h"
#include "net/net-events.h"
#include "kprintf.h"
#include "precise-time.h"
#include "server-functions.h"
#include "net/net-tcp-connections.h"
#include "net/net-rpc-targets.h"
#include "net/net-http-server.h"
#include "net/net-tcp-rpc-server.h"
#include "net/net-tcp-rpc-client.h"
#include "net/net-tcp-rpc-ext-server.h"
#include "net/net-crypto-aes.h"
#include "net/net-crypto-dh.h"
#include "mtproto-common.h"
#include "mtproto-config.h"
#include "common/tl-parse.h"
#include "engine/engine.h"
#include "engine/engine-net.h"
#ifndef COMMIT
#define COMMIT "unknown"
#endif
#define VERSION_STR "mtproxy-0.01"
const char FullVersionStr[] = VERSION_STR " compiled at " __DATE__ " " __TIME__ " by gcc " __VERSION__ " "
#ifdef __LP64__
"64-bit"
#else
"32-bit"
#endif
" after commit " COMMIT;
#define EXT_CONN_TABLE_SIZE (1 << 22)
#define EXT_CONN_HASH_SHIFT 20
#define EXT_CONN_HASH_SIZE (1 << EXT_CONN_HASH_SHIFT)
#define RPC_TIMEOUT_INTERVAL 5.0
#define MAX_HTTP_LISTEN_PORTS 128
#define HTTP_MAX_WAIT_TIMEOUT 960.0
#define PING_INTERVAL 5.0
#define STOP_INTERVAL (2 * ping_interval)
#define FAIL_INTERVAL (20 * ping_interval)
#define RESPONSE_FAIL_TIMEOUT 5
#define CONNECT_TIMEOUT 3
#define MAX_POST_SIZE (262144 * 4 - 4096)
#define DEFAULT_WINDOW_CLAMP 131072
// #define DEFAULT_OUTBOUND_CONNECTION_CREATION_RATE 1000000
#if 0
#define MAX_CONNECTION_BUFFER_SPACE (1 << 10) //(1 << 25)
#define MAX_MTFRONT_NB 1 //((NB_max * 3) >> 2)
#else
#define MAX_CONNECTION_BUFFER_SPACE (1 << 25)
#define MAX_MTFRONT_NB ((NB_max * 3) >> 2)
#endif
static double ping_interval = PING_INTERVAL;
static int window_clamp;
#define PROXY_MODE_OUT 2
static int proxy_mode;
#define IS_PROXY_IN 0
#define IS_PROXY_OUT 1
#define IS_PROXY_INOUT 1
#define TL_HTTP_QUERY_INFO 0xd45ab381
#define TL_PROXY_TAG 0xdb1e26ae
conn_type_t ct_http_server_mtfront, ct_tcp_rpc_ext_server_mtfront, ct_tcp_rpc_server_mtfront;
long long connections_failed_lru, connections_failed_flood;
long long api_invoke_requests;
volatile int sigpoll_cnt;
#define STATS_BUFF_SIZE (1 << 20)
int stats_buff_len;
char stats_buff[STATS_BUFF_SIZE];
// current HTTP query headers
char cur_http_origin[1024], cur_http_referer[1024], cur_http_user_agent[1024];
int cur_http_origin_len, cur_http_referer_len, cur_http_user_agent_len;
int check_conn_buffers (connection_job_t c);
void lru_insert_conn (connection_job_t c);
/*
*
* CONFIGURATION PARSER SETUP
*
*/
#define DEFAULT_CFG_MIN_CONNECTIONS 4
#define DEFAULT_CFG_MAX_CONNECTIONS 8
int default_cfg_min_connections = DEFAULT_CFG_MIN_CONNECTIONS;
int default_cfg_max_connections = DEFAULT_CFG_MAX_CONNECTIONS;
struct tcp_rpc_client_functions mtfront_rpc_client;
conn_type_t ct_tcp_rpc_client_mtfront;
struct conn_target_info default_cfg_ct = {
.min_connections = DEFAULT_CFG_MIN_CONNECTIONS,
.max_connections = DEFAULT_CFG_MAX_CONNECTIONS,
.type = &ct_tcp_rpc_client_mtfront,
.extra = (void *)&mtfront_rpc_client,
.reconnect_timeout = 17
};
/*
*
* EXTERNAL CONNECTIONS TABLE
*
*/
struct ext_connection {
struct ext_connection *o_prev, *o_next; // list of all with same out_fd
struct ext_connection *i_prev, *i_next; // list of all with same in_fd
struct ext_connection *h_next; // next in hash on (in_fd, in_conn_id)
int in_fd, in_gen;
int out_fd, out_gen;
long long in_conn_id;
long long out_conn_id;
long long auth_key_id;
struct ext_connection *lru_prev, *lru_next;
};
struct ext_connection_ref {
struct ext_connection *ref;
long long out_conn_id;
};
long long ext_connections, ext_connections_created;
struct ext_connection_ref OutExtConnections[EXT_CONN_TABLE_SIZE];
struct ext_connection *InExtConnectionHash[EXT_CONN_HASH_SIZE];
struct ext_connection ExtConnectionHead[MAX_CONNECTIONS];
void lru_delete_ext_conn (struct ext_connection *Ext);
static inline void check_engine_class (void) {
check_thread_class (JC_ENGINE);
}
static inline int ext_conn_hash (int in_fd, long long in_conn_id) {
unsigned long long h = (unsigned long long) in_fd * 11400714819323198485ULL + (unsigned long long) in_conn_id * 13043817825332782213ULL;
return (h >> (64 - EXT_CONN_HASH_SHIFT));
}
// makes sense only for !IS_PROXY_IN
// returns the only ext_connection with given in_fd
struct ext_connection *get_ext_connection_by_in_fd (int in_fd) {
check_engine_class ();
assert ((unsigned) in_fd < MAX_CONNECTIONS);
struct ext_connection *H = &ExtConnectionHead[in_fd];
struct ext_connection *Ex = H->i_next;
assert (H->i_next == H->i_prev);
if (!Ex || Ex == H) {
return 0;
}
assert (Ex->in_fd == in_fd);
return Ex;
}
// mode: 0 = find, 1 = delete, 2 = create if not found, 3 = find or create
struct ext_connection *get_ext_connection_by_in_conn_id (int in_fd, int in_gen, long long in_conn_id, int mode, int *created) {
check_engine_class ();
int h = ext_conn_hash (in_fd, in_conn_id);
struct ext_connection **prev = &InExtConnectionHash[h], *cur = *prev;
for (; cur; cur = *prev) {
if (cur->in_fd == in_fd && cur->in_conn_id == in_conn_id) {
assert (cur->out_conn_id);
if (mode == 0 || mode == 3) {
return cur;
}
if (mode != 1) {
return 0;
}
if (cur->i_next) {
cur->i_next->i_prev = cur->i_prev;
cur->i_prev->i_next = cur->i_next;
cur->i_next = cur->i_prev = 0;
}
if (cur->o_next) {
cur->o_next->o_prev = cur->o_prev;
cur->o_prev->o_next = cur->o_next;
cur->o_next = cur->o_prev = 0;
}
lru_delete_ext_conn (cur);
*prev = cur->h_next;
cur->h_next = 0;
int h = cur->out_conn_id & (EXT_CONN_TABLE_SIZE - 1);
assert (OutExtConnections[h].ref == cur);
assert (OutExtConnections[h].out_conn_id == cur->out_conn_id);
OutExtConnections[h].ref = 0;
cur->out_conn_id = 0;
memset (cur, 0, sizeof (struct ext_connection));
free (cur);
ext_connections--;
return (void *) -1L;
}
prev = &(cur->h_next);
}
if (mode != 2 && mode != 3) {
return 0;
}
assert (ext_connections < EXT_CONN_TABLE_SIZE / 2);
cur = calloc (sizeof (struct ext_connection), 1);
assert (cur);
cur->h_next = InExtConnectionHash[h];
InExtConnectionHash[h] = cur;
cur->in_fd = in_fd;
cur->in_gen = in_gen;
cur->in_conn_id = in_conn_id;
assert ((unsigned) in_fd < MAX_CONNECTIONS);
if (in_fd) {
struct ext_connection *H = &ExtConnectionHead[in_fd];
if (!H->i_next) {
H->i_next = H->i_prev = H;
}
assert (H->i_next == H);
cur->i_next = H;
cur->i_prev = H->i_prev;
H->i_prev->i_next = cur;
H->i_prev = cur;
}
h = in_conn_id ? lrand48() : in_fd;
while (OutExtConnections[h &= (EXT_CONN_TABLE_SIZE - 1)].ref) {
h = lrand48();
}
OutExtConnections[h].ref = cur;
cur->out_conn_id = OutExtConnections[h].out_conn_id = (OutExtConnections[h].out_conn_id | (EXT_CONN_TABLE_SIZE - 1)) + 1 + h;
assert (cur->out_conn_id);
if (created) {
++*created;
}
ext_connections++;
ext_connections_created++;
return cur;
}
struct ext_connection *find_ext_connection_by_out_conn_id (long long out_conn_id) {
check_engine_class ();
int h = out_conn_id & (EXT_CONN_TABLE_SIZE - 1);
struct ext_connection *cur = OutExtConnections[h].ref;
if (!cur || OutExtConnections[h].out_conn_id != out_conn_id) {
return 0;
}
assert (cur->out_conn_id == out_conn_id);
return cur;
}
// MUST be new
struct ext_connection *create_ext_connection (connection_job_t CI, long long in_conn_id, connection_job_t CO, long long auth_key_id) {
check_engine_class ();
struct ext_connection *Ex = get_ext_connection_by_in_conn_id (CONN_INFO(CI)->fd, CONN_INFO(CI)->generation, in_conn_id, 2, 0);
assert (Ex && "ext_connection already exists");
assert (!Ex->out_fd && !Ex->o_next && !Ex->auth_key_id);
assert (!CO || (unsigned) CONN_INFO(CO)->fd < MAX_CONNECTIONS);
assert (CO != CI);
if (CO) {
struct ext_connection *H = &ExtConnectionHead[CONN_INFO(CO)->fd];
assert (H->o_next);
Ex->o_next = H;
Ex->o_prev = H->o_prev;
H->o_prev->o_next = Ex;
H->o_prev = Ex;
Ex->out_fd = CONN_INFO(CO)->fd;
Ex->out_gen = CONN_INFO(CO)->generation;
}
Ex->auth_key_id = auth_key_id;
return Ex;
}
static int _notify_remote_closed (JOB_REF_ARG(C), long long out_conn_id);
void remove_ext_connection (struct ext_connection *Ex, int send_notifications) {
assert (Ex);
assert (Ex->out_conn_id);
assert (Ex == find_ext_connection_by_out_conn_id (Ex->out_conn_id));
if (Ex->out_fd) {
assert ((unsigned) Ex->out_fd < MAX_CONNECTIONS);
assert (Ex->o_next);
if (send_notifications & 1) {
connection_job_t CO = connection_get_by_fd_generation (Ex->out_fd, Ex->out_gen);
if (CO) {
_notify_remote_closed (JOB_REF_PASS (CO), Ex->out_conn_id);
}
}
}
if (Ex->in_fd) {
assert ((unsigned) Ex->in_fd < MAX_CONNECTIONS);
assert (Ex->i_next);
if (send_notifications & 2) {
connection_job_t CI = connection_get_by_fd_generation (Ex->in_fd, Ex->in_gen);
if (Ex->in_conn_id) {
assert (0);
} else {
if (CI) {
fail_connection (CI, -33);
job_decref (JOB_REF_PASS (CI));
}
}
}
}
assert (get_ext_connection_by_in_conn_id (Ex->in_fd, Ex->in_gen, Ex->in_conn_id, 1, 0) == (void *) -1L);
}
/*
*
* MULTIPROCESS STATISTICS
*
*/
#define MAX_WORKERS 256
struct worker_stats {
int cnt;
int updated_at;
struct buffers_stat bufs;
struct connections_stat conn;
int allocated_aes_crypto, allocated_aes_crypto_temp;
long long tot_dh_rounds[3];
int ev_heap_size;
int http_connections;
long long get_queries;
int pending_http_queries;
long long accept_calls_failed, accept_nonblock_set_failed, accept_connection_limit_failed,
accept_rate_limit_failed, accept_init_accepted_failed;
long long active_rpcs, active_rpcs_created;
long long rpc_dropped_running, rpc_dropped_answers;
long long tot_forwarded_queries, expired_forwarded_queries;
long long tot_forwarded_responses;
long long dropped_queries, dropped_responses;
long long tot_forwarded_simple_acks, dropped_simple_acks;
long long mtproto_proxy_errors;
long long connections_failed_lru, connections_failed_flood;
long long ext_connections, ext_connections_created;
long long http_queries, http_bad_headers;
};
struct worker_stats *WStats, SumStats;
int worker_id, workers, slave_mode, parent_pid;
int pids[MAX_WORKERS];
long long get_queries;
long long http_queries;
int pending_http_queries;
long long active_rpcs, active_rpcs_created;
long long rpc_dropped_running, rpc_dropped_answers;
long long tot_forwarded_queries, expired_forwarded_queries, dropped_queries;
long long tot_forwarded_responses, dropped_responses;
long long tot_forwarded_simple_acks, dropped_simple_acks;
long long mtproto_proxy_errors;
char proxy_tag[16];
int proxy_tag_set;
static void update_local_stats_copy (struct worker_stats *S) {
S->cnt++;
__sync_synchronize();
S->updated_at = now;
#define UPD(x) S->x = x;
fetch_tot_dh_rounds_stat (S->tot_dh_rounds);
fetch_connections_stat (&S->conn);
fetch_aes_crypto_stat (&S->allocated_aes_crypto, &S->allocated_aes_crypto_temp);
fetch_buffers_stat (&S->bufs);
UPD (ev_heap_size);
UPD (get_queries);
UPD (http_connections);
UPD (pending_http_queries);
UPD (active_rpcs);
UPD (active_rpcs_created);
UPD (rpc_dropped_running);
UPD (rpc_dropped_answers);
UPD (tot_forwarded_queries);
UPD (expired_forwarded_queries);
UPD (dropped_queries);
UPD (tot_forwarded_responses);
UPD (dropped_responses);
UPD (tot_forwarded_simple_acks);
UPD (dropped_simple_acks);
UPD (mtproto_proxy_errors);
UPD (connections_failed_lru);
UPD (connections_failed_flood);
UPD (ext_connections);
UPD (ext_connections_created);
UPD (http_queries);
UPD (http_bad_headers);
#undef UPD
__sync_synchronize();
S->cnt++;
__sync_synchronize();
}
static inline void add_stats (struct worker_stats *W) {
#define UPD(x) SumStats.x += W->x;
UPD (tot_dh_rounds[0]);
UPD (tot_dh_rounds[1]);
UPD (tot_dh_rounds[2]);
UPD (conn.active_connections);
UPD (conn.active_dh_connections);
UPD (conn.outbound_connections);
UPD (conn.active_outbound_connections);
UPD (conn.ready_outbound_connections);
UPD (conn.active_special_connections);
UPD (conn.max_special_connections);
UPD (conn.allocated_connections);
UPD (conn.allocated_outbound_connections);
UPD (conn.allocated_inbound_connections);
UPD (conn.allocated_socket_connections);
UPD (conn.allocated_targets);
UPD (conn.ready_targets);
UPD (conn.active_targets);
UPD (conn.inactive_targets);
UPD (conn.tcp_readv_calls);
UPD (conn.tcp_readv_intr);
UPD (conn.tcp_readv_bytes);
UPD (conn.tcp_writev_calls);
UPD (conn.tcp_writev_intr);
UPD (conn.tcp_writev_bytes);
UPD (conn.accept_calls_failed);
UPD (conn.accept_nonblock_set_failed);
UPD (conn.accept_rate_limit_failed);
UPD (conn.accept_init_accepted_failed);
UPD (allocated_aes_crypto);
UPD (allocated_aes_crypto_temp);
UPD (bufs.total_used_buffers_size);
UPD (bufs.allocated_buffer_bytes);
UPD (bufs.total_used_buffers);
UPD (bufs.allocated_buffer_chunks);
UPD (bufs.max_allocated_buffer_chunks);
UPD (bufs.max_allocated_buffer_bytes);
UPD (bufs.max_buffer_chunks);
UPD (bufs.buffer_chunk_alloc_ops);
UPD (ev_heap_size);
UPD (get_queries);
UPD (http_connections);
UPD (pending_http_queries);
UPD (active_rpcs);
UPD (active_rpcs_created);
UPD (rpc_dropped_running);
UPD (rpc_dropped_answers);
UPD (tot_forwarded_queries);
UPD (expired_forwarded_queries);
UPD (dropped_queries);
UPD (tot_forwarded_responses);
UPD (dropped_responses);
UPD (tot_forwarded_simple_acks);
UPD (dropped_simple_acks);
UPD (mtproto_proxy_errors);
UPD (connections_failed_lru);
UPD (connections_failed_flood);
UPD (ext_connections);
UPD (ext_connections_created);
UPD (http_queries);
UPD (http_bad_headers);
#undef UPD
}
void update_local_stats (void) {
if (!slave_mode) {
return;
}
update_local_stats_copy (WStats + worker_id * 2);
update_local_stats_copy (WStats + worker_id * 2 + 1);
}
void compute_stats_sum (void) {
if (!workers) {
return;
}
memset (&SumStats, 0, sizeof (SumStats));
int i;
for (i = 0; i < workers; i++) {
static struct worker_stats W;
struct worker_stats *F;
int s_cnt;
do {
F = WStats + i * 2;
do {
barrier ();
s_cnt = (++F)->cnt;
if (!(s_cnt & 1)) {
break;
}
s_cnt = (--F)->cnt;
} while (s_cnt & 1);
barrier ();
memcpy (&W, F, sizeof (W));
barrier ();
} while (s_cnt != F->cnt);
add_stats (&W);
}
}
/*
*
* SERVER
*
*/
void mtfront_prepare_stats (stats_buffer_t *sb) {
struct connections_stat conn;
struct buffers_stat bufs;
long long tot_dh_rounds[3];
int allocated_aes_crypto, allocated_aes_crypto_temp;
int uptime = now - start_time;
compute_stats_sum ();
fetch_connections_stat (&conn);
fetch_buffers_stat (&bufs);
fetch_tot_dh_rounds_stat (tot_dh_rounds);
fetch_aes_crypto_stat (&allocated_aes_crypto, &allocated_aes_crypto_temp);
sb_prepare (sb);
sb_memory (sb, AM_GET_MEMORY_USAGE_SELF);
#define S(x) ((x)+(SumStats.x))
#define S1(x) (SumStats.x)
#define SW(x) (workers ? S1(x) : S(x))
sb_printf (sb,
"config_filename\t%s\n"
"config_loaded_at\t%d\n"
"config_size\t%d\n"
"config_md5\t%s\n"
"config_auth_clusters\t%d\n"
"workers\t%d\n"
"queries_get\t%lld\n"
"qps_get\t%.3f\n"
"tot_forwarded_queries\t%lld\n"
"expired_forwarded_queries\t%lld\n"
"dropped_queries\t%lld\n"
"tot_forwarded_responses\t%lld\n"
"dropped_responses\t%lld\n"
"tot_forwarded_simple_acks\t%lld\n"
"dropped_simple_acks\t%lld\n"
"active_rpcs_created\t%lld\n"
"active_rpcs\t%lld\n"
"rpc_dropped_answers\t%lld\n"
"rpc_dropped_running\t%lld\n"
"window_clamp\t%d\n"
"total_ready_targets\t%d\n"
"total_allocated_targets\t%d\n"
"total_declared_targets\t%d\n"
"total_inactive_targets\t%d\n"
"total_connections\t%d\n"
"total_encrypted_connections\t%d\n"
"total_allocated_connections\t%d\n"
"total_allocated_outbound_connections\t%d\n"
"total_allocated_inbound_connections\t%d\n"
"total_allocated_socket_connections\t%d\n"
"total_dh_connections\t%d\n"
"total_dh_rounds\t%lld %lld %lld\n"
"total_special_connections\t%d\n"
"total_max_special_connections\t%d\n"
"total_accept_connections_failed\t%lld %lld %lld %lld %lld\n"
"ext_connections\t%lld\n"
"ext_connections_created\t%lld\n"
"total_active_network_events\t%d\n"
"total_network_buffers_used_size\t%lld\n"
"total_network_buffers_allocated_bytes\t%lld\n"
"total_network_buffers_used\t%d\n"
"total_network_buffer_chunks_allocated\t%d\n"
"total_network_buffer_chunks_allocated_max\t%d\n"
"mtproto_proxy_errors\t%lld\n"
"connections_failed_lru\t%lld\n"
"connections_failed_flood\t%lld\n"
"http_connections\t%d\n"
"pending_http_queries\t%d\n"
"http_queries\t%lld\n"
"http_bad_headers\t%lld\n"
"http_qps\t%.6f\n"
"proxy_mode\t%d\n"
"proxy_tag_set\t%d\n"
"version\t" VERSION_STR " compiled at " __DATE__ " " __TIME__ " by gcc " __VERSION__ " "
#ifdef __LP64__
"64-bit"
#else
"32-bit"
#endif
" after commit " COMMIT "\n",
config_filename,
CurConf->config_loaded_at,
CurConf->config_bytes,
CurConf->config_md5_hex,
CurConf->auth_stats.tot_clusters,
workers,
S(get_queries),
safe_div (S(get_queries), uptime),
S(tot_forwarded_queries),
S(expired_forwarded_queries),
S(dropped_queries),
S(tot_forwarded_responses),
S(dropped_responses),
S(tot_forwarded_simple_acks),
S(dropped_simple_acks),
S(active_rpcs_created),
S(active_rpcs),
S(rpc_dropped_answers),
S(rpc_dropped_running),
window_clamp,
SW(conn.ready_targets),
SW(conn.allocated_targets),
SW(conn.active_targets),
SW(conn.inactive_targets),
S(conn.active_connections),
S(allocated_aes_crypto),
S(conn.allocated_connections),
S(conn.allocated_outbound_connections),
S(conn.allocated_inbound_connections),
S(conn.allocated_socket_connections),
S(conn.active_dh_connections),
S(tot_dh_rounds[0]),
S(tot_dh_rounds[1]),
S(tot_dh_rounds[2]),
SW(conn.active_special_connections),
SW(conn.max_special_connections),
S(conn.accept_init_accepted_failed),
S(conn.accept_calls_failed),
S(conn.accept_connection_limit_failed),
S(conn.accept_rate_limit_failed),
S(conn.accept_nonblock_set_failed),
S(ext_connections),
S(ext_connections_created),
S(ev_heap_size),
SW(bufs.total_used_buffers_size),
SW(bufs.allocated_buffer_bytes),
SW(bufs.total_used_buffers),
SW(bufs.allocated_buffer_chunks),
SW(bufs.max_allocated_buffer_chunks),
S(mtproto_proxy_errors),
S(connections_failed_lru),
S(connections_failed_flood),
S(http_connections),
S(pending_http_queries),
S(http_queries),
S(http_bad_headers),
safe_div (S(http_queries), uptime),
proxy_mode,
proxy_tag_set
);
#undef S
#undef S1
#undef SW
}
/*
*
* JOB UTILS
*
*/
typedef int (*job_callback_func_t)(void *data, int len);
void schedule_job_callback (int context, job_callback_func_t func, void *data, int len);
struct job_callback_info {
job_callback_func_t func;
void *data[0];
};
int callback_job_run (job_t job, int op, struct job_thread *JT) {
struct job_callback_info *D = (struct job_callback_info *)(job->j_custom);
switch (op) {
case JS_RUN:
return D->func (D->data, job->j_custom_bytes - offsetof (struct job_callback_info, data));
// return JOB_COMPLETED;
case JS_FINISH:
return job_free (JOB_REF_PASS (job));
default:
assert (0);
}
}
void schedule_job_callback (int context, job_callback_func_t func, void *data, int len) {
job_t job = create_async_job (callback_job_run, JSP_PARENT_RWE | JSC_ALLOW (context, JS_RUN) | JSIG_FAST (JS_FINISH), -2, offsetof (struct job_callback_info, data) + len, 0, JOB_REF_NULL);
assert (job);
struct job_callback_info *D = (struct job_callback_info *)(job->j_custom);
D->func = func;
memcpy (D->data, data, len);
schedule_job (JOB_REF_PASS (job));
}
/*
*
* RPC CLIENT
*
*/
int client_send_message (JOB_REF_ARG (C), long long in_conn_id, struct tl_in_state *tlio_in, int flags);
int mtfront_client_ready (connection_job_t C);
int mtfront_client_close (connection_job_t C, int who);
int rpcc_execute (connection_job_t C, int op, struct raw_message *msg);
int tcp_rpcc_check_ready (connection_job_t C);
struct tcp_rpc_client_functions mtfront_rpc_client = {
.execute = rpcc_execute,
.check_ready = tcp_rpcc_default_check_ready,
.flush_packet = tcp_rpc_flush_packet,
.rpc_check_perm = tcp_rpcc_default_check_perm,
.rpc_init_crypto = tcp_rpcc_init_crypto,
.rpc_start_crypto = tcp_rpcc_start_crypto,
.rpc_ready = mtfront_client_ready,
.rpc_close = mtfront_client_close
};
int rpcc_exists;
static int _notify_remote_closed (JOB_REF_ARG(C), long long out_conn_id) {
TLS_START (JOB_REF_PASS(C)) {
tl_store_int (RPC_CLOSE_CONN);
tl_store_long (out_conn_id);
} TLS_END;
return 1;
}
void push_rpc_confirmation (JOB_REF_ARG (C), int confirm) {
if ((lrand48_j() & 1) || !(TCP_RPC_DATA(C)->flags & RPC_F_PAD)) {
struct raw_message *msg = malloc (sizeof (struct raw_message));
rwm_create (msg, "\xdd", 1);
rwm_push_data (msg, &confirm, 4);
mpq_push_w (CONN_INFO(C)->out_queue, msg, 0);
job_signal (JOB_REF_PASS (C), JS_RUN);
} else {
int x = -1;
struct raw_message m;
assert (rwm_create (&m, &x, 4) == 4);
assert (rwm_push_data (&m, &confirm, 4) == 4);
int z = lrand48_j() & 1;
while (z-- > 0) {
int t = lrand48_j();
assert (rwm_push_data (&m, &t, 4) == 4);
}
tcp_rpc_conn_send (JOB_REF_CREATE_PASS (C), &m, 0);
x = 0;
assert (rwm_create (&m, &x, 4) == 4);
z = lrand48_j() & 1;
while (z-- > 0) {
int t = lrand48_j();
assert (rwm_push_data (&m, &t, 4) == 4);
}
tcp_rpc_conn_send (JOB_REF_PASS (C), &m, 0);
}
}
struct client_packet_info {
struct event_timer ev;
struct raw_message msg;
connection_job_t conn;
int type;
};
int process_client_packet (struct tl_in_state *tlio_in, int op, connection_job_t C) {
int len = tl_fetch_unread ();
assert (op == tl_fetch_int ());
switch (op) {
case RPC_PONG:
return 1;
case RPC_PROXY_ANS:
if (len >= 16) {
int flags = tl_fetch_int ();
long long out_conn_id = tl_fetch_long ();
assert (tl_fetch_unread () == len - 16);
vkprintf (2, "got RPC_PROXY_ANS from connection %d:%llx, data size = %d, flags = %d\n", CONN_INFO(C)->fd, out_conn_id, tl_fetch_unread (), flags);
struct ext_connection *Ex = find_ext_connection_by_out_conn_id (out_conn_id);
connection_job_t D = 0;
if (Ex && Ex->out_fd == CONN_INFO(C)->fd && Ex->out_gen == CONN_INFO(C)->generation) {
D = connection_get_by_fd_generation (Ex->in_fd, Ex->in_gen);
}
if (D) {
vkprintf (2, "proxying answer into connection %d:%llx\n", Ex->in_fd, Ex->in_conn_id);
tot_forwarded_responses++;
client_send_message (JOB_REF_PASS(D), Ex->in_conn_id, tlio_in, flags);
} else {
vkprintf (2, "external connection not found, dropping proxied answer\n");
dropped_responses++;
_notify_remote_closed (JOB_REF_CREATE_PASS(C), out_conn_id);
}
return 1;
}
break;
case RPC_SIMPLE_ACK:
if (len == 16) {
long long out_conn_id = tl_fetch_long ();
int confirm = tl_fetch_int ();
vkprintf (2, "got RPC_SIMPLE_ACK for connection = %llx, value %08x\n", out_conn_id, confirm);
struct ext_connection *Ex = find_ext_connection_by_out_conn_id (out_conn_id);
connection_job_t D = 0;
if (Ex && Ex->out_fd == CONN_INFO(C)->fd && Ex->out_gen == CONN_INFO(C)->generation) {
D = connection_get_by_fd_generation (Ex->in_fd, Ex->in_gen);
}
if (D) {
vkprintf (2, "proxying simple ack %08x into connection %d:%llx\n", confirm, Ex->in_fd, Ex->in_conn_id);
if (Ex->in_conn_id) {
assert (0);
} else {
if (TCP_RPC_DATA(D)->flags & RPC_F_COMPACT) {
confirm = __builtin_bswap32 (confirm);
}
push_rpc_confirmation (JOB_REF_PASS (D), confirm);
}
tot_forwarded_simple_acks++;
} else {
vkprintf (2, "external connection not found, dropping simple ack\n");
dropped_simple_acks++;
_notify_remote_closed (JOB_REF_CREATE_PASS (C), out_conn_id);
}
return 1;
}
break;
case RPC_CLOSE_EXT:
if (len == 12) {
long long out_conn_id = tl_fetch_long ();
vkprintf (2, "got RPC_CLOSE_EXT for connection = %llx\n", out_conn_id);
struct ext_connection *Ex = find_ext_connection_by_out_conn_id (out_conn_id);
if (Ex) {
remove_ext_connection (Ex, 2);
}
return 1;
}
break;
default:
vkprintf (1, "unknown RPC operation %08x, ignoring\n", op);
}
return 0;
}
int client_packet_job_run (job_t job, int op, struct job_thread *JT) {
struct client_packet_info *D = (struct client_packet_info *)(job->j_custom);
switch (op) {
case JS_RUN: {
struct tl_in_state *tlio_in = tl_in_state_alloc ();
tlf_init_raw_message (tlio_in, &D->msg, D->msg.total_bytes, 0);
process_client_packet (tlio_in, D->type, D->conn);
tl_in_state_free (tlio_in);
return JOB_COMPLETED;
}
case JS_ALARM:
if (!job->j_error) {
job->j_error = ETIMEDOUT;
}
return JOB_COMPLETED;
case JS_ABORT:
if (!job->j_error) {
job->j_error = ECANCELED;
}
return JOB_COMPLETED;
case JS_FINISH:
if (D->conn) {
job_decref (JOB_REF_PASS (D->conn));
}
if (D->msg.magic) {
rwm_free (&D->msg);
}
return job_free (JOB_REF_PASS (job));
default:
return JOB_ERROR;
}
}
int rpcc_execute (connection_job_t C, int op, struct raw_message *msg) {
vkprintf (2, "rpcc_execute: fd=%d, op=%08x, len=%d\n", CONN_INFO(C)->fd, op, msg->total_bytes);
CONN_INFO(C)->last_response_time = precise_now;
switch (op) {
case RPC_PONG:
break;
case RPC_PROXY_ANS:
case RPC_SIMPLE_ACK:
case RPC_CLOSE_EXT: {
job_t job = create_async_job (client_packet_job_run, JSP_PARENT_RWE | JSC_ALLOW (JC_ENGINE, JS_RUN) | JSC_ALLOW (JC_ENGINE, JS_ABORT) | JSC_ALLOW (JC_ENGINE, JS_ALARM) | JSC_ALLOW (JC_ENGINE, JS_FINISH), -2, sizeof (struct client_packet_info), JT_HAVE_TIMER, JOB_REF_NULL);
struct client_packet_info *D = (struct client_packet_info *)(job->j_custom);
D->msg = *msg;
D->type = op;
D->conn = job_incref (C);
schedule_job (JOB_REF_PASS (job));
return 1;
}
default:
vkprintf (1, "unknown RPC operation %08x, ignoring\n", op);
}
return 0;
}
static inline int get_conn_tag (connection_job_t C) {
return 1 + (CONN_INFO(C)->generation & 0xffffff);
}
int mtfront_client_ready (connection_job_t C) {
check_engine_class ();
struct tcp_rpc_data *D = TCP_RPC_DATA(C);
int fd = CONN_INFO(C)->fd;
assert ((unsigned) fd < MAX_CONNECTIONS);
assert (!D->extra_int);
D->extra_int = get_conn_tag (C);
vkprintf (1, "Connected to RPC Middle-End (fd=%d)\n", fd);
rpcc_exists++;
struct ext_connection *H = &ExtConnectionHead[fd];
assert (!H->o_prev);
H->o_prev = H->o_next = H;
H->out_fd = fd;
CONN_INFO(C)->last_response_time = precise_now;
return 0;
}
int mtfront_client_close (connection_job_t C, int who) {
check_engine_class ();
struct tcp_rpc_data *D = TCP_RPC_DATA(C);
int fd = CONN_INFO(C)->fd;
assert ((unsigned) fd < MAX_CONNECTIONS);
vkprintf (1, "Disconnected from RPC Middle-End (fd=%d)\n", fd);
if (D->extra_int) {
assert (D->extra_int == get_conn_tag (C));
struct ext_connection *H = &ExtConnectionHead[fd], *Ex, *Ex_next;