-
Notifications
You must be signed in to change notification settings - Fork 564
/
net_tcp.c
2234 lines (1970 loc) · 61 KB
/
net_tcp.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
/*
* Copyright (C) 2014-2015 OpenSIPS Project
* Copyright (C) 2001-2003 FhG Fokus
*
* This file is part of opensips, a free SIP server.
*
* opensips 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.
*
* opensips 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 program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*
* history:
* ---------
* 2015-01-xx created (razvanc)
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sys/uio.h> /* writev*/
#include <netdb.h>
#include <stdlib.h> /*exit() */
#include <time.h> /*time() */
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include "../mem/mem.h"
#include "../mem/shm_mem.h"
#include "../globals.h"
#include "../locking.h"
#include "../socket_info.h"
#include "../ut.h"
#include "../pt.h"
#include "../pt_load.h"
#include "../daemonize.h"
#include "../status_report.h"
#include "../reactor.h"
#include "../timer.h"
#include "../ipc.h"
#include "tcp_passfd.h"
#include "net_tcp_proc.h"
#include "net_tcp_report.h"
#include "net_tcp.h"
#include "tcp_conn.h"
#include "tcp_conn_profile.h"
#include "trans.h"
struct struct_hist_list *con_hist;
enum tcp_worker_state { STATE_INACTIVE=0, STATE_ACTIVE, STATE_DRAINING};
/* definition of a TCP worker */
struct tcp_worker {
pid_t pid;
int unix_sock; /*!< Main-Worker comm, worker end */
int main_unix_sock; /*!< Main-Worker comm, TCP Main end */
int pt_idx; /*!< Index in the main Process Table */
enum tcp_worker_state state;
int n_reqs; /*!< number of requests serviced so far */
};
/* definition of a TCP partition */
struct tcp_partition {
/*! \brief connection hash table (after ip&port), includes also aliases */
struct tcp_conn_alias** tcpconn_aliases_hash;
/*! \brief connection hash table (after connection id) */
struct tcp_connection** tcpconn_id_hash;
gen_lock_t* tcpconn_lock;
};
/* array of TCP workers - to be used only by TCP MAIN */
struct tcp_worker *tcp_workers=0;
/* unique for each connection, used for
* quickly finding the corresponding connection for a reply */
static unsigned int* connection_id=0;
/* array of TCP partitions */
static struct tcp_partition tcp_parts[TCP_PARTITION_SIZE];
/*!< tcp protocol number as returned by getprotobyname */
static int tcp_proto_no=-1;
/* communication socket from generic proc to TCP main */
int unix_tcp_sock = -1;
/*!< current number of open connections */
static int tcp_connections_no = 0;
/*!< by default don't accept aliases */
int tcp_accept_aliases=0;
int tcp_connect_timeout=DEFAULT_TCP_CONNECT_TIMEOUT;
int tcp_con_lifetime=DEFAULT_TCP_CONNECTION_LIFETIME;
int tcp_socket_backlog=DEFAULT_TCP_SOCKET_BACKLOG;
/*!< by default choose the best method */
enum poll_types tcp_poll_method=0;
int tcp_max_connections=DEFAULT_TCP_MAX_CONNECTIONS;
/* the configured/starting number of TCP workers */
int tcp_workers_no = UDP_WORKERS_NO;
/* the maximum numbers of TCP workers */
int tcp_workers_max_no;
/* the name of the auto-scaling profile (optional) */
char* tcp_auto_scaling_profile = NULL;
/* Max number of seconds that we except a full SIP message
* to arrive in - anything above will lead to the connection to closed */
int tcp_max_msg_time = TCP_CHILD_MAX_MSG_TIME;
/* If the data reading may be performed across different workers (still
* serial) or by a single worker (the TCP conns sticks to one worker) */
int tcp_parallel_read_on_workers = 0;
#ifdef HAVE_SO_KEEPALIVE
int tcp_keepalive = 1;
#else
int tcp_keepalive = 0;
#endif
int tcp_keepcount = 0;
int tcp_keepidle = 0;
int tcp_keepinterval = 0;
/*!< should we allow opening a new TCP conn when sending data
* over UAC branches? - branch flag to be set in the SIP messages */
int tcp_no_new_conn_bflag = 0;
/*!< should we allow opening a new TCP conn when sending data
* back to UAS (replies)? - msg flag to be set in the SIP messages */
int tcp_no_new_conn_rplflag = 0;
/*!< should a new TCP conn be open if needed? - variable used to used for
* signalizing between SIP layer (branch flag) and TCP layer (tcp_send func)*/
int tcp_no_new_conn = 0;
/* if the TCP net layer is on or off (if no TCP based protos are loaded) */
static int tcp_disabled = 1;
/* is the process TCP MAIN ? */
int is_tcp_main = 0;
/* the ID of the TCP conn used for the last send operation in the
* current process - attention, this is a really ugly HACK here */
unsigned int last_outgoing_tcp_id = 0;
static struct scaling_profile *s_profile = NULL;
/****************************** helper functions *****************************/
extern void handle_sigs(void);
static inline int init_sock_keepalive(int s, struct tcp_conn_profile *prof)
{
int optval, ka;
if (prof->keepinterval || prof->keepidle || prof->keepcount)
ka = 1; /* force on */
else
ka = prof->keepalive;
#ifdef HAVE_SO_KEEPALIVE
if (setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,&ka,sizeof(ka))<0){
LM_WARN("setsockopt failed to enable SO_KEEPALIVE: %s\n",
strerror(errno));
return -1;
}
LM_DBG("TCP keepalive enabled on socket %d\n",s);
#endif
#ifdef HAVE_TCP_KEEPINTVL
if ((optval = prof->keepinterval)) {
if (setsockopt(s,IPPROTO_TCP,TCP_KEEPINTVL,&optval,sizeof(optval))<0){
LM_WARN("setsockopt failed to set keepalive probes interval: %s\n",
strerror(errno));
}
}
#endif
#ifdef HAVE_TCP_KEEPIDLE
if ((optval = prof->keepidle)) {
if (setsockopt(s,IPPROTO_TCP,TCP_KEEPIDLE,&optval,sizeof(optval))<0){
LM_WARN("setsockopt failed to set keepalive idle interval: %s\n",
strerror(errno));
}
}
#endif
#ifdef HAVE_TCP_KEEPCNT
if ((optval = prof->keepcount)) {
if (setsockopt(s,IPPROTO_TCP,TCP_KEEPCNT,&optval,sizeof(optval))<0){
LM_WARN("setsockopt failed to set maximum keepalive count: %s\n",
strerror(errno));
}
}
#endif
return 0;
}
/*! \brief Set all socket/fd options: disable nagle, tos lowdelay,
* non-blocking
* \return -1 on error */
int tcp_init_sock_opt(int s, struct tcp_conn_profile *prof)
{
int flags;
int optval;
#ifdef DISABLE_NAGLE
flags=1;
if ( (tcp_proto_no!=-1) && (setsockopt(s, tcp_proto_no , TCP_NODELAY,
&flags, sizeof(flags))<0) ){
LM_WARN("could not disable Nagle: %s\n", strerror(errno));
}
#endif
/* tos*/
optval = tos;
if (setsockopt(s, IPPROTO_IP, IP_TOS, (void*)&optval,sizeof(optval)) ==-1){
LM_WARN("setsockopt tos: %s\n", strerror(errno));
/* continue since this is not critical */
}
if (probe_max_sock_buff(s,1,MAX_SEND_BUFFER_SIZE,BUFFER_INCREMENT)) {
LM_WARN("setsockopt tcp snd buff: %s\n", strerror(errno));
/* continue since this is not critical */
}
init_sock_keepalive(s, prof);
/* non-blocking */
flags=fcntl(s, F_GETFL);
if (flags==-1){
LM_ERR("fcntl failed: (%d) %s\n", errno, strerror(errno));
goto error;
}
if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
LM_ERR("set non-blocking failed: (%d) %s\n", errno, strerror(errno));
goto error;
}
return 0;
error:
return -1;
}
static int send2worker(struct tcp_connection* tcpconn,int rw)
{
int i;
int min_load;
int idx;
long response[2];
unsigned int load;
min_load=100; /* it is a percentage */
idx=0;
for (i=0; i<tcp_workers_max_no; i++){
if (tcp_workers[i].state==STATE_ACTIVE) {
load = pt_get_1m_proc_load( tcp_workers[i].pt_idx );
#ifdef EXTRA_DEBUG
LM_DBG("checking TCP worker %d (proc %d), with load %u,"
"min_load so far %u\n", i, tcp_workers[i].pt_idx, load,
min_load);
#endif
if (min_load>load) {
min_load = load;
idx = i;
}
}
}
tcp_workers[idx].n_reqs++;
LM_DBG("to tcp worker %d (%d/%d) load %u, %p/%d rw %d\n", idx,
tcp_workers[idx].pid, tcp_workers[idx].pt_idx, min_load,
tcpconn, tcpconn->s, rw);
response[0]=(long)tcpconn;
response[1]=rw;
if (send_fd(tcp_workers[idx].unix_sock, response, sizeof(response),
tcpconn->s)<=0){
LM_ERR("send_fd failed\n");
return -1;
}
return 0;
}
/********************** TCP conn management functions ************************/
/* initializes an already defined TCP listener */
int tcp_init_listener(struct socket_info *si)
{
union sockaddr_union* addr;
int optval;
#ifdef DISABLE_NAGLE
int flag;
struct protoent* pe;
if (tcp_proto_no==-1){ /* if not already set */
pe=getprotobyname("tcp");
if (pe==0){
LM_ERR("could not get TCP protocol number\n");
tcp_proto_no=-1;
}else{
tcp_proto_no=pe->p_proto;
}
}
#endif
addr = &si->su;
if (init_su(addr, &si->address, si->port_no)<0){
LM_ERR("could no init sockaddr_union\n");
goto error;
}
si->socket = socket(AF2PF(addr->s.sa_family), SOCK_STREAM, 0);
if (si->socket==-1){
LM_ERR("socket failed with [%s]\n", strerror(errno));
goto error;
}
#ifdef DISABLE_NAGLE
flag=1;
if ( (tcp_proto_no!=-1) &&
(setsockopt(si->socket, tcp_proto_no , TCP_NODELAY,
&flag, sizeof(flag))<0) ){
LM_ERR("could not disable Nagle: %s\n",strerror(errno));
}
#endif
#if !defined(TCP_DONT_REUSEADDR)
/* Stevens, "Network Programming", Section 7.5, "Generic Socket
* Options": "...server started,..a child continues..on existing
* connection..listening server is restarted...call to bind fails
* ... ALL TCP servers should specify the SO_REUSEADDRE option
* to allow the server to be restarted in this situation
*/
optval=1;
if (setsockopt(si->socket, SOL_SOCKET, SO_REUSEADDR,
(void*)&optval, sizeof(optval))==-1) {
LM_ERR("setsockopt failed with [%s]\n", strerror(errno));
goto error;
}
#endif
/* tos */
optval = tos;
if (setsockopt(si->socket, IPPROTO_IP, IP_TOS, (void*)&optval,
sizeof(optval)) ==-1){
LM_WARN("setsockopt tos: %s\n", strerror(errno));
/* continue since this is not critical */
}
if (probe_max_sock_buff(si->socket,1,MAX_SEND_BUFFER_SIZE,
BUFFER_INCREMENT)) {
LM_WARN("setsockopt tcp snd buff: %s\n",strerror(errno));
/* continue since this is not critical */
}
init_sock_keepalive(si->socket, &tcp_con_df_profile);
if (bind(si->socket, &addr->s, sockaddru_len(*addr))==-1){
LM_ERR("bind(%x, %p, %d) on %s:%d : %s\n",
si->socket, &addr->s,
(unsigned)sockaddru_len(*addr),
si->address_str.s,
si->port_no,
strerror(errno));
goto error;
}
if (listen(si->socket, tcp_socket_backlog)==-1){
LM_ERR("listen(%x, %p, %d) on %s: %s\n",
si->socket, &addr->s,
(unsigned)sockaddru_len(*addr),
si->address_str.s,
strerror(errno));
goto error;
}
return 0;
error:
if (si->socket!=-1){
close(si->socket);
si->socket=-1;
}
return -1;
}
/*! \brief finds a connection, if id=0 return NULL
* \note WARNING: unprotected (locks) use tcpconn_get unless you really
* know what you are doing */
static struct tcp_connection* _tcpconn_find(unsigned int id)
{
struct tcp_connection *c;
unsigned hash;
if (id){
hash=tcp_id_hash(id);
for (c=TCP_PART(id).tcpconn_id_hash[hash]; c; c=c->id_next){
#ifdef EXTRA_DEBUG
LM_DBG("c=%p, c->id=%u, port=%d\n",c, c->id, c->rcv.src_port);
print_ip("ip=", &c->rcv.src_ip, "\n");
#endif
if ((id==c->id)&&(c->state!=S_CONN_BAD)) return c;
}
}
return 0;
}
/* returns the correlation ID of a TCP connection */
int tcp_get_correlation_id( unsigned int id, unsigned long long *cid)
{
struct tcp_connection* c;
TCPCONN_LOCK(id);
if ( (c=_tcpconn_find(id))!=NULL ) {
*cid = c->cid;
TCPCONN_UNLOCK(id);
return 0;
}
*cid = 0;
TCPCONN_UNLOCK(id);
return -1;
}
/*! \brief _tcpconn_find with locks and acquire fd */
int tcp_conn_get(unsigned int id, struct ip_addr* ip, int port,
enum sip_protos proto, void *proto_extra_id,
struct tcp_connection** conn, int* conn_fd,
struct socket_info* send_sock)
{
struct tcp_connection* c;
struct tcp_connection* tmp;
struct tcp_conn_alias* a;
unsigned hash;
long response[2];
unsigned int part;
int n;
int fd;
if (id) {
part = id;
TCPCONN_LOCK(part);
if ( (c=_tcpconn_find(part))!=NULL )
goto found;
TCPCONN_UNLOCK(part);
}
/* continue search based on IP address + port + transport */
#ifdef EXTRA_DEBUG
LM_DBG("%d port %u\n",id, port);
if (ip) print_ip("tcpconn_find: ip ", ip, "\n");
#endif
if (ip){
hash=tcp_addr_hash(ip, port);
for( part=0 ; part<TCP_PARTITION_SIZE ; part++ ) {
TCPCONN_LOCK(part);
for (a=TCP_PART(part).tcpconn_aliases_hash[hash]; a; a=a->next) {
#ifdef EXTRA_DEBUG
LM_DBG("a=%p, c=%p, c->id=%u, alias port= %d port=%d\n",
a, a->parent, a->parent->id, a->port,
a->parent->rcv.src_port);
print_ip("ip=",&a->parent->rcv.src_ip,"\n");
if (send_sock && a->parent->rcv.bind_address) {
print_ip("requested send_sock ip=", &send_sock->address,"\n");
print_ip("found send_sock ip=", &a->parent->rcv.bind_address->address,"\n");
}
#endif
c = a->parent;
if (c->state != S_CONN_BAD &&
c->flags&F_CONN_INIT &&
(send_sock==NULL || send_sock == a->parent->rcv.bind_address) &&
port == a->port &&
proto == c->type &&
ip_addr_cmp(ip, &c->rcv.src_ip) &&
(proto_extra_id==NULL ||
protos[proto].net.conn_match==NULL ||
protos[proto].net.conn_match( c, proto_extra_id)) )
goto found;
}
TCPCONN_UNLOCK(part);
}
}
/* not found */
*conn = NULL;
if (conn_fd) *conn_fd = -1;
return 0;
found:
c->refcnt++;
TCPCONN_UNLOCK(part);
sh_log(c->hist, TCP_REF, "tcp_conn_get, (%d)", c->refcnt);
LM_DBG("con found in state %d\n",c->state);
if (c->state!=S_CONN_OK || conn_fd==NULL) {
/* no need to acquired, just return the conn with an invalid fd */
*conn = c;
if (conn_fd) *conn_fd = -1;
return 1;
}
if (c->proc_id == process_no) {
LM_DBG("tcp connection found (%p) already in this process ( %d ) ,"
" fd = %d\n", c, c->proc_id, c->fd);
/* we already have the connection in this worker's reactor, */
/* no need to acquire FD */
*conn = c;
*conn_fd = c->fd;
return 1;
}
/* acquire the fd for this connection too */
LM_DBG("tcp connection found (%p), acquiring fd\n", c);
/* get the fd */
response[0]=(long)c;
response[1]=CONN_GET_FD;
n=send_all(unix_tcp_sock, response, sizeof(response));
if (n<=0){
LM_ERR("failed to get fd(write):%s (%d)\n",
strerror(errno), errno);
n=-1;
goto error;
}
LM_DBG("c= %p, n=%d, Usock=%d\n", c, n, unix_tcp_sock);
tmp = c;
n=receive_fd(unix_tcp_sock, &c, sizeof(c), &fd, MSG_WAITALL);
if (n<=0){
LM_ERR("failed to get fd(receive_fd):"
" %s (%d)\n", strerror(errno), errno);
n=-1;
goto error;
}
if (c!=tmp){
LM_CRIT("got different connection:"
" %p (id= %u, refcnt=%d state=%d != "
" %p (id= %u, refcnt=%d state=%d (n=%d)\n",
c, c->id, c->refcnt, c->state,
tmp, tmp->id, tmp->refcnt, tmp->state, n
);
n=-1; /* fail */
close(fd);
goto error;
}
LM_DBG("after receive_fd: c= %p n=%d fd=%d\n",c, n, fd);
*conn = c;
*conn_fd = fd;
return 1;
error:
tcpconn_put(c);
sh_log(c->hist, TCP_UNREF, "tcp_conn_get, (%d)", c->refcnt);
*conn = NULL;
*conn_fd = -1;
return -1;
}
/* used to tune the tcp_connection attributes - not to be used inside the
network layer, but onlu from the above layer (otherwise we may end up
in strange deadlocks!) */
int tcp_conn_fcntl(struct receive_info *rcv, int attr, void *value)
{
struct tcp_connection *con;
switch (attr) {
case DST_FCNTL_SET_LIFETIME:
/* set connection timeout */
TCPCONN_LOCK(rcv->proto_reserved1);
con =_tcpconn_find(rcv->proto_reserved1);
if (!con) {
LM_ERR("Strange, tcp conn not found (id=%u)\n",
rcv->proto_reserved1);
} else {
tcp_conn_set_lifetime( con, (int)(long)(value));
}
TCPCONN_UNLOCK(rcv->proto_reserved1);
return 0;
default:
LM_ERR("unsupported operation %d on conn\n",attr);
return -1;
}
return -1;
}
static struct tcp_connection* tcpconn_add(struct tcp_connection *c)
{
unsigned hash;
if (c){
TCPCONN_LOCK(c->id);
/* add it at the beginning of the list*/
hash=tcp_id_hash(c->id);
c->id_hash=hash;
tcpconn_listadd(TCP_PART(c->id).tcpconn_id_hash[hash], c, id_next,
id_prev);
hash=tcp_addr_hash(&c->rcv.src_ip, c->rcv.src_port);
/* set the first alias */
c->con_aliases[0].port=c->rcv.src_port;
c->con_aliases[0].hash=hash;
c->con_aliases[0].parent=c;
tcpconn_listadd(TCP_PART(c->id).tcpconn_aliases_hash[hash],
&c->con_aliases[0], next, prev);
c->aliases++;
TCPCONN_UNLOCK(c->id);
LM_DBG("hashes: %d, %d\n", hash, c->id_hash);
return c;
}else{
LM_CRIT("null connection pointer\n");
return 0;
}
}
static str e_tcp_src_ip = str_init("src_ip");
static str e_tcp_src_port = str_init("src_port");
static str e_tcp_dst_ip = str_init("dst_ip");
static str e_tcp_dst_port = str_init("dst_port");
static str e_tcp_c_proto = str_init("proto");
void tcp_disconnect_event_raise(struct tcp_connection* c)
{
evi_params_p list = 0;
str src_ip,dst_ip, proto;
int src_port,dst_port;
char src_ip_buf[IP_ADDR_MAX_STR_SIZE],dst_ip_buf[IP_ADDR_MAX_STR_SIZE];
// event has to be triggered - check for subscribers
if (!evi_probe_event(EVI_TCP_DISCONNECT)) {
goto end;
}
if (!(list = evi_get_params()))
goto end;
src_ip.s = ip_addr2a( &c->rcv.src_ip );
memcpy(src_ip_buf,src_ip.s,IP_ADDR_MAX_STR_SIZE);
src_ip.s = src_ip_buf;
src_ip.len = strlen(src_ip.s);
if (evi_param_add_str(list, &e_tcp_src_ip, &src_ip)) {
LM_ERR("unable to add parameter\n");
goto end;
}
src_port = c->rcv.src_port;
if (evi_param_add_int(list, &e_tcp_src_port, &src_port)) {
LM_ERR("unable to add parameter\n");
goto end;
}
dst_ip.s = ip_addr2a( &c->rcv.dst_ip );
memcpy(dst_ip_buf,dst_ip.s,IP_ADDR_MAX_STR_SIZE);
dst_ip.s = dst_ip_buf;
dst_ip.len = strlen(dst_ip.s);
if (evi_param_add_str(list, &e_tcp_dst_ip, &dst_ip)) {
LM_ERR("unable to add parameter\n");
goto end;
}
dst_port = c->rcv.dst_port;
if (evi_param_add_int(list, &e_tcp_dst_port, &dst_port)) {
LM_ERR("unable to add parameter\n");
goto end;
}
proto.s = protos[c->rcv.proto].name;
proto.len = strlen(proto.s);
if (evi_param_add_str(list, &e_tcp_c_proto, &proto)) {
LM_ERR("unable to add parameter\n");
goto end;
}
if (evi_raise_event(EVI_TCP_DISCONNECT, list)) {
LM_ERR("unable to send tcp disconnect event\n");
}
list = 0;
end:
if (list)
evi_free_params(list);
}
/*! \brief unsafe tcpconn_rm version (nolocks) */
static void _tcpconn_rm(struct tcp_connection* c)
{
int r;
tcpconn_listrm(TCP_PART(c->id).tcpconn_id_hash[c->id_hash], c,
id_next, id_prev);
/* remove all the aliases */
for (r=0; r<c->aliases; r++)
tcpconn_listrm(TCP_PART(c->id).tcpconn_aliases_hash[c->con_aliases[r].hash],
&c->con_aliases[r], next, prev);
lock_destroy(&c->write_lock);
if (c->async) {
for (r = 0; r<c->async->pending; r++)
shm_free(c->async->chunks[r]);
shm_free(c->async);
c->async = NULL;
}
if (protos[c->type].net.conn_clean)
protos[c->type].net.conn_clean(c);
tcp_disconnect_event_raise(c);
#ifdef DBG_TCPCON
sh_log(c->hist, TCP_DESTROY, "type=%d", c->type);
sh_unref(c->hist);
c->hist = NULL;
#endif
shm_free(c);
}
#if 0
static void tcpconn_rm(struct tcp_connection* c)
{
int r;
TCPCONN_LOCK(c->id);
tcpconn_listrm(TCP_PART(c->id).tcpconn_id_hash[c->id_hash], c,
id_next, id_prev);
/* remove all the aliases */
for (r=0; r<c->aliases; r++)
tcpconn_listrm(TCP_PART(c->id).tcpconn_aliases_hash
[c->con_aliases[r].hash],
&c->con_aliases[r], next, prev);
TCPCONN_UNLOCK(c->id);
lock_destroy(&c->write_lock);
if (protos[c->type].net.conn_clean)
protos[c->type].net.conn_clean(c);
shm_free(c);
}
#endif
/*! \brief add port as an alias for the "id" connection
* \return 0 on success,-1 on failure */
int tcpconn_add_alias(struct sip_msg *msg, unsigned int id, int port, int proto)
{
struct tcp_connection* c;
unsigned hash;
struct tcp_conn_alias* a;
a=0;
/* fix the port */
port=port ? port : protos[proto].default_port ;
TCPCONN_LOCK(id);
/* check if alias already exists */
c=_tcpconn_find(id);
if (c) {
if (msg && !(c->profile.alias_mode == TCP_ALIAS_ALWAYS
|| (c->profile.alias_mode == TCP_ALIAS_RFC_5923
&& msg->via1->alias))) {
LM_DBG("refusing to add alias (alias_mode: %u, via 'alias': %u)\n",
c->profile.alias_mode, !!msg->via1->alias);
TCPCONN_UNLOCK(id);
return 0;
}
hash=tcp_addr_hash(&c->rcv.src_ip, port);
/* search the aliases for an already existing one */
for (a=TCP_PART(id).tcpconn_aliases_hash[hash]; a; a=a->next) {
if (a->parent->state != S_CONN_BAD &&
port == a->port &&
proto == a->parent->type &&
ip_addr_cmp(&c->rcv.src_ip, &a->parent->rcv.src_ip)) {
/* found */
if (a->parent!=c) goto error_sec;
else goto ok;
}
}
if (c->aliases>=TCP_CON_MAX_ALIASES) goto error_aliases;
c->con_aliases[c->aliases].parent=c;
c->con_aliases[c->aliases].port=port;
c->con_aliases[c->aliases].hash=hash;
tcpconn_listadd(TCP_PART(id).tcpconn_aliases_hash[hash],
&c->con_aliases[c->aliases], next, prev);
c->aliases++;
}else goto error_not_found;
ok:
TCPCONN_UNLOCK(id);
#ifdef EXTRA_DEBUG
if (a) LM_DBG("alias already present\n");
else LM_DBG("alias port %d for hash %d, id %u\n", port, hash, id);
#endif
return 0;
error_aliases:
TCPCONN_UNLOCK(id);
LM_ERR("too many aliases for connection %p (%u)\n", c, id);
return -1;
error_not_found:
TCPCONN_UNLOCK(id);
LM_ERR("no connection found for id %u\n",id);
return -1;
error_sec:
LM_WARN("possible port hijack attempt\n");
LM_WARN("alias already present and points to another connection "
"(%d : %d and %u : %d)\n", a->parent->id, port, id, port);
TCPCONN_UNLOCK(id);
return -1;
}
void tcpconn_put(struct tcp_connection* c)
{
TCPCONN_LOCK(c->id);
c->refcnt--;
TCPCONN_UNLOCK(c->id);
}
static inline void tcpconn_ref(struct tcp_connection* c)
{
TCPCONN_LOCK(c->id);
c->refcnt++;
TCPCONN_UNLOCK(c->id);
}
static struct tcp_connection* tcpconn_new(int sock, union sockaddr_union* su,
struct socket_info* si, struct tcp_conn_profile *prof,
int state, int flags)
{
struct tcp_connection *c;
union sockaddr_union local_su;
unsigned int su_size;
c=(struct tcp_connection*)shm_malloc(sizeof(struct tcp_connection));
if (c==0){
LM_ERR("shared memory allocation failure\n");
return 0;
}
memset(c, 0, sizeof(struct tcp_connection)); /* zero init */
c->s=sock;
c->fd=-1; /* not initialized */
if (lock_init(&c->write_lock)==0){
LM_ERR("init lock failed\n");
goto error0;
}
c->rcv.src_su=*su;
c->refcnt=0;
su2ip_addr(&c->rcv.src_ip, su);
c->rcv.src_port=su_getport(su);
c->rcv.bind_address = si;
c->rcv.dst_ip = si->address;
su_size = sockaddru_len(local_su);
if (getsockname(sock, (struct sockaddr *)&local_su, &su_size)<0) {
LM_ERR("failed to get info on received interface/IP %d/%s\n",
errno, strerror(errno));
goto error;
}
c->rcv.dst_port = su_getport(&local_su);
print_ip("tcpconn_new: new tcp connection to: ", &c->rcv.src_ip, "\n");
LM_DBG("on port %d, proto %d\n", c->rcv.src_port, si->proto);
c->id=(*connection_id)++;
c->cid = (unsigned long long)c->id
| ( (unsigned long long)(startup_time&0xFFFFFF) << 32 )
| ( (unsigned long long)(rand()&0xFF) << 56 );
c->rcv.proto_reserved1=0; /* this will be filled before receive_message*/
c->rcv.proto_reserved2=0;
c->state=state;
c->extra_data=0;
c->type = si->proto;
c->rcv.proto = si->proto;
/* start with the default conn lifetime */
c->lifetime = get_ticks() + prof->con_lifetime;
c->profile = *prof;
c->flags|=F_CONN_REMOVED|flags;
#ifdef DBG_TCPCON
c->hist = sh_push(c, con_hist);
#endif
if (protos[si->proto].net.async_chunks) {
c->async = shm_malloc(sizeof(struct tcp_async_data) +
protos[si->proto].net.async_chunks *
sizeof(struct tcp_async_chunk));
if (c->async) {
c->async->allocated = protos[si->proto].net.async_chunks;
c->async->oldest = 0;
c->async->pending = 0;
} else {
LM_ERR("could not allocate async data for con!\n");
goto error;
}
}
tcp_connections_no++;
return c;
error:
lock_destroy(&c->write_lock);
error0:
shm_free(c);
return 0;
}
/* creates a new tcp connection structure
* if send2main is 1, the function informs the TCP Main about the new conn
* a +1 ref is set for the new conn !
* IMPORTANT - the function assumes you want to create a new TCP conn as
* a result of a connect operation - the conn will be set as connect !!
* Accepted connection are triggered internally only */
struct tcp_connection* tcp_conn_create(int sock, union sockaddr_union* su,
struct socket_info* si, struct tcp_conn_profile *prof,
int state, int send2main)
{
struct tcp_connection *c;
if (!prof)
tcp_con_get_profile(su, &si->su, si->proto, prof);
/* create the connection structure */
c = tcpconn_new(sock, su, si, prof, state, 0);
if (c==NULL) {
LM_ERR("tcpconn_new failed\n");
return NULL;
}
if (protos[c->type].net.conn_init &&
protos[c->type].net.conn_init(c) < 0) {
LM_ERR("failed to do proto %d specific init for conn %p\n",
c->type, c);
tcp_conn_destroy(c);
return NULL;
}
c->flags |= F_CONN_INIT;
c->refcnt++; /* safe to do it w/o locking, it's not yet
available to the rest of the world */
sh_log(c->hist, TCP_REF, "connect, (%d)", c->refcnt);
if (!send2main)
return c;
return (tcp_conn_send(c) == 0 ? c : NULL);
}
/* sends a new connection from a worker to main */
int tcp_conn_send(struct tcp_connection *c)
{
long response[2];
int n, fd;
/* inform TCP main about this new connection */
if (c->state==S_CONN_CONNECTING) {
/* store the local fd now, before TCP main overwrites it */
fd = c->s;
response[0]=(long)c;
response[1]=ASYNC_CONNECT;
n=send_fd(unix_tcp_sock, response, sizeof(response), fd);
if (n<=0) {
LM_ERR("Failed to send the socket to main for async connection\n");
goto error;
}
close(fd);
} else {
response[0]=(long)c;
response[1]=CONN_NEW;
n=send_fd(unix_tcp_sock, response, sizeof(response), c->s);
if (n<=0){
LM_ERR("failed send_fd: %s (%d)\n", strerror(errno), errno);
goto error;
}
}
return 0;
error:
/* no reporting as closed, as PROTO layer did not reporte it as
* OPEN yet */
_tcpconn_rm(c);
tcp_connections_no--;
return -1;
}
static inline void tcpconn_destroy(struct tcp_connection* tcpconn)
{
int fd;
int unsigned id = tcpconn->id;