Coverage Report

Created: 2026-07-30 06:37

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
    /* a write job is already queued for this connection and it owns
1517
     * exactly one reference, which it releases on completion; our
1518
     * callers treat success as a transfer of their own reference, so
1519
     * it has to be released here, otherwise it leaks and the
1520
     * connection can never be destroyed */
1521
0
    tcpconn_put(tcpconn);
1522
0
    return 0;
1523
0
  }
1524
1525
0
  tcpconn->flags |= F_CONN_WRITE_QUEUED;
1526
0
  tcpconn->wq_next = NULL;
1527
0
  if (tcp_write_queue->tail)
1528
0
    tcp_write_queue->tail->wq_next = tcpconn;
1529
0
  else
1530
0
    tcp_write_queue->head = tcpconn;
1531
0
  tcp_write_queue->tail = tcpconn;
1532
0
  cond_signal(&tcp_write_queue->cond);
1533
0
  cond_unlock(&tcp_write_queue->cond);
1534
0
  return 0;
1535
0
}
1536
1537
int tcp_run_task(tcp_thread_job_f run, void *data)
1538
0
{
1539
0
  struct tcp_job *job;
1540
1541
0
  if (!run)
1542
0
    return -1;
1543
1544
0
  if (!tcp_threads_active()) {
1545
0
    run(data);
1546
0
    return 0;
1547
0
  }
1548
1549
0
  job = thread_malloc(sizeof(*job));
1550
0
  if (!job) {
1551
0
    LM_ERR("oom while queuing TCP run job\n");
1552
0
    return -1;
1553
0
  }
1554
1555
0
  job->conn = NULL;
1556
0
  job->op = TCP_RUN_JOB;
1557
0
  job->run = run;
1558
0
  job->data = data;
1559
0
  job->resp = 0;
1560
0
  job->ret = -1;
1561
0
  job->next = NULL;
1562
1563
0
  cond_lock(&tcp_write_queue->cond);
1564
0
  if (tcp_pool.task_tail)
1565
0
    tcp_pool.task_tail->next = job;
1566
0
  else
1567
0
    tcp_pool.task_head = job;
1568
0
  tcp_pool.task_tail = job;
1569
0
  cond_signal(&tcp_write_queue->cond);
1570
0
  cond_unlock(&tcp_write_queue->cond);
1571
1572
0
  return 0;
1573
0
}
1574
1575
static inline int tcp_queue_write_job(struct tcp_connection *tcpconn)
1576
0
{
1577
0
  if (!(tcpconn->flags & F_CONN_REMOVED_READ) && tcpconn->fd != -1) {
1578
0
    if (reactor_del_reader(tcpconn->fd, -1, 0) == -1)
1579
0
      return -1;
1580
0
    tcpconn->flags |= F_CONN_REMOVED_READ;
1581
0
  }
1582
1583
0
  if (tcp_async_write_job(tcpconn) < 0)
1584
0
    return -1;
1585
1586
0
  return 0;
1587
0
}
1588
1589
static inline void tcp_fail_conn(struct tcp_connection *tcpconn,
1590
    const char *reason, int report)
1591
0
{
1592
0
  if ((tcpconn->flags & F_CONN_REMOVED) != F_CONN_REMOVED &&
1593
0
      tcpconn->fd != -1) {
1594
0
    reactor_del_all(tcpconn->fd, -1, IO_FD_CLOSING);
1595
0
    tcpconn->flags |= F_CONN_REMOVED;
1596
0
  }
1597
1598
0
  if (report)
1599
0
    tcp_trigger_report(tcpconn, TCP_REPORT_CLOSE, (void *)reason);
1600
1601
0
  tcpconn_destroy(tcpconn);
1602
0
}
1603
1604
static inline void tcp_complete_read(struct tcp_job *job)
1605
0
{
1606
0
  struct tcp_connection *tcpconn;
1607
1608
0
  tcpconn = job->conn;
1609
1610
0
  if (job->resp == -2) {
1611
0
    tcp_fail_conn(tcpconn, "Timeout waiting for a complete message", 1);
1612
0
    return;
1613
0
  }
1614
1615
0
  if (job->resp < 0 || tcpconn->state == S_CONN_BAD) {
1616
0
    tcp_fail_conn(tcpconn, "Read error", 1);
1617
0
    return;
1618
0
  }
1619
1620
0
  if (tcpconn->state == S_CONN_EOF) {
1621
0
    tcp_fail_conn(tcpconn, "EOF received", 1);
1622
0
    return;
1623
0
  }
1624
1625
0
  if (tcpconn->flags & F_CONN_REMOVED_READ) {
1626
0
    if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET, tcpconn) < 0) {
1627
0
      LM_ERR("failed to re-add TCP conn %p for read events\n", tcpconn);
1628
0
      tcp_fail_conn(tcpconn, "Failed to re-arm read", 0);
1629
0
      return;
1630
0
    }
1631
0
    tcpconn->flags &= ~F_CONN_REMOVED_READ;
1632
0
  }
1633
1634
0
  tcpconn_put(tcpconn);
1635
0
}
1636
1637
static inline void tcp_complete_write(struct tcp_job *job)
1638
0
{
1639
0
  struct tcp_connection *tcpconn;
1640
0
  int pending_chunks;
1641
1642
0
  tcpconn = job->conn;
1643
1644
0
  if (job->resp < 0 || tcpconn->state == S_CONN_BAD) {
1645
0
    tcp_fail_conn(tcpconn, "Write error", 1);
1646
0
    return;
1647
0
  }
1648
1649
0
  lock_get(&tcpconn->write_lock);
1650
0
  pending_chunks = (tcpconn->async && tcpconn->async->pending);
1651
0
  lock_release(&tcpconn->write_lock);
1652
1653
0
  if ((tcpconn->flags & F_CONN_REMOVED_READ) && tcpconn->fd != -1) {
1654
0
    if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1655
0
        tcpconn) < 0) {
1656
0
      LM_ERR("failed to add TCP conn %p for read events\n", tcpconn);
1657
0
      tcp_fail_conn(tcpconn, "Failed to arm read", 0);
1658
0
      return;
1659
0
    }
1660
0
    tcpconn->flags &= ~F_CONN_REMOVED_READ;
1661
0
  }
1662
1663
0
  if (job->resp == 1) {
1664
0
    if (reactor_add_writer(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET, tcpconn) < 0) {
1665
0
      LM_ERR("failed to re-add TCP conn %p for write events\n", tcpconn);
1666
0
      tcp_fail_conn(tcpconn, "Failed to re-arm write", 0);
1667
0
      return;
1668
0
    }
1669
0
    tcpconn->flags &= ~F_CONN_REMOVED_WRITE;
1670
0
    tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1671
0
    tcpconn_put(tcpconn);
1672
0
    return;
1673
0
  }
1674
1675
0
  if (pending_chunks) {
1676
0
    tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1677
0
    if (tcp_async_write_job(tcpconn) < 0) {
1678
0
      LM_ERR("failed queuing follow-up TCP write job\n");
1679
0
      tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1680
0
      if (reactor_add_writer(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET, tcpconn) < 0) {
1681
0
        tcp_fail_conn(tcpconn, "Failed queueing follow-up write", 0);
1682
0
        return;
1683
0
      }
1684
0
      tcpconn->flags &= ~F_CONN_REMOVED_WRITE;
1685
0
      tcpconn_put(tcpconn);
1686
0
    }
1687
0
    return;
1688
0
  }
1689
1690
0
  tcpconn->flags &= ~F_CONN_WRITE_QUEUED;
