Coverage Report

Created: 2026-08-31 06:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensips/net/net_tcp.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2014-2015 OpenSIPS Project
3
 * Copyright (C) 2001-2003 FhG Fokus
4
 *
5
 * This file is part of opensips, a free SIP server.
6
 *
7
 * opensips is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * opensips is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
 *
21
 *
22
 * history:
23
 * ---------
24
 *  2015-01-xx  created (razvanc)
25
 */
26
27
#include <sys/types.h>
28
#include <sys/socket.h>
29
#include <netinet/in.h>
30
#include <netinet/in_systm.h>
31
#include <netinet/ip.h>
32
#include <netinet/tcp.h>
33
#include <sys/uio.h>  /* writev*/
34
#include <netdb.h>
35
#include <stdlib.h> /*exit() */
36
#include <time.h>   /*time() */
37
#include <unistd.h>
38
#include <errno.h>
39
#include <string.h>
40
#include <pthread.h>
41
#include <stdint.h>
42
43
#include "../mem/mem.h"
44
#include "../mem/shm_mem.h"
45
#include "../globals.h"
46
#include "../locking.h"
47
#include "../socket_info.h"
48
#include "../ut.h"
49
#include "../pt.h"
50
#include "../pt_load.h"
51
#include "../daemonize.h"
52
#include "../status_report.h"
53
#include "../reactor.h"
54
#include "../timer.h"
55
#include "../ipc.h"
56
#include "../receive.h"
57
#include "../lib/cond.h"
58
#include "../cfg_reload.h"
59
60
#include "tcp_passfd.h"
61
#include "net_tcp_proc.h"
62
#include "net_tcp_report.h"
63
#include "net_tcp.h"
64
#include "tcp_common.h"
65
#include "tcp_conn.h"
66
#include "tcp_conn_profile.h"
67
#include "trans.h"
68
#include "net_tcp_dbg.h"
69
70
struct struct_hist_list *con_hist;
71
72
enum tcp_worker_state { STATE_INACTIVE=0, STATE_ACTIVE, STATE_DRAINING};
73
74
static int tcpconn_prepare_write(struct tcp_connection *tcpconn);
75
76
/* definition of a TCP worker - the array of these TCP workers is
77
 * mainly intended to be used by the TCP main, to keep track of the
78
 * workers, about their load and so. Nevertheless, since the addition
79
 * of the process auto-scaling, other processes may need access to this
80
 * data, thus it's relocation in SHM (versus initial PKG). For example,
81
 * the attendant process is the one forking new TCP workers (scaling up),
82
 * so it must be able to set the ENABLE state for the TCP worker (and being
83
 * (seen by the TCP main proc). Similar, when a TCP worker shuts down, it has
84
 * to mark itself as DISABLED and the TCP main must see that.
85
 * Again, 99% this array is intended for TCP Main ops, it is not lock
86
 * protected, so be very careful with any ops from other procs.
87
 */
88
struct tcp_worker {
89
  pid_t pid;
90
  int pt_idx;     /*!< Index in the main Process Table */
91
  enum tcp_worker_state state;
92
};
93
94
/* definition of a TCP partition */
95
struct tcp_partition {
96
  /*! \brief connection hash table (after ip&port), includes also aliases */
97
  struct tcp_conn_alias** tcpconn_aliases_hash;
98
  /*! \brief connection hash table (after connection id) */
99
  struct tcp_connection** tcpconn_id_hash;
100
  gen_lock_t* tcpconn_lock;
101
};
102
103
104
/* array of TCP workers - to be used only by TCP MAIN */
105
struct tcp_worker *tcp_workers=0;
106
static int tcp_dispatch_sock[2] = { -1, -1 };
107
108
/* unique for each connection, used for
109
 * quickly finding the corresponding connection for a reply */
110
static unsigned int* connection_id=0;
111
static int *tcp_main_proc_no = 0;
112
113
/* connections are created both by TCP main (on accept) and by any other
114
 * process (on connect), so the counter above must be incremented under lock -
115
 * otherwise concurrent creations may end up sharing the same connection ID */
116
static gen_lock_t* connection_id_lock=0;
117
118
/* array of TCP partitions */
119
static struct tcp_partition tcp_parts[TCP_PARTITION_SIZE];
120
121
/*!< current number of open connections */
122
static unsigned int *tcp_connections_no = 0;
123
static gen_lock_t *tcp_connections_lock = 0;
124
125
/*!< by default don't accept aliases */
126
int tcp_accept_aliases=0;
127
int tcp_connect_timeout=DEFAULT_TCP_CONNECT_TIMEOUT;
128
int tcp_con_lifetime=DEFAULT_TCP_CONNECTION_LIFETIME;
129
int tcp_socket_backlog=DEFAULT_TCP_SOCKET_BACKLOG;
130
/*!< by default choose the best method */
131
enum poll_types tcp_poll_method=0;
132
int tcp_max_connections=DEFAULT_TCP_MAX_CONNECTIONS;
133
/* the configured/starting number of TCP workers */
134
int tcp_workers_no = UDP_WORKERS_NO;
135
/* the maximum numbers of TCP workers */
136
int tcp_workers_max_no;
137
/* the name of the auto-scaling profile (optional) */
138
char* tcp_auto_scaling_profile = NULL;
139
/* Max number of seconds that we expect a full SIP message
140
 * to arrive in. Anything above will close the connection. */
141
int tcp_max_msg_time = TCP_CHILD_MAX_MSG_TIME;
142
#ifdef HAVE_SO_KEEPALIVE
143
    int tcp_keepalive = 1;
144
#else
145
    int tcp_keepalive = 0;
146
#endif
147
int tcp_keepcount = 0;
148
int tcp_keepidle = 0;
149
int tcp_keepinterval = 0;
150
151
/*!< should we allow opening a new TCP conn when sending data 
152
 * over UAC branches? - branch flag to be set in the SIP messages */
153
int tcp_no_new_conn_bflag = 0;
154
/*!< should we allow opening a new TCP conn when sending data 
155
 * back to UAS (replies)? - msg flag to be set in the SIP messages */
156
int tcp_no_new_conn_rplflag = 0;
157
/*!< should a new TCP conn be open if needed? - variable used to used for
158
 * signalizing between SIP layer (branch flag) and TCP layer (tcp_send func)*/
159
int tcp_no_new_conn = 0;
160
int tcp_threads = 0;
161
162
/* if the TCP net layer is on or off (if no TCP based protos are loaded) */
163
static int tcp_disabled = 1;
164
165
/* is the process TCP MAIN ? */
166
int is_tcp_main = 0;
167
168
/* the ID of the TCP conn used for the last send operation in the
169
 * current process - attention, this is a really ugly HACK here */
170
unsigned int last_outgoing_tcp_id = 0;
171
172
static struct scaling_profile *s_profile = NULL;
173
174
/****************************** helper functions *****************************/
175
extern void handle_sigs(void);
176
177
static inline int init_sock_keepalive(int s, const struct tcp_conn_profile *prof)
178
0
{
179
0
  int ka;
180
0
#if defined(HAVE_TCP_KEEPINTVL) || defined(HAVE_TCP_KEEPIDLE) || defined(HAVE_TCP_KEEPCNT)
181
0
  int optval;
182
0
#endif
183
184
0
  if (prof->keepinterval || prof->keepidle || prof->keepcount)
185
0
    ka = 1; /* force on */
186
0
  else
187
0
    ka = prof->keepalive;
188
189
0
#ifdef HAVE_SO_KEEPALIVE
190
0
  if (setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,&ka,sizeof(ka))<0){
191
0
    LM_WARN("setsockopt failed to enable SO_KEEPALIVE: %s\n",
192
0
      strerror(errno));
193
0
    return -1;
194
0
  }
195
0
  LM_DBG("TCP keepalive enabled on socket %d\n",s);
196
0
#endif
197
0
#ifdef HAVE_TCP_KEEPINTVL
198
0
  if ((optval = prof->keepinterval)) {
199
0
    if (setsockopt(s,IPPROTO_TCP,TCP_KEEPINTVL,&optval,sizeof(optval))<0){
200
0
      LM_WARN("setsockopt failed to set keepalive probes interval: %s\n",
201
0
        strerror(errno));
202
0
    }
203
0
  }
204
0
#endif
205
0
#ifdef HAVE_TCP_KEEPIDLE
206
0
  if ((optval = prof->keepidle)) {
207
0
    if (setsockopt(s,IPPROTO_TCP,TCP_KEEPIDLE,&optval,sizeof(optval))<0){
208
0
      LM_WARN("setsockopt failed to set keepalive idle interval: %s\n",
209
0
        strerror(errno));
210
0
    }
211
0
  }
212
0
#endif
213
0
#ifdef HAVE_TCP_KEEPCNT
214
0
  if ((optval = prof->keepcount)) {
215
0
    if (setsockopt(s,IPPROTO_TCP,TCP_KEEPCNT,&optval,sizeof(optval))<0){
216
0
      LM_WARN("setsockopt failed to set maximum keepalive count: %s\n",
217
0
        strerror(errno));
218
0
    }
219
0
  }
220
0
#endif
221
0
  return 0;
222
0
}
223
224
static inline void set_sock_reuseport(int s)
225
0
{
226
0
  int yes = 1;
227
228
0
  if (setsockopt(s,SOL_SOCKET,SO_REUSEPORT,&yes,sizeof(yes))<0){
229
0
    LM_WARN("setsockopt failed to set SO_REUSEPORT: %s\n",
230
0
      strerror(errno));
231
0
  }
232
0
  if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes))<0){
233
0
    LM_WARN("setsockopt failed to set SO_REUSEADDR: %s\n",
234
0
      strerror(errno));
235
0
  }
236
0
}
237
238
/*! \brief Set all socket/fd options:  disable nagle, tos lowdelay,
239
 * non-blocking
240
 * \return -1 on error */
241
int tcp_init_sock_opt(int s, const struct tcp_conn_profile *prof, enum si_flags socketflags, int sock_tos)
242
0
{
243
0
  int flags;
244
0
  int optval;
245
246
0
#ifdef DISABLE_NAGLE
247
0
  flags=1;
248
0
  if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags)) < 0){
249
0
    LM_WARN("could not disable Nagle: %s\n", strerror(errno));
250
0
  }
251
0
#endif
252
  /* tos*/
253
0
  optval = (sock_tos > 0) ? sock_tos : tos;
254
0
  if (optval > 0) {
255
0
    if (setsockopt(s, IPPROTO_IP, IP_TOS, (void*)&optval,sizeof(optval)) ==-1){
256
0
      LM_WARN("setsockopt tos: %s\n",  strerror(errno));
257
      /* continue since this is not critical */
258
0
    }
259
0
  }
260
261
0
  if (probe_max_sock_buff(s,1,MAX_SEND_BUFFER_SIZE,BUFFER_INCREMENT)) {
262
0
    LM_WARN("setsockopt tcp snd buff: %s\n", strerror(errno));
263
    /* continue since this is not critical */
264
0
  }
265
266
0
  init_sock_keepalive(s, prof);
267
0
  if (socketflags & SI_REUSEPORT)
268
0
    set_sock_reuseport(s);
269
270
  /* non-blocking */
271
0
  flags=fcntl(s, F_GETFL);
272
0
  if (flags==-1){
273
0
    LM_ERR("fcntl failed: (%d) %s\n", errno, strerror(errno));
274
0
    goto error;
275
0
  }
276
0
  if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
277
0
    LM_ERR("set non-blocking failed: (%d) %s\n", errno, strerror(errno));
278
0
    goto error;
279
0
  }
280
0
  return 0;
281
0
error:
282
0
  return -1;
283
0
}
284
285
struct tcp_ipc_payload {
286
  struct receive_info rcv;
287
  struct tcp_connection *conn;
288
  int msg_len;
289
  int data_len;
290
  char msg_buf[0];
291
};
292
293
int tcp_dispatch_msg(char *msg, int len,
294
    struct receive_info *rcv, const void *data, int data_len)
295
0
{
296
0
  struct tcp_ipc_payload *payload;
297
0
  struct tcp_connection *conn = NULL;
298
0
  unsigned int alloc_len;
299
0
  int n;
300
0
  uintptr_t payload_ptr;
301
302
0
  if (len < 0) {
303
0
    LM_BUG("negative TCP message length: %d\n", len);
304
0
    return -1;
305
0
  }
306
0
  if (len && !msg) {
307
0
    LM_BUG("NULL TCP message buffer with non-zero length: %d\n", len);
308
0
    return -1;
309
0
  }
310
0
  if (data_len < 0) {
311
0
    LM_BUG("negative TCP dispatch data length: %d\n", data_len);
312
0
    return -1;
313
0
  }
314
0
  if (data_len && !data) {
315
0
    LM_BUG("missing TCP dispatch data buffer for %d bytes\n", data_len);
316
0
    return -1;
317
0
  }
318
319
0
  alloc_len = sizeof(*payload) + len + 1 + data_len;
320
0
  payload = shm_malloc(alloc_len);
321
0
  if (!payload) {
322
0
    LM_ERR("oom while allocating TCP IPC payload (%u bytes)\n", alloc_len);
323
0
    return -1;
324
0
  }
325
326
0
  memcpy(&payload->rcv, rcv, sizeof(payload->rcv));
327
0
  payload->conn = NULL;
328
0
  payload->msg_len = len;
329
0
  payload->data_len = data_len;
330
0
  memcpy(payload->msg_buf, msg, len);
331
0
  payload->msg_buf[len] = '\0';
332
0
  if (data_len)
333
0
    memcpy(payload->msg_buf + len + 1, data, data_len);
334
335
0
  if (rcv->proto_reserved1 &&
336
0
      tcp_conn_get(rcv->proto_reserved1, NULL, 0, PROTO_NONE,
337
0
        NULL, &conn, NULL) > 0) {
338
0
    payload->conn = conn;
339
0
  }
340
341
0
  payload_ptr = (uintptr_t)payload;
342
0
  n = send(tcp_dispatch_sock[1], &payload_ptr, sizeof(payload_ptr), 0);
343
0
  if (n != (int)sizeof(payload_ptr)) {
344
0
    LM_ERR("failed to dispatch TCP message to worker socket: %s\n",
345
0
      (n < 0) ? strerror(errno) : "short write");
346
0
    if (payload->conn)
347
0
      tcpconn_put(payload->conn);
348
0
    shm_free(payload);
349
0
    return -1;
350
0
  }
351
352
0
  return 0;
353
0
}
354
355
enum tcp_job_op {
356
  TCP_READ_JOB = 1,
357
  TCP_WRITE_JOB = 2,
358
  TCP_RUN_JOB = 3,
359
};
360
361
struct tcp_job {
362
  struct tcp_connection *conn;
363
  int op;
364
  tcp_thread_job_f run;
365
  void *data;
366
  long resp;
367
  int ret;
368
  struct tcp_job *next;
369
};
370
371
static struct tcp_pool {
372
  pthread_t *threads;
373
  int threads_no;
374
  int stop;
375
  struct tcp_job *task_head;
376
  struct tcp_job *task_tail;
377
378
  pthread_mutex_t done_lock;
379
  struct tcp_job *done_head;
380
  struct tcp_job *done_tail;
381
382
  int notify_pipe[2];
383
} tcp_pool = {
384
  .threads = NULL,
385
  .threads_no = 0,
386
  .stop = 0,
387
  .task_head = NULL,
388
  .task_tail = NULL,
389
  .done_lock = PTHREAD_MUTEX_INITIALIZER,
390
  .done_head = NULL,
391
  .done_tail = NULL,
392
  .notify_pipe = {-1, -1},
393
};
394
395
struct tcp_shared_write_queue {
396
  gen_cond_t cond;
397
  struct tcp_connection *head;
398
  struct tcp_connection *tail;
399
};
400
401
static struct tcp_shared_write_queue *tcp_write_queue = NULL;
402
403
static inline int tcp_threads_active(void)
404
0
{
405
0
  return tcp_pool.threads_no > 0;
406
0
}
407
408
int tcp_write_in_main(void)
409
0
{
410
  /* This is a process-independent policy: TCP writes are handled by the
411
   * dedicated TCP main process, regardless of the caller process. */
412
0
  return !tcp_disabled;
413
0
}
414
415
416
417
/********************** TCP conn management functions ************************/
418
419
/* initializes an already defined TCP listener */
420
int tcp_init_listener(struct socket_info *si)
421
0
{
422
0
  union sockaddr_union* addr = &si->su;
423
424
0
  if (init_su(addr, &si->address, si->port_no)<0){
425
0
    LM_ERR("could no init sockaddr_union\n");
426
0
    return -1;
427
0
  }
428
429
0
  return 0;
430
0
}
431
432
/* binding an defined TCP listener */
433
int tcp_bind_listener(struct socket_info *si)
434
0
{
435
0
  union sockaddr_union* addr;
436
0
  int optval;
437
0
#ifdef DISABLE_NAGLE
438
0
  int flag;
439
0
#endif
440
441
0
  addr = &si->su;
442
0
  si->socket = socket(AF2PF(addr->s.sa_family), SOCK_STREAM, 0);
443
0
  if (si->socket==-1){
444
0
    LM_ERR("socket failed with [%s]\n", strerror(errno));
445
0
    goto error;
446
0
  }
447
0
#ifdef DISABLE_NAGLE
448
0
  flag=1;
449
0
  if (setsockopt(si->socket, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)) < 0){
450
0
    LM_ERR("could not disable Nagle: %s\n",strerror(errno));
451
0
  }
