Coverage Report

Created: 2026-07-25 07:08

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