1691
0
  tcpconn_put(tcpconn);
1692
0
}
1693
1694
static inline int handle_tcp_notify(int fd)
1695
0
{
1696
0
  char buf[64];
1697
0
  int n;
1698
0
  struct tcp_job *job;
1699
1700
0
  while ((n = read(fd, buf, sizeof(buf))) > 0)
1701
0
    ;
1702
0
  if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)
1703
0
    LM_ERR("failed to read TCP IO notify fd: %s\n", strerror(errno));
1704
1705
0
  while ((job = tcp_pop_done_job()) != NULL) {
1706
0
    if (job->op == TCP_READ_JOB)
1707
0
      tcp_complete_read(job);
1708
0
    else
1709
0
      tcp_complete_write(job);
1710
0
    thread_free(job);
1711
0
  }
1712
1713
0
  return 0;
1714
0
}
1715
1716
1717
/************************ TCP MAIN process functions ************************/
1718
1719
/*! \brief
1720
 * handles a new connection, called internally by tcp_main_loop/handle_io.
1721
 * \param si - pointer to one of the tcp socket_info structures on which
1722
 *              an io event was detected (connection attempt)
1723
 * \return  handle_* return convention: -1 on error, 0 on EAGAIN (no more
1724
 *           io events queued), >0 on success. success/error refer only to
1725
 *           the accept.
1726
 */
1727
static inline int handle_new_connect(const struct socket_info* si)
1728
0
{
1729
0
  union sockaddr_union su;
1730
0
  struct tcp_connection* tcpconn;
1731
0
  struct tcp_conn_profile prof;
1732
0
  socklen_t su_len = sizeof(su);
1733
0
  int new_sock;
1734
0
  unsigned int id;
1735
1736
  /* coverity[overrun-buffer-arg: FALSE] - union has 28 bytes, CID #200070 */
1737
0
  new_sock = accept(si->socket, &(su.s), &su_len);
1738
0
  if (new_sock == -1) {
1739
0
    if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
1740
0
      return 0;
1741
0
    LM_ERR("failed to accept connection(%d): %s\n", errno, strerror(errno));
1742
0
    return -1;
1743
0
  }
1744
1745
0
  tcp_con_get_profile(&su, &si->su, si->proto, &prof);
1746
0
  if (tcp_init_sock_opt(new_sock, &prof, si->flags, si->tos) < 0) {
1747
0
    LM_ERR("tcp_init_sock_opt failed\n");
1748
0
    close(new_sock);
1749
0
    return 1; /* success, because the accept was successful */
1750
0
  }
1751
1752
  /* add socket to list */
1753
0
  tcpconn = tcpconn_new(new_sock, &su, si, &prof, S_CONN_OK,
1754
0
    F_CONN_ACCEPTED);
1755
0
  if (tcpconn) {
1756
    /* Safe: the connection is not yet visible outside TCP main. */
1757
0
    tcpconn->refcnt++;
1758
0
    sh_log(tcpconn->hist, TCP_REF, "accept, (%d)", tcpconn->refcnt);
1759
0
    tcpconn_add(tcpconn);
1760
0
    LM_DBG("new connection: %p %d flags: %04x\n",
1761
0
      tcpconn, tcpconn->fd, tcpconn->flags);
1762
0
    if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1763
0
        tcpconn) < 0) {
1764
0
      LM_ERR("failed to add accepted TCP conn to reactor\n");
1765
0
      id = tcpconn->id;
1766
0
      TCPCONN_LOCK(id);
1767
0
      tcpconn->refcnt--;
1768
0
      if (tcpconn->refcnt == 0) {
1769
0
        _tcpconn_rm(tcpconn, 1);
1770
0
        close(new_sock);
1771
0
      } else {
1772
0
        tcpconn->lifetime = 0;
1773
0
        tcpconn->timeout = 0;
1774
0
      }
1775
0
      TCPCONN_UNLOCK(id);
1776
0
    } else {
1777
0
      tcpconn->flags &= ~F_CONN_REMOVED_READ;
1778
0
      tcpconn_put(tcpconn);
1779
0
    }
1780
0
  } else {
1781
0
    LM_ERR("tcpconn_new failed, closing socket\n");
1782
0
    close(new_sock);
1783
0
  }
1784
0
  return 1; /* accept() was successful */
1785
0
}
1786
1787
1788
/*! \brief
1789
 * handles an io event on one of the watched tcp connections
1790
 *
1791
 * \param    tcpconn - pointer to the tcp_connection for which we have an io ev.
1792
 * \param    fd_i    - index in the fd_array table (needed for delete)
1793
 * \return   handle_* return convention, but on success it always returns 0
1794
 */
1795
inline static int handle_tcpconn_ev(struct tcp_connection* tcpconn, int fd_i,
1796
    int event_type)
1797
0
{
1798
0
  int err;
1799
0
  unsigned int err_len;
1800
1801
0
  if (event_type == IO_WATCH_READ) {
1802
0
    LM_DBG("data available on %p %d\n", tcpconn, tcpconn->fd);
1803
0
    if (reactor_del_reader(tcpconn->fd, fd_i, 0) == -1)
1804
0
      return -1;
1805
0
    tcpconn->flags |= F_CONN_REMOVED_READ;
1806
0
    tcpconn_ref(tcpconn); /* refcnt ++ */
1807
0
    sh_log(tcpconn->hist, TCP_REF, "tcp-main read queued, (%d)",
1808
0
      tcpconn->refcnt);
1809
0
    if (tcp_queue_job(tcpconn, TCP_READ_JOB) < 0) {
1810
0
      LM_ERR("failed queuing TCP read job\n");
1811
0
      if (reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1812
0
          tcpconn) < 0) {
1813
0
        tcp_fail_conn(tcpconn, "Failed queueing read", 0);
1814
0
        return 0;
1815
0
      }
1816
0
      tcpconn->flags &= ~F_CONN_REMOVED_READ;
1817
0
      tcpconn_put(tcpconn);
1818
0
    }
1819
0
    return 0;
1820
0
  } else {
1821
0
    LM_DBG("connection %p fd %d is now writable\n", tcpconn, tcpconn->fd);
1822
    /* we received a write event */
1823
0
    if (tcpconn->state == S_CONN_CONNECTING) {
1824
      /* we're coming from an async connect & write
1825
       * let's see if we connected successfully */
1826
0
      err_len = sizeof(err);
1827
0
      if (getsockopt(tcpconn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len) < 0 ||
1828
0
          err != 0) {
1829
0
        LM_DBG("Failed connection attempt\n");
1830
0
        tcpconn_ref(tcpconn);
1831
0
        sh_log(tcpconn->hist, TCP_REF, "tcpconn connect, (%d)", tcpconn->refcnt);
1832
0
        reactor_del_all(tcpconn->fd, fd_i, IO_FD_CLOSING);
1833
0
        tcpconn->flags|=F_CONN_REMOVED;
1834
0
        tcp_trigger_report(tcpconn, TCP_REPORT_CLOSE,
1835
0
          "Async connect failed");
1836
0
        sh_log(tcpconn->hist, TCP_UNREF, "tcpconn connect, (%d)", tcpconn->refcnt);
1837
0
        tcpconn_destroy(tcpconn);
1838
0
        return 0;
1839
0
      }
1840
1841
      /* we successfully connected - further treat this case as if we
1842
       * were coming from an async write */
1843
0
      tcpconn->state = S_CONN_OK;
1844
0
      LM_DBG("Successfully completed previous async connect\n");
1845
1846
      /* now that we completed the async connection, we also need to
1847
       * listen for READ events, otherwise these will get lost */
1848
0
      if (tcpconn->flags & F_CONN_REMOVED_READ) {
1849
0
          reactor_add_reader(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1850
0
            tcpconn);
1851
0
          tcpconn->flags &= ~F_CONN_REMOVED_READ;
1852
0
        }
1853
1854
0
      goto async_write;
1855
0
    } else {
1856
0
async_write:
1857
      /* no more write events for now */
1858
0
        if (reactor_del_writer(tcpconn->fd, fd_i, 0) == -1)
1859
0
          return -1;
1860
0
      tcpconn->flags |= F_CONN_REMOVED_WRITE;
1861
0
      tcpconn_ref(tcpconn); /* refcnt ++ */
1862
0
      sh_log(tcpconn->hist, TCP_REF, "tcpconn write, (%d)",
1863
0
        tcpconn->refcnt);
1864
0
      if (tcp_queue_write_job(tcpconn) < 0) {
1865
0
        LM_ERR("failed queuing TCP write job\n");
1866
0
        if (reactor_add_writer(tcpconn->fd, F_TCPCONN, RCT_PRIO_NET,
1867
0
            tcpconn) < 0) {
1868
0
          tcp_fail_conn(tcpconn, "Failed queueing write", 0);
1869
0
          return 0;
1870
0
        }
1871
0
        tcpconn->flags &= ~F_CONN_REMOVED_WRITE;
1872
0
        tcpconn_put(tcpconn);
1873
0
      }
1874
0
      return 0;
1875
0
    }
1876
0
  }