452
0
#endif
453
454
0
#if  !defined(TCP_DONT_REUSEADDR)
455
  /* Stevens, "Network Programming", Section 7.5, "Generic Socket
456
   * Options": "...server started,..a child continues..on existing
457
   * connection..listening server is restarted...call to bind fails
458
   * ... ALL TCP servers should specify the SO_REUSEADDRE option
459
   * to allow the server to be restarted in this situation
460
   */
461
0
  optval=1;
462
0
  if (setsockopt(si->socket, SOL_SOCKET, SO_REUSEADDR,
463
0
  (void*)&optval, sizeof(optval))==-1) {
464
0
    LM_ERR("setsockopt failed with [%s]\n", strerror(errno));
465
0
    goto error;
466
0
  }
467
0
#endif
468
  /* tos */
469
0
  optval = (si->tos > 0) ? si->tos : tos;
470
0
  if (optval > 0) {
471
0
    if (setsockopt(si->socket, IPPROTO_IP, IP_TOS, (void*)&optval,
472
0
    sizeof(optval)) ==-1){
473
0
      LM_WARN("setsockopt tos: %s\n", strerror(errno));
474
      /* continue since this is not critical */
475
0
    }
476
0
  }
477
478
0
  if (probe_max_sock_buff(si->socket,1,MAX_SEND_BUFFER_SIZE,
479
0
  BUFFER_INCREMENT)) {
480
0
    LM_WARN("setsockopt tcp snd buff: %s\n",strerror(errno));
481
    /* continue since this is not critical */
482
0
  }
483
484
0
  init_sock_keepalive(si->socket, &tcp_con_df_profile);
485
0
  if (si->flags & SI_REUSEPORT)
486
0
    set_sock_reuseport(si->socket);
487
0
  if (bind(si->socket, &addr->s, sockaddru_len(*addr))==-1){
488
0
    LM_ERR("bind(%x, %p, %d) on %s:%d : %s\n",
489
0
        si->socket, &addr->s,
490
0
        (unsigned)sockaddru_len(*addr),
491
0
        si->address_str.s,
492
0
        si->port_no,
493
0
        strerror(errno));
494
0
    goto error;
495
0
  }
496
0
  if (listen(si->socket, tcp_socket_backlog)==-1){
497
0
    LM_ERR("listen(%x, %p, %d) on %s: %s\n",
498
0
        si->socket, &addr->s,
499
0
        (unsigned)sockaddru_len(*addr),
500
0
        si->address_str.s,
501
0
        strerror(errno));
502
0
    goto error;
503
0
  }
504
505
0
  return 0;
506
0
error:
507
0
  if (si->socket!=-1){
508
0
    close(si->socket);
509
0
    si->socket=-1;
510
0
  }
511
0
  return -1;
512
0
}
513
514
515
/*! \brief finds a connection, if id=0 return NULL
516
 * \note WARNING: unprotected (locks) use tcpconn_get unless you really
517
 * know what you are doing */
518
static struct tcp_connection* _tcpconn_find(unsigned int id)
519
0
{
520
0
  struct tcp_connection *c;
521
0
  unsigned hash;
522
523
0
  if (id){
524
0
    hash=tcp_id_hash(id);
525
0
    for (c=TCP_PART(id).tcpconn_id_hash[hash]; c; c=c->id_next){
526
#ifdef EXTRA_DEBUG
527
      LM_DBG("c=%p, c->id=%u, port=%d\n",c, c->id, c->rcv.src_port);
528
      print_ip("ip=", &c->rcv.src_ip, "\n");
529
#endif
530
0
      if ((id==c->id) && c->state!=S_CONN_BAD &&
531
0
          !(c->flags & F_CONN_FORCE_CLOSED))
532
0
        return c;
533
0
    }
534
0
  }
535
0
  return 0;
536
0
}
537
538
539
/* returns the correlation ID of a TCP connection */
540
int tcp_get_correlation_id( unsigned int id, unsigned long long *cid)
541
0
{
542
0
  struct tcp_connection* c;
543
544
0
  TCPCONN_LOCK(id);
545
0
  if ( (c=_tcpconn_find(id))!=NULL ) {
546
0
    *cid = c->cid;
547
0
    TCPCONN_UNLOCK(id);
548
0
    return 0;
549
0
  }
550
0
  *cid = 0;
551
0
  TCPCONN_UNLOCK(id);
552
0
  return -1;
553
0
}
554
555
/* returns the correlation ID of a TCP connection */
556
int tcp_get_rcv( unsigned int id, struct receive_info *ri)
557
0
{
558
0
  struct tcp_connection* c;
559
560
0
  TCPCONN_LOCK(id);
561
0
  if ( (c=_tcpconn_find(id))!=NULL ) {
562
0
    memcpy(ri, &c->rcv, sizeof *ri);
563
0
    TCPCONN_UNLOCK(id);
564
0
    return 0;
565
0
  }
566
0
  TCPCONN_UNLOCK(id);
567
0
  return -1;
568
0
}
569
570
int tcp_get_main_proc_no(void)
571
0
{
572
0
  return tcp_main_proc_no ? *tcp_main_proc_no : -1;
573
0
}
574
575
576
/*! \brief _tcpconn_find with locks and acquire a shared connection reference */
577
int tcp_conn_get(unsigned int id, struct ip_addr* ip, int port,
578
    enum sip_protos proto, void *proto_extra_id,
579
    struct tcp_connection** conn, const struct socket_info* send_sock)
580
0
{
581
0
  struct tcp_connection* c;
582
0
  struct tcp_conn_alias* a;
583
0
  unsigned hash;
584
0
  unsigned int part;
585
586
0
  if (id) {
587
0
    part = id;
588
0
    TCPCONN_LOCK(part);
589
0
    if ( (c=_tcpconn_find(part))!=NULL )
590
0
      goto found;
591
0
    TCPCONN_UNLOCK(part);
592
0
  }
593
594
  /* continue search based on IP address + port + transport */
595
#ifdef EXTRA_DEBUG
596
  LM_DBG("%d  port %u\n",id, port);
597
  if (ip) print_ip("tcpconn_find: ip ", ip, "\n");
598
#endif
599
0
  if (ip){
600
0
    hash=tcp_addr_hash(ip, port);
601
0
    for( part=0 ; part<TCP_PARTITION_SIZE ; part++ ) {
602
0
      TCPCONN_LOCK(part);
603
0
      for (a=TCP_PART(part).tcpconn_aliases_hash[hash]; a; a=a->next) {
604
#ifdef EXTRA_DEBUG
605
        LM_DBG("a=%p, c=%p, c->id=%u, alias port= %d port=%d\n",
606
          a, a->parent, a->parent->id, a->port,
607
          a->parent->rcv.src_port);
608
        print_ip("ip=",&a->parent->rcv.src_ip,"\n");
609
        if (send_sock && a->parent->rcv.bind_address) {
610
          print_ip("requested send_sock ip=", &send_sock->address,"\n");
611
          print_ip("found send_sock ip=", &a->parent->rcv.bind_address->address,"\n");
612
        }
613
#endif
614
0
        c = a->parent;
615
0
        if (c->state != S_CONN_BAD &&
616
0
            !(c->flags & F_CONN_FORCE_CLOSED) &&
617
0
            ((c->flags & F_CONN_INIT) ||
618
0
             (c->state == S_CONN_CONNECTING && c->fd == -1)) &&
619
0
            (send_sock==NULL || send_sock == a->parent->rcv.bind_address) &&
620
0
            port == a->port &&
621
0
            proto == c->type &&
622
0
            ip_addr_cmp(ip, &c->rcv.src_ip) &&
623
0
            (proto_extra_id == NULL ||
624
0
             ((c->flags & F_CONN_INIT) &&
625
0
              (protos[proto].net.stream.conn.match == NULL ||
626
0
               protos[proto].net.stream.conn.match(c, proto_extra_id)))) )
627
0
            goto found;
628
0
        }
629
0
      TCPCONN_UNLOCK(part);
630
0
    }
631
0
  }
632
633
  /* not found */
634
0
  *conn = NULL;
635
0
  return 0;
636
637
0
found:
638
0
  c->refcnt++;
639
0
  TCPCONN_UNLOCK(part);
640
0
  sh_log(c->hist, TCP_REF, "tcp_conn_get, (%d)", c->refcnt);
641
642
0
  LM_DBG("con found in state %d\n",c->state);
643
644
0
  *conn = c;
645
0
  return 1;
646
0
}
647
648
649
/* used to tune the tcp_connection attributes - not to be used inside the
650
   network layer, but onlu from the above layer (otherwise we may end up
651
   in strange deadlocks!) */
652
int tcp_conn_fcntl(struct receive_info *rcv, int attr, void *value)
653
0
{
654
0
  struct tcp_connection *con;
655
656
0
  switch (attr) {
657
0
  case DST_FCNTL_SET_LIFETIME:
658
    /* set connection timeout */
659
0
    TCPCONN_LOCK(rcv->proto_reserved1);
660
0
    con =_tcpconn_find(rcv->proto_reserved1);
661
0
    if (!con) {
662
0
      LM_ERR("Strange, tcp conn not found (id=%u)\n",
663
0
        rcv->proto_reserved1);
664
0
    } else {
665
0
      tcp_conn_set_lifetime( con, (int)(long)(value));
666
0
    }
667
0
    TCPCONN_UNLOCK(rcv->proto_reserved1);
668
0
    return 0;
669
0
  default:
670
0
    LM_ERR("unsupported operation %d on conn\n",attr);
671
0
    return -1;
672
0
  }
673
0
  return -1;
674
0
}
675
676
677
static struct tcp_connection* tcpconn_add(struct tcp_connection *c)
678
0
{
679
0
  unsigned hash;
680
681
0
  if (c){
682
0
    TCPCONN_LOCK(c->id);
683
    /* add it at the beginning of the list*/
684
0
    hash=tcp_id_hash(c->id);
685
0
    c->id_hash=hash;
686
0
    tcpconn_listadd(TCP_PART(c->id).tcpconn_id_hash[hash], c, id_next,
687
0
      id_prev);
688
689
0
    hash=tcp_addr_hash(&c->rcv.src_ip, c->rcv.src_port);
690
    /* set the first alias */
691
0
    c->con_aliases[0].port=c->rcv.src_port;
692
0
    c->con_aliases[0].hash=hash;
693
0
    c->con_aliases[0].parent=c;
694
0
    tcpconn_listadd(TCP_PART(c->id).tcpconn_aliases_hash[hash],
695
0
      &c->con_aliases[0], next, prev);
696
0
    c->aliases++;
697
0
    c->flags |= F_CONN_HASHED;
698
0
    TCPCONN_UNLOCK(c->id);
699
0
    LM_DBG("hashes: %d, %d\n", hash, c->id_hash);
700
0
    return c;
701
0
  }else{
702
0
    LM_CRIT("null connection pointer\n");
703
0
    return 0;
704
0
  }
705
0
}
706
707
static str e_tcp_src_ip = str_init("src_ip");
708
static str e_tcp_src_port = str_init("src_port");
709
static str e_tcp_dst_ip = str_init("dst_ip");
710
static str e_tcp_dst_port = str_init("dst_port");
711
static str e_tcp_c_proto = str_init("proto");
712
713
static void tcp_disconnect_event_raise(struct tcp_connection* c)
714
0
{
715
0
  evi_params_p list = 0;
716
0
  str src_ip,dst_ip, proto;
717
0
  int src_port,dst_port;
718
0
  char src_ip_buf[IP_ADDR_MAX_STR_SIZE],dst_ip_buf[IP_ADDR_MAX_STR_SIZE];
719
720
  // event has to be triggered - check for subscribers
721
0
  if (!evi_probe_event(EVI_TCP_DISCONNECT)) {
722
0
    goto end;
723
0
  }
724
725
0
  if (!(list = evi_get_params()))
726
0
    goto end;
727
728
0
  src_ip.s = ip_addr2a( &c->rcv.src_ip );
729
0
  memcpy(src_ip_buf,src_ip.s,IP_ADDR_MAX_STR_SIZE);
730
0
  src_ip.s = src_ip_buf;
731
0
  src_ip.len = strlen(src_ip.s);
732
733
0
  if (evi_param_add_str(list, &e_tcp_src_ip, &src_ip)) {
734
0
    LM_ERR("unable to add parameter\n");
735
0
    goto end;
736
0
  }
737
738
0
  src_port = c->rcv.src_port;
739
740
0
  if (evi_param_add_int(list, &e_tcp_src_port, &src_port)) {
741
0
    LM_ERR("unable to add parameter\n");
742
0
    goto end;
743
0
  }
744
745
0
  dst_ip.s = ip_addr2a( &c->rcv.dst_ip );
746
0
  memcpy(dst_ip_buf,dst_ip.s,IP_ADDR_MAX_STR_SIZE);
747
0
  dst_ip.s = dst_ip_buf;
748
0
  dst_ip.len = strlen(dst_ip.s);
749
750
0
  if (evi_param_add_str(list, &e_tcp_dst_ip, &dst_ip)) {
751
0
    LM_ERR("unable to add parameter\n");
752
0
    goto end;
753
0
  }
754
755
0
  dst_port = c->rcv.dst_port;
756
757
0
  if (evi_param_add_int(list, &e_tcp_dst_port, &dst_port)) {
758
0
    LM_ERR("unable to add parameter\n");
759
0
    goto end;
760
0
  }
761
762
0
  proto.s = protos[c->rcv.proto].name;
763
0
  proto.len = strlen(proto.s);
764
765
0
  if (evi_param_add_str(list, &e_tcp_c_proto, &proto)) {
766
0
    LM_ERR("unable to add parameter\n");
767
0
    goto end;
768
0
  }
769
770
0
  if (is_tcp_main) {
771
0
    if (evi_dispatch_event(EVI_TCP_DISCONNECT, list)) {
772
0
      LM_ERR("unable to dispatch tcp disconnect event\n");
773
0
    }
774
0
  } else {
775
0
    if (evi_raise_event(EVI_TCP_DISCONNECT, list)) {
776
0
      LM_ERR("unable to send tcp disconnect event\n");
777
0
    }
778
0
  }
779
0
  list = 0;
780
781
0
end:
782
0
  if (list)
783
0
    evi_free_params(list);
784
0
}
785
786
/* convenience macro to aid in shm_free() debugging */
787
#define _tcpconn_rm(c, ne) \
788
0
  do {\
789
0
    __tcpconn_rm(c, ne);\
790
0
    shm_free(c);\
791
0
  } while (0)
