Coverage Report

Created: 2026-12-01 06:30

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