1877
0
}
1878
1879
1880
/*! \brief generic handle io routine, it will call the appropiate
1881
 *  handle_xxx() based on the fd_map type
1882
 *
1883
 * \param  fm  - pointer to a fd hash entry
1884
 * \param  idx - index in the fd_array (or -1 if not known)
1885
 * \return -1 on error
1886
 *          0 on EAGAIN or when by some other way it is known that no more
1887
 *            io events are queued on the fd (the receive buffer is empty).
1888
 *            Usefull to detect when there are no more io events queued for
1889
 *            sigio_rt, epoll_et, kqueue.
1890
 *         >0 on successful read from the fd (when there might be more io
1891
 *            queued -- the receive buffer might still be non-empty)
1892
 */
1893
inline static int handle_io(struct fd_map* fm, int idx,int event_type)
1894
0
{
1895
0
  int ret = 0;
1896
1897
0
  pt_become_active();
1898
  /* for now we do not do any profiling here as all ops here are
1899
     only internals related to TCP passing beetween processing, no real
1900
     processing
1901
   */
1902
0
  switch(fm->type){
1903
0
    case F_TCP_LISTENER:
1904
0
      ret = handle_new_connect((const struct socket_info*)fm->data);
1905
0
      break;
1906
0
    case F_TCPCONN:
1907
0
      ret = handle_tcpconn_ev((struct tcp_connection*)fm->data, idx,
1908
0
        event_type);
1909
0
      break;
1910
0
    case F_TCP_NOTIFY:
1911
0
      ret = handle_tcp_notify(fm->fd);
1912
0
      break;
1913
0
    case F_IPC:
1914
0
      ipc_handle_job(fm->fd);
1915
0
      break;
1916
0
    case F_NONE:
1917
0
      LM_CRIT("empty fd map\n");
1918
0
      goto error;
1919
0
    default:
1920
0
      LM_CRIT("unknown fd type %d\n", fm->type);
1921
0
      goto error;
1922
0
  }
1923
0
  pt_become_idle();
1924
0
  return ret;
1925
0
error:
1926
0
  pt_become_idle();
1927
0
  return -1;
1928
0
}
1929
1930
1931
/*
1932
 * iterates through all TCP connections and closes expired ones
1933
 * Note: runs once per second at most
1934
 */
1935
#define tcpconn_lifetime(last_sec) \
1936
  do { \
1937
    int now; \
1938
    now = get_ticks(); \
1939
    if (last_sec != now) { \
1940
      last_sec = now; \
1941
      __tcpconn_lifetime(0); \
1942
    } \
1943
  } while (0)
1944
1945
1946
/*! \brief very inefficient for now - FIXME
1947
 * keep in sync with tcpconn_destroy, the "delete" part should be
1948
 * the same except for io_watch_del..
1949
 * \todo FIXME (very inefficient for now)
1950
 */