792
793
struct tcp_req *tcp_conn_get_req(struct tcp_connection *c)
794
0
{
795
0
  if (!c)
796
0
    return NULL;
797
798
0
  if (c->con_req)
799
0
    return c->con_req;
800
801
0
  c->con_req = thread_malloc(sizeof(*c->con_req));
802
0
  if (!c->con_req) {
803
0
    LM_ERR("failed to allocate TCP request buffer for connection %u\n",
804
0
      c->id);
805
0
    return NULL;
806
0
  }
807
0
  memset(c->con_req, 0, sizeof(*c->con_req));
808
809
0
  return c->con_req;
810
0
}
811
812
void tcp_conn_destroy_req(struct tcp_connection *c)
813
0
{
814
0
  if (!c || !c->con_req)
815
0
    return;
816
817
0
  thread_free(c->con_req);
818
0
  c->con_req = NULL;
819
0
}
820
821
/*! \brief unsafe tcpconn_rm version (nolocks) */
822
static void __tcpconn_rm(struct tcp_connection* c, int no_event)
823
0
{
824
0
  int r;
825
826
0
  if (c->flags & F_CONN_HASHED) {
827
0
    tcpconn_listrm(TCP_PART(c->id).tcpconn_id_hash[c->id_hash], c,
828
0
      id_next, id_prev);
829
    /* remove all the aliases */
830
0
    for (r=0; r<c->aliases; r++)
831
0
      tcpconn_listrm(TCP_PART(c->id).tcpconn_aliases_hash[
832
0
        c->con_aliases[r].hash], &c->con_aliases[r], next, prev);
833
0
    c->flags &= ~F_CONN_HASHED;
834
0
  }
835
0
  lock_destroy(&c->write_lock);
836
837
0
  if (c->async) {
838
0
    for (r = 0; r<c->async->pending; r++)
839
0
      shm_free(c->async->chunks[r]);
840
0
    shm_free(c->async);
841
0
    c->async = NULL;
842
0
  }
843
844
0
  lock_get(tcp_connections_lock);
845
0
  (*tcp_connections_no)--;
846
0
  lock_release(tcp_connections_lock);
847
848
  /* Only TCP main has valid process-private connection state. */
849
0
  if (is_tcp_main) {
850
0
    if (c->proto_req)
851
0
      thread_free(c->proto_req);
852
0
    c->proto_req = NULL;
853
0
    tcp_conn_destroy_req(c);
854
855
0
    if (protos[c->type].net.stream.conn.clean)
856
0
      protos[c->type].net.stream.conn.clean(c);
857
0
  }
858
859
0
  if (!no_event) tcp_disconnect_event_raise(c);
860
861
#ifdef DBG_TCPCON
862
  sh_log(c->hist, TCP_DESTROY, "type=%d", c->type);
863
  sh_unref(c->hist);
864
  c->hist = NULL;
865
#endif
866
867
  /* shm_free(c); -- freed by _tcpconn_rm() */
868
0
}
869
870
/*! \brief add port as an alias for the "id" connection
871
 * \return 0 on success,-1 on failure */
872
int tcpconn_add_alias(struct sip_msg *msg, unsigned int id, int port, int proto)
873
0
{
874
0
  struct tcp_connection* c;
875
0
  unsigned hash;
876
0
  struct tcp_conn_alias* a;
877
878
0
  a=0;
879
  /* fix the port */
880
0
  port=port ? port : protos[proto].default_port ;
881
0
  TCPCONN_LOCK(id);
882
  /* check if alias already exists */
883
0
  c=_tcpconn_find(id);
884
0
  if (c) {
885
0
    if (msg && !(c->profile.alias_mode == TCP_ALIAS_ALWAYS
886
0
                   || (c->profile.alias_mode == TCP_ALIAS_RFC_5923
887
0
                       && msg->via1->alias))) {
888
0
      LM_DBG("refusing to add alias (alias_mode: %u, via 'alias': %u)\n",
889
0
              c->profile.alias_mode, !!msg->via1->alias);
890
0
      TCPCONN_UNLOCK(id);
891
0
      return 0;
892
0
    }
893
894
0
    hash=tcp_addr_hash(&c->rcv.src_ip, port);
895
    /* search the aliases for an already existing one */
896
0
    for (a=TCP_PART(id).tcpconn_aliases_hash[hash]; a; a=a->next) {
897
0
      if (a->parent->state != S_CONN_BAD &&
898
0
          port == a->port &&
899
0
          proto == a->parent->type &&
900
0
          ip_addr_cmp(&c->rcv.src_ip, &a->parent->rcv.src_ip)) {
901
        /* found */
902
0
        if (a->parent!=c) goto error_sec;
903
0
        else goto ok;
904
0
      }
905
0
    }
906
0
    if (c->aliases>=TCP_CON_MAX_ALIASES) goto error_aliases;
907
0
    c->con_aliases[c->aliases].parent=c;
908
0
    c->con_aliases[c->aliases].port=port;
909
0
    c->con_aliases[c->aliases].hash=hash;
910
0
    tcpconn_listadd(TCP_PART(id).tcpconn_aliases_hash[hash],
911
0
                &c->con_aliases[c->aliases], next, prev);
912
0
    c->aliases++;
913
0
  }else goto error_not_found;
914
0
ok:
915
0
  TCPCONN_UNLOCK(id);
916
#ifdef EXTRA_DEBUG
917
  if (a) LM_DBG("alias already present\n");
918
  else   LM_DBG("alias port %d for hash %d, id %u\n", port, hash, id);
919
#endif
920
0
  return 0;
921
0
error_aliases:
922
0
  TCPCONN_UNLOCK(id);
923
0
  LM_ERR("too many aliases for connection %p (%u)\n", c, id);
924
0
  return -1;
925
0
error_not_found:
926
0
  TCPCONN_UNLOCK(id);
927
0
  LM_ERR("no connection found for id %u\n",id);
928
0
  return -1;
929
0
error_sec:
930
0
  LM_WARN("possible port hijack attempt\n");
931
0
  LM_WARN("alias already present and points to another connection "
932
0
      "(%d : %d and %u : %d)\n", a->parent->id,  port, id, port);
933
0
  TCPCONN_UNLOCK(id);
934
0
  return -1;
935
0
}
936
937
938
static void tcpconn_put_rpc(int pid, void *param)
939
0
{
940
0
  tcpconn_put(param);
941
0
}
942
943
944
void tcpconn_put(struct tcp_connection* c)
945
0
{
946
0
  int destroy = 0;
947
0
  int release_in_main = 0;
948
0
  int tcp_main_proc;
949
950
0
  TCPCONN_LOCK(c->id);
951
0
  if ((c->flags & F_CONN_HASHED) == 0) {
952
0
    if (!is_tcp_main && c->refcnt == 1) {
953
      /* Keep the last reference until TCP main accepts ownership. */
954
0
      release_in_main = 1;
955
0
    } else {
956
0
      c->refcnt--;
957
0
      if (c->refcnt == 0)
958
0
        destroy = 1;
959
0
    }
960
0
  } else {
961
    /* Hashed connections are destroyed by TCP main lifetime handling. */
962
0
    c->refcnt--;
963
0
  }
964
0
  TCPCONN_UNLOCK(c->id);
965
966
0
  if (release_in_main) {
967
0
    tcp_main_proc = tcp_get_main_proc_no();
968
0
    if (tcp_main_proc < 0 ||
969
0
        ipc_send_rpc(tcp_main_proc, tcpconn_put_rpc, c) < 0)
970
0
      LM_ERR("failed to release connection %p (%u) in TCP main; "
971
0
        "leaving its final reference intact\n", c, c->id);
972
0
  } else if (destroy) {
973
0
    _tcpconn_rm(c, 1);
974
0
  }
975
0
}
976
977
978
static inline void tcpconn_ref(struct tcp_connection* c)
979
0
{
980
0
  TCPCONN_LOCK(c->id);
981
0
  c->refcnt++;
982
0
  TCPCONN_UNLOCK(c->id);
983
0
}
984
985
986
static inline unsigned int tcpconn_next_id(void)
987
0
{
988
0
  unsigned int id;
989
990
0
  lock_get(connection_id_lock);
991
0
  id = (*connection_id)++;
992
0
  lock_release(connection_id_lock);
993
994
0
  return id;
995
0
}
996
997
998
static struct tcp_connection* tcpconn_new(int sock, const union sockaddr_union* su,
999
                    const struct socket_info* si, const struct tcp_conn_profile *prof,
1000
                    int state, int flags)
1001
0
{
1002
0
  struct tcp_connection *c;
1003
0
  union sockaddr_union local_su;
1004
0
  unsigned int su_size;
1005
0
  int counted = 0;
1006
1007
0
  lock_get(tcp_connections_lock);
1008
0
  if (*tcp_connections_no >= (unsigned int)tcp_max_connections) {
1009
0
    lock_release(tcp_connections_lock);
1010
0
    LM_ERR("maximum number of connections exceeded: %u/%d\n",
1011
0
      *tcp_connections_no, tcp_max_connections);
1012
0
    return 0;
1013
0
  }
1014
0
  (*tcp_connections_no)++;
1015
0
  lock_release(tcp_connections_lock);
1016
0
  counted = 1;
1017
1018
0
  c=(struct tcp_connection*)shm_malloc(sizeof(struct tcp_connection));
1019
0
  if (c==0){
1020
0
    LM_ERR("shared memory allocation failure\n");
1021
0
    goto error_count;
1022
0
  }
1023
0
  memset(c, 0, sizeof(struct tcp_connection)); /* zero init */
1024
0
  c->fd=sock;
1025
0
  if (lock_init(&c->write_lock)==0){
1026
0
    LM_ERR("init lock failed\n");
1027
0
    goto error0;
1028
0
  }
1029
1030
0
  c->rcv.src_su=*su;
1031
1032
0
  c->refcnt=0;
1033
0
  su2ip_addr(&c->rcv.src_ip, su);
1034
0
  c->rcv.src_port=su_getport(su);
1035
0
  c->rcv.bind_address = si;
1036
0
  c->rcv.dst_ip = si->address;
1037
0
  if (sock >= 0) {
1038
0
    su_size = sockaddru_len(*su);
1039
0
    if (getsockname(sock, (struct sockaddr *)&local_su, &su_size)<0) {
1040
0
      LM_ERR("failed to get info on received interface/IP %d/%s\n",
1041
0
        errno, strerror(errno));
1042
0
      goto error;
1043
0
    }
1044
0
    c->rcv.dst_port = su_getport(&local_su);
1045
0
  } else {
1046
0
    c->rcv.dst_port = (si->flags & SI_REUSEPORT) ? su_getport(&si->su) : 0;
1047
0
  }
1048
0
  print_ip("tcpconn_new: new tcp connection to: ", &c->rcv.src_ip, "\n");
1049
0
  LM_DBG("on port %d, proto %d\n", c->rcv.src_port, si->proto);
1050
0
  c->id=tcpconn_next_id();
1051
0
  c->cid = (unsigned long long)c->id
1052
0
        | ( (unsigned long long)(startup_time&0xFFFFFF) << 32 )
1053
0
          | ( (unsigned long long)(rand()&0xFF) << 56 );
1054
1055
0
  c->rcv.proto_reserved1=0; /* this will be filled before receive_message*/
1056
0
  c->rcv.proto_reserved2=0;
1057
0
  c->state=state;
1058
0
  c->extra_data=0;
1059
0
  c->type = si->proto;
1060
0
  c->rcv.proto = si->proto;
1061
  /* start with the default conn lifetime */
1062
0
  c->lifetime = get_ticks() + prof->con_lifetime;
1063
0
  c->timeout = c->lifetime;
1064
0
  c->profile = *prof;
1065
0
  c->flags|=F_CONN_REMOVED|flags;
1066
#ifdef DBG_TCPCON
1067
  c->hist = sh_push(c, con_hist);
1068
#endif
1069
1070
0
  if (protos[si->proto].net.stream.async_chunks) {
1071
0
    c->async = shm_malloc(sizeof(struct tcp_async_data) +
1072
0
        protos[si->proto].net.stream.async_chunks *
1073
0
        sizeof(struct tcp_async_chunk));
1074
0
    if (c->async) {
1075
0
      c->async->allocated = protos[si->proto].net.stream.async_chunks;
1076
0
      c->async->oldest = 0;
1077
0
      c->async->pending = 0;
1078
0
    } else {
1079
0
      LM_ERR("could not allocate async data for con!\n");
1080
0
      goto error;
1081
0
    }
1082
0
  }
1083
0
  if (sock >= 0) {
1084
0
    if (protos[si->proto].net.stream.conn.init &&
1085
0
        protos[si->proto].net.stream.conn.init(c) < 0) {
1086
0
      LM_ERR("failed to do proto %d specific init for conn %p\n",
1087
0
          c->type, c);
1088
0
      goto error;
1089
0
    }
1090
0
    c->flags |= F_CONN_INIT;
1091
0
  }
1092
0
  return c;
1093
1094
0
error:
1095
0
  lock_destroy(&c->write_lock);
1096
0
error0:
1097
0
  shm_free(c);
1098
0
error_count:
1099
0
  if (counted) {
1100
0
    lock_get(tcp_connections_lock);
1101
0
    (*tcp_connections_no)--;
1102
0
    lock_release(tcp_connections_lock);
1103
0
  }
1104
0
  return 0;
1105
0
}
1106
1107
1108
/* creates a new tcp connection structure
1109
 * for an outgoing connection request; local private state is initialized later
1110
 * a +1 ref is set for the new conn !
1111
 * IMPORTANT - the function assumes you want to create a new TCP conn as
1112
 * a result of a connect operation - the conn will be set as connect !!
1113
 * Accepted connection are triggered internally only */
1114
struct tcp_connection* tcp_conn_create(const union sockaddr_union* su,
1115
    const struct socket_info* si, struct tcp_conn_profile *prof,
1116
    int state)
