forked from TelegramMessenger/MTProxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnet-connections.c
2204 lines (1837 loc) · 60.4 KB
/
net-connections.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 Library.
Mtproto-proxy Library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
Mtproto-proxy Library 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Mtproto-proxy Library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009-2013 Vkontakte Ltd
2008-2013 Nikolai Durov
2008-2013 Andrey Lopatin
Copyright 2014 Telegram Messenger Inc
2014 Nikolai Durov
2014 Andrey Lopatin
Copyright 2015-2016 Telegram Messenger Inc
2015-2016 Vitaly Valtman
*/
#define _FILE_OFFSET_BITS 64
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <time.h>
#include <unistd.h>
#include "crc32.h"
#include "jobs/jobs.h"
#include "net/net-events.h"
//#include "net/net-buffers.h"
#include "kprintf.h"
#include "precise-time.h"
#include "server-functions.h"
#include "net/net-connections.h"
#include "net/net-config.h"
#include "vv/vv-io.h"
#include "vv/vv-tree.h"
#include "pid.h"
#include "common/mp-queue.h"
#include "net/net-msg-buffers.h"
#include "net/net-tcp-connections.h"
#include "common/common-stats.h"
//struct process_id PID;
#define USE_EPOLLET 1
#define MAX_RECONNECT_INTERVAL 20
#define MODULE connections
static int max_accept_rate;
static double cur_accept_rate_remaining;
static double cur_accept_rate_time;
static int max_connection;
static int conn_generation;
static int max_connection_fd = MAX_CONNECTIONS;
int active_special_connections, max_special_connections = MAX_CONNECTIONS;
int special_listen_sockets;
static struct {
int fd, generation;
} special_socket[MAX_SPECIAL_LISTEN_SOCKETS];
static struct mp_queue *free_later_queue;
MODULE_STAT_TYPE {
int active_connections, active_dh_connections;
int outbound_connections, active_outbound_connections, ready_outbound_connections, listening_connections;
int allocated_outbound_connections, allocated_inbound_connections;
int inbound_connections, active_inbound_connections;
long long outbound_connections_created, inbound_connections_accepted;
int ready_targets;
long long netw_queries, netw_update_queries, total_failed_connections, total_connect_failures, unused_connections_closed;
int allocated_targets, active_targets, inactive_targets, free_targets;
int allocated_connections, allocated_socket_connections;
long long accept_calls_failed, accept_nonblock_set_failed, accept_connection_limit_failed,
accept_rate_limit_failed, accept_init_accepted_failed;
long long tcp_readv_calls, tcp_writev_calls, tcp_readv_intr, tcp_writev_intr;
long long tcp_readv_bytes, tcp_writev_bytes;
int free_later_size;
long long free_later_total;
};
MODULE_INIT
MODULE_STAT_FUNCTION
SB_SUM_ONE_I (active_connections);
SB_SUM_ONE_I (active_dh_connections);
SB_SUM_ONE_I (outbound_connections);
SB_SUM_ONE_I (ready_outbound_connections);
SB_SUM_ONE_I (active_outbound_connections);
SB_SUM_ONE_LL (outbound_connections_created);
SB_SUM_ONE_LL (total_connect_failures);
SB_SUM_ONE_I (inbound_connections);
//SB_SUM_ONE_I (ready_inbound_connections);
SB_SUM_ONE_I (active_inbound_connections);
SB_SUM_ONE_LL (inbound_connections_accepted);
SB_SUM_ONE_I (listening_connections);
SB_SUM_ONE_LL (unused_connections_closed);
SB_SUM_ONE_I (ready_targets);
SB_SUM_ONE_I (allocated_targets);
SB_SUM_ONE_I (active_targets);
SB_SUM_ONE_I (inactive_targets);
SB_SUM_ONE_I (free_targets);
sb_printf (sb,
"max_connections\t%d\n"
"active_special_connections\t%d\n"
"max_special_connections\t%d\n"
,
max_connection_fd,
active_special_connections,
max_special_connections
);
SBP_PRINT_I32(max_accept_rate);
SBP_PRINT_DOUBLE(cur_accept_rate_remaining);
SBP_PRINT_I32(max_connection);
SBP_PRINT_I32(conn_generation);
SB_SUM_ONE_I (allocated_connections);
SB_SUM_ONE_I (allocated_outbound_connections);
SB_SUM_ONE_I (allocated_inbound_connections);
SB_SUM_ONE_I (allocated_socket_connections);
SB_SUM_ONE_LL (tcp_readv_calls);
SB_SUM_ONE_LL (tcp_readv_intr);
SB_SUM_ONE_LL (tcp_readv_bytes);
SB_SUM_ONE_LL (tcp_writev_calls);
SB_SUM_ONE_LL (tcp_writev_intr);
SB_SUM_ONE_LL (tcp_writev_bytes);
SB_SUM_ONE_I (free_later_size);
SB_SUM_ONE_LL (free_later_total);
SB_SUM_ONE_LL (accept_calls_failed);
SB_SUM_ONE_LL (accept_nonblock_set_failed);
SB_SUM_ONE_LL (accept_connection_limit_failed);
SB_SUM_ONE_LL (accept_rate_limit_failed);
SB_SUM_ONE_LL (accept_init_accepted_failed);
MODULE_STAT_FUNCTION_END
void fetch_connections_stat (struct connections_stat *st) {
#define COLLECT_I(__x) st->__x = SB_SUM_I (__x);
#define COLLECT_LL(__x) st->__x = SB_SUM_LL (__x);
COLLECT_I (active_connections);
COLLECT_I (active_dh_connections);
COLLECT_I (outbound_connections);
COLLECT_I (active_outbound_connections);
COLLECT_I (ready_outbound_connections);
st->max_special_connections = max_special_connections;
st->active_special_connections = active_special_connections;
COLLECT_I (allocated_connections);
COLLECT_I (allocated_outbound_connections);
COLLECT_I (allocated_inbound_connections);
COLLECT_I (allocated_socket_connections);
COLLECT_I (allocated_targets);
COLLECT_I (ready_targets);
COLLECT_I (active_targets);
COLLECT_I (inactive_targets);
COLLECT_LL (tcp_readv_calls);
COLLECT_LL (tcp_readv_intr);
COLLECT_LL (tcp_readv_bytes);
COLLECT_LL (tcp_writev_calls);
COLLECT_LL (tcp_writev_intr);
COLLECT_LL (tcp_writev_bytes);
COLLECT_LL (accept_calls_failed);
COLLECT_LL (accept_nonblock_set_failed);
COLLECT_LL (accept_rate_limit_failed);
COLLECT_LL (accept_init_accepted_failed);
COLLECT_LL (accept_connection_limit_failed);
#undef COLLECT_I
#undef COLLECT_LL
}
void connection_event_incref (int fd, long long val);
void tcp_set_max_accept_rate (int rate) {
max_accept_rate = rate;
}
int set_write_timer (connection_job_t C);
int prealloc_tcp_buffers (void);
int clear_connection_write_timeout (connection_job_t c);
static int tcp_recv_buffers_num;
static int tcp_recv_buffers_total_size;
static struct iovec tcp_recv_iovec[MAX_TCP_RECV_BUFFERS + 1];
static struct msg_buffer *tcp_recv_buffers[MAX_TCP_RECV_BUFFERS];
int prealloc_tcp_buffers (void) /* {{{ */ {
assert (!tcp_recv_buffers_num);
int i;
for (i = MAX_TCP_RECV_BUFFERS - 1; i >= 0; i--) {
struct msg_buffer *X = alloc_msg_buffer ((tcp_recv_buffers_num) ? tcp_recv_buffers[i + 1] : 0, TCP_RECV_BUFFER_SIZE);
if (!X) {
vkprintf (0, "**FATAL**: cannot allocate tcp receive buffer\n");
exit (2);
}
vkprintf (3, "allocated %d byte tcp receive buffer #%d at %p\n", X->chunk->buffer_size, i, X);
tcp_recv_buffers[i] = X;
tcp_recv_iovec[i + 1].iov_base = X->data;
tcp_recv_iovec[i + 1].iov_len = X->chunk->buffer_size;
++ tcp_recv_buffers_num;
tcp_recv_buffers_total_size += X->chunk->buffer_size;
}
return tcp_recv_buffers_num;
}
/* }}} */
int tcp_prepare_iovec (struct iovec *iov, int *iovcnt, int maxcnt, struct raw_message *raw) /* {{{ */ {
int t = rwm_prepare_iovec (raw, iov, maxcnt, raw->total_bytes);
if (t < 0) {
*iovcnt = maxcnt;
int i;
t = 0;
for (i = 0; i < maxcnt; i++) {
t += iov[i].iov_len;
}
assert (t < raw->total_bytes);
return t;
} else {
*iovcnt = t;
return raw->total_bytes;
}
}
/* }}} */
void assert_main_thread (void) {}
void assert_net_cpu_thread (void) {}
void assert_net_net_thread (void) {}
void assert_engine_thread (void) {
assert (this_job_thread && (this_job_thread->thread_class == JC_ENGINE || this_job_thread->thread_class == JC_MAIN));
}
socket_connection_job_t alloc_new_socket_connection (connection_job_t C);
#define X_TYPE connection_job_t
#define X_CMP(a,b) (((a) < (b)) ? -1 : ((a) > (b)) ? 1 : 0)
#define TREE_NAME connection
#define TREE_MALLOC
#define TREE_PTHREAD
#define TREE_INCREF job_incref
#define TREE_DECREF job_decref_f
#include "vv/vv-tree.c"
static inline int connection_is_active (int flags) {
return (flags & C_CONNECTED) && !(flags & C_READY_PENDING);
}
/* {{{ compute_conn_events */
#if USE_EPOLLET
static inline int compute_conn_events (socket_connection_job_t c) {
unsigned flags = SOCKET_CONN_INFO(c)->flags;
if (flags & C_ERROR) {
return 0;
} else {
return EVT_READ | EVT_WRITE | EVT_SPEC;
}
}
#else
static inline int compute_conn_events (connection_job_t c) {
unsigned flags = CONN_INFO(c)->flags;
if (flags & (C_ERROR | C_FAILED | C_NET_FAILED)) {
return 0;
}
return (((flags & (C_WANTRD | C_STOPREAD)) == C_WANTRD) ? EVT_READ : 0) | (flags & C_WANTWR ? EVT_WRITE : 0) | EVT_SPEC
| (((flags & (C_WANTRD | C_NORD)) == (C_WANTRD | C_NORD))
|| ((flags & (C_WANTWR | C_NOWR)) == (C_WANTWR | C_NOWR)) ? EVT_LEVEL : 0);
}
#endif
/* }}} */
void connection_write_close (connection_job_t C) /* {{{ */ {
struct connection_info *c = CONN_INFO (C);
if (c->status == conn_working) {
socket_connection_job_t S = c->io_conn;
if (S) {
__sync_fetch_and_or (&SOCKET_CONN_INFO(S)->flags, C_STOPREAD);
}
__sync_fetch_and_or (&c->flags, C_STOPREAD);
c->status = conn_write_close;
job_signal (JOB_REF_CREATE_PASS (C), JS_RUN);
}
}
/* }}} */
/* qack {{{ */
static inline void disable_qack (int fd) {
vkprintf (2, "disable TCP_QUICKACK for %d\n", fd);
assert (setsockopt (fd, IPPROTO_TCP, TCP_QUICKACK, (int[]){0}, sizeof (int)) >= 0);
}
static inline void cond_disable_qack (socket_connection_job_t C) {
struct socket_connection_info *c = SOCKET_CONN_INFO (C);
if (c->flags & C_NOQACK) {
disable_qack (c->fd);
}
}
/* }}} */
/* {{{ CPU PART OF CONNECTION */
/* {{{ TIMEOUT */
int set_connection_timeout (connection_job_t C, double timeout) /* {{{ */ {
struct connection_info *c = CONN_INFO (C);
if (c->flags & C_ERROR) { return 0; }
__sync_fetch_and_and (&c->flags, ~C_ALARM);
if (timeout > 0) {
job_timer_insert (C, precise_now + timeout);
return 0;
} else {
job_timer_remove (C);
return 0;
}
}
/* }}} */
int clear_connection_timeout (connection_job_t C) /* {{{ */ {
set_connection_timeout (C, 0);
return 0;
}
/* }}} */
/* }}} */
/*
can be called from any thread and without lock
just sets error code and sends JS_ABORT to connection job
*/
void fail_connection (connection_job_t C, int err) /* {{{ */ {
struct connection_info *c = CONN_INFO (C);
if (!(__sync_fetch_and_or (&c->flags, C_ERROR) & C_ERROR)) {
c->status = conn_error;
if (c->error >= 0) {
c->error = err;
}
job_signal (JOB_REF_CREATE_PASS (C), JS_ABORT);
}
}
/* }}} */
/*
just runs ->reader and ->writer virtual methods
*/
int cpu_server_read_write (connection_job_t C) /* {{{ */ {
struct connection_info *c = CONN_INFO (C);
c->type->reader (C);
c->type->writer (C);
return 0;
}
/* }}} */
/*
frees connection structure, including mpq and buffers
*/
int cpu_server_free_connection (connection_job_t C) /* {{{ */ {
assert_net_cpu_thread ();
assert (C->j_refcnt == 1);
struct connection_info *c = CONN_INFO (C);
if (!(c->flags & C_ERROR)) {
vkprintf (0, "target = %p, basic=%d\n", c->target, c->basic_type);
}
assert (c->flags & C_ERROR);
assert (c->flags & C_FAILED);
assert (!c->target);
assert (!c->io_conn);
vkprintf (1, "Closing connection socket #%d\n", c->fd);
while (1) {
struct raw_message *raw = mpq_pop_nw (c->out_queue, 4);
if (!raw) { break; }
rwm_free (raw);
free (raw);
}
free_mp_queue (c->out_queue);
c->out_queue = NULL;
while (1) {
struct raw_message *raw = mpq_pop_nw (c->in_queue, 4);
if (!raw) { break; }
rwm_free (raw);
free (raw);
}
free_mp_queue (c->in_queue);
c->in_queue = NULL;
if (c->type->crypto_free) {
c->type->crypto_free (C);
}
close (c->fd);
c->fd = -1;
MODULE_STAT->allocated_connections --;
if (c->basic_type == ct_outbound) {
MODULE_STAT->allocated_outbound_connections --;
}
if (c->basic_type == ct_inbound) {
MODULE_STAT->allocated_inbound_connections --;
}
return c->type->free_buffers (C);
}
/* }}} */
/*
deletes link to io_conn
deletes link to target
aborts pending queries
updates stats
*/
int cpu_server_close_connection (connection_job_t C, int who) /* {{{ */ {
assert_net_cpu_thread ();
struct connection_info *c = CONN_INFO(C);
assert (c->flags & C_ERROR);
assert (c->status == conn_error);
assert (c->flags & C_FAILED);
if (c->error != -17) {
MODULE_STAT->total_failed_connections ++;
if (!connection_is_active (c->flags)) {
MODULE_STAT->total_connect_failures ++;
}
} else {
MODULE_STAT->unused_connections_closed ++;
}
if (c->flags & C_ISDH) {
MODULE_STAT->active_dh_connections --;
__sync_fetch_and_and (&c->flags, ~C_ISDH);
}
assert (c->io_conn);
job_signal (JOB_REF_PASS (c->io_conn), JS_ABORT);
if (c->basic_type == ct_outbound) {
MODULE_STAT->outbound_connections --;
if (connection_is_active (c->flags)) {
MODULE_STAT->active_outbound_connections --;
}
if (c->target) {
job_signal (JOB_REF_PASS (c->target), JS_RUN);
}
} else {
MODULE_STAT->inbound_connections --;
if (connection_is_active (c->flags)) {
MODULE_STAT->active_inbound_connections --;
}
}
if (connection_is_active (c->flags)) {
MODULE_STAT->active_connections --;
}
if (c->flags & C_SPECIAL) {
c->flags &= ~C_SPECIAL;
int orig_special_connections = __sync_fetch_and_add (&active_special_connections, -1);
if (orig_special_connections == max_special_connections) {
int i;
for (i = 0; i < special_listen_sockets; i++) {
connection_job_t LC = connection_get_by_fd_generation (special_socket[i].fd, special_socket[i].generation);
assert (LC);
job_signal (JOB_REF_PASS (LC), JS_AUX);
}
}
}
job_timer_remove (C);
return 0;
}
/* }}} */
int do_connection_job (job_t job, int op, struct job_thread *JT) /* {{{ */ {
connection_job_t C = job;
struct connection_info *c = CONN_INFO (C);
if (op == JS_RUN) { // RUN IN NET-CPU THREAD
assert_net_cpu_thread ();
if (!(c->flags & C_ERROR)) {
if (c->flags & C_READY_PENDING) {
assert (c->flags & C_CONNECTED);
__sync_fetch_and_and (&c->flags, ~C_READY_PENDING);
MODULE_STAT->active_outbound_connections ++;
MODULE_STAT->active_connections ++;
if (c->target) {
__sync_fetch_and_add (&CONN_TARGET_INFO(c->target)->active_outbound_connections, 1);
}
if (c->status == conn_connecting) {
if (!__sync_bool_compare_and_swap (&c->status, conn_connecting, conn_working)) {
assert (c->status == conn_error);
}
}
c->type->connected (C);
}
c->type->read_write (C);
}
return 0;
}
if (op == JS_ALARM) { // RUN IN NET-CPU THREAD
if (!job_timer_check (job)) {
return 0;
}
if (!(c->flags & C_ERROR)) {
c->type->alarm (C);
}
return 0;
}
if (op == JS_ABORT) { // RUN IN NET-CPU THREAD
assert (c->flags & C_ERROR);
if (!(__sync_fetch_and_or (&c->flags, C_FAILED) & C_FAILED)) {
c->type->close (C, 0);
}
return JOB_COMPLETED;
}
if (op == JS_FINISH) { // RUN IN NET-CPU THREAD
assert (C->j_refcnt == 1);
c->type->free (C);
return job_free (JOB_REF_PASS (C));
}
return JOB_ERROR;
}
/* }}} */
/*
allocates inbound or outbound connection
runs init_accepted or init_outbound
updates stats
creates socket_connection
*/
connection_job_t alloc_new_connection (int cfd, conn_target_job_t CTJ, listening_connection_job_t LCJ, int basic_type, conn_type_t *conn_type, void *conn_extra, unsigned peer, unsigned char peer_ipv6[16], int peer_port) /* {{{ */ {
if (cfd < 0) {
return NULL;
}
assert_main_thread ();
struct conn_target_info *CT = CTJ ? CONN_TARGET_INFO (CTJ) : NULL;
struct listening_connection_info *LC = LCJ ? LISTEN_CONN_INFO (LCJ) : NULL;
unsigned flags;
if ((flags = fcntl (cfd, F_GETFL, 0) < 0) || fcntl (cfd, F_SETFL, flags | O_NONBLOCK) < 0) {
kprintf ("cannot set O_NONBLOCK on accepted socket #%d: %m\n", cfd);
MODULE_STAT->accept_nonblock_set_failed ++;
close (cfd);
return NULL;
}
flags = 1;
setsockopt (cfd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof (flags));
if (tcp_maximize_buffers) {
maximize_sndbuf (cfd, 0);
maximize_rcvbuf (cfd, 0);
}
if (cfd >= max_connection_fd) {
vkprintf (2, "cfd = %d, max_connection_fd = %d\n", cfd, max_connection_fd);
MODULE_STAT->accept_connection_limit_failed ++;
close (cfd);
return NULL;
}
if (cfd > max_connection) {
max_connection = cfd;
}
connection_job_t C = create_async_job (do_connection_job, JSC_ALLOW (JC_CONNECTION, JS_RUN) | JSC_ALLOW (JC_CONNECTION, JS_ALARM) | JSC_ALLOW (JC_CONNECTION, JS_ABORT) | JSC_ALLOW (JC_CONNECTION, JS_FINISH), -2, sizeof (struct connection_info), JT_HAVE_TIMER, JOB_REF_NULL);
struct connection_info *c = CONN_INFO (C);
//memset (c, 0, sizeof (*c)); /* no need, create_async_job memsets itself */
c->fd = cfd;
c->target = CTJ;
c->generation = new_conn_generation ();
c->flags = 0;//SS ? C_WANTWR : C_WANTRD;
if (basic_type == ct_inbound) {
c->flags = C_CONNECTED;
}
int raw = C_RAWMSG;
if (raw) {
c->flags |= C_RAWMSG;
rwm_init (&c->in, 0);
rwm_init (&c->out, 0);
rwm_init (&c->in_u, 0);
rwm_init (&c->out_p, 0);
} else {
assert (0);
}
c->type = conn_type;
c->extra = conn_extra;
assert (c->type);
c->basic_type = basic_type;
c->status = (basic_type == ct_outbound) ? conn_connecting : conn_working;
c->flags |= c->type->flags & C_EXTERNAL;
if (LC) {
c->flags |= LC->flags & C_EXTERNAL;
}
union sockaddr_in46 self;
unsigned self_addrlen = sizeof (self);
memset (&self, 0, sizeof (self));
getsockname (cfd, (struct sockaddr *) &self, &self_addrlen);
if (self.a4.sin_family == AF_INET) {
assert (self_addrlen == sizeof (struct sockaddr_in));
c->our_ip = ntohl (self.a4.sin_addr.s_addr);
c->our_port = ntohs (self.a4.sin_port);
assert (peer);
c->remote_ip = peer;
} else {
assert (self.a6.sin6_family == AF_INET6);
assert (!peer);
if (is_4in6 (peer_ipv6)) {
assert (is_4in6 (self.a6.sin6_addr.s6_addr));
c->our_ip = ntohl (extract_4in6 (self.a6.sin6_addr.s6_addr));
c->our_port = ntohs (self.a6.sin6_port);
c->remote_ip = ntohl (extract_4in6 (peer_ipv6));
} else {
memcpy (c->our_ipv6, self.a6.sin6_addr.s6_addr, 16);
c->our_port = ntohs (self.a6.sin6_port);
c->flags |= C_IPV6;
memcpy (c->remote_ipv6, peer_ipv6, 16);
}
}
c->remote_port = peer_port;
c->in_queue = alloc_mp_queue_w ();
c->out_queue = alloc_mp_queue_w ();
//c->out_packet_queue = alloc_mp_queue_w ();
if (basic_type == ct_outbound) {
vkprintf (1, "New outbound connection #%d %s:%d -> %s:%d\n", c->fd, show_our_ip (C), c->our_port, show_remote_ip (C), c->remote_port);
} else {
vkprintf (1, "New inbound connection #%d %s:%d -> %s:%d\n", c->fd, show_remote_ip (C), c->remote_port, show_our_ip (C), c->our_port);
}
int (*func)(connection_job_t) = (basic_type == ct_outbound) ? c->type->init_outbound : c->type->init_accepted;
vkprintf (3, "func = %p\n", func);
if (func (C) >= 0) {
if (basic_type == ct_outbound) {
MODULE_STAT->outbound_connections ++;
MODULE_STAT->allocated_outbound_connections ++;
MODULE_STAT->outbound_connections_created ++;
if (CTJ) {
job_incref (CTJ);
CT->outbound_connections ++;
}
} else {
MODULE_STAT->inbound_connections_accepted ++;
MODULE_STAT->allocated_inbound_connections ++;
MODULE_STAT->inbound_connections ++;
MODULE_STAT->active_inbound_connections ++;
MODULE_STAT->active_connections ++;
if (LCJ) {
c->listening = LC->fd;
c->listening_generation = LC->generation;
if (LC->flags & C_NOQACK) {
c->flags |= C_NOQACK;
}
c->window_clamp = LC->window_clamp;
if (LC->flags & C_SPECIAL) {
c->flags |= C_SPECIAL;
__sync_fetch_and_add (&active_special_connections, 1);
if (active_special_connections > max_special_connections) {
vkprintf (active_special_connections >= max_special_connections + 16 ? 0 : 1, "ERROR: forced to accept connection when special connections limit was reached (%d of %d)\n", active_special_connections, max_special_connections);
}
if (active_special_connections >= max_special_connections) {
vkprintf (2, "**Invoking epoll_remove(%d)\n", LC->fd);
epoll_remove (LC->fd);
}
}
}
if (c->window_clamp) {
if (setsockopt (cfd, IPPROTO_TCP, TCP_WINDOW_CLAMP, &c->window_clamp, 4) < 0) {
vkprintf (0, "error while setting window size for socket #%d to %d: %m\n", cfd, c->window_clamp);
} else {
int t1 = -1, t2 = -1;
socklen_t s1 = 4, s2 = 4;
getsockopt (cfd, IPPROTO_TCP, TCP_WINDOW_CLAMP, &t1, &s1);
getsockopt (cfd, SOL_SOCKET, SO_RCVBUF, &t2, &s2);
vkprintf (2, "window clamp for socket #%d is %d, receive buffer is %d\n", cfd, t1, t2);
}
}
}
alloc_new_socket_connection (C);
MODULE_STAT->allocated_connections ++;
return C;
} else {
MODULE_STAT->accept_init_accepted_failed ++;
if (c->flags & C_RAWMSG) {
rwm_free (&c->in);
rwm_free (&c->out);
rwm_free (&c->in_u);
rwm_free (&c->out_p);
}
c->basic_type = ct_none;
close (cfd);
free_mp_queue (c->in_queue);
free_mp_queue (c->out_queue);
job_free (JOB_REF_PASS (C));
this_job_thread->jobs_active --;
return NULL;
}
}
/* }}} */
/* }}} */
/* {{{ IO PART OF CONNECTION */
/*
Have to have lock on socket_connection to run this method
removes event from evemt heap and epoll
*/
void fail_socket_connection (socket_connection_job_t C, int who) /* {{{ */ {
assert_main_thread ();
struct socket_connection_info *c = SOCKET_CONN_INFO (C);
assert (C->j_flags & JF_LOCKED);
if (!(__sync_fetch_and_or (&c->flags, C_ERROR) & C_ERROR)) {
job_timer_remove (C);
remove_event_from_heap (c->ev, 0);
connection_event_incref (c->fd, -1);
epoll_insert (c->fd, 0);
c->ev = NULL;
c->type->socket_close (C);
fail_connection (c->conn, who);
}
}
/* }}} */
/*
Frees socket_connection structure
Removes link to cpu_connection
*/
int net_server_socket_free (socket_connection_job_t C) /* {{{ */ {
assert_net_net_thread ();
struct socket_connection_info *c = SOCKET_CONN_INFO (C);
assert (!c->ev);
assert (c->flags & C_ERROR);
if (c->conn) {
fail_connection (c->conn, -201);
job_decref (JOB_REF_PASS (c->conn));
}
while (1) {
struct raw_message *raw = mpq_pop_nw (c->out_packet_queue, 4);
if (!raw) { break; }
rwm_free (raw);
free (raw);
}
free_mp_queue (c->out_packet_queue);
rwm_free (&c->out);
MODULE_STAT->allocated_socket_connections --;
return 0;
}
/* }}} */
/*
Reads data from socket until all data is read
Then puts it to conn->in_queue and send JS_RUN signal
*/
int net_server_socket_reader (socket_connection_job_t C) /* {{{ */ {
assert_net_net_thread ();
struct socket_connection_info *c = SOCKET_CONN_INFO (C);
while ((c->flags & (C_WANTRD | C_NORD | C_STOPREAD | C_ERROR | C_NET_FAILED)) == C_WANTRD) {
if (!tcp_recv_buffers_num) {
prealloc_tcp_buffers ();
}
struct raw_message *in = malloc (sizeof (*in));
rwm_init (in, 0);
int s = tcp_recv_buffers_total_size;
assert (s > 0);
int p = 1;
__sync_fetch_and_or (&c->flags, C_NORD);
int r = readv (c->fd, tcp_recv_iovec + p, MAX_TCP_RECV_BUFFERS + 1 - p);
MODULE_STAT->tcp_readv_calls ++;
if (r <= 0) {
if (r < 0 && errno == EAGAIN) {
} else if (r < 0 && errno == EINTR) {
__sync_fetch_and_and (&c->flags, ~C_NORD);
MODULE_STAT->tcp_readv_intr ++;
continue;
} else {
vkprintf (1, "Connection %d: Fatal error %m\n", c->fd);
job_signal (JOB_REF_CREATE_PASS (C), JS_ABORT);
__sync_fetch_and_or (&c->flags, C_NET_FAILED);
return 0;
}
} else {
__sync_fetch_and_and (&c->flags, ~C_NORD);
}
if (verbosity > 0 && r < 0 && errno != EAGAIN) {
perror ("recv()");
}
vkprintf (2, "readv from %d: %d read out of %d\n", c->fd, r, s);
if (r <= 0) {
rwm_free (in);
free (in);
break;
}
MODULE_STAT->tcp_readv_bytes += r;
struct msg_part *mp = 0;
assert (p == 1);
mp = new_msg_part (0, tcp_recv_buffers[p - 1]);
assert (tcp_recv_buffers[p - 1]->data == tcp_recv_iovec[p].iov_base);
mp->offset = 0;
mp->data_end = r > tcp_recv_iovec[p].iov_len ? tcp_recv_iovec[p].iov_len : r;
r -= mp->data_end;
in->first = in->last = mp;
in->total_bytes = mp->data_end;
in->first_offset = 0;
in->last_offset = mp->data_end;
p ++;
int rs = r;
while (rs > 0) {
mp = new_msg_part (0, tcp_recv_buffers[p - 1]);
mp->offset = 0;
mp->data_end = rs > tcp_recv_iovec[p].iov_len ? tcp_recv_iovec[p].iov_len : rs;
rs -= mp->data_end;
in->last->next = mp;
in->last = mp;
in->last_offset = mp->data_end;
in->total_bytes += mp->data_end;
p ++;
}
assert (!rs);
int i;
for (i = 0; i < p - 1; i++) {
struct msg_buffer *X = alloc_msg_buffer (tcp_recv_buffers[i], TCP_RECV_BUFFER_SIZE);
if (!X) {
vkprintf (0, "**FATAL**: cannot allocate tcp receive buffer\n");
assert (0);
}
tcp_recv_buffers[i] = X;
tcp_recv_iovec[i + 1].iov_base = X->data;
tcp_recv_iovec[i + 1].iov_len = X->chunk->buffer_size;
}
assert (c->conn);
mpq_push_w (CONN_INFO(c->conn)->in_queue, in, 0);
job_signal (JOB_REF_CREATE_PASS (c->conn), JS_RUN);
}
return 0;
}
/* }}} */
/*
Get data from out raw message and writes it to socket
*/
int net_server_socket_writer (socket_connection_job_t C) /* {{{ */{
assert_net_net_thread ();
struct socket_connection_info *c = SOCKET_CONN_INFO (C);
struct raw_message *out = &c->out;
int check_watermark = out->total_bytes >= c->write_low_watermark;
int t = 0;
int stop = c->flags & C_STOPWRITE;
while ((c->flags & (C_WANTWR | C_NOWR | C_ERROR | C_NET_FAILED)) == C_WANTWR) {
if (!out->total_bytes) {
__sync_fetch_and_and (&c->flags, ~C_WANTWR);
break;
}
struct iovec iov[384];
int iovcnt = -1;
int s = tcp_prepare_iovec (iov, &iovcnt, sizeof (iov) / sizeof (iov[0]), out);
assert (iovcnt > 0 && s > 0);
__sync_fetch_and_or (&c->flags, C_NOWR);
int r = writev (c->fd, iov, iovcnt);
MODULE_STAT->tcp_writev_calls ++;
if (r <= 0) {
if (r < 0 && errno == EAGAIN) {
if (++c->eagain_count > 100) {
kprintf ("Too much EAGAINs for connection %d (%s), dropping\n", c->fd, show_remote_socket_ip (C));
job_signal (JOB_REF_CREATE_PASS (C), JS_ABORT);
__sync_fetch_and_or (&c->flags, C_NET_FAILED);
return 0;
}
} else if (r < 0 && errno == EINTR) {
__sync_fetch_and_and (&c->flags, ~C_NOWR);
MODULE_STAT->tcp_writev_intr ++;
continue;
} else {
vkprintf (1, "Connection %d: Fatal error %m\n", c->fd);
job_signal (JOB_REF_CREATE_PASS (C), JS_ABORT);
__sync_fetch_and_or (&c->flags, C_NET_FAILED);
return 0;
}
} else {
__sync_fetch_and_and (&c->flags, ~C_NOWR);
MODULE_STAT->tcp_writev_bytes += r;
c->eagain_count = 0;
t += r;
}
if (verbosity && r < 0 && errno != EAGAIN) {
perror ("writev()");
}