1951
static inline void __tcpconn_lifetime(int shutdown)
1952
0
{
1953
0
  struct tcp_connection *c, *next;
1954
0
  unsigned int ticks,part;
1955
0
  unsigned h;
1956
0
  int fd;
1957
0
  void *reason;
1958
1959
0
  if (have_ticks())
1960
0
    ticks=get_ticks();
1961
0
  else
1962
0
    ticks=0;
1963
1964
0
  for( part=0 ; part<TCP_PARTITION_SIZE ; part++ ) {
1965
0
    if (!shutdown) TCPCONN_LOCK(part); /* fixme: we can lock only on delete IMO */
1966
0
    for(h=0; h<TCP_ID_HASH_SIZE; h++){
1967
0
      c=TCP_PART(part).tcpconn_id_hash[h];
1968
0
      while(c){
1969
0
        next=c->id_next;
1970
0
        if (shutdown || ((c->refcnt == 0) &&
1971
0
        ((ticks > c->lifetime) ||
1972
0
        (c->msg_attempts && ticks > c->timeout)))) {
1973
0
          if (!shutdown)
1974
0
            LM_DBG("timeout for hash=%d - %p"
1975
0
                " (%d > %d)\n", h, c, ticks, c->lifetime);
1976
0
          fd=c->fd;
1977
          /* report the closing of the connection . Note that
1978
           * there are connectioned that use an foced expire to 0
1979
           * as a way to be deleted - we are not interested in */
1980
          /* Also, do not trigger reporting when shutdown
1981
           * is done */
1982
0
          if (c->lifetime>0 && !shutdown) {
1983
0
            reason = (c->msg_attempts && ticks > c->timeout) ?
1984
0
              "Timeout waiting for a complete message" :
1985
0
              "Timeout on no traffic";
1986
0
            tcp_trigger_report(c, TCP_REPORT_CLOSE, reason);
1987
0
          }
1988
0
          if ((!shutdown)&&(fd>0)&&(c->refcnt==0)) {
1989
            /* if any of read or write are set, we need to remove
1990
             * the fd from the reactor */
1991
0
            if ((c->flags & F_CONN_REMOVED) != F_CONN_REMOVED){
1992
0
              reactor_del_all( fd, -1, IO_FD_CLOSING);
1993
0
              c->flags|=F_CONN_REMOVED;
1994
0
            }
1995
0
            close(fd);
1996
0
            c->fd = -1;
1997
0
            }
1998
0
            _tcpconn_rm(c, shutdown?1:0);
1999
0
          }
2000
0
          c=next;
2001
0
        }
2002
0
    }
2003
0
    if (!shutdown) TCPCONN_UNLOCK(part);
2004
0
  }
2005
0
}
2006
2007
2008
static void tcp_main_server(void)
2009
0
{
2010
0
  static unsigned int last_sec = 0;
2011
0
  struct socket_info_full* sif;
2012
0
  struct sr_module *m;
2013
0
  int n;
2014
2015
  /* instruct tls_mgm to initialize all TLS domains */
2016
0
  for (m=modules; m; m = m->next) {
2017
0
    if (strcmp(m->exports->name, "tls_mgm") == 0)
2018
0
      if (init_child(PROC_TCP_MAIN) < 0) {
2019
0
        LM_ERR("error in init_child for PROC_TCP_MAIN\n");
2020
0
        goto error;
2021
0
      }
2022
0
  }
2023
2024
  /* we run in a separate, dedicated process, with its own reactor
2025
   * (reactors are per process) */
2026
0
  if (init_worker_reactor("TCP_main", RCT_PRIO_MAX)<0)
2027
0
    goto error;
2028
2029
  /* now start watching all the fds */
2030
2031
  /* add all the sockets we listens on for connections */
2032
0
  for (n = PROTO_FIRST; n < PROTO_LAST; n++)
2033
0
    if (is_tcp_based_proto(n))
2034
0
      for (sif = protos[n].listeners; sif; sif = sif->next) {
2035
0
        struct socket_info* si = &sif->socket_info;
2036
0
        if (protos[n].tran.bind_listener &&
2037
0
            protos[n].tran.bind_listener(si) < 0) {
2038
0
          LM_ERR("failed to bind listener [%.*s], proto %s\n",
2039
0
            si->name.len, si->name.s, protos[n].name);
2040
0
          goto error;
2041
0
        }
2042
0
        if (si->socket != -1 &&
2043
0
            reactor_add_reader(si->socket, F_TCP_LISTENER,
2044
0
              RCT_PRIO_NET, si) < 0) {
2045
0
          LM_ERR("failed to add listen socket to reactor\n");
2046
0
          goto error;
2047
0
        }
2048
0
      }
2049
  /* init: start watching for the IPC jobs */
2050
0
  if (reactor_add_reader(IPC_FD_READ_SELF, F_IPC, RCT_PRIO_ASYNC, NULL)<0){
2051
0
    LM_CRIT("failed to add IPC pipe to reactor\n");
2052
0
    goto error;
2053
0
  }
2054
2055
0
  if (tcp_pool_init() < 0)
2056
0
    goto error;
2057
2058
0
  is_tcp_main = 1;
2059
2060
  /* main loop (requires "handle_io()" implementation) */
2061
0
  reactor_main_loop( TCP_MAIN_SELECT_TIMEOUT, error,
2062
0
      tcpconn_lifetime(last_sec) );
2063
2064
0
error:
2065
0
  tcp_pool_destroy();
2066
0
  destroy_worker_reactor();
2067
0
  LM_CRIT("exiting...");
2068
0
  exit(-1);
2069
0
}
2070
2071
2072
2073
/**************************** Control functions ******************************/
2074
2075
/* initializes the TCP network level in terms of data structures */
2076
int tcp_init(void)
2077
0
{
2078
0
  unsigned int i;
2079
2080
  /* first we do auto-detection to see if there are any TCP based
2081
   * protocols loaded */
2082
0
  for ( i=PROTO_FIRST ; i<PROTO_LAST ; i++ )
2083
0
    if (is_tcp_based_proto(i) && proto_has_listeners(i)) {
2084
0
      tcp_disabled=0;
2085
0
      break;
2086
0
    }
2087
2088
0
  tcp_init_con_profiles();
2089
2090
0
  if (tcp_disabled)
2091
0
    return 0;
2092
2093
#ifdef DBG_TCPCON
2094
  con_hist = shl_init("TCP con", 10000, 0);
2095
  if (!con_hist) {
2096
    LM_ERR("oom con hist\n");
2097
    goto error;
2098
  }
2099
#endif
2100
2101
0
  if (tcp_auto_scaling_profile) {
2102
0
    s_profile = get_scaling_profile(tcp_auto_scaling_profile);
2103
0
    if (s_profile==NULL) {
2104
0
      LM_WARN("TCP scaling profile <%s> not defined "
2105
0
        "-> ignoring it...\n", tcp_auto_scaling_profile);
2106
0
    } else {
2107
0
      auto_scaling_enabled = 1;
2108
0
    }
2109
0
  }
2110
2111
0
  tcp_workers_max_no = (s_profile && (tcp_workers_no<s_profile->max_procs)) ?
2112
0
    s_profile->max_procs : tcp_workers_no ;
2113
2114
  /* init tcp workers array */
2115
0
  tcp_workers = (struct tcp_worker*)shm_malloc
2116
0
    ( tcp_workers_max_no*sizeof(struct tcp_worker) );
2117
0
  if (tcp_workers==0) {
2118
0
    LM_CRIT("could not alloc tcp_workers array in shm memory\n");
2119
0
    goto error;
2120
0
  }
2121
0
  memset( tcp_workers, 0, tcp_workers_max_no*sizeof(struct tcp_worker));
2122
  /* init globals */
2123
0
  connection_id=(unsigned int*)shm_malloc(sizeof(unsigned int));
2124
0
  if (connection_id==0){
2125
0
    LM_CRIT("could not alloc globals in shm memory\n");
2126
0
    goto error;
2127
0
  }
2128
  // The  rand()  function returns a pseudo-random integer in the range 0 to
2129
  // RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).
2130
0
  *connection_id=(unsigned int)rand();
2131
0
  tcp_connections_no = (unsigned int *)shm_malloc(sizeof(*tcp_connections_no));
2132
0
  if (tcp_connections_no == 0) {
2133
0
    LM_CRIT("could not alloc tcp connection counter in shm memory\n");
2134
0
    goto error;
2135
0
  }
2136
0
  *tcp_connections_no = 0;
2137
0
  tcp_main_proc_no = (int *)shm_malloc(sizeof(*tcp_main_proc_no));
2138
0
  if (tcp_main_proc_no == 0) {
2139
0
    LM_CRIT("could not alloc tcp main proc slot in shm memory\n");
2140
0
    goto error;
2141
0
  }
2142
0
  *tcp_main_proc_no = -1;
2143
0
  tcp_write_queue = shm_malloc(sizeof(*tcp_write_queue));
2144
0
  if (tcp_write_queue == 0) {
2145
0
    LM_CRIT("could not alloc tcp shared write queue in shm memory\n");
2146
0
    goto error;
2147
0
  }
2148
0
  memset(tcp_write_queue, 0, sizeof(*tcp_write_queue));
2149
0
  if (cond_init(&tcp_write_queue->cond) != 0) {
2150
0
    LM_CRIT("could not init tcp shared write queue cond\n");
2151
0
    shm_free(tcp_write_queue);
2152
0
    tcp_write_queue = 0;
2153
0
    goto error;
2154
0
  }
2155
0
  tcp_connections_lock = lock_alloc();
2156
0
  if (tcp_connections_lock == 0) {
2157
0
    LM_CRIT("could not alloc tcp connection counter lock\n");
2158
0
    goto error;
2159
0
  }
2160
0
  if (lock_init(tcp_connections_lock) == 0) {
2161
0
    LM_CRIT("could not init tcp connection counter lock\n");
2162
0
    lock_dealloc((void *)tcp_connections_lock);
2163
0
    tcp_connections_lock = 0;
2164
0
    goto error;
2165
0
  }
2166
0
  memset( &tcp_parts, 0, TCP_PARTITION_SIZE*sizeof(struct tcp_partition));
2167
  /* init partitions */
2168
0
  for( i=0 ; i<TCP_PARTITION_SIZE ; i++ ) {
2169
    /* init lock */
2170
0
    tcp_parts[i].tcpconn_lock=lock_alloc();
2171
0
    if (tcp_parts[i].tcpconn_lock==0){
2172
0
      LM_CRIT("could not alloc lock\n");
2173
0
      goto error;
2174
0
    }
2175
0
    if (lock_init(tcp_parts[i].tcpconn_lock)==0){
2176
0
      LM_CRIT("could not init lock\n");
2177
0
      lock_dealloc((void*)tcp_parts[i].tcpconn_lock);
2178
0
      tcp_parts[i].tcpconn_lock=0;
2179
0
      goto error;
2180
0
    }
2181
    /* alloc hashtables*/
2182
0
    tcp_parts[i].tcpconn_aliases_hash=(struct tcp_conn_alias**)
2183
0
      shm_malloc(TCP_ALIAS_HASH_SIZE* sizeof(struct tcp_conn_alias*));
2184
0
    if (tcp_parts[i].tcpconn_aliases_hash==0){
2185
0
      LM_CRIT("could not alloc address hashtable in shm memory\n");
2186
0
      goto error;
2187
0
    }
2188
0
    tcp_parts[i].tcpconn_id_hash=(struct tcp_connection**)
2189
0
      shm_malloc(TCP_ID_HASH_SIZE*sizeof(struct tcp_connection*));
2190
0
    if (tcp_parts[i].tcpconn_id_hash==0){
2191
0
      LM_CRIT("could not alloc id hashtable in shm memory\n");
2192
0
      goto error;
2193
0
    }
2194
    /* init hashtables*/
2195
0
    memset((void*)tcp_parts[i].tcpconn_aliases_hash, 0,
2196
0
      TCP_ALIAS_HASH_SIZE * sizeof(struct tcp_conn_alias*));
2197
0
    memset((void*)tcp_parts[i].tcpconn_id_hash, 0,
2198
0
      TCP_ID_HASH_SIZE * sizeof(struct tcp_connection*));
2199
0
  }
2200
2201
0
  return 0;
2202
0
error:
2203
  /* clean-up */
2204
0
  tcp_destroy();
2205
0
  return -1;
2206
0
}
2207
2208
2209
/* destroys the TCP data */
2210
void tcp_destroy(void)
2211
0
{
2212
0
  int part;
2213
2214
0
  if (tcp_parts[0].tcpconn_id_hash)
2215
      /* force close/expire for all active tcpconns*/
2216
0
      __tcpconn_lifetime(1);
2217
2218
0
  if (connection_id){
2219
0
    shm_free(connection_id);
2220
0
    connection_id=0;
2221
0
  }
2222
2223
0
  if (tcp_connections_no) {
2224
0
    shm_free(tcp_connections_no);
2225
0
    tcp_connections_no = 0;
2226
0
  }
2227
2228
0
  if (tcp_main_proc_no) {
2229
0
    shm_free(tcp_main_proc_no);
2230
0
    tcp_main_proc_no = 0;
2231
0
  }
2232
2233
0
  if (tcp_dispatch_sock[0] >= 0) {
2234
0
    close(tcp_dispatch_sock[0]);
2235
0
    tcp_dispatch_sock[0] = -1;
2236
0
  }
2237
0
  if (tcp_dispatch_sock[1] >= 0) {
2238
0
    close(tcp_dispatch_sock[1]);
2239
0
    tcp_dispatch_sock[1] = -1;
2240
0
  }
2241
2242
0
  if (tcp_write_queue) {
2243
    /* Skip cond teardown during attendant shutdown. */
2244
    /* cond_destroy(&tcp_write_queue->cond); */
2245
0
    shm_free(tcp_write_queue);
2246
0
    tcp_write_queue = 0;
2247
0
  }
2248
2249
0
  if (tcp_connections_lock) {
2250
0
    lock_destroy(tcp_connections_lock);
2251
0
    lock_dealloc((void *)tcp_connections_lock);
2252
0
    tcp_connections_lock = 0;
2253
0
  }
2254
2255
0
  for ( part=0 ; part<TCP_PARTITION_SIZE ; part++ ) {
2256
0
    if (tcp_parts[part].tcpconn_id_hash){
2257
0
      shm_free(tcp_parts[part].tcpconn_id_hash);
2258
0
      tcp_parts[part].tcpconn_id_hash=0;
2259
0
    }
2260
0
    if (tcp_parts[part].tcpconn_aliases_hash){
2261
0
      shm_free(tcp_parts[part].tcpconn_aliases_hash);
2262
0
      tcp_parts[part].tcpconn_aliases_hash=0;
2263
0
    }
2264
0
    if (tcp_parts[part].tcpconn_lock){
2265
0
      lock_destroy(tcp_parts[part].tcpconn_lock);
2266
0
      lock_dealloc((void*)tcp_parts[part].tcpconn_lock);
2267
0
      tcp_parts[part].tcpconn_lock=0;
2268
0
    }
2269
0
  }
2270
0
}
2271
2272
2273
static int _get_own_tcp_worker_id(void)
2274
0
{
2275
0
  pid_t pid;
2276
0
  int i;
2277
2278
0
  pid = getpid();
2279
0
  for( i=0 ; i<tcp_workers_max_no ; i++)
2280
0
    if(tcp_workers[i].pid==pid)
2281
0
      return i;
2282
2283
0
  return -1;
2284
0
}
2285
2286
2287
void tcp_reset_worker_slot(void)
2288
0
{
2289
0
  int i;
2290
2291
0
  if ((i=_get_own_tcp_worker_id())>=0) {
2292
0
    tcp_workers[i].state=STATE_INACTIVE;
2293
0
    tcp_workers[i].pid=0;
2294
0
    tcp_workers[i].pt_idx=0;
2295
0
  }
2296
0
}
2297
2298
2299
static int fork_dynamic_tcp_process(void *foo)
2300
0
{
2301
0
  int p_id;
2302
0
  int r;
2303
0
  const struct internal_fork_params ifp_sr_tcp = {
2304
0
    .proc_desc = "SIP receiver TCP",
2305
0
    .flags = OSS_PROC_DYNAMIC|OSS_PROC_NEEDS_SCRIPT,
2306
0
    .type = TYPE_TCP,
2307
0
  };
2308
2309
  /* search for a free slot in the TCP workers table */
2310
0
  for (r = 0; r < tcp_workers_max_no; r++)
2311
0
    if (tcp_workers[r].state == STATE_INACTIVE)
2312
0
      break;
2313
2314
0
  if (r == tcp_workers_max_no) {
2315
0
    LM_BUG("trying to fork one more TCP worker but no free slot in "
2316
0
      "the TCP table (size=%d)\n", tcp_workers_max_no);
2317
0
    return -1;
2318
0
  }
2319
2320
0
  if ((p_id = internal_fork(&ifp_sr_tcp)) < 0) {
2321
0
    LM_ERR("cannot fork dynamic TCP worker process\n");
2322
0
    return -1;
2323
0
  } else if (p_id == 0) {
2324
    /* new TCP worker process */
2325
0
    if (tcp_dispatch_sock[1] >= 0)
2326
0
      close(tcp_dispatch_sock[1]);
2327
0
    tcp_dispatch_sock[1] = -1;
2328
2329
0
    set_proc_attrs("TCP receiver");
2330
0
    tcp_workers[r].pid = getpid();
2331
2332
0
    if (tcp_worker_proc_reactor_init(tcp_dispatch_sock[0]) < 0 ||
2333
0
    init_child(20000) ||
2334
0
    self_update_routing_script() < 0)
2335
0
      goto error;
2336
2337
0
    report_conditional_status(1, 0);
2338
0
    clean_read_pipeend();
2339
2340
0
    tcp_worker_proc_loop();
2341
0
    destroy_worker_reactor();
2342
2343
0
error:
2344
0
    report_failure_status();
2345
0
    LM_ERR("initializing new TCP worker failed, exiting with error\n");
2346
0
    pt[process_no].flags |= OSS_PROC_SELFEXIT;
2347
0
    exit(-1);
2348
0
  } else {
2349
    /* parent/attendant */
2350
0
    tcp_workers[r].state = STATE_ACTIVE;
2351
0
    tcp_workers[r].pt_idx = p_id;
2352
0
    return p_id;
2353
0
  }
2354
2355
0
  return 0;
2356
0
}
2357
2358
2359
static void tcp_process_graceful_terminate(int sender, void *param)
2360
0
{
2361
0
  int i;
2362
2363
  /* accept this only from the attendant process */
2364
0
  if (sender != 0) {
2365
0
    LM_BUG("graceful terminate received from a non-main process\n");
2366
0
    return;
2367
0
  }
2368
0
  LM_NOTICE("process %d received RPC to terminate from Main\n", process_no);
2369
2370
  /* reserve this slot until tcp_terminate_worker() detaches the process
2371
   * from the shared dispatch queue and completes its pending async work */
2372
0
  if ((i = _get_own_tcp_worker_id()) >= 0)
2373
0
    tcp_workers[i].state = STATE_DRAINING;
2374
2375
0
  tcp_terminate_worker();
2376
0
}
2377
2378
2379
/* counts the number of TCP processes to start with; this number may
2380
 * change during runtime due auto-scaling */