1117
0
{
1118
0
  struct tcp_connection *c;
1119
0
  struct tcp_conn_profile default_prof;
1120
1121
0
  if (!prof) {
1122
0
    tcp_con_get_profile(su, &si->su, si->proto, &default_prof);
1123
0
    prof = &default_prof;
1124
0
  }
1125
1126
  /* create the connection structure */
1127
0
  c = tcpconn_new(-1, su, si, prof, state, 0);
1128
0
  if (c==NULL) {
1129
0
    LM_ERR("tcpconn_new failed\n");
1130
0
    return NULL;
1131
0
  }
1132
1133
0
  c->refcnt++; /* safe to do it w/o locking, it's not yet
1134
          available to the rest of the world */
1135
0
  sh_log(c->hist, TCP_REF, "connect, (%d)", c->refcnt);
1136
0
  return c;
1137
0
}
1138
1139
1140
static inline void tcpconn_destroy(struct tcp_connection* tcpconn)
1141
0
{
1142
0
  int fd;
1143
0
  int unsigned id = tcpconn->id;
1144
0
  int hashed;
1145
1146
0
  TCPCONN_LOCK(id); /*avoid races w/ tcp_send*/
1147
0
  tcpconn->refcnt--;
1148
0
  if (tcpconn->refcnt==0){
1149
0
    LM_DBG("destroying connection %p, flags %04x\n",
1150
0
        tcpconn, tcpconn->flags);
1151
0
    fd=tcpconn->fd;
1152
    /* no reporting here - the tcpconn_destroy() function is called
1153
     * from the TCP_MAIN reactor when handling connectioned received
1154
     * from a worker; and we generate the CLOSE reports from WORKERs */
1155
0
    hashed = (tcpconn->flags & F_CONN_HASHED);
1156
0
    _tcpconn_rm(tcpconn, hashed ? 0 : 1);
1157
0
    if (fd >= 0)
1158
0
      close(fd);
1159
0
  }else{
1160
    /* force timeout */
1161
0
    tcpconn->lifetime=0;
1162
0
    tcpconn->timeout=0;
1163
0
    tcpconn->state=S_CONN_BAD;
1164
0
    sh_log(tcpconn->hist, TCP_DEL_DELAY, "tcpconn_destroy delayed, (%d)",
1165
0
      tcpconn->refcnt);
1166
0
    LM_DBG("delaying (%p, flags %04x) ref = %d ...\n",
1167
0
        tcpconn, tcpconn->flags, tcpconn->refcnt);
1168
1169
0
  }
1170
0
  TCPCONN_UNLOCK(id);
1171
0
}
1172
1173
static void tcpconn_destroy_rpc(int _, void *param)
1174
0
{
1175
0
  tcpconn_destroy(param);
1176
0
}
1177
1178
/* wrapper to the internally used function */
1179
void tcp_conn_destroy(struct tcp_connection* tcpconn)
1180
0
{
1181
0
  int tcp_main_proc;
1182
1183
0
  tcp_trigger_report(tcpconn, TCP_REPORT_CLOSE,
1184
0
        "Closed by Proto layer");
1185
0
  sh_log(tcpconn->hist, TCP_UNREF, "tcp_conn_destroy, (%d)", tcpconn->refcnt);
1186
1187
0
  if (!is_tcp_main) {
1188
0
    tcp_main_proc = tcp_get_main_proc_no();
1189
0
    if (tcp_main_proc < 0 ||
1190
0
        ipc_send_rpc(tcp_main_proc, tcpconn_destroy_rpc, tcpconn) < 0)
1191
0
      LM_ERR("failed to destroy connection %p (%u) in TCP main; "
1192
0
        "leaving its reference intact\n", tcpconn, tcpconn->id);
1193
0
    return;
1194
0
  }
1195
1196
0
  tcpconn_destroy(tcpconn);
1197
0
}
1198
1199
static inline int tcp_set_nonblock(int fd)
1200
0
{
1201
0
  int flags;
1202
1203
0
  flags = fcntl(fd, F_GETFL);
1204
0
  if (flags == -1) {
1205
0
    LM_ERR("fcntl(F_GETFL) failed for %d: %s\n", fd, strerror(errno));
1206
0
    return -1;
1207
0
  }
1208
1209
0
  if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
1210
0
    LM_ERR("fcntl(F_SETFL) failed for %d: %s\n", fd, strerror(errno));
1211
0
    return -1;
1212
0
  }
1213
1214
0
  return 0;
1215
0
}
1216
1217
static void tcp_push_done_job(struct tcp_job *job)
1218
0
{
1219
0
  pthread_mutex_lock(&tcp_pool.done_lock);
1220
0
  if (tcp_pool.done_tail)
1221
0
    tcp_pool.done_tail->next = job;
1222
0
  else
1223
0
    tcp_pool.done_head = job;
1224
0
  tcp_pool.done_tail = job;
1225
0
  pthread_mutex_unlock(&tcp_pool.done_lock);
1226
0
}
1227
1228
static struct tcp_job *tcp_pop_done_job(void)
1229
0
{
1230
0
  struct tcp_job *job;
1231
1232
0
  pthread_mutex_lock(&tcp_pool.done_lock);
1233
0
  job = tcp_pool.done_head;
1234
0
  if (job) {
1235
0
    tcp_pool.done_head = job->next;
1236
0
    if (tcp_pool.done_head == NULL)
1237
0
      tcp_pool.done_tail = NULL;
1238
0
  }
1239
0
  pthread_mutex_unlock(&tcp_pool.done_lock);
1240
1241
0
  return job;
1242
0
}
1243
1244
static inline struct tcp_connection *tcp_pop_shared_write_conn_locked(void)
1245
0
{
1246
0
  struct tcp_connection *conn;
1247
1248
0
  conn = tcp_write_queue->head;
1249
0
  if (conn) {
1250
0
    tcp_write_queue->head = conn->wq_next;
1251
0
    if (tcp_write_queue->head == NULL)
1252
0
      tcp_write_queue->tail = NULL;
1253
0
    conn->wq_next = NULL;
1254
0
  }
1255
1256
0
  return conn;
1257
0
}
1258
1259
static void *tcp_thread_routine(void *arg)
1260
0
{
1261
0
  struct tcp_job *job;
1262
0
  struct tcp_connection *conn;
1263
0
  char wake = 'x';
1264
0
  int rc;
1265
1266
0
  (void)arg;
1267
1268
  /* Reactor operations stay in TCP main; IO threads only run read/write
1269
   * callbacks and notify completion back to the main thread. */
1270
0
  while (1) {
1271
0
    cond_lock(&tcp_write_queue->cond);
1272
0
    while (!tcp_pool.stop && tcp_pool.task_head == NULL &&
1273
0
        tcp_write_queue->head == NULL)
1274
0
      cond_wait(&tcp_write_queue->cond);
1275
1276
0
    if (tcp_pool.stop && tcp_pool.task_head == NULL &&
1277
0
        tcp_write_queue->head == NULL) {
1278
0
      cond_unlock(&tcp_write_queue->cond);
1279
0
      break;
1280
0
    }
1281
1282
0
    job = tcp_pool.task_head;
1283
0
    if (job) {
1284
0
      tcp_pool.task_head = job->next;
1285
0
      if (tcp_pool.task_head == NULL)
1286
0
        tcp_pool.task_tail = NULL;
1287
0
    } else if ((conn = tcp_pop_shared_write_conn_locked()) != NULL) {
1288
0
      job = thread_malloc(sizeof(*job));
1289
0
      if (!job) {
1290
0
        LM_ERR("oom while building shared TCP write job\n");
1291
0
        conn->flags &= ~F_CONN_WRITE_QUEUED;
1292
0
        cond_unlock(&tcp_write_queue->cond);
1293
0
        tcpconn_put(conn);
1294
0
        continue;
1295
0
      }
1296
0
      job->conn = conn;
1297
0
      job->op = TCP_WRITE_JOB;
1298
0
      job->run = NULL;
1299
0
      job->data = NULL;
1300
0
      job->resp = 0;
1301
0
      job->ret = 0;
1302
0
      job->next = NULL;
1303
0
    }
1304
0
    cond_unlock(&tcp_write_queue->cond);
1305
1306
0
    conn = job->conn;
1307
0
    if (job->op == TCP_READ_JOB) {
1308
0
      if (conn->msg_attempts && get_ticks() > conn->timeout) {
1309
0
        job->ret = -1;
1310
0
        job->resp = -2;
1311
0
      } else if (protos[conn->type].net.stream.read) {
1312
0
        job->resp = protos[conn->type].net.stream.read(conn, &job->ret);
1313
0
      } else {
1314
0
        LM_ERR("missing stream.read callback for proto %d\n", conn->type);
1315
0
        job->ret = -1;
1316
0
        job->resp = -1;
1317
0
      }
1318
0
    } else if (job->op == TCP_WRITE_JOB) {
1319
0
      if (protos[conn->type].net.stream.write) {
1320
0
        if (tcpconn_prepare_write(conn) < 0) {
1321
0
          job->ret = -1;
1322
0
          job->resp = -1;
1323
0
          goto done_job;
1324
0
        }
1325
0
        lock_get(&conn->write_lock);
1326
0
        job->resp = protos[conn->type].net.stream.write(conn, conn->fd);
1327
0
        lock_release(&conn->write_lock);
1328
0
        job->ret = (job->resp < 0) ? -1 : 0;
1329
0
      } else {
1330
0
        LM_ERR("missing stream.write callback for proto %d\n", conn->type);
1331
0
        job->ret = -1;
1332
0
        job->resp = -1;
1333
0
      }
1334
0
    } else if (job->op == TCP_RUN_JOB) {
1335
0
      job->ret = job->run ? job->run(job->data) : -1;
1336
0
      thread_free(job);
1337
0
      continue;
1338
0
    } else {
1339
0
      LM_ERR("unknown TCP job op %d\n", job->op);
1340
0
      job->ret = -1;
1341
0
      job->resp = -1;
1342
0
    }
1343
1344
0
done_job:
1345
0
    job->next = NULL;
1346
0
    tcp_push_done_job(job);
1347
1348
0
    rc = write(tcp_pool.notify_pipe[1], &wake, 1);
1349
0
    if (rc < 0 && errno != EAGAIN && errno != EWOULDBLOCK)
1350
0
      LM_ERR("failed to notify TCP IO completion: %s\n", strerror(errno));
1351
0
  }
1352
1353
0
  return NULL;
1354
0
}
1355
1356
static int tcp_pool_init(void)
1357
0
{
1358
0
  int i;
1359
0
  int started = 0;
1360
0
  int threads_no;
1361
0
  long cpu_no;
1362
1363
0
  if (tcp_threads > 0)
1364
0
    threads_no = tcp_threads;
1365
0
  else {
1366
0
    cpu_no = sysconf(_SC_NPROCESSORS_ONLN);
1367
0
    if (cpu_no > 0)
1368
0
      threads_no = (int)cpu_no;
1369
0
    else if (tcp_workers_no > 0)
1370
0
      threads_no = tcp_workers_no;
1371
0
    else
1372
0
      threads_no = 1;
1373
0
  }
1374
1375
0
  if (pipe(tcp_pool.notify_pipe) < 0) {
1376
0
    LM_ERR("failed to create TCP IO notification pipe: %s\n", strerror(errno));
1377
0
    goto error;
1378
0
  }
1379
1380
0
  if (tcp_set_nonblock(tcp_pool.notify_pipe[0]) < 0 ||
1381
0
      tcp_set_nonblock(tcp_pool.notify_pipe[1]) < 0)
1382
0
    goto error;
1383
1384
0
  if (reactor_add_reader(tcp_pool.notify_pipe[0],
1385
0
    F_TCP_NOTIFY, RCT_PRIO_PROC, NULL) < 0) {
1386
0
    LM_ERR("failed to add TCP IO notify pipe to reactor\n");
1387
0
    goto error;
1388
0
  }
1389
1390
0
  tcp_pool.threads = pkg_malloc(sizeof(*tcp_pool.threads) * threads_no);
1391
0
  if (!tcp_pool.threads) {
1392
0
    LM_ERR("oom while allocating TCP IO threads array\n");
1393
0
    goto error;
1394
0
  }
1395
1396
0
  tcp_pool.stop = 0;
1397
0
  tcp_pool.threads_no = threads_no;
1398
1399
0
  for (i = 0; i < threads_no; i++) {
1400
0
    if (pthread_create(&tcp_pool.threads[i], NULL,
1401
0
        tcp_thread_routine, NULL) != 0) {
1402
0
      LM_ERR("failed to start TCP IO thread %d/%d\n", i + 1, threads_no);
1403
0
      goto error;
1404
0
    }
1405
0
    started++;
1406
0
  }
1407
1408
0
  LM_NOTICE("TCP single IO mode started with %d threads\n", threads_no);
1409
0
  return 0;
1410
1411
0
error:
1412
0
  cond_lock(&tcp_write_queue->cond);
1413
0
  tcp_pool.stop = 1;
1414
0
  cond_broadcast(&tcp_write_queue->cond);
1415
0
  cond_unlock(&tcp_write_queue->cond);
1416
1417
0
  if (tcp_pool.threads) {
1418
0
    for (i = 0; i < started; i++)
1419
0
      pthread_join(tcp_pool.threads[i], NULL);
1420
0
    pkg_free(tcp_pool.threads);
1421
0
    tcp_pool.threads = NULL;
1422
0
  }
1423
0
  tcp_pool.threads_no = 0;
1424
1425
0
  if (tcp_pool.notify_pipe[0] >= 0) {
1426
0
    reactor_del_reader(tcp_pool.notify_pipe[0], -1, 0);
1427
0
    close(tcp_pool.notify_pipe[0]);
1428
0
    tcp_pool.notify_pipe[0] = -1;
1429
0
  }
1430
0
  if (tcp_pool.notify_pipe[1] >= 0) {
1431
0
    close(tcp_pool.notify_pipe[1]);
1432
0
    tcp_pool.notify_pipe[1] = -1;
1433
0
  }
1434
1435
0
  return -1;
1436
0
}
1437
1438
static void tcp_pool_destroy(void)
1439
0
{
1440
0
  int i;
1441
0
  struct tcp_job *job;
1442
0
  struct tcp_job *next;
1443
0
  struct tcp_connection *conn;
1444
1445
0
  if (!tcp_threads_active() && tcp_pool.notify_pipe[0] < 0)
1446
0
    return;
1447
1448
0
  cond_lock(&tcp_write_queue->cond);
1449
0
  tcp_pool.stop = 1;
1450
0
  cond_broadcast(&tcp_write_queue->cond);
1451
0
  cond_unlock(&tcp_write_queue->cond);
1452
1453
0
  for (i = 0; i < tcp_pool.threads_no; i++)
1454
0
    pthread_join(tcp_pool.threads[i], NULL);
1455
1456
0
  if (tcp_pool.threads) {
1457
0
    pkg_free(tcp_pool.threads);
1458
0
    tcp_pool.threads = NULL;
1459
0
  }
1460
0
  tcp_pool.threads_no = 0;
1461
1462
0
  if (tcp_pool.notify_pipe[0] >= 0) {
1463
0
    reactor_del_reader(tcp_pool.notify_pipe[0], -1, 0);
1464
0
    close(tcp_pool.notify_pipe[0]);
1465
0
    tcp_pool.notify_pipe[0] = -1;
1466
0
  }
1467
0
  if (tcp_pool.notify_pipe[1] >= 0) {
1468
0
    close(tcp_pool.notify_pipe[1]);
1469
0
    tcp_pool.notify_pipe[1] = -1;
1470
0
  }
1471
1472
0
  cond_lock(&tcp_write_queue->cond);
1473
0
  for (job = tcp_pool.task_head; job; job = next) {
1474
0
    next = job->next;
1475
0
    if (job->conn)
1476
0
      tcpconn_put(job->conn);
1477
0
    thread_free(job);
1478
0
  }
1479
0
  tcp_pool.task_head = tcp_pool.task_tail = NULL;
1480
0
  while ((conn = tcp_pop_shared_write_conn_locked()) != NULL) {
1481
0
    conn->flags &= ~F_CONN_WRITE_QUEUED;
1482
0
    tcpconn_put(conn);
1483
0
  }
1484
0
  cond_unlock(&tcp_write_queue->cond);
1485
1486
0
  pthread_mutex_lock(&tcp_pool.done_lock);
1487
0
  for (job = tcp_pool.done_head; job; job = next) {
1488
0
    next = job->next;
1489
0
    if (job->conn)
1490
0
      tcpconn_put(job->conn);
1491
0
    thread_free(job);
1492
0
  }
1493
0
  tcp_pool.done_head = tcp_pool.done_tail = NULL;
1494
0
  pthread_mutex_unlock(&tcp_pool.done_lock);
1495
0
}
1496
1497
static int tcp_queue_job(struct tcp_connection *tcpconn, int op)
1498
0
{
1499
0
  struct tcp_job *job;
1500
1501
0
  if (!tcp_threads_active())
1502
0
    return -1;
1503
1504
0
  job = thread_malloc(sizeof(*job));
1505
0
  if (!job) {
1506
0
    LM_ERR("oom while queuing TCP IO job\n");
1507
0
    return -1;
1508
0
  }
1509
1510
0
  job->conn = tcpconn;
1511
0
  job->op = op;
1512
0
  job->run = NULL;
1513
0
  job->data = NULL;
1514
0
  job->resp = 0;
1515
0
  job->ret = 0;
1516
0
  job->next = NULL;
1517
1518
0
  cond_lock(&tcp_write_queue->cond);
1519
0
  if (tcp_pool.task_tail)
1520
0
    tcp_pool.task_tail->next = job;
1521
0
  else
1522
0
    tcp_pool.task_head = job;
1523
0
  tcp_pool.task_tail = job;
1524
0
  cond_signal(&tcp_write_queue->cond);
1525
0
  cond_unlock(&tcp_write_queue->cond);
1526
1527
0
  return 0;
1528
0
}
1529
1530
int tcp_async_write_job(struct tcp_connection *tcpconn)
1531
0
{
1532
0
  if (!tcp_write_queue)
1533
0
    return -1;
1534
0
  if ((tcpconn->flags & F_CONN_HASHED) == 0)
1535
0
    tcpconn_add(tcpconn);
1536
1537
0
  cond_lock(&tcp_write_queue->cond);
1538
0
  if (tcpconn->flags & F_CONN_WRITE_QUEUED) {
1539
0
    cond_unlock(&tcp_write_queue->cond);
1540
    /* a write job is already queued for this connection and it owns
1541
     * exactly one reference, which it releases on completion; our
1542
     * callers treat success as a transfer of their own reference, so
1543
     * it has to be released here, otherwise it leaks and the
1544
     * connection can never be destroyed */
1545
0
    tcpconn_put(tcpconn);
1546
0
    return 0;
1547
0
  }
1548
1549
0
  tcpconn->flags |= F_CONN_WRITE_QUEUED;
1550
0
  tcpconn->wq_next = NULL;
1551
0
  if (tcp_write_queue->tail)
1552
0
    tcp_write_queue->tail->wq_next = tcpconn;
1553
0
  else
1554
0
    tcp_write_queue->head = tcpconn;
1555
0
  tcp_write_queue->tail = tcpconn;
1556
0
  cond_signal(&tcp_write_queue->cond);
1557
0
  cond_unlock(&tcp_write_queue->cond);
1558
0
  return 0;
1559
0
}
1560
1561
int tcp_run_task(tcp_thread_job_f run, void *data)
1562
0
{
1563
0
  struct tcp_job *job;
1564
1565
0
  if (!run)
1566
0
    return -1;
1567
1568
0
  if (!tcp_threads_active()) {
1569
0
    run(data);
1570
0
    return 0;
1571
0
  }
1572
1573
0
  job = thread_malloc(sizeof(*job));
1574
0
  if (!job) {
1575
0
    LM_ERR("oom while queuing TCP run job\n");
1576
0
    return -1;
1577
0
  }
1578
1579
0
  job->conn = NULL;
1580
0
  job->op = TCP_RUN_JOB;
1581
0
  job->run = run;
1582
0
  job->data = data;
1583
0
  job->resp = 0;
1584
0
  job->ret = -1;
1585
0
  job->next = NULL;
1586
1587
0
  cond_lock(&tcp_write_queue->cond);
1588
0
  if (tcp_pool.task_tail)
1589
0
    tcp_pool.task_tail->next = job;
1590
0
  else
1591
0
    tcp_pool.task_head = job;
1592
0
  tcp_pool.task_tail = job;
1593
0
  cond_signal(&tcp_write_queue->cond);
1594
0
  cond_unlock(&tcp_write_queue->cond);
1595
1596
0
  return 0;
1597
0
}
1598
1599
static inline int tcp_queue_write_job(struct tcp_connection *tcpconn)
1600
0
{
1601
0
  if (!(tcpconn->flags & F_CONN_REMOVED_READ) && tcpconn->fd != -1) {
1602
0
    if (reactor_del_reader(tcpconn->fd, -1, 0) == -1)
1603
0
      return -1;
1604
0
    tcpconn->flags |= F_CONN_REMOVED_READ;
1605
0
  }
1606
1607
0
  if (tcp_async_write_job(tcpconn) < 0)
1608
0
    return -1;
1609
1610
0
  return 0;
1611
0
}
1612
1613
static inline void tcp_fail_conn(struct tcp_connection *tcpconn,
1614
    const char *reason, int report)
