-
Notifications
You must be signed in to change notification settings - Fork 564
/
net_tcp.c
2054 lines (1832 loc) · 55.1 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 "../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 "trans.h"
struct struct_hist_list *con_hist;
/* definition of a TCP worker */
struct tcp_child {
pid_t pid;
int unix_sock; /*!< unix "read child" sock fd */
int busy;
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_child *tcp_children=0;
/* unique for each connection, used for
* quickly finding the corresponding connection for a reply */
static 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_listen_backlog=DEFAULT_TCP_LISTEN_BACKLOG;
/*!< by default choose the best method */
enum poll_types tcp_poll_method=0;
int tcp_max_connections=DEFAULT_TCP_MAX_CONNECTIONS;
/* number of TCP workers */
int tcp_children_no = CHILD_NO;
/* 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;
#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 a new TCP conn be open if needed? - branch flag to be set in
* the SIP messages - configuration option */
int tcp_no_new_conn_bflag = 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 */
int last_outgoing_tcp_id = 0;
/****************************** helper functions *****************************/
extern void handle_sigs(void);
static inline int init_sock_keepalive(int s)
{
int optval;
if (tcp_keepinterval || tcp_keepidle || tcp_keepcount) {
tcp_keepalive = 1; /* force on */
}
#ifdef HAVE_SO_KEEPALIVE
if ((optval = tcp_keepalive)) {
if (setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,&optval,sizeof(optval))<0){
LM_WARN("setsockopt failed to enable SO_KEEPALIVE: %s\n",
strerror(errno));
return -1;
}
LM_INFO("TCP keepalive enabled on socket %d\n",s);
}
#endif
#ifdef HAVE_TCP_KEEPINTVL
if ((optval = tcp_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 = tcp_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 = tcp_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)
{
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);
/* 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;
}
/*! \brief blocking connect on a non-blocking fd; it will timeout after
* tcp_connect_timeout
* if BLOCKING_USE_SELECT and HAVE_SELECT are defined it will internally
* use select() instead of poll (bad if fd > FD_SET_SIZE, poll is preferred)
*/
int tcp_connect_blocking_timeout(int fd, const struct sockaddr *servaddr,
socklen_t addrlen, int timeout)
{
int n;
#if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
fd_set sel_set;
fd_set orig_set;
struct timeval timeout;
#else
struct pollfd pf;
#endif
int elapsed;
int to;
int err;
struct timeval begin;
unsigned int err_len;
int poll_err;
char *ip;
unsigned short port;
poll_err=0;
to = timeout*1000;
if (gettimeofday(&(begin), NULL)) {
LM_ERR("Failed to get TCP connect start time\n");
goto error;
}
again:
n=connect(fd, servaddr, addrlen);
if (n==-1){
if (errno==EINTR){
elapsed=get_time_diff(&begin);
if (elapsed<to) goto again;
else goto error_timeout;
}
if (errno!=EINPROGRESS && errno!=EALREADY){
get_su_info( servaddr, ip, port);
LM_ERR("[server=%s:%d] (%d) %s\n",ip, port, errno, strerror(errno));
goto error;
}
}else goto end;
/* poll/select loop */
#if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
FD_ZERO(&orig_set);
FD_SET(fd, &orig_set);
#else
pf.fd=fd;
pf.events=POLLOUT;
#endif
while(1){
elapsed = get_time_diff(&begin);
if (elapsed<to)
to-=elapsed;
else
goto error_timeout;
#if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
sel_set=orig_set;
timeout.tv_sec = to/1000000;
timeout.tv_usec = to%1000000;
n=select(fd+1, 0, &sel_set, 0, &timeout);
#else
n=poll(&pf, 1, to/1000);
#endif
if (n<0){
if (errno==EINTR) continue;
get_su_info( servaddr, ip, port);
LM_ERR("poll/select failed:[server=%s:%d] (%d) %s\n",
ip, port, errno, strerror(errno));
goto error;
}else if (n==0) /* timeout */ continue;
#if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
if (FD_ISSET(fd, &sel_set))
#else
if (pf.revents&(POLLERR|POLLHUP|POLLNVAL)){
LM_ERR("poll error: flags %d - %d %d %d %d \n", pf.revents,
POLLOUT,POLLERR,POLLHUP,POLLNVAL);
poll_err=1;
}
#endif
{
err_len=sizeof(err);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
if ((err==0) && (poll_err==0)) goto end;
if (err!=EINPROGRESS && err!=EALREADY){
get_su_info( servaddr, ip, port);
LM_ERR("failed to retrieve SO_ERROR [server=%s:%d] (%d) %s\n",
ip, port, err, strerror(err));
goto error;
}
}
}
error_timeout:
/* timeout */
LM_ERR("connect timed out, %d us elapsed out of %d us\n", elapsed,
timeout*1000);
error:
return -1;
end:
return 0;
}
int tcp_connect_blocking(int fd, const struct sockaddr *servaddr,
socklen_t addrlen)
{
return tcp_connect_blocking_timeout(fd, servaddr, addrlen,
tcp_connect_timeout);
}
static int send2child(struct tcp_connection* tcpconn,int rw)
{
int i;
int min_busy;
int idx;
long response[2];
min_busy=tcp_children[0].busy;
idx=0;
for (i=0; i<tcp_children_no; i++){
if (!tcp_children[i].busy){
idx=i;
min_busy=0;
break;
}else if (min_busy>tcp_children[i].busy){
min_busy=tcp_children[i].busy;
idx=i;
}
}
tcp_children[idx].busy++;
tcp_children[idx].n_reqs++;
if (min_busy) {
LM_DBG("no free tcp receiver, connection passed to the least "
"busy one (proc #%d, %d con)\n", idx, min_busy);
}
LM_DBG("to tcp child %d (%d), %p rw %d\n", idx,
tcp_children[idx].pid, tcpconn,rw);
response[0]=(long)tcpconn;
response[1]=rw;
if (send_fd(tcp_children[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);
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_listen_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(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=%d, 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( 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(int id, struct ip_addr* ip, int port, enum sip_protos proto,
struct tcp_connection** conn, int* conn_fd)
{
struct tcp_connection* c;
struct tcp_connection* tmp;
struct tcp_conn_alias* a;
unsigned hash;
long response[2];
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 %d\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=%d, 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");
#endif
c = a->parent;
if (c->state != S_CONN_BAD &&
port == a->port &&
proto == c->type &&
ip_addr_cmp(ip, &c->rcv.src_ip))
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= %d, refcnt=%d state=%d != "
" %p (id= %d, 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=%d)\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;
}
}
/*! \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 (protos[c->type].net.conn_clean)
protos[c->type].net.conn_clean(c);
sh_log(c->hist, TCP_DESTROY, "type=%d", c->type);
sh_unref(c->hist, con_hist);
c->hist = NULL;
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(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){
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 %d\n", port, hash, id);
#endif
return 0;
error_aliases:
TCPCONN_UNLOCK(id);
LM_ERR("too many aliases for connection %p (%d)\n", c, id);
return -1;
error_not_found:
TCPCONN_UNLOCK(id);
LM_ERR("no connection found for id %d\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 %d : %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--; /* FIXME: atomic_dec */
TCPCONN_UNLOCK(c->id);
}
static inline void tcpconn_ref(struct tcp_connection* c)
{
TCPCONN_LOCK(c->id);
c->refcnt++; /* FIXME: atomic_dec */
TCPCONN_UNLOCK(c->id);
}
static struct tcp_connection* tcpconn_new(int sock, union sockaddr_union* su,
struct socket_info* si, 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);
getsockname(sock, (struct sockaddr *)&local_su, &su_size);
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()+tcp_con_lifetime;
c->flags|=F_CONN_REMOVED|flags;
c->hist = sh_push(c, con_hist);
if (protos[si->proto].net.conn_init &&
protos[si->proto].net.conn_init(c)<0) {
LM_ERR("failed to do proto %d specific init for conn %p\n",
si->proto,c);
goto error1;
}
tcp_connections_no++;
return c;
error1:
lock_destroy(&c->write_lock);
error0:
shm_free(c);
return 0;
}
/* creates a new tcp connection structure and informs the TCP Main on that
* 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, int state)
{
struct tcp_connection *c;
/* create the connection structure */
c = tcp_conn_new(sock, su, si, state);
if (c==NULL)
return NULL;
return (tcp_conn_send(c) == 0 ? c : NULL);
}
struct tcp_connection* tcp_conn_new(int sock, union sockaddr_union* su,
struct socket_info* si, int state)
{
struct tcp_connection *c;
/* create the connection structure */
c = tcpconn_new(sock, su, si, state, 0);
if (c==NULL) {
LM_ERR("tcpconn_new failed\n");
return NULL;
}
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);
return c;
}
/* 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 id = tcpconn->id;
TCPCONN_LOCK(id); /*avoid races w/ tcp_send*/
tcpconn->refcnt--;
if (tcpconn->refcnt==0){
LM_DBG("destroying connection %p, flags %04x\n",
tcpconn, tcpconn->flags);
fd=tcpconn->s;
/* no reporting here - the tcpconn_destroy() function is called
* from the TCP_MAIN reactor when handling connectioned received
* from a worker; and we generate the CLOSE reports from WORKERs */
_tcpconn_rm(tcpconn);
if (fd >= 0)
close(fd);
tcp_connections_no--;
}else{
/* force timeout */
tcpconn->lifetime=0;
tcpconn->state=S_CONN_BAD;
LM_DBG("delaying (%p, flags %04x) ref = %d ...\n",
tcpconn, tcpconn->flags, tcpconn->refcnt);
}
TCPCONN_UNLOCK(id);