2381
int tcp_count_processes(unsigned int *extra)
2382
0
{
2383
0
  if (extra) *extra = 0;
2384
2385
0
  if (tcp_disabled)
2386
0
    return 0;
2387
2388
0
  if (s_profile && extra && s_profile->max_procs > tcp_workers_no)
2389
0
    *extra = s_profile->max_procs - tcp_workers_no;
2390
2391
0
  return 1 /* tcp main / IO process */ + tcp_workers_no /* dispatch workers */;
2392
0
}
2393
2394
2395
int tcp_start_processes(int *chd_rank, int *startup_done)
2396
0
{
2397
0
  int r, p_id, flags;
2398
0
  const struct internal_fork_params ifp_sr_tcp = {
2399
0
    .proc_desc = "SIP receiver TCP",
2400
0
    .flags = OSS_PROC_NEEDS_SCRIPT,
2401
0
    .type = TYPE_TCP,
2402
0
  };
2403
2404
0
  if (tcp_disabled)
2405
0
    return 0;
2406
2407
  /* create the shared dispatch socket from TCP main to TCP workers */
2408
0
  if (socketpair(AF_UNIX, SOCK_DGRAM, 0, tcp_dispatch_sock) < 0) {
2409
0
    LM_ERR("socketpair failed for TCP worker dispatch: %s\n",
2410
0
      strerror(errno));
2411
0
    goto error;
2412
0
  }
2413
0
  flags = fcntl(tcp_dispatch_sock[0], F_GETFL);
2414
0
  if (flags == -1) {
2415
0
    LM_ERR("fcntl failed for TCP worker dispatch socket: %s\n",
2416
0
      strerror(errno));
2417
0
    goto error;
2418
0
  }
2419
0
  if (fcntl(tcp_dispatch_sock[0], F_SETFL, flags | O_NONBLOCK) == -1) {
2420
0
    LM_ERR("failed to set non-blocking on TCP worker dispatch socket: %s\n",
2421
0
      strerror(errno));
2422
0
    goto error;
2423
0
  }
2424
0
  flags = fcntl(tcp_dispatch_sock[1], F_GETFL);
2425
0
  if (flags == -1) {
2426
0
    LM_ERR("fcntl failed for TCP worker dispatch socket: %s\n",
2427
0
      strerror(errno));
2428
0
    goto error;
2429
0
  }
2430
0
  if (fcntl(tcp_dispatch_sock[1], F_SETFL, flags | O_NONBLOCK) == -1) {
2431
0
    LM_ERR("failed to set non-blocking on TCP worker dispatch socket: %s\n",
2432
0
      strerror(errno));
2433
0
    goto error;
2434
0
  }
2435
2436
0
  if (auto_scaling_enabled && s_profile &&
2437
0
  create_process_group(TYPE_TCP, NULL, s_profile,
2438
0
    fork_dynamic_tcp_process, tcp_process_graceful_terminate) != 0)
2439
0
    LM_ERR("failed to create TCP auto-scaling process group; "
2440
0
      "automatic scaling will not be possible\n");
2441
2442
0
  for (r = 0; r < tcp_workers_no; r++) {
2443
0
    (*chd_rank)++;
2444
0
    p_id = internal_fork(&ifp_sr_tcp);
2445
0
    if (p_id < 0) {
2446
0
      LM_ERR("cannot fork TCP worker process %d\n", r);
2447
0
      goto error;
2448
0
    } else if (p_id > 0) {
2449
      /* parent */
2450
0
      tcp_workers[r].state = STATE_ACTIVE;
2451
0
      tcp_workers[r].pt_idx = p_id;
2452
0
      continue;
2453
0
    }
2454
2455
    /* child */
2456
0
    if (tcp_dispatch_sock[1] >= 0)
2457
0
      close(tcp_dispatch_sock[1]);
2458
0
    tcp_dispatch_sock[1] = -1;
2459
2460
0
    set_proc_attrs("TCP receiver");
2461
0
    tcp_workers[r].pid = getpid();
2462
2463
0
    if (tcp_worker_proc_reactor_init(tcp_dispatch_sock[0]) < 0 ||
2464
0
        init_child(*chd_rank) < 0) {
2465
0
      LM_ERR("init_child failed for TCP worker %d\n", r);
2466
0
      report_failure_status();
2467
0
      if (startup_done)
2468
0
        *startup_done = -1;
2469
0
      exit(-1);
2470
0
    }
2471
2472
    /* first TCP worker runs startup_route if not already run */
2473
0
    if (startup_done && *startup_done == 0 && r == 0) {
2474
0
      LM_DBG("running startup route for first TCP worker\n");
2475
0
      if (run_startup_route() < 0) {
2476
0
        LM_ERR("startup route processing failed in TCP worker\n");
2477
0
        report_failure_status();
2478
0
        *startup_done = -1;
2479
0
        exit(-1);
2480
0
      }
2481
0
      *startup_done = 1;
2482
0
    }
2483
2484
0
    report_conditional_status((!no_daemon_mode), 0);
2485
0
    tcp_worker_proc_loop();
2486
0
  }
2487
2488
  /* Keep the worker endpoint in the attendant when auto-scaling is enabled,
2489
   * so dynamically forked TCP workers can inherit the shared queue. */
2490
0
  if (!s_profile && tcp_dispatch_sock[0] >= 0) {
2491
0
    close(tcp_dispatch_sock[0]);
2492
0
    tcp_dispatch_sock[0] = -1;
2493
0
  }
2494
2495
0
  if (startup_done && tcp_workers_no > 0)
2496
0
    while (!(*startup_done)) {
2497
0
      usleep(5);
2498
0
      handle_sigs();
2499
0
    }
2500
2501
0
  return 0;
2502
0
error:
2503
0
  if (tcp_dispatch_sock[0] >= 0) {
2504
0
    close(tcp_dispatch_sock[0]);
2505
0
    tcp_dispatch_sock[0] = -1;
2506
0
  }
2507
0
  if (tcp_dispatch_sock[1] >= 0) {
2508
0
    close(tcp_dispatch_sock[1]);
2509
0
    tcp_dispatch_sock[1] = -1;
2510
0
  }
2511
0
  return -1;
2512
0
}
2513
2514
static int tcpconn_update_local_port(struct tcp_connection *tcpconn)
2515
0
{
2516
0
  union sockaddr_union local_su;
2517
0
  socklen_t su_size;
2518
2519
0
  su_size = sockaddru_len(tcpconn->rcv.src_su);
2520
0
  if (getsockname(tcpconn->fd, (struct sockaddr *)&local_su, &su_size) < 0) {
2521
0
    LM_ERR("failed to get local socket info on conn %u: %s\n",
2522
0
      tcpconn->id, strerror(errno));
2523
0
    return -1;
2524
0
  }
2525
2526
0
  tcpconn->rcv.dst_port = su_getport(&local_su);
2527
0
  return 0;
2528
0
}
2529
2530
static int tcpconn_prepare_write(struct tcp_connection *tcpconn)
2531
0
{
2532
0
  int fd;
2533
0
  int connected = 0;
2534
2535
0
  if ((tcpconn->flags & F_CONN_INIT) == 0) {
2536
0
    if (protos[tcpconn->type].net.stream.conn.init &&
2537
0
        protos[tcpconn->type].net.stream.conn.init(tcpconn) < 0) {
2538
0
      LM_ERR("failed to init proto %d conn %p in TCP main\n",
2539
0
        tcpconn->type, tcpconn);
2540
0
      return -1;
2541
0
    }
2542
0
    tcpconn->flags |= F_CONN_INIT;
2543
0
  }
2544
2545
0
  if (tcpconn->fd < 0) {
2546
0
    if (!tcpconn->rcv.bind_address) {
2547
0
      LM_ERR("missing bind_address for outbound conn %u\n", tcpconn->id);
2548
0
      return -1;
2549
0
    }
2550
2551
0
    fd = tcp_sync_connect_fd(&tcpconn->rcv.bind_address->su,
2552
0
        &tcpconn->rcv.src_su, tcpconn->type, &tcpconn->profile,
2553
0
        tcpconn->rcv.bind_address->flags,
2554
0
        tcpconn->rcv.bind_address->tos);
2555
0
    if (fd < 0)
2556
0
      return -1;
2557
2558
0
    tcpconn->fd = fd;
2559
0
    if (tcpconn_update_local_port(tcpconn) < 0) {
2560
0
      close(fd);
2561
0
      tcpconn->fd = -1;
2562
0
      return -1;
2563
0
    }
2564
2565
0
    tcpconn->state = S_CONN_OK;
2566
0
    connected = 1;
2567
0
  }
2568
2569
0
  if (connected && protos[tcpconn->type].net.stream.conn.connect) {
2570
0
    if (protos[tcpconn->type].net.stream.conn.connect(tcpconn) < 0) {
2571
0
      LM_ERR("failed to finish proto %d connect on conn %u\n",
2572
0
        tcpconn->type, tcpconn->id);
2573
0
      return -1;
2574
0
    }
2575
0
  }
2576
2577
0
  return 0;
2578
0
}
2579
2580
2581
int tcp_start_listener(void)
2582
0
{
2583
0
  int p_id;
2584
0
  const struct internal_fork_params ifp_tcp_main = {
2585
0
    .proc_desc = "TCP main",
2586
0
    .flags = 0,
2587
0
    .type = TYPE_NONE,
2588
0
  };
2589
2590
0
  if (tcp_disabled)
2591
0
    return 0;
2592
2593
  /* start the TCP manager process */
2594
0
  if ( (p_id=internal_fork(&ifp_tcp_main))<0 ) {
2595
0
    LM_CRIT("cannot fork tcp main process\n");
2596
0
    goto error;
2597
0
  }else if (p_id==0){
2598
      /* child */
2599
0
    report_conditional_status( (!no_daemon_mode), 0);
2600
2601
0
    tcp_main_server();
2602
0
    exit(-1);
2603
0
  }
2604
0
  *tcp_main_proc_no = p_id;
2605
2606
0
  return 0;
2607
0
error:
2608
0
  return -1;
2609
0
}
2610
2611
int tcp_has_async_write(void)
2612
0
{
2613
0
  return reactor_has_async();
2614
0
}
2615
2616
static int tcp_close_conn_run(void *data)
2617
0
{
2618
0
  struct tcp_connection *conn = data;
2619
2620
0
  if (!conn)
2621
0
    return -1;
2622
2623
0
  tcp_conn_destroy(conn);
2624
0
  return 0;
2625
0
}
2626
2627
static void tcp_close_conn_rpc(int pid, void *param)
2628
0
{
2629
0
  tcp_close_conn_run(param);
2630
0
}
2631
2632
int tcp_close_connection(str *ipport)
2633
0
{
2634
0
  struct tcp_connection *conn = NULL;
2635
0
  struct ip_addr *ip;
2636
0
  str host;
2637
0
  unsigned int id;
2638
0
  int port, proto, rc, tcp_main_proc;
2639
0
  int start_proto, end_proto;
2640
0
  unsigned int p;
2641
0
  char *sep;
2642
2643
0
  if (tcp_disabled)
2644
0
    return 0;
2645
2646
0
  sep = q_memchr(ipport->s, ':', ipport->len);
2647
0
  if (!sep) {
2648
0
    if (str2int(ipport, &id) < 0) {
2649
0
      LM_ERR("failed to parse tcp connection [%.*s]\n",
2650
0
        ipport->len, ipport->s);
2651
0
      return -1;
2652
0
    }
2653
2654
0
    switch (tcp_conn_get(id, NULL, 0, PROTO_NONE, NULL, &conn, NULL)) {
2655
0
    case 1:
2656
0
      goto found;
2657
0
    case -1:
2658
0
      return -1;
2659
0
    default:
2660
0
      return 0;
2661
0
    }
2662
0
  }
2663
2664
0
  if (parse_phostport(ipport->s, ipport->len, &host.s, &host.len,
2665
0
  &port, &proto) != 0 || port <= 0) {
2666
0
    LM_ERR("failed to parse tcp connection [%.*s]\n",
2667
0
      ipport->len, ipport->s);
2668
0
    return -1;
2669
0
  }
2670
2671
0
  ip = str2ip(&host);
2672
0
  if (!ip)
2673
0
    ip = str2ip6(&host);
2674
0
  if (!ip) {
2675
0
    LM_ERR("invalid IP in tcp connection [%.*s]\n",
2676
0
      ipport->len, ipport->s);
2677
0
    return -1;
2678
0
  }
2679
2680
0
  if (proto != PROTO_NONE) {
2681
0
    if (!is_tcp_based_proto(proto)) {
2682
0
      LM_ERR("protocol %d is not TCP based for [%.*s]\n",
2683
0
        proto, ipport->len, ipport->s);
2684
0
      return -1;
2685
0
    }
2686
0
    start_proto = proto;
2687
0
    end_proto = proto + 1;
2688
0
  } else {
2689
0
    start_proto = 0;
2690
0
    end_proto = PROTO_LAST;
2691
0
  }
2692
2693
0
  for (p = start_proto; p < (unsigned int)end_proto; p++) {
2694
0
    if (!is_tcp_based_proto(p))
2695
0
      continue;
2696
2697
0
    switch (tcp_conn_get(0, ip, port, p, NULL, &conn, NULL)) {
2698
0
    case 1:
2699
0
      goto found;
2700
0
    case -1:
2701
0
      return -1;
2702
0
    }
2703
0
  }
2704
2705
0
  return 0;
2706
2707
0
found:
2708
0
  TCPCONN_LOCK(conn->id);
2709
0
  conn->flags |= F_CONN_FORCE_CLOSED;
2710
0
  TCPCONN_UNLOCK(conn->id);
2711
2712
0
  tcp_main_proc = tcp_get_main_proc_no();
2713
0
  if (tcp_main_proc < 0)
2714
0
    rc = -1;
2715
0
  else if (process_no == tcp_main_proc)
2716
0
    rc = tcp_close_conn_run(conn);
2717
0
  else
2718
0
    rc = ipc_send_rpc(tcp_main_proc, tcp_close_conn_rpc, conn);
2719
2720
0
  if (rc < 0) {
2721
0
    TCPCONN_LOCK(conn->id);
2722
0
    conn->flags &= ~F_CONN_FORCE_CLOSED;
2723
0
    TCPCONN_UNLOCK(conn->id);
2724
0
    tcp_conn_release(conn, 0);
2725
0
    return -1;
2726
0
  }
2727
2728
0
  return 1;
2729
0
}
2730
2731
2732
/***************************** MI functions **********************************/
2733
2734
mi_response_t *mi_tcp_list_conns(const mi_params_t *params,
2735
            struct mi_handler *async_hdl)