1615
0
{
1616
0
  if ((tcpconn->flags & F_CONN_REMOVED) != F_CONN_REMOVED &&
1617
0
      tcpconn->fd != -1) {
1618
0
    reactor_del_all(tcpconn->fd, -1, IO_FD_CLOSING);
1619
0
    tcpconn->flags |= F_CONN_REMOVED;
1620
0
  }
1621
1622
0
  if (report)
1623
0
    tcp_trigger_report(tcpconn, TCP_REPORT_CLOSE, (void *)reason);
1624
1625
0
  tcpconn_destroy(tcpconn);
1626
0
}
1627
1628
static inline void tcp_complete_read(struct tcp_job *job)
1629
0
{
1630
0
  struct tcp_connection *tcpconn;
1631
1632
0
  tcpconn = job->conn;
1633
1634
0
  if (job->resp == -2) {
1635
0
    tcp_fail_conn(tcpconn, "Timeout waiting for a complete message", 1);
1636
0
    return;
1637
0
  }
1638
1639
0
  if (job->resp < 0 || tcpconn->state == S_CONN_BAD) {
1640
0
    tcp_fail_conn(tcpconn, "Read error", 1);
1641
0
    return;
1642
0
  }
1643
1644
0
  if (tcpconn->state == S_CONN_EOF) {
1645
0
    tcp_fail_conn(tcpconn, "EOF received", 1);
1646
0
    return;
1647
0
  }
1648
1649
0
  if (tcpconn->flags & F_CONN_REMOVED_READ) {
1650
0
    if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET, tcpconn) < 0) {
1651
0
      LM_ERR("failed to re-add TCP conn %p for read events\n", tcpconn);
1652
0
      tcp_fail_conn(tcpconn, "Failed to re-arm read", 0);
1653
0
      return;
1654
0
    }
1655
0
    tcpconn->flags &= ~F_CONN_REMOVED_READ;
1656
0
  }
1657
1658
0
  tcpconn_put(tcpconn);
1659
0
}
1660
1661
static inline void tcp_complete_write(struct tcp_job *job)
1662
0
{
1663
0
  struct tcp_connection *tcpconn;
1664
0
  int pending_chunks;
1665
1666
0
  tcpconn = job->conn;
1667
1668
0
  if (job->resp < 0 || tcpconn->state == S_CONN_BAD) {
1669
0
    tcp_fail_conn(tcpconn, "Write error", 1);
1670
0
    return;
1671
0
  }
1672
1673
0
  lock_get(&tcpconn->write_lock);
1674
0
  pending_chunks = (tcpconn->async && tcpconn->async->pending);
1675
0
  lock_release(&tcpconn->write_lock);
1676
1677
0
  if ((tcpconn->flags & F_CONN_REMOVED_READ) && tcpconn->fd != -1) {
1678
0
    if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1679
0
        tcpconn) < 0) {
1680
0
      LM_ERR("failed to add TCP conn %p for read events\n", tcpconn);
1681
0
      tcp_fail_conn(tcpconn, "Failed to arm read", 0);
1682
0
      return;
1683
0
    }
1684
0
    tcpconn->flags &= ~F_CONN_REMOVED_READ;
1685
0
  }
1686
1687
0
  if (job->resp == 1) {
1688
0
    if (reactor_add_writer(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET, tcpconn) < 0) {
1689
0
      LM_ERR("failed to re-add TCP conn %p for write events\n", tcpconn);
1690
0
      tcp_fail_conn(tcpconn, "Failed to re-arm write", 0);
1691
0
      return;
1692
0
    }
1693
0
    tcpconn->flags &= ~F_CONN_REMOVED_WRITE;
1694
0
    tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1695
0
    tcpconn_put(tcpconn);
1696
0
    return;
1697
0
  }
1698
1699
0
  if (pending_chunks) {
1700
0
    tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1701
0
    if (tcp_async_write_job(tcpconn) < 0) {
1702
0
      LM_ERR("failed queuing follow-up TCP write job\n");
1703
0
      tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1704
0
      if (reactor_add_writer(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET, tcpconn) < 0) {
1705
0
        tcp_fail_conn(tcpconn, "Failed queueing follow-up write", 0);
1706
0
        return;
1707
0
      }
1708
0
      tcpconn->flags &= ~F_CONN_REMOVED_WRITE;
1709
0
      tcpconn_put(tcpconn);
1710
0
    }
1711
0
    return;
1712
0
  }
1713
1714
0
  tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1715
0
  tcpconn_put(tcpconn);
1716
0
}
1717
1718
static inline int handle_tcp_notify(int fd)
1719
0
{
1720
0
  char buf[64];
1721
0
  int n;
1722
0
  struct tcp_job *job;
1723
1724
0
  while ((n = read(fd, buf, sizeof(buf))) > 0)
1725
0
    ;
1726
0
  if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)
1727
0
    LM_ERR("failed to read TCP IO notify fd: %s\n", strerror(errno));
1728
1729
0
  while ((job = tcp_pop_done_job()) != NULL) {
1730
0
    if (job->op == TCP_READ_JOB)
1731
0
      tcp_complete_read(job);
1732
0
    else
1733
0
      tcp_complete_write(job);
1734
0
    thread_free(job);
1735
0
  }
1736
1737
0
  return 0;
1738
0
}
1739
1740
1741
/************************ TCP MAIN process functions ************************/
1742
1743
/*! \brief
1744
 * handles a new connection, called internally by tcp_main_loop/handle_io.
1745
 * \param si - pointer to one of the tcp socket_info structures on which
1746
 *              an io event was detected (connection attempt)
1747
 * \return  handle_* return convention: -1 on error, 0 on EAGAIN (no more
1748
 *           io events queued), >0 on success. success/error refer only to
1749
 *           the accept.
1750
 */
1751
static inline int handle_new_connect(const struct socket_info* si)
1752
0
{
1753
0
  union sockaddr_union su;
1754
0
  struct tcp_connection* tcpconn;
1755
0
  struct tcp_conn_profile prof;
1756
0
  socklen_t su_len = sizeof(su);
1757
0
  int new_sock;
1758
0
  unsigned int id;
1759
1760
  /* coverity[overrun-buffer-arg: FALSE] - union has 28 bytes, CID #200070 */
1761
0
  new_sock = accept(si->socket, &(su.s), &su_len);
1762
0
  if (new_sock == -1) {
1763
0
    if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
1764
0
      return 0;
1765
0
    LM_ERR("failed to accept connection(%d): %s\n", errno, strerror(errno));
1766
0
    return -1;
1767
0
  }
1768
1769
0
  tcp_con_get_profile(&su, &si->su, si->proto, &prof);
1770
0
  if (tcp_init_sock_opt(new_sock, &prof, si->flags, si->tos) < 0) {
1771
0
    LM_ERR("tcp_init_sock_opt failed\n");
1772
0
    close(new_sock);
1773
0
    return 1; /* success, because the accept was successful */
1774
0
  }
1775
1776
  /* add socket to list */
1777
0
  tcpconn = tcpconn_new(new_sock, &su, si, &prof, S_CONN_OK,
1778
0
    F_CONN_ACCEPTED);
1779
0
  if (tcpconn) {
1780
    /* Safe: the connection is not yet visible outside TCP main. */
1781
0
    tcpconn->refcnt++;
1782
0
    sh_log(tcpconn->hist, TCP_REF, "accept, (%d)", tcpconn->refcnt);
1783
0
    tcpconn_add(tcpconn);
1784
0
    LM_DBG("new connection: %p %d flags: %04x\n",
1785
0
      tcpconn, tcpconn->fd, tcpconn->flags);
1786
0
    if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1787
0
        tcpconn) < 0) {
1788
0
      LM_ERR("failed to add accepted TCP conn to reactor\n");
1789
0
      id = tcpconn->id;
1790
0
      TCPCONN_LOCK(id);
1791
0
      tcpconn->refcnt--;
1792
0
      if (tcpconn->refcnt == 0) {
1793
0
        _tcpconn_rm(tcpconn, 1);
1794
0
        close(new_sock);
1795
0
      } else {
1796
0
        tcpconn->lifetime = 0;
1797
0
        tcpconn->timeout = 0;
1798
0
      }
1799
0
      TCPCONN_UNLOCK(id);
1800
0
    } else {
1801
0
      tcpconn->flags &= ~F_CONN_REMOVED_READ;
1802
0
      tcpconn_put(tcpconn);
1803
0
    }
1804
0
  } else {
1805
0
    LM_ERR("tcpconn_new failed, closing socket\n");
1806
0
    close(new_sock);
1807
0
  }
1808
0
  return 1; /* accept() was successful */
1809
0
}
1810
1811
1812
/*! \brief
1813
 * handles an io event on one of the watched tcp connections
1814
 *
1815
 * \param    tcpconn - pointer to the tcp_connection for which we have an io ev.
1816
 * \param    fd_i    - index in the fd_array table (needed for delete)
1817
 * \return   handle_* return convention, but on success it always returns 0
1818
 */
1819
inline static int handle_tcpconn_ev(struct tcp_connection* tcpconn, int fd_i,
1820
    int event_type)
1821
0
{
1822
0
  int err;
1823
0
  unsigned int err_len;
1824
1825
0
  if (event_type == IO_WATCH_READ) {
1826
0
    LM_DBG("data available on %p %d\n", tcpconn, tcpconn->fd);
1827
0
    if (reactor_del_reader(tcpconn->fd, fd_i, 0) == -1)
1828
0
      return -1;
1829
0
    tcpconn->flags |= F_CONN_REMOVED_READ;
1830
0
    tcpconn_ref(tcpconn); /* refcnt ++ */
1831
0
    sh_log(tcpconn->hist, TCP_REF, "tcp-main read queued, (%d)",
1832
0
      tcpconn->refcnt);
1833
0
    if (tcp_queue_job(tcpconn, TCP_READ_JOB) < 0) {
1834
0
      LM_ERR("failed queuing TCP read job\n");
1835
0
      if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1836
0
          tcpconn) < 0) {
1837
0
        tcp_fail_conn(tcpconn, "Failed queueing read", 0);
1838
0
        return 0;
1839
0
      }
1840
0
      tcpconn->flags &= ~F_CONN_REMOVED_READ;
1841
0
      tcpconn_put(tcpconn);
1842
0
    }
1843
0
    return 0;
1844
0
  } else {
1845
0
    LM_DBG("connection %p fd %d is now writable\n", tcpconn, tcpconn->fd);
1846
    /* we received a write event */
1847
0
    if (tcpconn->state == S_CONN_CONNECTING) {
1848
      /* we're coming from an async connect & write
1849
       * let's see if we connected successfully */
1850
0
      err_len = sizeof(err);
1851
0
      if (getsockopt(tcpconn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len) < 0 ||
1852
0
          err != 0) {
1853
0
        LM_DBG("Failed connection attempt\n");
1854
0
        tcpconn_ref(tcpconn);
1855
0
        sh_log(tcpconn->hist, TCP_REF, "tcpconn connect, (%d)", tcpconn->refcnt);
1856
0
        reactor_del_all(tcpconn->fd, fd_i, IO_FD_CLOSING);
1857
0
        tcpconn->flags|=F_CONN_REMOVED;
1858
0
        tcp_trigger_report(tcpconn, TCP_REPORT_CLOSE,
1859
0
          "Async connect failed");
1860
0
        sh_log(tcpconn->hist, TCP_UNREF, "tcpconn connect, (%d)", tcpconn->refcnt);
1861
0
        tcpconn_destroy(tcpconn);
1862
0
        return 0;
1863
0
      }
1864
1865
      /* we successfully connected - further treat this case as if we
1866
       * were coming from an async write */
1867
0
      tcpconn->state = S_CONN_OK;
1868
0
      LM_DBG("Successfully completed previous async connect\n");
1869
1870
      /* now that we completed the async connection, we also need to
1871
       * listen for READ events, otherwise these will get lost */
1872
0
      if (tcpconn->flags & F_CONN_REMOVED_READ) {
1873
0
        if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1874
0
            tcpconn) < 0) {
1875
0
          LM_ERR("failed to re-arm TCP conn %p for read events\n",
1876
0
            tcpconn);
1877
0
          tcp_fail_conn(tcpconn, "Failed to re-arm read", 0);
1878
0
          return 0;
1879
0
        }
1880
0
        tcpconn->flags &= ~F_CONN_REMOVED_READ;
1881
0
      }
1882
1883
0
      goto async_write;
1884
0
    } else {
1885
0
async_write:
1886
      /* no more write events for now */
1887
0
        if (reactor_del_writer(tcpconn->fd, fd_i, 0) == -1)
1888
0
          return -1;
1889
0
      tcpconn->flags |= F_CONN_REMOVED_WRITE;
1890
0
      tcpconn_ref(tcpconn); /* refcnt ++ */
1891
0
      sh_log(tcpconn->hist, TCP_REF, "tcpconn write, (%d)",
1892
0
        tcpconn->refcnt);
1893
0
      if (tcp_queue_write_job(tcpconn) < 0) {
1894
0
        LM_ERR("failed queuing TCP write job\n");
1895
0
        if (reactor_add_writer(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1896
0
            tcpconn) < 0) {
1897
0
          tcp_fail_conn(tcpconn, "Failed queueing write", 0);
1898
0
          return 0;
1899
0
        }
1900
0
        tcpconn->flags &= ~F_CONN_REMOVED_WRITE;
1901
0
        tcpconn_put(tcpconn);
1902
0
      }
1903
0
      return 0;
1904
0
    }
1905
0
  }
1906
0
}
1907
1908
1909
/*! \brief generic handle io routine, it will call the appropiate
1910
 *  handle_xxx() based on the fd_map type
1911
 *
1912
 * \param  fm  - pointer to a fd hash entry
1913
 * \param  idx - index in the fd_array (or -1 if not known)
1914
 * \return -1 on error
1915
 *          0 on EAGAIN or when by some other way it is known that no more
1916
 *            io events are queued on the fd (the receive buffer is empty).
1917
 *            Usefull to detect when there are no more io events queued for
1918
 *            sigio_rt, epoll_et, kqueue.
1919
 *         >0 on successful read from the fd (when there might be more io
1920
 *            queued -- the receive buffer might still be non-empty)
1921
 */
1922
inline static int handle_io(struct fd_map* fm, int idx,int event_type)
1923
0
{
1924
0
  int ret = 0;
1925
1926
0
  pt_become_active();
1927
  /* for now we do not do any profiling here as all ops here are
1928
     only internals related to TCP passing beetween processing, no real
1929
     processing
1930
   */
1931
0
  switch(fm->type){
1932
0
    case F_TCP_LISTENER:
1933
0
      ret = handle_new_connect((const struct socket_info*)fm->data);
1934
0
      break;
1935
0
    case F_TCPCONN:
1936
0
      ret = handle_tcpconn_ev((struct tcp_connection*)fm->data, idx,
1937
0
        event_type);
1938
0
      break;
1939
0
    case F_TCP_NOTIFY:
1940
0
      ret = handle_tcp_notify(fm->fd);
1941
0
      break;
1942
0
    case F_IPC:
1943
0
      ipc_handle_job(fm->fd);
1944
0
      break;
1945
0
    case F_NONE:
1946
0
      LM_CRIT("empty fd map\n");
1947
0
      goto error;
1948
0
    default:
1949
0
      LM_CRIT("unknown fd type %d\n", fm->type);
1950
0
      goto error;
1951
0
  }
1952
0
  pt_become_idle();
1953
0
  return ret;
1954
0
error:
1955
0
  pt_become_idle();
1956
0
  return -1;
1957
0
}
1958
1959
1960
/*
1961
 * iterates through all TCP connections and closes expired ones
1962
 * Note: runs once per second at most
1963
 */
1964
#define tcpconn_lifetime(last_sec) \
1965
  do { \
1966
    int now; \
1967
    now = get_ticks(); \
1968
    if (last_sec != now) { \
1969
      last_sec = now; \
1970
      __tcpconn_lifetime(0); \
1971
    } \
1972
  } while (0)
1973
1974
1975
/*! \brief very inefficient for now - FIXME
1976
 * keep in sync with tcpconn_destroy, the "delete" part should be
1977
 * the same except for io_watch_del..
1978
 * \todo FIXME (very inefficient for now)
1979
 */