2736
0
{
2737
0
  mi_response_t *resp;
2738
0
  mi_item_t *resp_obj;
2739
0
  mi_item_t *conns_arr, *conn_item;
2740
0
  struct tcp_connection *conn;
2741
0
  time_t _ts;
2742
0
  char date_buf[MI_DATE_BUF_LEN];
2743
0
  int date_buf_len;
2744
0
  unsigned int i,j,part;
2745
0
  char proto_buf[PROTO_NAME_MAX_SIZE];
2746
0
  char *proto_s;
2747
0
  int proto_len;
2748
0
  int proto_filter = PROTO_NONE;
2749
0
  int filter_by_proto = 0;
2750
0
  str proto_name;
2751
0
  struct tm ltime;
2752
0
  char *p;
2753
2754
0
  if (tcp_disabled)
2755
0
    return init_mi_result_null();
2756
2757
0
  switch (try_get_mi_string_param(params, "proto", &proto_s, &proto_len)) {
2758
0
  case 0:
2759
0
    proto_name.s = proto_s;
2760
0
    proto_name.len = proto_len;
2761
2762
0
    if (proto_len == 3 && str_strcasecmp(&proto_name, _str("any")) == 0)
2763
0
      ;
2764
0
    else if (parse_proto((unsigned char *)proto_s, proto_len,
2765
0
        (int *)&proto_filter) < 0)
2766
0
      return init_mi_error(400, MI_SSTR("Bad protocol"));
2767
0
    else
2768
0
      filter_by_proto = 1;
2769
0
    break;
2770
0
  case -1:
2771
0
    break;
2772
0
  default:
2773
0
    return init_mi_param_error();
2774
0
  }
2775
2776
0
  resp = init_mi_result_object(&resp_obj);
2777
0
  if (!resp)
2778
0
    return 0;
2779
2780
0
  conns_arr = add_mi_array(resp_obj, MI_SSTR("Connections"));
2781
0
  if (!conns_arr) {
2782
0
    free_mi_response(resp);
2783
0
    return 0;
2784
0
  }
2785
2786
0
  for( part=0 ; part<TCP_PARTITION_SIZE ; part++) {
2787
0
    TCPCONN_LOCK(part);
2788
0
    for( i=0; i<TCP_ID_HASH_SIZE ; i++ ) {
2789
0
      for(conn=TCP_PART(part).tcpconn_id_hash[i];conn;conn=conn->id_next){
2790
0
        if (filter_by_proto && conn->type != proto_filter)
2791
0
          continue;
2792
2793
        /* add one object fo each conn */
2794
0
        conn_item = add_mi_object(conns_arr, 0, 0);
2795
0
        if (!conn_item)
2796
0
          goto error;
2797
2798
        /* add ID */
2799
0
        if (add_mi_number(conn_item, MI_SSTR("ID"), conn->id) < 0)
2800
0
          goto error;
2801
2802
        /* add type/proto */
2803
0
        p = proto2str(conn->type, proto_buf);
2804
0
        if (add_mi_string(conn_item, MI_SSTR("Type"), proto_buf,
2805
0
          (int)(long)(p-proto_buf)) < 0)
2806
0
          goto error;
2807
2808
        /* add state */
2809
0
        if (add_mi_number(conn_item, MI_SSTR("State"), conn->state) < 0)
2810
0
          goto error;
2811
2812
        /* add Remote IP:Port */
2813
0
        if (add_mi_string_fmt(conn_item, MI_SSTR("Remote"), "%s:%d",
2814
0
          ip_addr2a(&conn->rcv.src_ip), conn->rcv.src_port) < 0)
2815
0
          goto error;
2816
2817
        /* add Local IP:Port */
2818
0
        if (add_mi_string_fmt(conn_item, MI_SSTR("Local"), "%s:%d",
2819
0
          ip_addr2a(&conn->rcv.dst_ip), conn->rcv.dst_port) < 0)
2820
0
          goto error;
2821
2822
0
        if (protos[conn->type].net.stream.conn.dump &&
2823
0
            protos[conn->type].net.stream.conn.dump(conn,
2824
0
              conn_item) < 0)
2825
0
          goto error;
2826
2827
        /* add lifetime */
2828
0
        _ts = (time_t)conn->lifetime + startup_time;
2829
0
        localtime_r(&_ts, &ltime);
2830
0
        date_buf_len = strftime(date_buf, MI_DATE_BUF_LEN - 1,
2831
0
                    "%Y-%m-%d %H:%M:%S", &ltime);
2832
0
        if (date_buf_len != 0) {
2833
0
          if (add_mi_string(conn_item, MI_SSTR("Lifetime"),
2834
0
            date_buf, date_buf_len) < 0)
2835
0
            goto error;
2836
0
        } else {
2837
0
          if (add_mi_number(conn_item, MI_SSTR("Lifetime"), _ts) < 0)
2838
0
            goto error;
2839
0
        }
2840
2841
        /* add the port-aliases */
2842
0
        for( j=0 ; j<conn->aliases ; j++ )
2843
          /* add one node for each conn */
2844
0
          add_mi_number( conn_item, MI_SSTR("Alias port"),
2845
0
            conn->con_aliases[j].port );
2846
2847
0
      }
2848
0
    }
2849
2850
0
    TCPCONN_UNLOCK(part);
2851
0
  }
2852
2853
0
  return resp;
2854
2855
0
error:
2856
0
  TCPCONN_UNLOCK(part);
2857
0
  LM_ERR("failed to add MI item\n");
2858
0
  free_mi_response(resp);
2859
0
  return 0;
2860
0
}
2861
2862
2863
mi_response_t *mi_tcp_close_conn(const mi_params_t *params,
2864
            struct mi_handler *_)
2865
0
{
2866
0
  str ipport;
2867
0
  int rc;
2868
2869
0
  if (get_mi_string_param(params, "ipport", &ipport.s, &ipport.len) < 0)
2870
0
    return init_mi_param_error();
2871
2872
0
  rc = tcp_close_connection(&ipport);
2873
0
  if (rc < 0)
2874
0
    return init_mi_error(400, MI_SSTR("Bad tcp connection"));
2875
0
  if (rc == 0)
2876
0
    return init_mi_result_null();
2877
2878
0
  return init_mi_result_ok();
2879
0
}