1980
static inline void __tcpconn_lifetime(int shutdown)
1981
0
{
1982
0
  struct tcp_connection *c, *next;
1983
0
  unsigned int ticks,part;
1984
0
  unsigned h;
1985
0
  int fd;
1986
0
  void *reason;
1987
1988
0
  if (have_ticks())
1989
0
    ticks=get_ticks();
1990
0
  else
1991
0
    ticks=0;
1992
1993
0
  for( part=0 ; part<TCP_PARTITION_SIZE ; part++ ) {
1994
0
    if (!shutdown) TCPCONN_LOCK(part); /* fixme: we can lock only on delete IMO */
1995
0
    for(h=0; h<TCP_ID_HASH_SIZE; h++){
1996
0
      c=TCP_PART(part).tcpconn_id_hash[h];
1997
0
      while(c){
1998
0
        next=c->id_next;
1999
0
        if (shutdown || ((c->refcnt == 0) &&
2000
0
        ((ticks > c->lifetime) ||
2001
0
        (c->msg_attempts && ticks > c->timeout)))) {
2002
0
          if (!shutdown)
2003
0
            LM_DBG("timeout for hash=%d - %p"
2004
0
                " (%d > %d)\n", h, c, ticks, c->lifetime);
2005
0
          fd=c->fd;
2006
          /* report the closing of the connection . Note that
2007
           * there are connectioned that use an foced expire to 0
2008
           * as a way to be deleted - we are not interested in */
2009
          /* Also, do not trigger reporting when shutdown
2010
           * is done */
2011
0
          if (c->lifetime>0 && !shutdown) {
2012
0
            reason = (c->msg_attempts && ticks > c->timeout) ?
2013
0
              "Timeout waiting for a complete message" :
2014
0
              "Timeout on no traffic";
2015
0
            tcp_trigger_report(c, TCP_REPORT_CLOSE, reason);
2016
0
          }
2017
0
          if ((!shutdown)&&(fd>0)&&(c->refcnt==0)) {
2018
            /* if any of read or write are set, we need to remove
2019
             * the fd from the reactor */
2020
0
            if ((c->flags & F_CONN_REMOVED) != F_CONN_REMOVED){
2021
0
              reactor_del_all( fd, -1, IO_FD_CLOSING);
2022
0
              c->flags|=F_CONN_REMOVED;
2023
0
            }
2024
0
            close(fd);
2025
0
            c->fd = -1;
2026
0
            }
2027
0
            _tcpconn_rm(c, shutdown?1:0);
2028
0
          }
2029
0
          c=next;
2030
0
        }
2031
0
    }
2032
0
    if (!shutdown) TCPCONN_UNLOCK(part);
2033
0
  }
2034
0
}
2035
2036
2037
static void tcp_main_server(void)
2038
0
{
2039
0
  static unsigned int last_sec = 0;
2040
0
  struct socket_info_full* sif;
2041
0
  struct sr_module *m;
2042
0
  int n;
2043
2044
  /* instruct tls_mgm to initialize all TLS domains */
2045
0
  for (m=modules; m; m = m->next) {
2046
0
    if (strcmp(m->exports->name, "tls_mgm") == 0)
2047
0
      if (init_child(PROC_TCP_MAIN) < 0) {
2048
0
        LM_ERR("error in init_child for PROC_TCP_MAIN\n");
2049
0
        goto error;
2050
0
      }
2051
0
  }
2052
2053
  /* we run in a separate, dedicated process, with its own reactor
2054
   * (reactors are per process) */
2055
0
  if (init_worker_reactor("TCP_main", RCT_PRIO_MAX)<0)
2056
0
    goto error;
2057
2058
  /* now start watching all the fds */
2059
2060
  /* add all the sockets we listens on for connections */
2061
0
  for (n = PROTO_FIRST; n < PROTO_LAST; n++)
2062
0
    if (is_tcp_based_proto(n))
2063
0
      for (sif = protos[n].listeners; sif; sif = sif->next) {
2064
0
        struct socket_info* si = &sif->socket_info;
2065
0
        if (protos[n].tran.bind_listener &&
2066
0
            protos[n].tran.bind_listener(si) < 0) {
2067
0
          LM_ERR("failed to bind listener [%.*s], proto %s\n",
2068
0
            si->name.len, si->name.s, protos[n].name);
2069
0
          goto error;
2070
0
        }
2071
0
        if (si->socket != -1 &&
2072
0
            reactor_add_reader(si->socket, F_TCP_LISTENER,
2073
0
              RCT_PRIO_NET, si) < 0) {
2074
0
          LM_ERR("failed to add listen socket to reactor\n");
2075
0
          goto error;
2076
0
        }
2077
0
      }
2078
  /* init: start watching for the IPC jobs */
2079
0
  if (reactor_add_reader(IPC_FD_READ_SELF, F_IPC, RCT_PRIO_ASYNC, NULL)<0){
2080
0
    LM_CRIT("failed to add IPC pipe to reactor\n");
2081
0
    goto error;
2082
0
  }
2083
2084
0
  if (tcp_pool_init() < 0)
2085
0
    goto error;
2086
2087
0
  is_tcp_main = 1;
2088
2089
  /* main loop (requires "handle_io()" implementation) */
2090
0
  reactor_main_loop( TCP_MAIN_SELECT_TIMEOUT, error,
2091
0
      tcpconn_lifetime(last_sec) );
2092
2093
0
error:
2094
0
  tcp_pool_destroy();
2095
0
  destroy_worker_reactor();
2096
0
  LM_CRIT("exiting...");
2097
0
  exit(-1);
2098
0
}
2099
2100
2101
2102
/**************************** Control functions ******************************/
2103
2104
/* initializes the TCP network level in terms of data structures */
2105
int tcp_init(void)
2106
0
{
2107
0
  unsigned int i;
2108
2109
  /* first we do auto-detection to see if there are any TCP based
2110
   * protocols loaded */
2111
0
  for ( i=PROTO_FIRST ; i<PROTO_LAST ; i++ )
2112
0
    if (is_tcp_based_proto(i) && proto_has_listeners(i)) {
2113
0
      tcp_disabled=0;
2114
0
      break;
2115
0
    }
2116
2117
0
  tcp_init_con_profiles();
2118
2119
0
  if (tcp_disabled)
2120
0
    return 0;
2121
2122
#ifdef DBG_TCPCON
2123
  con_hist = shl_init("TCP con", 10000, 0);
2124
  if (!con_hist) {
2125
    LM_ERR("oom con hist\n");
2126
    goto error;
2127
  }
2128
#endif
2129
2130
0
  if (tcp_auto_scaling_profile) {
2131
0
    s_profile = get_scaling_profile(tcp_auto_scaling_profile);
2132
0
    if (s_profile==NULL) {
2133
0
      LM_WARN("TCP scaling profile <%s> not defined "
2134
0
        "-> ignoring it...\n", tcp_auto_scaling_profile);
2135
0
    } else {
2136
0
      auto_scaling_enabled = 1;
2137
0
    }
2138
0
  }
2139
2140
0
  tcp_workers_max_no = (s_profile && (tcp_workers_no<s_profile->max_procs)) ?
2141
0
    s_profile->max_procs : tcp_workers_no ;
2142
2143
  /* init tcp workers array */
2144
0
  tcp_workers = (struct tcp_worker*)shm_malloc
2145
0
    ( tcp_workers_max_no*sizeof(struct tcp_worker) );
2146
0
  if (tcp_workers==0) {
2147
0
    LM_CRIT("could not alloc tcp_workers array in shm memory\n");
2148
0
    goto error;
2149
0
  }
2150
0
  memset( tcp_workers, 0, tcp_workers_max_no*sizeof(struct tcp_worker));
2151
  /* init globals */
2152
0
  connection_id=(unsigned int*)shm_malloc(sizeof(unsigned int));
2153
0
  if (connection_id==0){
2154
0
    LM_CRIT("could not alloc globals in shm memory\n");
2155
0
    goto error;
2156
0
  }
2157
  // The  rand()  function returns a pseudo-random integer in the range 0 to
2158
  // RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).
2159
0
  *connection_id=(unsigned int)rand();
2160
0
  connection_id_lock=lock_alloc();
2161
0
  if (connection_id_lock==0){
2162
0
    LM_CRIT("could not alloc connection ID lock\n");
2163
0
    goto error;
2164
0
  }
2165
0
  if (lock_init(connection_id_lock)==0){
2166
0
    LM_CRIT("could not init connection ID lock\n");
2167
0
    lock_dealloc((void*)connection_id_lock);
2168
0
    connection_id_lock=0;
2169
0
    goto error;
2170
0
  }
2171
0
  tcp_connections_no = (unsigned int *)shm_malloc(sizeof(*tcp_connections_no));
2172
0
  if (tcp_connections_no == 0) {
2173
0
    LM_CRIT("could not alloc tcp connection counter in shm memory\n");
2174
0
    goto error;
2175
0
  }
2176
0
  *tcp_connections_no = 0;
2177
0
  tcp_main_proc_no = (int *)shm_malloc(sizeof(*tcp_main_proc_no));
2178
0
  if (tcp_main_proc_no == 0) {
2179
0
    LM_CRIT("could not alloc tcp main proc slot in shm memory\n");
2180
0
    goto error;
2181
0
  }
2182
0
  *tcp_main_proc_no = -1;
2183
0
  tcp_write_queue = shm_malloc(sizeof(*tcp_write_queue));
2184
0
  if (tcp_write_queue == 0) {
2185
0
    LM_CRIT("could not alloc tcp shared write queue in shm memory\n");
2186
0
    goto error;
2187
0
  }
2188
0
  memset(tcp_write_queue, 0, sizeof(*tcp_write_queue));
2189
0
  if (cond_init(&tcp_write_queue->cond) != 0) {
2190
0
    LM_CRIT("could not init tcp shared write queue cond\n");
2191
0
    shm_free(tcp_write_queue);
2192
0
    tcp_write_queue = 0;
2193
0
    goto error;
2194
0
  }
2195
0
  tcp_connections_lock = lock_alloc();
2196
0
  if (tcp_connections_lock == 0) {
2197
0
    LM_CRIT("could not alloc tcp connection counter lock\n");
2198
0
    goto error;
2199
0
  }
2200
0
  if (lock_init(tcp_connections_lock) == 0) {
2201
0
    LM_CRIT("could not init tcp connection counter lock\n");
2202
0
    lock_dealloc((void *)tcp_connections_lock);
2203
0
    tcp_connections_lock = 0;
2204
0
    goto error;
2205
0
  }
2206
0
  memset( &tcp_parts, 0, TCP_PARTITION_SIZE*sizeof(struct tcp_partition));
2207
  /* init partitions */
2208
0
  for( i=0 ; i<TCP_PARTITION_SIZE ; i++ ) {
2209
    /* init lock */
2210
0
    tcp_parts[i].tcpconn_lock=lock_alloc();
2211
0
    if (tcp_parts[i].tcpconn_lock==0){
2212
0
      LM_CRIT("could not alloc lock\n");
2213
0
      goto error;
2214
0
    }
2215
0
    if (lock_init(tcp_parts[i].tcpconn_lock)==0){
2216
0
      LM_CRIT("could not init lock\n");
2217
0
      lock_dealloc((void*)tcp_parts[i].tcpconn_lock);
2218
0
      tcp_parts[i].tcpconn_lock=0;
2219
0
      goto error;
2220
0
    }
2221
    /* alloc hashtables*/
2222
0
    tcp_parts[i].tcpconn_aliases_hash=(struct tcp_conn_alias**)
2223
0
      shm_malloc(TCP_ALIAS_HASH_SIZE* sizeof(struct tcp_conn_alias*));
2224
0
    if (tcp_parts[i].tcpconn_aliases_hash==0){
2225
0
      LM_CRIT("could not alloc address hashtable in shm memory\n");
2226
0
      goto error;
2227
0
    }
2228
0
    tcp_parts[i].tcpconn_id_hash=(struct tcp_connection**)
2229
0
      shm_malloc(TCP_ID_HASH_SIZE*sizeof(struct tcp_connection*));
2230
0
    if (tcp_parts[i].tcpconn_id_hash==0){
2231
0
      LM_CRIT("could not alloc id hashtable in shm memory\n");
2232
0
      goto error;
2233
0
    }
2234
    /* init hashtables*/
2235
0
    memset((void*)tcp_parts[i].tcpconn_aliases_hash, 0,
2236
0
      TCP_ALIAS_HASH_SIZE * sizeof(struct tcp_conn_alias*));
2237
0
    memset((void*)tcp_parts[i].tcpconn_id_hash, 0,
2238
0
      TCP_ID_HASH_SIZE * sizeof(struct tcp_connection*));
2239
0
  }
2240
2241
0
  return 0;
2242
0
error:
2243
  /* clean-up */
2244
0
  tcp_destroy();
2245
0
  return -1;
2246
0
}
2247
2248
2249
/* destroys the TCP data */
2250
void tcp_destroy(void)
2251
0
{
2252
0
  int part;
2253
2254
0
  if (tcp_parts[0].tcpconn_id_hash)
2255
      /* force close/expire for all active tcpconns*/
2256
0
      __tcpconn_lifetime(1);
2257
2258
0
  if (connection_id){
2259
0
    shm_free(connection_id);
2260
0
    connection_id=0;
2261
0
  }
2262
2263
0
  if (tcp_connections_no) {
2264
0
    shm_free(tcp_connections_no);
2265
0
    tcp_connections_no = 0;
2266
0
  }
2267
2268
0
  if (tcp_main_proc_no) {
2269
0
    shm_free(tcp_main_proc_no);
2270
0
    tcp_main_proc_no = 0;
2271
0
  }
2272
2273
0
  if (tcp_dispatch_sock[0] >= 0) {
2274
0
    close(tcp_dispatch_sock[0]);
2275
0
    tcp_dispatch_sock[0] = -1;
2276
0
  }
2277
0
  if (tcp_dispatch_sock[1] >= 0) {
2278
0
    close(tcp_dispatch_sock[1]);
2279
0
    tcp_dispatch_sock[1] = -1;
2280
0
  }
2281
2282
0
  if (tcp_write_queue) {
2283
    /* Skip cond teardown during attendant shutdown. */
2284
    /* cond_destroy(&tcp_write_queue->cond); */
2285
0
    shm_free(tcp_write_queue);
2286
0
    tcp_write_queue = 0;
2287
0
  }
2288
2289
0
  if (tcp_connections_lock) {
2290
0
    lock_destroy(tcp_connections_lock);
2291
0
    lock_dealloc((void *)tcp_connections_lock);
2292
0
    tcp_connections_lock = 0;
2293
0
  }
2294
2295
0
  if (connection_id_lock){
2296
0
    lock_destroy(connection_id_lock);
2297
0
    lock_dealloc((void*)connection_id_lock);
2298
0
    connection_id_lock=0;
2299
0
  }
2300
2301
0
  for ( part=0 ; part<TCP_PARTITION_SIZE ; part++ ) {
2302
0
    if (tcp_parts[part].tcpconn_id_hash){
2303
0
      shm_free(tcp_parts[part].tcpconn_id_hash);
2304
0
      tcp_parts[part].tcpconn_id_hash=0;
2305
0
    }
2306
0
    if (tcp_parts[part].tcpconn_aliases_hash){
2307
0
      shm_free(tcp_parts[part].tcpconn_aliases_hash);
2308
0
      tcp_parts[part].tcpconn_aliases_hash=0;
2309
0
    }
2310
0
    if (tcp_parts[part].tcpconn_lock){
2311
0
      lock_destroy(tcp_parts[part].tcpconn_lock);
2312
0
      lock_dealloc((void*)tcp_parts[part].tcpconn_lock);
2313
0
      tcp_parts[part].tcpconn_lock=0;
2314
0
    }
2315
0
  }
2316
0
}
2317
2318
2319
static int _get_own_tcp_worker_id(void)
2320
0
{
2321
0
  pid_t pid;
2322
0
  int i;
2323
2324
0
  pid = getpid();
2325
0
  for( i=0 ; i<tcp_workers_max_no ; i++)
2326
0
    if(tcp_workers[i].pid==pid)
2327
0
      return i;
2328
2329
0
  return -1;
2330
0
}
2331
2332
2333
void tcp_reset_worker_slot(void)
2334
0
{
2335
0
  int i;
2336
2337
0
  if ((i=_get_own_tcp_worker_id())>=0) {
2338
0
    tcp_workers[i].state=STATE_INACTIVE;
2339
0
    tcp_workers[i].pid=0;
2340
0
    tcp_workers[i].pt_idx=0;
2341
0
  }
2342
0
}
2343
2344
2345
static int fork_dynamic_tcp_process(void *foo)
2346
0
{
2347
0
  int p_id;
2348
0
  int r;
2349
0
  const struct internal_fork_params ifp_sr_tcp = {
2350
0
    .proc_desc = "SIP receiver TCP",
2351
0
    .flags = OSS_PROC_DYNAMIC|OSS_PROC_NEEDS_SCRIPT,
2352
0
    .type = TYPE_TCP,
2353
0
  };
2354
2355
  /* search for a free slot in the TCP workers table */
2356
0
  for (r = 0; r < tcp_workers_max_no; r++)
2357
0
    if (tcp_workers[r].state == STATE_INACTIVE)
2358
0
      break;
2359
2360
0
  if (r == tcp_workers_max_no) {
2361
0
    LM_BUG("trying to fork one more TCP worker but no free slot in "
2362
0
      "the TCP table (size=%d)\n", tcp_workers_max_no);
2363
0
    return -1;
2364
0
  }
2365
2366
0
  if ((p_id = internal_fork(&ifp_sr_tcp)) < 0) {
2367
0
    LM_ERR("cannot fork dynamic TCP worker process\n");
2368
0
    return -1;
2369
0
  } else if (p_id == 0) {
2370
    /* new TCP worker process */
2371
0
    if (tcp_dispatch_sock[1] >= 0)
2372
0
      close(tcp_dispatch_sock[1]);
2373
0
    tcp_dispatch_sock[1] = -1;
2374
2375
0
    set_proc_attrs("TCP receiver");
2376
0
    tcp_workers[r].pid = getpid();
2377
2378
0
    if (tcp_worker_proc_reactor_init(tcp_dispatch_sock[0]) < 0 ||
2379
0
    init_child(20000) ||
2380
0
    self_update_routing_script() < 0)
2381
0
      goto error;
2382
2383
0
    report_conditional_status(1, 0);
2384
0
    clean_read_pipeend();
2385
2386
0
    tcp_worker_proc_loop();
2387
0
    destroy_worker_reactor();
2388
2389
0
error:
2390
0
    report_failure_status();
2391
0
    LM_ERR("initializing new TCP worker failed, exiting with error\n");
2392
0
    pt[process_no].flags |= OSS_PROC_SELFEXIT;
2393
0
    exit(-1);
2394
0
  } else {
2395
    /* parent/attendant */
2396
0
    tcp_workers[r].state = STATE_ACTIVE;
2397
0
    tcp_workers[r].pt_idx = p_id;
2398
0
    return p_id;
2399
0
  }
2400
2401
0
  return 0;
2402
0
}
2403
2404
2405
static void tcp_process_graceful_terminate(int sender, void *param)
2406
0
{
2407
0
  int i;
2408
2409
  /* accept this only from the attendant process */
2410
0
  if (sender != 0) {
2411
0
    LM_BUG("graceful terminate received from a non-main process\n");
2412
0
    return;
2413
0
  }
2414
0
  LM_NOTICE("process %d received RPC to terminate from Main\n", process_no);
2415
2416
  /* reserve this slot until tcp_terminate_worker() detaches the process
2417
   * from the shared dispatch queue and completes its pending async work */
2418
0
  if ((i = _get_own_tcp_worker_id()) >= 0)
2419
0
    tcp_workers[i].state = STATE_DRAINING;
2420
2421
0
  tcp_terminate_worker();
2422
0
}
2423
2424
2425
/* counts the number of TCP processes to start with; this number may
2426
 * change during runtime due auto-scaling */
2427
int tcp_count_processes(unsigned int *extra)
2428
0
{
2429
0
  if (extra) *extra = 0;
2430
2431
0
  if (tcp_disabled)
2432
0
    return 0;
2433
2434
0
  if (s_profile && extra && s_profile->max_procs > tcp_workers_no)
2435
0
    *extra = s_profile->max_procs - tcp_workers_no;
2436
2437
0
  return 1 /* tcp main / IO process */ + tcp_workers_no /* dispatch workers */;
2438
0
}
2439
2440
2441
int tcp_start_processes(int *chd_rank, int *startup_done)
2442
0
{
2443
0
  int r, p_id, flags;
2444
0
  const struct internal_fork_params ifp_sr_tcp = {
2445
0
    .proc_desc = "SIP receiver TCP",
2446
0
    .flags = OSS_PROC_NEEDS_SCRIPT,
2447
0
    .type = TYPE_TCP,
2448
0
  };
2449
2450
0
  if (tcp_disabled)
2451
0
    return 0;
2452
2453
  /* create the shared dispatch socket from TCP main to TCP workers */
2454
0
  if (socketpair(AF_UNIX, SOCK_DGRAM, 0, tcp_dispatch_sock) < 0) {
2455
0
    LM_ERR("socketpair failed for TCP worker dispatch: %s\n",
2456
0
      strerror(errno));
2457
0
    goto error;
2458
0
  }
2459
0
  flags = fcntl(tcp_dispatch_sock[0], F_GETFL);
2460
0
  if (flags == -1) {
2461
0
    LM_ERR("fcntl failed for TCP worker dispatch socket: %s\n",
2462
0
      strerror(errno));
2463
0
    goto error;
2464
0
  }
2465
0
  if (fcntl(tcp_dispatch_sock[0], F_SETFL, flags | O_NONBLOCK) == -1) {
2466
0
    LM_ERR("failed to set non-blocking on TCP worker dispatch socket: %s\n",
2467
0
      strerror(errno));
2468
0
    goto error;
2469
0
  }
2470
0
  flags = fcntl(tcp_dispatch_sock[1], F_GETFL);
2471
0
  if (flags == -1) {
2472
0
    LM_ERR("fcntl failed for TCP worker dispatch socket: %s\n",
2473
0
      strerror(errno));
2474
0
    goto error;
2475
0
  }
2476
0
  if (fcntl(tcp_dispatch_sock[1], F_SETFL, flags | O_NONBLOCK) == -1) {
2477
0
    LM_ERR("failed to set non-blocking on TCP worker dispatch socket: %s\n",
2478
0
      strerror(errno));
2479
0
    goto error;
2480
0
  }
2481
2482
0
  if (auto_scaling_enabled && s_profile &&
2483
0
  create_process_group(TYPE_TCP, NULL, s_profile,
2484
0
    fork_dynamic_tcp_process, tcp_process_graceful_terminate) != 0)
2485
0
    LM_ERR("failed to create TCP auto-scaling process group; "
2486
0
      "automatic scaling will not be possible\n");
2487
2488
0
  for (r = 0; r < tcp_workers_no; r++) {
2489
0
    (*chd_rank)++;
2490
0
    p_id = internal_fork(&ifp_sr_tcp);
2491
0
    if (p_id < 0) {
2492
0
      LM_ERR("cannot fork TCP worker process %d\n", r);
2493
0
      goto error;
2494
0
    } else if (p_id > 0) {
2495
      /* parent */
2496
0
      tcp_workers[r].state = STATE_ACTIVE;
2497
0
      tcp_workers[r].pt_idx = p_id;
2498
0
      continue;
2499
0
    }
2500
2501
    /* child */
2502
0
    if (tcp_dispatch_sock[1] >= 0)
2503
0
      close(tcp_dispatch_sock[1]);
2504
0
    tcp_dispatch_sock[1] = -1;
2505
2506
0
    set_proc_attrs("TCP receiver");
2507
0
    tcp_workers[r].pid = getpid();
2508
2509
0
    if (tcp_worker_proc_reactor_init(tcp_dispatch_sock[0]) < 0 ||
2510
0
        init_child(*chd_rank) < 0) {
2511
0
      LM_ERR("init_child failed for TCP worker %d\n", r);
2512
0
      report_failure_status();
2513
0
      if (startup_done)
2514
0
        *startup_done = -1;
2515
0
      exit(-1);
2516
0
    }
2517
2518
    /* first TCP worker runs startup_route if not already run */
2519
0
    if (startup_done && *startup_done == 0 && r == 0) {
2520
0
      LM_DBG("running startup route for first TCP worker\n");
2521
0
      if (run_startup_route() < 0) {
2522
0
        LM_ERR("startup route processing failed in TCP worker\n");
2523
0
        report_failure_status();
2524
0
        *startup_done = -1;
2525
0
        exit(-1);
2526
0
      }
2527
0
      *startup_done = 1;
2528
0
    }
2529
2530
0
    report_conditional_status((!no_daemon_mode), 0);
2531
0
    tcp_worker_proc_loop();
2532
0
  }
2533
2534
  /* Keep the worker endpoint in the attendant when auto-scaling is enabled,
2535
   * so dynamically forked TCP workers can inherit the shared queue. */
2536
0
  if (!s_profile && tcp_dispatch_sock[0] >= 0) {
2537
0
    close(tcp_dispatch_sock[0]);
2538
0
    tcp_dispatch_sock[0] = -1;
2539
0
  }
2540
2541
0
  if (startup_done && tcp_workers_no > 0)
2542
0
    while (!(*startup_done)) {
2543
0
      usleep(5);
2544
0
      handle_sigs();
2545
0
    }
2546
2547
0
  return 0;
2548
0
error:
2549
0
  if (tcp_dispatch_sock[0] >= 0) {
2550
0
    close(tcp_dispatch_sock[0]);
2551
0
    tcp_dispatch_sock[0] = -1;
2552
0
  }
2553
0
  if (tcp_dispatch_sock[1] >= 0) {
2554
0
    close(tcp_dispatch_sock[1]);
2555
0
    tcp_dispatch_sock[1] = -1;
2556
0
  }
2557
0
  return -1;
2558
0
}
2559
2560
static int tcpconn_update_local_port(struct tcp_connection *tcpconn)
2561
0
{
2562
0
  union sockaddr_union local_su;
2563
0
  socklen_t su_size;
2564
2565
0
  su_size = sockaddru_len(tcpconn->rcv.src_su);
2566
0
  if (getsockname(tcpconn->fd, (struct sockaddr *)&local_su, &su_size) < 0) {
2567
0
    LM_ERR("failed to get local socket info on conn %u: %s\n",
2568
0
      tcpconn->id, strerror(errno));
2569
0
    return -1;
2570
0
  }
2571
2572
0
  tcpconn->rcv.dst_port = su_getport(&local_su);
2573
0
  return 0;
2574
0
}
2575
2576
static int tcpconn_prepare_write(struct tcp_connection *tcpconn)
2577
0
{
2578
0
  int fd;
2579
0
  int connected = 0;
2580
2581
0
  if ((tcpconn->flags & F_CONN_INIT) == 0) {
2582
0
    if (protos[tcpconn->type].net.stream.conn.init &&
2583
0
        protos[tcpconn->type].net.stream.conn.init(tcpconn) < 0) {
2584
0
      LM_ERR("failed to init proto %d conn %p in TCP main\n",
2585
0
        tcpconn->type, tcpconn);
2586
0
      return -1;
2587
0
    }
2588
0
    tcpconn->flags |= F_CONN_INIT;
2589
0
  }
2590
2591
0
  if (tcpconn->fd < 0) {
2592
0
    if (!tcpconn->rcv.bind_address) {
2593
0
      LM_ERR("missing bind_address for outbound conn %u\n", tcpconn->id);
2594
0
      return -1;
2595
0
    }
2596
2597
0
    fd = tcp_sync_connect_fd(&tcpconn->rcv.bind_address->su,
2598
0
        &tcpconn->rcv.src_su, tcpconn->type, &tcpconn->profile,
2599
0
        tcpconn->rcv.bind_address->flags,
2600
0
        tcpconn->rcv.bind_address->tos);
2601
0
    if (fd < 0)
2602
0
      return -1;
2603
2604
0
    tcpconn->fd = fd;
2605
0
    if (tcpconn_update_local_port(tcpconn) < 0) {
2606
0
      close(fd);
2607
0
      tcpconn->fd = -1;
2608
0
      return -1;
2609
0
    }
2610
2611
0
    tcpconn->state = S_CONN_OK;
2612
0
    connected = 1;
2613
0
  }
2614
2615
0
  if (connected && protos[tcpconn->type].net.stream.conn.connect) {
2616
0
    if (protos[tcpconn->type].net.stream.conn.connect(tcpconn) < 0) {
2617
0
      LM_ERR("failed to finish proto %d connect on conn %u\n",
2618
0
        tcpconn->type, tcpconn->id);
2619
0
      return -1;
2620
0
    }
2621
0
  }
2622
2623
0
  return 0;
2624
0
}
2625
2626
2627
int tcp_start_listener(void)
2628
0
{
2629
0
  int p_id;
2630
0
  const struct internal_fork_params ifp_tcp_main = {
2631
0
    .proc_desc = "TCP main",
2632
0
    .flags = 0,
2633
0
    .type = TYPE_NONE,
2634
0
  };
2635
2636
0
  if (tcp_disabled)
2637
0
    return 0;
2638
2639
  /* start the TCP manager process */
2640
0
  if ( (p_id=internal_fork(&ifp_tcp_main))<0 ) {
2641
0
    LM_CRIT("cannot fork tcp main process\n");
2642
0
    goto error;
2643
0
  }else if (p_id==0){
2644
      /* child */
2645
0
    report_conditional_status( (!no_daemon_mode), 0);
2646
2647
0
    tcp_main_server();
2648
0
    exit(-1);
2649
0
  }
2650
0
  *tcp_main_proc_no = p_id;
2651
2652
0
  return 0;
2653
0
error:
2654
0
  return -1;
2655
0
}
2656
2657
int tcp_has_async_write(void)
2658
0
{
2659
0
  return reactor_has_async();
2660
0
}
2661
2662
static int tcp_close_conn_run(void *data)
2663
0
{
2664
0
  struct tcp_connection *conn = data;
2665
2666
0
  if (!conn)
2667
0
    return -1;
2668
2669
0
  tcp_conn_destroy(conn);
2670
0
  return 0;
2671
0
}
2672
2673
static void tcp_close_conn_rpc(int pid, void *param)
2674
0
{
2675
0
  tcp_close_conn_run(param);
2676
0
}
2677
2678
int tcp_close_connection(str *ipport)
2679
0
{
2680
0
  struct tcp_connection *conn = NULL;
2681
0
  struct ip_addr *ip;
2682
0
  str host;
2683
0
  unsigned int id;
2684
0
  int port, proto, rc, tcp_main_proc;
2685
0
  int start_proto, end_proto;
2686
0
  unsigned int p;
2687
0
  char *sep;
2688
2689
0
  if (tcp_disabled)
2690
0
    return 0;
2691
2692
0
  sep = q_memchr(ipport->s, ':', ipport->len);
2693
0
  if (!sep) {
2694
0
    if (str2int(ipport, &id) < 0) {
2695
0
      LM_ERR("failed to parse tcp connection [%.*s]\n",
2696
0
        ipport->len, ipport->s);
2697
0
      return -1;
2698
0
    }
2699
2700
0
    switch (tcp_conn_get(id, NULL, 0, PROTO_NONE, NULL, &conn, NULL)) {
2701
0
    case 1:
2702
0
      goto found;
2703
0
    case -1:
2704
0
      return -1;
2705
0
    default:
2706
0
      return 0;
2707
0
    }
2708
0
  }
2709
2710
0
  if (parse_phostport(ipport->s, ipport->len, &host.s, &host.len,
2711
0
  &port, &proto) != 0 || port <= 0) {
2712
0
    LM_ERR("failed to parse tcp connection [%.*s]\n",
2713
0
      ipport->len, ipport->s);
2714
0
    return -1;
2715
0
  }
2716
2717
0
  ip = str2ip(&host);
2718
0
  if (!ip)
2719
0
    ip = str2ip6(&host);
2720
0
  if (!ip) {
2721
0
    LM_ERR("invalid IP in tcp connection [%.*s]\n",
2722
0
      ipport->len, ipport->s);
2723
0
    return -1;
2724
0
  }
2725
2726
0
  if (proto != PROTO_NONE) {
2727
0
    if (!is_tcp_based_proto(proto)) {
2728
0
      LM_ERR("protocol %d is not TCP based for [%.*s]\n",
2729
0
        proto, ipport->len, ipport->s);
2730
0
      return -1;
2731
0
    }
2732
0
    start_proto = proto;
2733
0
    end_proto = proto + 1;
2734
0
  } else {
2735
0
    start_proto = 0;
2736
0
    end_proto = PROTO_LAST;
2737
0
  }
2738
2739
0
  for (p = start_proto; p < (unsigned int)end_proto; p++) {
2740
0
    if (!is_tcp_based_proto(p))
2741
0
      continue;
2742
2743
0
    switch (tcp_conn_get(0, ip, port, p, NULL, &conn, NULL)) {
2744
0
    case 1:
2745
0
      goto found;
2746
0
    case -1:
2747
0
      return -1;
2748
0
    }
2749
0
  }
2750
2751
0
  return 0;
2752
2753
0
found:
2754
0
  TCPCONN_LOCK(conn->id);
2755
0
  conn->flags |= F_CONN_FORCE_CLOSED;
2756
0
  TCPCONN_UNLOCK(conn->id);
2757
2758
0
  tcp_main_proc = tcp_get_main_proc_no();
2759
0
  if (tcp_main_proc < 0)
2760
0
    rc = -1;
2761
0
  else if (process_no == tcp_main_proc)
2762
0
    rc = tcp_close_conn_run(conn);
2763
0
  else
2764
0
    rc = ipc_send_rpc(tcp_main_proc, tcp_close_conn_rpc, conn);
2765
2766
0
  if (rc < 0) {
2767
0
    TCPCONN_LOCK(conn->id);
2768
0
    conn->flags &= ~F_CONN_FORCE_CLOSED;
2769
0
    TCPCONN_UNLOCK(conn->id);
2770
0
    tcp_conn_release(conn, 0);
2771
0
    return -1;
2772
0
  }
2773
2774
0
  return 1;
2775
0
}
2776
2777
2778
/***************************** MI functions **********************************/
2779
2780
mi_response_t *mi_tcp_list_conns(const mi_params_t *params,
2781
            struct mi_handler *async_hdl)
2782
0
{
2783
0
  mi_response_t *resp;
2784
0
  mi_item_t *resp_obj;
2785
0
  mi_item_t *conns_arr, *conn_item;
2786
0
  struct tcp_connection *conn;
2787
0
  time_t _ts;
2788
0
  char date_buf[MI_DATE_BUF_LEN];
2789
0
  int date_buf_len;
2790
0
  unsigned int i,j,part;
2791
0
  char proto_buf[PROTO_NAME_MAX_SIZE];
2792
0
  char *proto_s;
2793
0
  int proto_len;
2794
0
  int proto_filter = PROTO_NONE;
2795
0
  int filter_by_proto = 0;
2796
0
  str proto_name;
2797
0
  struct tm ltime;
2798
0
  char *p;
2799
2800
0
  if (tcp_disabled)
2801
0
    return init_mi_result_null();
2802
2803
0
  switch (try_get_mi_string_param(params, "proto", &proto_s, &proto_len)) {
2804
0
  case 0:
2805
0
    proto_name.s = proto_s;
2806
0
    proto_name.len = proto_len;
2807
2808
0
    if (proto_len == 3 && str_strcasecmp(&proto_name, _str("any")) == 0)
2809
0
      ;
2810
0
    else if (parse_proto((unsigned char *)proto_s, proto_len,
2811
0
        (int *)&proto_filter) < 0)
2812
0
      return init_mi_error(400, MI_SSTR("Bad protocol"));
2813
0
    else
2814
0
      filter_by_proto = 1;
2815
0
    break;
2816
0
  case -1:
2817
0
    break;
2818
0
  default:
2819
0
    return init_mi_param_error();
2820
0
  }
2821
2822
0
  resp = init_mi_result_object(&resp_obj);
2823
0
  if (!resp)
2824
0
    return 0;
2825
2826
0
  conns_arr = add_mi_array(resp_obj, MI_SSTR("Connections"));
2827
0
  if (!conns_arr) {
2828
0
    free_mi_response(resp);
2829
0
    return 0;
2830
0
  }
2831
2832
0
  for( part=0 ; part<TCP_PARTITION_SIZE ; part++) {
2833
0
    TCPCONN_LOCK(part);
2834
0
    for( i=0; i<TCP_ID_HASH_SIZE ; i++ ) {
2835
0
      for(conn=TCP_PART(part).tcpconn_id_hash[i];conn;conn=conn->id_next){
2836
0
        if (filter_by_proto && conn->type != proto_filter)
2837
0
          continue;
2838
2839
        /* add one object fo each conn */
2840
0
        conn_item = add_mi_object(conns_arr, 0, 0);
2841
0
        if (!conn_item)
2842
0
          goto error;
2843
2844
        /* add ID */
2845
0
        if (add_mi_number(conn_item, MI_SSTR("ID"), conn->id) < 0)
2846
0
          goto error;
2847
2848
        /* add type/proto */
2849
0
        p = proto2str(conn->type, proto_buf);
2850
0
        if (add_mi_string(conn_item, MI_SSTR("Type"), proto_buf,
2851
0
          (int)(long)(p-proto_buf)) < 0)
2852
0
          goto error;
2853
2854
        /* add state */
2855
0
        if (add_mi_number(conn_item, MI_SSTR("State"), conn->state) < 0)
2856
0
          goto error;
2857
2858
        /* add Remote IP:Port */
2859
0
        if (add_mi_string_fmt(conn_item, MI_SSTR("Remote"), "%s:%d",
2860
0
          ip_addr2a(&conn->rcv.src_ip), conn->rcv.src_port) < 0)
2861
0
          goto error;
2862
2863
        /* add Local IP:Port */
2864
0
        if (add_mi_string_fmt(conn_item, MI_SSTR("Local"), "%s:%d",
2865
0
          ip_addr2a(&conn->rcv.dst_ip), conn->rcv.dst_port) < 0)
2866
0
          goto error;
2867
2868
0
        if (protos[conn->type].net.stream.conn.dump &&
2869
0
            protos[conn->type].net.stream.conn.dump(conn,
2870
0
              conn_item) < 0)
2871
0
          goto error;
2872
2873
        /* add lifetime */
2874
0
        _ts = (time_t)conn->lifetime + startup_time;
2875
0
        localtime_r(&_ts, &ltime);
2876
0
        date_buf_len = strftime(date_buf, MI_DATE_BUF_LEN - 1,
2877
0
                    "%Y-%m-%d %H:%M:%S", &ltime);
2878
0
        if (date_buf_len != 0) {
2879
0
          if (add_mi_string(conn_item, MI_SSTR("Lifetime"),
2880
0
            date_buf, date_buf_len) < 0)
2881
0
            goto error;
2882
0
        } else {
2883
0
          if (add_mi_number(conn_item, MI_SSTR("Lifetime"), _ts) < 0)
2884
0
            goto error;
2885
0
        }
2886
2887
        /* add the port-aliases */
2888
0
        for( j=0 ; j<conn->aliases ; j++ )
2889
          /* add one node for each conn */
2890
0
          add_mi_number( conn_item, MI_SSTR("Alias port"),
2891
0
            conn->con_aliases[j].port );
2892
2893
0
      }
2894
0
    }
2895
2896
0
    TCPCONN_UNLOCK(part);
2897
0
  }
2898
2899
0
  return resp;
2900
2901
0
error:
2902
0
  TCPCONN_UNLOCK(part);
2903
0
  LM_ERR("failed to add MI item\n");
2904
0
  free_mi_response(resp);
2905
0
  return 0;
2906
0
}
2907
2908
2909
mi_response_t *mi_tcp_close_conn(const mi_params_t *params,
2910
            struct mi_handler *_)
2911
0
{
2912
0
  str ipport;
2913
0
  int rc;
2914
2915
0
  if (get_mi_string_param(params, "ipport", &ipport.s, &ipport.len) < 0)
2916
0
    return init_mi_param_error();
2917
2918
0
  rc = tcp_close_connection(&ipport);
2919
0
  if (rc < 0)
2920
0
    return init_mi_error(400, MI_SSTR("Bad tcp connection"));
2921
0
  if (rc == 0)
2922
0
    return init_mi_result_null();
2923
2924
0
  return init_mi_result_ok();
2925
0
}