Coverage Report

Created: 2023-11-19 07:01

/src/kamailio/src/main.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (C) 2001-2003 FhG Fokus
3
 *
4
 * This file is part of Kamailio, a free SIP server.
5
 *
6
 * Kamailio is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 2 of the License, or
9
 * (at your option) any later version
10
 *
11
 * Kamailio is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19
 *
20
 */
21
22
/** Kamailio core :: main file (init, daemonize, startup)
23
 * @file main.c
24
 * @ingroup core
25
 * Module: core
26
 */
27
28
/*! @defgroup core Kamailio core
29
 *
30
 * sip router core part.
31
 */
32
33
#ifdef KSR_PTHREAD_MUTEX_SHARED
34
#define _GNU_SOURCE
35
#include <pthread.h>
36
#include <dlfcn.h>
37
#endif
38
39
#include <stdio.h>
40
#include <stdlib.h>
41
#include <errno.h>
42
#include <ctype.h>
43
#include <string.h>
44
#include <getopt.h>
45
#include <netdb.h>
46
#include <unistd.h>
47
#include <sys/types.h>
48
#include <sys/socket.h>
49
#if defined(HAVE_NETINET_IN_SYSTM)
50
#include <netinet/in_systm.h>
51
#endif
52
#include <netinet/in.h>
53
#include <netinet/ip.h>
54
#include <arpa/inet.h>
55
#include <sys/utsname.h>
56
#include <sys/stat.h>
57
#include <sys/mman.h>
58
#include <fcntl.h>
59
#include <sys/time.h>
60
#include <sys/wait.h>
61
#include <pwd.h>
62
#include <grp.h>
63
#include <signal.h>
64
65
#include <sys/ioctl.h>
66
#include <net/if.h>
67
#ifdef HAVE_SYS_SOCKIO_H
68
#include <sys/sockio.h>
69
#endif
70
71
#include "core/config.h"
72
#include "core/dprint.h"
73
#include "core/daemonize.h"
74
#include "core/route.h"
75
#include "core/udp_server.h"
76
#include "core/globals.h"
77
#include "core/mem/mem.h"
78
#include "core/mem/shm_mem.h"
79
#include "core/shm_init.h"
80
#include "core/sr_module.h"
81
#include "core/modparam.h"
82
#include "core/timer.h"
83
#include "core/parser/msg_parser.h"
84
#include "core/ip_addr.h"
85
#include "core/resolve.h"
86
#include "core/parser/parse_hname2.h"
87
#include "core/parser/digest/digest_parser.h"
88
#include "core/name_alias.h"
89
#include "core/hash_func.h"
90
#include "core/pt.h"
91
#include "core/script_cb.h"
92
#include "core/nonsip_hooks.h"
93
#include "core/ut.h"
94
#include "core/events.h"
95
#include "core/signals.h"
96
#ifdef USE_RAW_SOCKS
97
#include "core/raw_sock.h"
98
#endif /* USE_RAW_SOCKS */
99
#ifdef USE_TCP
100
#include "core/poll_types.h"
101
#include "core/tcp_init.h"
102
#include "core/tcp_options.h"
103
#ifdef CORE_TLS
104
#include "core/tls/tls_init.h"
105
#define tls_has_init_si() 1
106
#define tls_loaded() 1
107
#else
108
#include "core/tls_hooks_init.h"
109
#endif /* CORE_TLS */
110
#endif /* USE_TCP */
111
#ifdef USE_SCTP
112
#include "core/sctp_core.h"
113
#endif
114
#include "core/usr_avp.h"
115
#include "core/rpc_lookup.h"
116
#include "core/core_cmd.h"
117
#include "core/flags.h"
118
#include "core/lock_ops_init.h"
119
#include "core/atomic_ops_init.h"
120
#ifdef USE_DNS_CACHE
121
#include "core/dns_cache.h"
122
#endif
123
#ifdef USE_DST_BLOCKLIST
124
#include "core/dst_blocklist.h"
125
#endif
126
#include "core/rand/fastrand.h" /* seed */
127
#include "core/rand/kam_rand.h"
128
#include "core/rand/cryptorand.h"
129
130
#include "core/counters.h"
131
#include "core/cfg/cfg.h"
132
#include "core/cfg/cfg_struct.h"
133
#include "core/cfg_core.h"
134
#include "core/endianness.h" /* init */
135
#include "core/basex.h"    /* init */
136
#include "core/pvapi.h"    /* init PV api */
137
#include "core/pv_core.h"  /* register core pvars */
138
#include "core/ppcfg.h"
139
#include "core/sock_ut.h"
140
#include "core/async_task.h"
141
#include "core/dset.h"
142
#include "core/timer_proc.h"
143
#include "core/srapi.h"
144
#include "core/receive.h"
145
146
#ifdef DEBUG_DMALLOC
147
#include <dmalloc.h>
148
#endif
149
#include "core/ver.h"
150
151
/* define SIG_DEBUG by default */
152
#ifdef NO_SIG_DEBUG
153
#undef SIG_DEBUG
154
#else
155
#define SIG_DEBUG
156
#endif
157
158
159
static char help_msg[] =
160
    "\
161
Usage: " NAME " [options]\n\
162
Options:\n\
163
    -a mode      Auto aliases mode: enable with yes or on,\n\
164
                  disable with no or off\n\
165
    --alias=val  Add an alias, the value has to be '[proto:]hostname[:port]'\n\
166
                  (like for 'alias' global parameter)\n\
167
    --atexit=val Control atexit callbacks execution from external libraries\n\
168
                  which may access destroyed shm memory causing crash on shutdown.\n\
169
                  Can be y[es] or 1 to enable atexit callbacks, n[o] or 0 to disable,\n\
170
                  default is no.\n\
171
    -A define    Add config pre-processor define (e.g., -A WITH_AUTH,\n\
172
                  -A 'FLT_ACC=1', -A 'DEFVAL=\"str-val\"')\n\
173
    -b nr        Maximum OS UDP receive buffer size which will not be exceeded by\n\
174
                  auto-probing-and-increase procedure even if OS allows\n\
175
    -B nr        Maximum OS UDP send buffer size which will not be exceeded by\n\
176
                  auto-probing-and-increase procedure even if OS allows\n\
177
    -c           Check configuration file for syntax errors\n\
178
    --cfg-print  Print configuration file evaluating includes and ifdefs\n\
179
    -d           Debugging level control (multiple -d to increase the level from 0)\n\
180
    --debug=val  Debugging level value\n\
181
    -D           Control how daemonize is done:\n\
182
                  -D..do not fork (almost) anyway;\n\
183
                  -DD..do not daemonize creator;\n\
184
                  -DDD..daemonize (default)\n\
185
    -e           Log messages printed in terminal colors (requires -E)\n\
186
    -E           Log to stderr\n\
187
    -f file      Configuration file (default: " CFG_FILE ")\n\
188
    -g gid       Change gid (group id)\n\
189
    -G file      Create a pgid file\n\
190
    -h           This help message\n\
191
    --help       Long option for `-h`\n\
192
    -I           Print more internal compile flags and options\n\
193
    -K           Turn on \"via:\" host checking when forwarding replies\n\
194
    -l address   Listen on the specified address/interface (multiple -l\n\
195
                  mean listening on more addresses). The address format is\n\
196
                  [proto:]addr_lst[:port][/advaddr], \n\
197
                  where proto=udp|tcp|tls|sctp, \n\
198
                  addr_lst= addr|(addr, addr_lst), \n\
199
                  addr=host|ip_address|interface_name and \n\
200
                  advaddr=addr[:port] (advertised address). \n\
201
                  E.g: -l localhost, -l udp:127.0.0.1:5080, -l eth0:5062,\n\
202
                  -l udp:127.0.0.1:5080/1.2.3.4:5060,\n\
203
                  -l \"sctp:(eth0)\", -l \"(eth0, eth1, 127.0.0.1):5065\".\n\
204
                  The default behaviour is to listen on all the interfaces.\n\
205
    --loadmodule=name load the module specified by name\n\
206
    --log-engine=log engine name and data\n\
207
    -L path      Modules search path (default: " MODS_DIR ")\n\
208
    -m nr        Size of shared memory allocated in Megabytes\n\
209
    --modparam=modname:paramname:type:value set the module parameter\n\
210
                  type has to be 's' for string value and 'i' for int value, \n\
211
                  example: --modparam=corex:alias_subdomains:s:" NAME ".org\n\
212
    --all-errors Print details about all config errors that can be detected\n\
213
    -M nr        Size of private memory allocated, in Megabytes\n\
214
    -n processes Number of child processes to fork per interface\n\
215
                  (default: 8)\n"
216
#ifdef USE_TCP
217
    "    -N           Number of tcp child processes (default: equal to "
218
    "`-n')\n"
219
#endif
220
    "    -O nr        Script optimization level (debugging option)\n\
221
    -P file      Create a pid file\n"
222
#ifdef USE_SCTP
223
    "    -Q           Number of sctp child processes (default: equal to "
224
    "`-n')\n"
225
#endif /* USE_SCTP */
226
    "    -r           Use dns to check if is necessary to add a \"received=\"\n\
227
                  field to a via\n\
228
    -R           Same as `-r` but use reverse dns;\n\
229
                  (to use both use `-rR`)\n"
230
    "    --server-id=num set the value for server_id\n\
231
    --subst=exp set a subst preprocessor directive\n\
232
    --substdef=exp set a substdef preprocessor directive\n\
233
    --substdefs=exp set a substdefs preprocessor directive\n"
234
#ifdef USE_SCTP
235
    "    -S           disable sctp\n"
236
#endif
237
    "    -t dir       Chroot to \"dir\"\n"
238
#ifdef USE_TCP
239
    "    -T           Disable tcp\n"
240
#endif
241
    "    -u uid       Change uid (user id)\n\
242
    -v           Version number\n\
243
    --version    Long option for `-v`\n\
244
    -V           Alternative for `-v`\n\
245
    -x name      Specify internal manager for shared memory (shm)\n\
246
                  - can be: fm, qm or tlsf\n\
247
    -X name      Specify internal manager for private memory (pkg)\n\
248
                  - if omitted, the one for shm is used\n\
249
    -Y dir       Runtime dir path\n\
250
    -w dir       Change the working directory to \"dir\" (default: \"/\")\n"
251
#ifdef USE_TCP
252
    "    -W type      poll method (depending on support in OS, it can be: poll,\n\
253
                  epoll_lt, epoll_et, sigio_rt, select, kqueue, /dev/poll)\n"
254
#endif
255
    ;
256
257
258
/* print compile-time constants */
259
void print_ct_constants(void)
260
0
{
261
0
#ifdef ADAPTIVE_WAIT
262
0
  printf("ADAPTIVE_WAIT_LOOPS %d, ", ADAPTIVE_WAIT_LOOPS);
263
0
#endif
264
  /*
265
  printf("SHM_MEM_SIZE %dMB, ", SHM_MEM_SIZE);
266
*/
267
0
  printf("MAX_RECV_BUFFER_SIZE %d, MAX_SEND_BUFFER_SIZE %d,"
268
0
       " MAX_URI_SIZE %d, BUF_SIZE %d, DEFAULT PKG_SIZE %uMB\n",
269
0
      MAX_RECV_BUFFER_SIZE, MAX_SEND_BUFFER_SIZE, MAX_URI_SIZE, BUF_SIZE,
270
0
      PKG_MEM_SIZE);
271
0
#ifdef USE_TCP
272
0
  printf("poll method support: %s.\n", poll_support);
273
0
#endif
274
0
}
275
276
/* print compile-time constants */
277
void print_internals(void)
278
0
{
279
0
  printf("Print out of %s internals\n", NAME);
280
0
  printf("  Version: %s\n", full_version);
281
0
  printf("  Default config: %s\n", CFG_FILE);
282
0
  printf("  Default paths to modules: %s\n", MODS_DIR);
283
0
  printf("  Compile flags: %s\n", ver_flags);
284
0
  printf("  MAX_RECV_BUFFER_SIZE=%d\n", MAX_RECV_BUFFER_SIZE);
285
0
  printf("  MAX_SEND_BUFFER_SIZE=%d\n", MAX_SEND_BUFFER_SIZE);
286
0
  printf("  MAX_URI_SIZE=%d\n", MAX_URI_SIZE);
287
0
  printf("  BUF_SIZE=%d\n", BUF_SIZE);
288
0
  printf("  DEFAULT PKG_SIZE=%uMB\n", PKG_MEM_SIZE);
289
0
  printf("  DEFAULT SHM_SIZE=%uMB\n", SHM_MEM_SIZE);
290
0
#ifdef ADAPTIVE_WAIT
291
0
  printf("  ADAPTIVE_WAIT_LOOPS=%d\n", ADAPTIVE_WAIT_LOOPS);
292
0
#endif
293
0
#ifdef USE_TCP
294
0
  printf("  TCP poll methods: %s\n", poll_support);
295
0
#endif
296
0
  printf("  Source code revision ID: %s\n", ver_id);
297
0
  printf("  Compiled with: %s\n", ver_compiler);
298
0
  printf("  Compiled architecture: %s\n", ARCH);
299
0
  printf("  Compiled on: %s\n", ver_compiled_time);
300
0
  printf("Thank you for flying %s!\n", NAME);
301
0
}
302
303
304
/* global vars */
305
306
int own_pgid = 0; /* whether or not we have our own pgid (and it's ok
307
           to use kill(0, sig) */
308
309
char *mods_dir = MODS_DIR; /* search path for dyn. loadable modules */
310
int mods_dir_cmd = 0;    /* mods dir path set in command lin e*/
311
312
char *cfg_file = 0;
313
unsigned int maxbuffer =
314
    MAX_RECV_BUFFER_SIZE; /* maximum receive buffer size we do
315
                          not want to exceed during the
316
                          auto-probing procedure; may
317
                          be re-configured */
318
unsigned int maxsndbuffer =
319
    MAX_SEND_BUFFER_SIZE; /* maximum send buffer size we do
320
                          not want to exceed during the
321
                          auto-probing procedure; may
322
                          be re-configured */
323
unsigned int sql_buffer_size =
324
    65535;      /* Size for the SQL buffer. Defaults to 64k.
325
                                         This may be re-configured */
326
int socket_workers = 0; /* number of workers processing requests for a socket
327
                 - it's reset everytime with a new listen socket */
328
int children_no = 0;  /* number of children processing requests */
329
#ifdef USE_TCP
330
int tcp_cfg_children_no = 0; /* set via config or command line option */
331
int tcp_children_no = 0; /* based on socket_workers and tcp_cfg_children_no */
332
int tcp_disable = 0;   /* 1 if tcp is disabled */
333
#endif
334
#ifdef USE_TLS
335
#ifdef CORE_TLS
336
int tls_disable = 0; /* tls enabled by default */
337
#else
338
int tls_disable = 1; /* tls disabled by default */
339
#endif /* CORE_TLS */
340
#endif /* USE_TLS */
341
#ifdef USE_SCTP
342
int sctp_children_no = 0;
343
int sctp_disable = 2; /* 1 if sctp is disabled, 2 if auto mode, 0 enabled */
344
#endif          /* USE_SCTP */
345
346
struct process_table *pt = 0; /*array with children pids, 0= main proc,
347
                  alloc'ed in shared mem if possible*/
348
int *process_count = 0;     /* Total number of SER processes currently
349
                   running */
350
gen_lock_t *process_lock;   /* lock on the process table */
351
int process_no = 0;       /* index of process in the pt */
352
353
time_t up_since;
354
int sig_flag = 0; /* last signal received */
355
int dont_fork = 0;
356
int dont_daemonize = 0;
357
int log_stderr = 0;
358
int log_color = 0;
359
int log_cee = 0;
360
/* set custom app name for syslog printing */
361
char *log_name = 0;
362
char *log_prefix_fmt = 0;
363
char *log_fqdn = 0;
364
pid_t creator_pid = (pid_t)-1;
365
int config_check = 0;
366
/* check if reply first via host==us */
367
int check_via = 0;
368
/* translate user=phone URIs to TEL URIs */
369
int phone2tel = 1;
370
/* debugging level for timer debugging */
371
int timerlog = L_WARN;
372
/* should replies include extensive warnings? by default no,
373
   good for trouble-shooting
374
*/
375
int sip_warning = 0;
376
/* should locally-generated messages include server's signature?
377
   be default yes, good for trouble-shooting
378
*/
379
int server_signature = 1;
380
str server_hdr = {SERVER_HDR, SERVER_HDR_LEN};
381
str user_agent_hdr = {USER_AGENT, USER_AGENT_LEN};
382
str version_table = {VERSION_TABLE, VERSION_TABLE_LEN};
383
/* should ser try to locate outbound interface on multihomed
384
 * host? by default not -- too expensive
385
 */
386
int mhomed = 0;
387
/* use dns and/or rdns or to see if we need to add
388
   a ;received=x.x.x.x to via: */
389
int received_dns = 0;
390
/* add or not the rev dns names to aliases list */
391
int sr_auto_aliases = 1;
392
char *working_dir = 0;
393
char *chroot_dir = 0;
394
char *runtime_dir = "" RUN_DIR;
395
char *user = 0;
396
char *group = 0;
397
int uid = 0;
398
int gid = 0;
399
char *sock_user = 0;
400
char *sock_group = 0;
401
int sock_uid = -1;
402
int sock_gid = -1;
403
int sock_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; /* rw-rw---- */
404
405
int server_id = 0; /* Configurable unique ID of the server */
406
407
/* maximum number of branches for transaction */
408
unsigned int sr_dst_max_branches = MAX_BRANCHES_DEFAULT;
409
410
/* set timeval for each received sip message */
411
int sr_msg_time = 1;
412
413
/* onsend_route is executed for replies*/
414
int onsend_route_reply = 0;
415
416
/* more config stuff */
417
int disable_core_dump = 0; /* by default enabled */
418
int open_files_limit = -1; /* don't touch it by default */
419
420
/* memory options */
421
int shm_force_alloc = 0; /* force immediate (on startup) page allocation
422
              (by writing 0 in the pages), useful if
423
              mlock_pages is also 1 */
424
int mlock_pages = 0;   /* default off, try to disable swapping */
425
426
/* real time options */
427
int real_time = 0; /* default off, flags: 1 on only timer, 2  slow timer,
428
                    4 all procs (7=all) */
429
int rt_prio = 0;
430
int rt_policy = 0;      /* SCHED_OTHER */
431
int rt_timer1_prio = 0;   /* "fast" timer */
432
int rt_timer2_prio = 0;   /* "slow" timer */
433
int rt_timer1_policy = 0; /* "fast" timer, SCHED_OTHER */
434
int rt_timer2_policy = 0; /* "slow" timer, SCHED_OTHER */
435
436
437
/* a hint to reply modules whether they should send reply
438
   to IP advertised in Via or IP from which a request came
439
*/
440
int reply_to_via = 0;
441
442
#ifdef USE_MCAST
443
int mcast_loopback = 0;
444
int mcast_ttl = -1; /* if -1, don't touch it, use the default (usually 1) */
445
char *mcast = 0;
446
#endif /* USE_MCAST */
447
448
int tos = IPTOS_LOWDELAY;
449
int pmtu_discovery = 0;
450
451
int auto_bind_ipv6 = 0;
452
int sr_bind_ipv6_link_local = 0;
453
454
struct socket_info *udp_listen = 0;
455
#ifdef USE_TCP
456
int tcp_main_pid = 0; /* set after the tcp main process is started */
457
struct socket_info *tcp_listen = 0;
458
#endif
459
#ifdef USE_TLS
460
struct socket_info *tls_listen = 0;
461
#endif
462
#ifdef USE_SCTP
463
struct socket_info *sctp_listen = 0;
464
#endif
465
struct socket_info *bind_address = 0; /* pointer to the crt. proc.
466
                   listening address*/
467
struct socket_info *sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
468
struct socket_info *sendipv6; /* same as above for ipv6 */
469
#ifdef USE_RAW_SOCKS
470
int raw_udp4_send_sock = -1; /* raw socket used for sending udp4 packets */
471
#endif             /* USE_RAW_SOCKS */
472
#ifdef USE_TCP
473
struct socket_info *sendipv4_tcp;
474
struct socket_info *sendipv6_tcp;
475
#endif
476
#ifdef USE_TLS
477
struct socket_info *sendipv4_tls;
478
struct socket_info *sendipv6_tls;
479
#endif
480
#ifdef USE_SCTP
481
struct socket_info *sendipv4_sctp;
482
struct socket_info *sendipv6_sctp;
483
#endif
484
485
unsigned short port_no = 0; /* default port*/
486
#ifdef USE_TLS
487
unsigned short tls_port_no = 0; /* default port */
488
#endif
489
490
struct host_alias *aliases = 0; /* name aliases list */
491
492
/* Parameter to child_init */
493
int child_rank = 0;
494
495
/* how much to wait for children to terminate, before taking extreme measures*/
496
int ser_kill_timeout = DEFAULT_SER_KILL_TIMEOUT;
497
498
int ksr_verbose_startup = 0;
499
int ksr_all_errors = 0;
500
501
/* cfg parsing */
502
int cfg_errors = 0;
503
int cfg_warnings = 0;
504
505
506
/* shared memory (in MB) */
507
unsigned long shm_mem_size = 0;
508
/* private (pkg) memory (in MB) */
509
unsigned long pkg_mem_size = 0;
510
511
/* export command-line to anywhere else */
512
int my_argc;
513
char **my_argv;
514
515
/* set to 1 when the cfg framework and core cfg is initialized/registered */
516
static int cfg_ok = 0;
517
518
#define MAX_FD \
519
  32 /* maximum number of inherited open file descriptors,
520
        (normally it shouldn't  be bigger  than 3) */
521
522
523
extern FILE *yyin;
524
extern int yyparse(void);
525
526
527
int _ksr_is_main = 1; /* flag = is this the  "main" process? */
528
int fixup_complete = 0; /* flag = is the fixup complete ? */
529
530
char *pid_file = 0; /* filename as asked by use */
531
char *pgid_file = 0;
532
533
int ksr_msg_recv_max_size = 32767; /* 2^15 - 1 */
534
int ksr_tcp_msg_read_timeout = 20; /* timeout (secs) to read SIP message */
535
int ksr_tcp_msg_data_timeout =
536
    20; /* timeout (secs) to receive first msg data */
537
int ksr_tcp_accept_iplimit = 1024; /* limit of accepted connections per IP */
538
int ksr_tcp_check_timer = -1;    /* seconds to check tcp connections */
539
540
/* memory manager */
541
0
#define SR_MEMMNG_DEFAULT "qm"
542
543
char *sr_memmng_pkg = NULL;
544
char *sr_memmng_shm = NULL;
545
546
static int *_sr_instance_started = NULL;
547
548
int ksr_cfg_print_mode = 0;
549
int ksr_atexit_mode = 0;
550
551
int ksr_wait_worker1_mode = 0;
552
int ksr_wait_worker1_time = 4000000;
553
int ksr_wait_worker1_usleep = 100000;
554
int *ksr_wait_worker1_done = NULL;
555
556
/**
557
 * return 1 if all child processes were forked
558
 * - note: they might still be in init phase (i.e., child init)
559
 * - note: see also sr_insance_ready()
560
 */
561
int sr_instance_started(void)
562
0
{
563
0
  if(_sr_instance_started != NULL && *_sr_instance_started == 1) {
564
0
    return 1;
565
0
  }
566
0
  return 0;
567
0
}
568
569
/* call it before exiting; if show_status==1, mem status is displayed */
570
void cleanup(int show_status)
571
0
{
572
0
  int memlog;
573
574
  /*clean-up*/
575
0
#ifndef SHM_SAFE_MALLOC
576
0
  if(shm_initialized()) {
577
    /* force-unlock the shared memory lock in case some process crashed
578
     * and let it locked; this will allow an almost gracious shutdown */
579
0
    shm_global_unlock();
580
0
  }
581
0
#endif
582
0
  destroy_rpcs();
583
0
  destroy_modules();
584
0
#ifdef USE_DNS_CACHE
585
0
  destroy_dns_cache();
586
0
#endif
587
0
#ifdef USE_DST_BLOCKLIST
588
0
  destroy_dst_blocklist();
589
0
#endif
590
  /* restore the original core configuration before the
591
   * config block is freed, otherwise even logging is unusable,
592
   * it can case segfault */
593
0
  if(cfg_ok) {
594
0
    cfg_update();
595
    /* copy current config into default_core_cfg */
596
0
    if(core_cfg)
597
0
      default_core_cfg = *((struct cfg_group_core *)core_cfg);
598
0
  }
599
0
  core_cfg = &default_core_cfg;
600
0
  cfg_destroy();
601
0
#ifdef USE_TCP
602
0
  destroy_tcp();
603
0
#ifdef USE_TLS
604
0
  destroy_tls();
605
0
#endif /* USE_TLS */
606
0
#endif /* USE_TCP */
607
0
#ifdef USE_SCTP
608
0
  sctp_core_destroy();
609
0
#endif
610
0
  destroy_timer();
611
0
  pv_destroy_api();
612
0
  ksr_route_locks_set_destroy();
613
0
  destroy_script_cb();
614
0
  destroy_nonsip_hooks();
615
0
  destroy_routes();
616
0
  destroy_atomic_ops();
617
0
  destroy_counters();
618
0
  memlog = cfg_get(core, core_cfg, memlog);
619
#ifdef PKG_MALLOC
620
  if(show_status && memlog <= cfg_get(core, core_cfg, debug)) {
621
    if(cfg_get(core, core_cfg, mem_summary) & 1) {
622
      LOG(memlog, "Memory status (pkg):\n");
623
      pkg_status();
624
    }
625
    if(cfg_get(core, core_cfg, mem_summary) & 4) {
626
      LOG(memlog, "Memory still-in-use summary (pkg):\n");
627
      pkg_sums();
628
    }
629
  }
630
#endif
631
0
  if(pt)
632
0
    shm_free(pt);
633
0
  pt = 0;
634
0
  if(show_status && memlog <= cfg_get(core, core_cfg, debug)) {
635
0
    if(cfg_get(core, core_cfg, mem_summary) & 2) {
636
0
      LOG(memlog, "Memory status (shm):\n");
637
0
      shm_status();
638
0
    }
639
0
    if(cfg_get(core, core_cfg, mem_summary) & 8) {
640
0
      LOG(memlog, "Memory still-in-use summary (shm):\n");
641
0
      shm_sums();
642
0
    }
643
0
  }
644
  /* zero all shmem alloc vars that we still use */
645
0
  shm_destroy_manager();
646
0
  destroy_lock_ops();
647
0
  if(pid_file)
648
0
    unlink(pid_file);
649
0
  if(pgid_file)
650
0
    unlink(pgid_file);
651
0
  pkg_destroy_manager();
652
0
}
653
654
655
/* tries to send a signal to all our processes
656
 * if daemonized  is ok to send the signal to all the process group,
657
 * however if not daemonized we might end up sending the signal also
658
 * to the shell which launched us => most signals will kill it if
659
 * it's not in interactive mode and we don't want this. The non-daemonized
660
 * case can occur when an error is encountered before daemonize is called
661
 * (e.g. when parsing the config file) or when ser is started in "dont-fork"
662
 *  mode. Sending the signal to all the processes in pt[] will not work
663
 *  for processes forked from modules (which have no correspondent entry in
664
 *  pt), but this can happen only in dont_fork mode (which is only for
665
 *  debugging). So in the worst case + "dont-fork" we might leave some
666
 *  zombies. -- andrei */
667
static void kill_all_children(int signum)
668
0
{
669
0
  int r;
670
671
0
  if(own_pgid)
672
0
    kill(0, signum);
673
0
  else if(pt) {
674
    /* lock processes table only if this is a child process
675
      * (only main can add processes, so from main is safe not to lock
676
      *  and moreover it avoids the lock-holding suicidal children problem)
677
      */
678
0
    if(!_ksr_is_main)
679
0
      lock_get(process_lock);
680
0
    for(r = 1; r < *process_count; r++) {
681
0
      if(r == process_no)
682
0
        continue; /* try not to be suicidal */
683
0
      if(pt[r].pid) {
684
0
        kill(pt[r].pid, signum);
685
0
      } else
686
0
        LM_CRIT("killing: %s > %d no pid!!!\n", pt[r].desc, pt[r].pid);
687
0
    }
688
0
    if(!_ksr_is_main)
689
0
      lock_release(process_lock);
690
0
  }
691
0
}
692
693
694
/* if this handler is called, a critical timeout has occurred while
695
 * waiting for the children to finish => we should kill everything and exit */
696
static void sig_alarm_kill(int signo)
697
0
{
698
0
  kill_all_children(SIGKILL); /* this will kill the whole group
699
                  including "this" process;
700
                  for debugging replace with SIGABRT
701
                  (but warning: it might generate lots
702
                   of cores) */
703
0
}
704
705
706
/* like sig_alarm_kill, but the timeout has occurred when cleaning up
707
 * => try to leave a core for future diagnostics */
708
static void sig_alarm_abort(int signo)
709
0
{
710
  /* LOG is not signal safe, but who cares, we are abort-ing anyway :-) */
711
0
  LM_CRIT("shutdown timeout triggered, dying...");
712
0
  abort();
713
0
}
714
715
716
static void shutdown_children(int sig, int show_status)
717
0
{
718
0
  sr_corecb_void_exec(app_shutdown);
719
720
0
  kill_all_children(sig);
721
0
  if(set_sig_h(SIGALRM, sig_alarm_kill) == SIG_ERR) {
722
0
    LM_ERR("could not install SIGALARM handler\n");
723
    /* continue, the process will die anyway if no
724
     * alarm is installed which is exactly what we want */
725
0
  }
726
0
  alarm(ser_kill_timeout);
727
0
  while((wait(0) > 0) || (errno == EINTR))
728
0
    ; /* wait for all the
729
                         children to terminate*/
730
0
  set_sig_h(SIGALRM, sig_alarm_abort);
731
0
  cleanup(show_status); /* cleanup & show status*/
732
0
  alarm(0);
733
0
  set_sig_h(SIGALRM, SIG_IGN);
734
0
}
735
736
737
void handle_sigs(void)
738
0
{
739
0
  pid_t chld;
740
0
  int chld_status;
741
0
  int any_chld_stopped;
742
0
  int memlog;
743
744
0
  switch(sig_flag) {
745
0
    case 0:
746
0
      break; /* do nothing*/
747
0
    case SIGPIPE:
748
      /* SIGPIPE might be rarely received on use of
749
           exec module; simply ignore it
750
         */
751
0
      LM_WARN("SIGPIPE received and ignored\n");
752
0
      break;
753
0
    case SIGINT:
754
0
    case SIGTERM:
755
      /* we end the program in all these cases */
756
0
      if(sig_flag == SIGINT)
757
0
        LM_DBG("INT received, program terminates\n");
758
0
      else
759
0
        LM_DBG("SIGTERM received, program terminates\n");
760
0
      LM_NOTICE("Thank you for flying " NAME "!!!\n");
761
      /* shutdown/kill all the children */
762
0
      shutdown_children(SIGTERM, 1);
763
0
      ksr_exit(0);
764
0
      break;
765
766
0
    case SIGUSR1:
767
0
      memlog = cfg_get(core, core_cfg, memlog);
768
#ifdef PKG_MALLOC
769
      if(memlog <= cfg_get(core, core_cfg, debug)) {
770
        if(cfg_get(core, core_cfg, mem_summary) & 1) {
771
          LOG(memlog, "Memory status (pkg):\n");
772
          pkg_status();
773
        }
774
        if(cfg_get(core, core_cfg, mem_summary) & 4) {
775
          LOG(memlog, "Memory still-in-use summary (pkg):\n");
776
          pkg_sums();
777
        }
778
      }
779
#endif
780
0
      if(memlog <= cfg_get(core, core_cfg, debug)) {
781
0
        if(cfg_get(core, core_cfg, mem_summary) & 2) {
782
0
          LOG(memlog, "Memory status (shm):\n");
783
0
          shm_status();
784
0
        }
785
0
        if(cfg_get(core, core_cfg, mem_summary) & 8) {
786
0
          LOG(memlog, "Memory still-in-use summary (shm):\n");
787
0
          shm_sums();
788
0
        }
789
0
      }
790
0
      break;
791
792
0
    case SIGCHLD:
793
0
      any_chld_stopped = 0;
794
0
      while((chld = waitpid(-1, &chld_status, WNOHANG)) > 0) {
795
0
        any_chld_stopped = 1;
796
0
        if(WIFEXITED(chld_status))
797
0
          LM_ALERT("child process %ld exited normally,"
798
0
               " status=%d\n",
799
0
              (long)chld, WEXITSTATUS(chld_status));
800
0
        else if(WIFSIGNALED(chld_status)) {
801
0
          LM_ALERT("child process %ld exited by a signal"
802
0
               " %d\n",
803
0
              (long)chld, WTERMSIG(chld_status));
804
0
#ifdef WCOREDUMP
805
0
          LM_ALERT("core was %sgenerated\n",
806
0
              WCOREDUMP(chld_status) ? "" : "not ");
807
0
#endif
808
0
        } else if(WIFSTOPPED(chld_status))
809
0
          LM_ALERT("child process %ld stopped by a"
810
0
               " signal %d\n",
811
0
              (long)chld, WSTOPSIG(chld_status));
812
0
      }
813
814
      /* If it appears that no child process has stopped, then do not terminate on SIGCHLD.
815
         Certain modules like app_python can run external scripts which cause child processes to be started and
816
         stopped. That can result in SIGCHLD being received here even though there is no real problem. Therefore,
817
         we do not terminate Kamailio unless we can find the child process which has stopped. */
818
0
      if(!any_chld_stopped) {
819
0
        LM_INFO("SIGCHLD received, but no child has stopped, ignoring "
820
0
            "it\n");
821
0
        break;
822
0
      }
823
824
0
      if(dont_fork) {
825
0
        LM_INFO("dont_fork turned on, living on\n");
826
0
        break;
827
0
      }
828
0
      LM_INFO("terminating due to SIGCHLD\n");
829
830
      /* exit */
831
0
      shutdown_children(SIGTERM, 1);
832
0
      if(WIFSIGNALED(chld_status)) {
833
0
        ksr_exit(1);
834
0
      } else {
835
0
        ksr_exit(0);
836
0
      }
837
0
      break;
838
839
0
    case SIGHUP: /* ignoring it*/
840
0
      LM_DBG("SIGHUP received, ignoring it\n");
841
0
      break;
842
0
    default:
843
0
      LM_CRIT("unhandled signal %d\n", sig_flag);
844
0
  }
845
0
  sig_flag = 0;
846
0
}
847
848
849
/* added by jku; allows for regular exit on a specific signal;
850
   good for profiling which only works if exited regularly and
851
   not by default signal handlers
852
    - modified by andrei: moved most of the stuff to handle_sigs,
853
       made it safer for the "fork" case
854
*/
855
void sig_usr(int signo)
856
0
{
857
0
#ifdef SIG_DEBUG
858
#ifdef PKG_MALLOC
859
  int memlog;
860
#endif
861
0
#endif
862
863
0
  if(_ksr_is_main) {
864
0
    if(sig_flag == 0)
865
0
      sig_flag = signo;
866
0
    else /*  previous sig. not processed yet, ignoring? */
867
0
      return;
868
0
    ;
869
0
    if(dont_fork)
870
      /* only one proc, doing everything from the sig handler,
871
        unsafe, but this is only for debugging mode*/
872
0
      handle_sigs();
873
0
  } else {
874
    /* process the important signals */
875
0
    switch(signo) {
876
0
      case SIGPIPE:
877
0
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
878
0
        LM_INFO("signal %d received\n", signo);
879
0
#endif
880
0
        break;
881
0
      case SIGINT:
882
0
      case SIGTERM:
883
0
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
884
0
        LM_INFO("signal %d received\n", signo);
885
        /* print memory stats for non-main too */
886
#ifdef PKG_MALLOC
887
        /* make sure we have current cfg values, but update only
888
            the safe part (values not requiring callbacks), to
889
            account for processes that might not have registered
890
            config support */
891
        cfg_update_no_cbs();
892
        memlog = cfg_get(core, core_cfg, memlog);
893
        if(memlog <= cfg_get(core, core_cfg, debug)) {
894
          if(cfg_get(core, core_cfg, mem_summary) & 1) {
895
            LOG(memlog, "Memory status (pkg):\n");
896
            pkg_status();
897
          }
898
          if(cfg_get(core, core_cfg, mem_summary) & 4) {
899
            LOG(memlog, "Memory still-in-use summary (pkg):"
900
                  "\n");
901
            pkg_sums();
902
          }
903
        }
904
#endif
905
0
#endif
906
0
        _exit(0);
907
0
        break;
908
0
      case SIGUSR1:
909
0
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
910
0
        LM_INFO("signal %d received\n", signo);
911
#ifdef PKG_MALLOC
912
        cfg_update_no_cbs();
913
        memlog = cfg_get(core, core_cfg, memlog);
914
        if(memlog <= cfg_get(core, core_cfg, debug)) {
915
          if(cfg_get(core, core_cfg, mem_summary) & 1) {
916
            LOG(memlog, "Memory status (pkg):\n");
917
            pkg_status();
918
          }
919
          if(cfg_get(core, core_cfg, mem_summary) & 4) {
920
            LOG(memlog, "Memory still-in-use summary (pkg):\n");
921
            pkg_sums();
922
          }
923
        }
924
#endif
925
0
#endif
926
0
        break;
927
        /* ignored*/
928
0
      case SIGUSR2:
929
0
      case SIGHUP:
930
0
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
931
0
        LM_INFO("signal %d received - ignoring\n", signo);
932
0
#endif
933
0
        break;
934
0
      case SIGCHLD:
935
0
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
936
0
        LM_DBG("SIGCHLD received: "
937
0
             "we do not worry about grand-children\n");
938
0
#endif
939
0
        break;
940
0
    }
941
0
  }
942
0
}
943
944
945
/* install the signal handlers, returns 0 on success, -1 on error */
946
int install_sigs(void)
947
0
{
948
  /* added by jku: add exit handler */
949
0
  if(set_sig_h(SIGINT, sig_usr) == SIG_ERR) {
950
0
    ERR("no SIGINT signal handler can be installed\n");
951
0
    goto error;
952
0
  }
953
  /* if we debug and write to a pipe, we want to exit nicely too */
954
0
  if(set_sig_h(SIGPIPE, sig_usr) == SIG_ERR) {
955
0
    ERR("no SIGINT signal handler can be installed\n");
956
0
    goto error;
957
0
  }
958
0
  if(set_sig_h(SIGUSR1, sig_usr) == SIG_ERR) {
959
0
    ERR("no SIGUSR1 signal handler can be installed\n");
960
0
    goto error;
961
0
  }
962
0
  if(set_sig_h(SIGCHLD, sig_usr) == SIG_ERR) {
963
0
    ERR("no SIGCHLD signal handler can be installed\n");
964
0
    goto error;
965
0
  }
966
0
  if(set_sig_h(SIGTERM, sig_usr) == SIG_ERR) {
967
0
    ERR("no SIGTERM signal handler can be installed\n");
968
0
    goto error;
969
0
  }
970
0
  if(set_sig_h(SIGHUP, sig_usr) == SIG_ERR) {
971
0
    ERR("no SIGHUP signal handler can be installed\n");
972
0
    goto error;
973
0
  }
974
0
  if(set_sig_h(SIGUSR2, sig_usr) == SIG_ERR) {
975
0
    ERR("no SIGUSR2 signal handler can be installed\n");
976
0
    goto error;
977
0
  }
978
0
  return 0;
979
0
error:
980
0
  return -1;
981
0
}
982
983
/* returns -1 on error, 0 on success
984
 * sets proto */
985
int parse_proto(unsigned char *s, long len, int *proto)
986
0
{
987
0
#define PROTO2UINT3(a, b, c)                                   \
988
0
  (((((unsigned int)(a)) << 16) + (((unsigned int)(b)) << 8) \
989
0
       + ((unsigned int)(c)))                            \
990
0
      | 0x20202020)
991
0
#define PROTO2UINT4(a, b, c, d)                                    \
992
0
  (((((unsigned int)(a)) << 24) + (((unsigned int)(b)) << 16)    \
993
0
       + (((unsigned int)(c)) << 8) + (((unsigned int)(d)))) \
994
0
      | 0x20202020)
995
0
  unsigned int i;
996
0
  if(likely(len == 3)) {
997
0
    i = PROTO2UINT3(s[0], s[1], s[2]);
998
0
    switch(i) {
999
0
      case PROTO2UINT3('u', 'd', 'p'):
1000
0
        *proto = PROTO_UDP;
1001
0
        break;
1002
0
#ifdef USE_TCP
1003
0
      case PROTO2UINT3('t', 'c', 'p'):
1004
0
        if(tcp_disable) {
1005
0
          return -1;
1006
0
        }
1007
0
        *proto = PROTO_TCP;
1008
0
        break;
1009
0
#ifdef USE_TLS
1010
0
      case PROTO2UINT3('t', 'l', 's'):
1011
0
        if(tcp_disable || tls_disable) {
1012
0
          return -1;
1013
0
        }
1014
0
        *proto = PROTO_TLS;
1015
0
        break;
1016
0
#endif
1017
0
#endif
1018
0
      default:
1019
0
        return -1;
1020
0
    }
1021
0
  }
1022
0
#ifdef USE_SCTP
1023
0
  else if(likely(len == 4)) {
1024
0
    i = PROTO2UINT4(s[0], s[1], s[2], s[3]);
1025
0
    if(i == PROTO2UINT4('s', 'c', 't', 'p')) {
1026
0
      if(sctp_disable) {
1027
0
        return -1;
1028
0
      }
1029
0
      *proto = PROTO_SCTP;
1030
0
    } else {
1031
0
      return -1;
1032
0
    }
1033
0
  }
1034
0
#endif /* USE_SCTP */
1035
0
  else
1036
    /* Deliberately leaving out PROTO_WS and PROTO_WSS as these are just
1037
     upgraded TCP/TLS connections. */
1038
0
    return -1;
1039
0
  return 0;
1040
0
}
1041
1042
1043
static struct name_lst *mk_name_lst_elem(char *name, int name_len, int flags)
1044
0
{
1045
0
  struct name_lst *l;
1046
1047
0
  l = pkg_malloc(sizeof(struct name_lst) + name_len + 1 /* 0 */);
1048
0
  if(l) {
1049
0
    l->name = ((char *)l) + sizeof(struct name_lst);
1050
0
    memcpy(l->name, name, name_len);
1051
0
    l->name[name_len] = 0;
1052
0
    l->flags = flags;
1053
0
    l->next = 0;
1054
0
    return l;
1055
0
  } else {
1056
0
    PKG_MEM_ERROR;
1057
0
    return 0;
1058
0
  }
1059
0
}
1060
1061
1062
/* free a name_lst list with elements allocated with mk_name_lst_elem
1063
 * (single block both for the structure and for the name) */
1064
static void free_name_lst(struct name_lst *lst)
1065
0
{
1066
0
  struct name_lst *l;
1067
1068
0
  while(lst) {
1069
0
    l = lst;
1070
0
    lst = lst->next;
1071
0
    pkg_free(l);
1072
0
  }
1073
0
}
1074
1075
1076
/* parse h and returns a name lst (flags are set to SI_IS_MHOMED if
1077
 * h contains more than one name or contains a name surrounded by '(' ')' )
1078
 * valid formats:    "hostname"
1079
 *                   "(hostname, hostname1, hostname2)"
1080
 *                   "(hostname hostname1 hostname2)"
1081
 *                   "(hostname)"
1082
 */
1083
static struct name_lst *parse_name_lst(char *h, int h_len)
1084
0
{
1085
0
  char *last;
1086
0
  char *p;
1087
0
  struct name_lst *n_lst;
1088
0
  struct name_lst *l;
1089
0
  struct name_lst **tail;
1090
0
  int flags;
1091
1092
0
  n_lst = 0;
1093
0
  tail = &n_lst;
1094
0
  last = h + h_len - 1;
1095
0
  flags = 0;
1096
  /* eat whitespace */
1097
0
  for(; h <= last && ((*h == ' ') || (*h == '\t')); h++)
1098
0
    ;
1099
0
  for(; last > h && ((*last == ' ') || (*last == '\t')); last--)
1100
0
    ;
1101
  /* catch empty strings and invalid lens */
1102
0
  if(h > last)
1103
0
    goto error;
1104
1105
0
  if(*h == '(') {
1106
    /* list mode */
1107
0
    if(*last != ')' || ((h + 1) > (last - 1)))
1108
0
      goto error;
1109
0
    h++;
1110
0
    last--;
1111
0
    flags = SI_IS_MHOMED;
1112
0
    for(p = h; p <= last; p++)
1113
0
      switch(*p) {
1114
0
        case ',':
1115
0
        case ';':
1116
0
        case ' ':
1117
0
        case '\t':
1118
0
          if((int)(p - h) > 0) {
1119
0
            l = mk_name_lst_elem(h, (int)(p - h), flags);
1120
0
            if(l == 0)
1121
0
              goto error;
1122
0
            *tail = l;
1123
0
            tail = &l->next;
1124
0
          }
1125
0
          h = p + 1;
1126
0
          break;
1127
0
      }
1128
0
  } else {
1129
    /* single addr. mode */
1130
0
    flags = 0;
1131
0
    p = last + 1;
1132
0
  }
1133
0
  if((int)(p - h) > 0) {
1134
0
    l = mk_name_lst_elem(h, (int)(p - h), flags);
1135
0
    if(l == 0)
1136
0
      goto error;
1137
0
    *tail = l;
1138
0
    tail = &l->next;
1139
0
  }
1140
0
  return n_lst;
1141
0
error:
1142
0
  if(n_lst)
1143
0
    free_name_lst(n_lst);
1144
0
  return 0;
1145
0
}
1146
1147
1148
/*
1149
 * parses [proto:]host[:port]  or
1150
 *  [proto:](host_1, host_2, ... host_n)[:port]
1151
 * where proto= udp|tcp|tls
1152
 * returns  fills proto, port, host and returns list of addresses on success
1153
 * (pkg malloc'ed) and 0 on failure
1154
 */
1155
/** get protocol host and port from a string representation.
1156
 * parses [proto:]host[:port]  or
1157
 *  [proto:](host_1, host_2, ... host_n)[:port]
1158
 * where proto= udp|tcp|tls|sctp
1159
 * @param s  - string (like above)
1160
 * @param host - will be filled with the host part
1161
 *               Note: for multi-homing it will contain all the addresses
1162
 *               (e.g.: "sctp:(1.2.3.4, 5.6.7.8)" => host="(1.2.3.4, 5.6.7.8)")
1163
 * @param hlen - will be filled with the length of the host part.
1164
 * @param port - will be filled with the port if present or 0 if it's not.
1165
 * @param proto - will be filled with the protocol if present or PROTO_NONE
1166
 *                if it's not.
1167
 * @return  fills proto, port, host and returns 0 on success and -1 on failure.
1168
 */
1169
int parse_phostport(char *s, char **host, int *hlen, int *port, int *proto)
1170
0
{
1171
0
  char *first;  /* first ':' occurrence */
1172
0
  char *second; /* second ':' occurrence */
1173
0
  char *p;
1174
0
  int bracket;
1175
0
  char *tmp;
1176
1177
0
  first = second = 0;
1178
0
  bracket = 0;
1179
1180
  /* find the first 2 ':', ignoring possible ipv6 addresses
1181
   * (substrings between [])
1182
   */
1183
0
  for(p = s; *p; p++) {
1184
0
    switch(*p) {
1185
0
      case '[':
1186
0
        bracket++;
1187
0
        if(bracket > 1)
1188
0
          goto error_brackets;
1189
0
        break;
1190
0
      case ']':
1191
0
        bracket--;
1192
0
        if(bracket < 0)
1193
0
          goto error_brackets;
1194
0
        break;
1195
0
      case ':':
1196
0
        if(bracket == 0) {
1197
0
          if(first == 0)
1198
0
            first = p;
1199
0
          else if(second == 0)
1200
0
            second = p;
1201
0
          else
1202
0
            goto error_colons;
1203
0
        }
1204
0
        break;
1205
0
    }
1206
0
  }
1207
0
  if(p == s)
1208
0
    return -1;
1209
0
  if(*(p - 1) == ':')
1210
0
    goto error_colons;
1211
1212
0
  if(first == 0) { /* no ':' => only host */
1213
0
    *host = s;
1214
0
    *hlen = (int)(p - s);
1215
0
    *port = 0;
1216
0
    *proto = 0;
1217
0
    goto end;
1218
0
  }
1219
0
  if(second) { /* 2 ':' found => check if valid */
1220
0
    if(parse_proto((unsigned char *)s, first - s, proto) < 0)
1221
0
      goto error_proto;
1222
0
    *port = strtol(second + 1, &tmp, 10);
1223
0
    if((tmp == 0) || (*tmp) || (tmp == second + 1))
1224
0
      goto error_port;
1225
0
    *host = first + 1;
1226
0
    *hlen = (int)(second - *host);
1227
0
    goto end;
1228
0
  }
1229
  /* only 1 ':' found => it's either proto:host or host:port */
1230
0
  *port = strtol(first + 1, &tmp, 10);
1231
0
  if((tmp == 0) || (*tmp) || (tmp == first + 1)) {
1232
    /* invalid port => it's proto:host */
1233
0
    if(parse_proto((unsigned char *)s, first - s, proto) < 0)
1234
0
      goto error_proto;
1235
0
    *port = 0;
1236
0
    *host = first + 1;
1237
0
    *hlen = (int)(p - *host);
1238
0
  } else {
1239
    /* valid port => it is host:port */
1240
0
    *proto = 0;
1241
0
    *host = s;
1242
0
    *hlen = (int)(first - *host);
1243
0
  }
1244
0
end:
1245
0
  return 0;
1246
0
error_brackets:
1247
0
  LM_ERR("too many brackets in %s\n", s);
1248
0
  return -1;
1249
0
error_colons:
1250
0
  LM_ERR("too many colons in %s\n", s);
1251
0
  return -1;
1252
0
error_proto:
1253
0
  LM_ERR("bad protocol in %s\n", s);
1254
0
  return -1;
1255
0
error_port:
1256
0
  LM_ERR("bad port number in %s\n", s);
1257
0
  return -1;
1258
0
}
1259
1260
1261
/** get protocol host, port and MH addresses list from a string representation.
1262
 * parses [proto:]host[:port]  or
1263
 *  [proto:](host_1, host_2, ... host_n)[:port]
1264
 * where proto= udp|tcp|tls|sctp
1265
 * @param s  - string (like above)
1266
 * @param host - will be filled with the host part
1267
 *               Note: for multi-homing it will contain all the addresses
1268
 *               (e.g.: "sctp:(1.2.3.4, 5.6.7.8)" => host="(1.2.3.4, 5.6.7.8)")
1269
 * @param hlen - will be filled with the length of the host part.
1270
 * @param port - will be filled with the port if present or 0 if it's not.
1271
 * @param proto - will be filled with the protocol if present or PROTO_NONE
1272
 *                if it's not.
1273
 * @return  fills proto, port, host and returns list of addresses on success
1274
 * (pkg malloc'ed) and 0 on failure
1275
 */
1276
static struct name_lst *parse_phostport_mh(
1277
    char *s, char **host, int *hlen, int *port, int *proto)
1278
0
{
1279
0
  if(parse_phostport(s, host, hlen, port, proto) == 0)
1280
0
    return parse_name_lst(*host, *hlen);
1281
0
  return 0;
1282
0
}
1283
1284
1285
/** Update \c cfg_file variable to contain full pathname or '-' (for stdin)
1286
 * allocated in system memory. The function updates
1287
 * the value of \c cfg_file global variable to contain full absolute pathname
1288
 * to the main configuration file. The function uses CFG_FILE macro to
1289
 * determine the default path to the configuration file if the user did not
1290
 * specify one using the command line option. If \c cfg_file contains an
1291
 * absolute pathname then it is cloned unmodified, if it contains a relative
1292
 * pathname then the value returned by \c getcwd function will be added at the
1293
 * beginning. This function must be run before changing its current working
1294
 * directory to / (in daemon mode).
1295
 * @return Zero on success, negative number
1296
 * on error.
1297
 */
1298
int fix_cfg_file(void)
1299
0
{
1300
0
  char *res = NULL;
1301
0
  size_t max_len, cwd_len, cfg_len;
1302
1303
0
  if(cfg_file == NULL)
1304
0
    cfg_file = CFG_FILE;
1305
0
  if(cfg_file[0] == '/') {
1306
0
    cfg_len = strlen(cfg_file);
1307
0
    if(cfg_len < 2) {
1308
      /* do not accept only '/' */
1309
0
      fprintf(stderr, "ERROR: invalid cfg file value\n");
1310
0
      return -1;
1311
0
    }
1312
0
    if((res = malloc(cfg_len + 1)) == NULL)
1313
0
      goto error;
1314
0
    memcpy(res, cfg_file, cfg_len);
1315
0
    res[cfg_len] = 0;
1316
0
    cfg_file = res;
1317
0
    return 0;
1318
0
  }
1319
0
  if(cfg_file[0] == '-') {
1320
0
    cfg_len = strlen(cfg_file);
1321
0
    if(cfg_len == 1) {
1322
0
      if((res = malloc(2)) == NULL)
1323
0
        goto error;
1324
0
      res[0] = '-';
1325
0
      res[1] = '\0';
1326
0
      cfg_file = res;
1327
0
      return 0;
1328
0
    }
1329
0
  }
1330
1331
  /* cfg_file contains a relative pathname, get the current
1332
   * working directory and add it at the beginning
1333
   */
1334
0
  cfg_len = strlen(cfg_file);
1335
1336
0
  max_len = pathmax();
1337
0
  if((res = malloc(max_len)) == NULL)
1338
0
    goto error;
1339
1340
0
  if(getcwd(res, max_len) == NULL)
1341
0
    goto error;
1342
0
  cwd_len = strlen(res);
1343
1344
  /* Make sure that the buffer is big enough */
1345
0
  if(cwd_len + 1 + cfg_len >= max_len)
1346
0
    goto error;
1347
1348
0
  res[cwd_len] = '/';
1349
0
  memcpy(res + cwd_len + 1, cfg_file, cfg_len);
1350
1351
0
  res[cwd_len + 1 + cfg_len] = '\0'; /* Add terminating zero */
1352
0
  cfg_file = res;
1353
0
  return 0;
1354
1355
0
error:
1356
0
  fprintf(stderr, "ERROR: Unable to fix cfg file to contain full pathname\n");
1357
0
  if(res)
1358
0
    free(res);
1359
0
  return -1;
1360
0
}
1361
1362
1363
/* main loop */
1364
int main_loop(void)
1365
0
{
1366
0
  int i;
1367
0
  pid_t pid;
1368
0
  struct socket_info *si;
1369
0
  char si_desc[MAX_PT_DESC];
1370
#ifdef EXTRA_DEBUG
1371
  int r;
1372
#endif
1373
0
  int nrprocs;
1374
0
  int woneinit;
1375
1376
0
  if(_sr_instance_started == NULL) {
1377
0
    _sr_instance_started = shm_malloc(sizeof(int));
1378
0
    if(_sr_instance_started == NULL) {
1379
0
      SHM_MEM_ERROR;
1380
0
      goto error;
1381
0
    }
1382
0
    *_sr_instance_started = 0;
1383
0
  }
1384
  /* one "main" process and n children handling i/o */
1385
0
  if(dont_fork) {
1386
0
    if(udp_listen == 0) {
1387
0
      LM_ERR("no fork mode requires at least one"
1388
0
           " udp listen address, exiting...\n");
1389
0
      goto error;
1390
0
    }
1391
    /* only one address, we ignore all the others */
1392
0
    if(udp_init(udp_listen) == -1)
1393
0
      goto error;
1394
0
    bind_address = udp_listen;
1395
0
    if(bind_address->address.af == AF_INET) {
1396
0
      sendipv4 = bind_address;
1397
0
#ifdef USE_RAW_SOCKS
1398
      /* always try to have a raw socket opened if we are using ipv4 */
1399
0
      raw_udp4_send_sock = raw_socket(IPPROTO_RAW, 0, 0, 1);
1400
0
      if(raw_udp4_send_sock < 0) {
1401
0
        if(default_core_cfg.udp4_raw > 0) {
1402
          /* force use raw socket failed */
1403
0
          ERR("could not initialize raw udp send socket (ipv4):"
1404
0
            " %s (%d)\n",
1405
0
              strerror(errno), errno);
1406
0
          if(errno == EPERM)
1407
0
            ERR("could not initialize raw socket on startup"
1408
0
              " due to inadequate permissions, please"
1409
0
              " restart as root or with CAP_NET_RAW\n");
1410
0
          goto error;
1411
0
        }
1412
0
        default_core_cfg.udp4_raw = 0; /* disabled */
1413
0
      } else {
1414
0
        register_fds(1);
1415
0
        if(default_core_cfg.udp4_raw < 0) {
1416
          /* auto-detect => use it */
1417
0
          default_core_cfg.udp4_raw = 1; /* enabled */
1418
0
          LM_DBG("raw socket possible => turning it on\n");
1419
0
        }
1420
0
        if(default_core_cfg.udp4_raw_ttl < 0) {
1421
          /* auto-detect */
1422
0
          default_core_cfg.udp4_raw_ttl =
1423
0
              sock_get_ttl(sendipv4->socket);
1424
0
          if(default_core_cfg.udp4_raw_ttl < 0)
1425
            /* error, use some default value */
1426
0
            default_core_cfg.udp4_raw_ttl = 63;
1427
0
        }
1428
0
      }
1429
#else
1430
      default_core_cfg.udp4_raw = 0;
1431
#endif /* USE_RAW_SOCKS */
1432
0
    } else
1433
0
      sendipv6 = bind_address;
1434
0
    if(udp_listen->next) {
1435
0
      LM_WARN("using only the first listen address (no fork)\n");
1436
0
    }
1437
1438
    /* delay cfg_shmize to the last moment (it must be called _before_
1439
       forking). Changes to default cfgs after this point will be
1440
       ignored.
1441
    */
1442
0
    if(cfg_shmize() < 0) {
1443
0
      LM_CRIT("could not initialize shared configuration\n");
1444
0
      goto error;
1445
0
    }
1446
1447
    /* Register the children that will keep updating their
1448
     * local configuration */
1449
0
    cfg_register_child(1   /* main = udp listener */
1450
0
               + 1 /* timer */
1451
0
#ifdef USE_SLOW_TIMER
1452
0
               + 1 /* slow timer */
1453
0
#endif
1454
0
    );
1455
0
    if(do_suid() == -1)
1456
0
      goto error; /* try to drop privileges */
1457
    /* process_no now initialized to zero -- increase from now on
1458
       as new processes are forked (while skipping 0 reserved for main
1459
    */
1460
1461
    /* Temporary set the local configuration of the main process
1462
     * to make the group instances available in PROC_INIT.
1463
     */
1464
0
    cfg_main_set_local();
1465
1466
    /* init log prefix format */
1467
0
    log_prefix_init();
1468
1469
    /* init childs with rank==PROC_INIT before forking any process,
1470
     * this is a place for delayed (after mod_init) initializations
1471
     * (e.g. shared vars that depend on the total number of processes
1472
     * that is known only after all mod_inits have been executed )
1473
     * WARNING: the same init_child will be called latter, a second time
1474
     * for the "main" process with rank PROC_MAIN (make sure things are
1475
     * not initialized twice)*/
1476
0
    if(init_child(PROC_INIT) < 0) {
1477
0
      LM_ERR("init_child(PROC_INT) -- exiting\n");
1478
0
      cfg_main_reset_local();
1479
0
      goto error;
1480
0
    }
1481
0
    cfg_main_reset_local();
1482
0
    if(counters_prefork_init(get_max_procs()) == -1)
1483
0
      goto error;
1484
1485
0
#ifdef USE_SLOW_TIMER
1486
    /* we need another process to act as the "slow" timer*/
1487
0
    pid = fork_process(PROC_TIMER, "slow timer", 0);
1488
0
    if(pid < 0) {
1489
0
      LM_CRIT("Cannot fork\n");
1490
0
      goto error;
1491
0
    }
1492
0
    if(pid == 0) {
1493
      /* child */
1494
      /* timer!*/
1495
0
      if(real_time & 2)
1496
0
        set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1497
1498
0
      if(arm_slow_timer() < 0)
1499
0
        goto error;
1500
0
      slow_timer_main();
1501
0
    } else {
1502
0
      slow_timer_pid = pid;
1503
0
    }
1504
0
#endif
1505
    /* we need another process to act as the "main" timer*/
1506
0
    pid = fork_process(PROC_TIMER, "timer", 0);
1507
0
    if(pid < 0) {
1508
0
      LM_CRIT("Cannot fork\n");
1509
0
      goto error;
1510
0
    }
1511
0
    if(pid == 0) {
1512
      /* child */
1513
      /* timer!*/
1514
0
      if(real_time & 1)
1515
0
        set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1516
0
      if(arm_timer() < 0)
1517
0
        goto error;
1518
0
      timer_main();
1519
0
    } else {
1520
      /* do nothing for main timer */
1521
0
    }
1522
1523
0
    if(sr_wtimer_start() < 0) {
1524
0
      LM_CRIT("Cannot start wtimer\n");
1525
0
      goto error;
1526
0
    }
1527
    /* main process, receive loop */
1528
0
    process_no = 0; /*main process number*/
1529
0
    pt[process_no].pid = getpid();
1530
0
    snprintf(pt[process_no].desc, MAX_PT_DESC,
1531
0
        "stand-alone receiver @ %s:%s", bind_address->name.s,
1532
0
        bind_address->port_no_str.s);
1533
1534
    /* call it also w/ PROC_MAIN to make sure modules that init things
1535
     * only in PROC_MAIN get a chance to run */
1536
0
    if(init_child(PROC_MAIN) < 0) {
1537
0
      LM_ERR("init_child(PROC_MAIN) -- exiting\n");
1538
0
      goto error;
1539
0
    }
1540
1541
    /* We will call child_init even if we
1542
     * do not fork - and it will be called with rank 1 because
1543
     * in fact we behave like a child, not like main process
1544
     */
1545
1546
0
    if(init_child(PROC_SIPINIT) < 0) {
1547
0
      LM_ERR("init_child failed\n");
1548
0
      goto error;
1549
0
    }
1550
1551
0
    if(init_child(PROC_POSTCHILDINIT) < 0) {
1552
0
      LM_ERR("error in init_child for rank PROC_POSTCHILDINIT\n");
1553
0
      goto error;
1554
0
    }
1555
1556
0
    *_sr_instance_started = 1;
1557
0
    return udp_rcv_loop();
1558
0
  } else { /* fork: */
1559
1560
    /* Register the children that will keep updating their
1561
     * local configuration. (udp/tcp/sctp listeneres
1562
     * will be added later.) */
1563
0
    cfg_register_child(1 /* timer */
1564
0
#ifdef USE_SLOW_TIMER
1565
0
               + 1 /* slow timer */
1566
0
#endif
1567
0
    );
1568
1569
0
    for(si = udp_listen; si; si = si->next) {
1570
      /* create the listening socket (for each address)*/
1571
      /* udp */
1572
0
      if(udp_init(si) == -1)
1573
0
        goto error;
1574
      /* get first ipv4/ipv6 socket*/
1575
0
      if((si->address.af == AF_INET)
1576
0
          && ((sendipv4 == 0)
1577
0
              || (sendipv4->flags & (SI_IS_LO | SI_IS_MCAST))))
1578
0
        sendipv4 = si;
1579
0
      if(((sendipv6 == 0) || (sendipv6->flags & (SI_IS_LO | SI_IS_MCAST)))
1580
0
          && (si->address.af == AF_INET6))
1581
0
        sendipv6 = si;
1582
      /* children_no per each socket */
1583
0
      cfg_register_child((si->workers > 0) ? si->workers : children_no);
1584
0
    }
1585
0
#ifdef USE_RAW_SOCKS
1586
    /* always try to have a raw socket opened if we are using ipv4 */
1587
0
    if(sendipv4) {
1588
0
      raw_udp4_send_sock = raw_socket(IPPROTO_RAW, 0, 0, 1);
1589
0
      if(raw_udp4_send_sock < 0) {
1590
0
        if(default_core_cfg.udp4_raw > 0) {
1591
          /* force use raw socket failed */
1592
0
          ERR("could not initialize raw udp send socket (ipv4):"
1593
0
            " %s (%d)\n",
1594
0
              strerror(errno), errno);
1595
0
          if(errno == EPERM)
1596
0
            ERR("could not initialize raw socket on startup"
1597
0
              " due to inadequate permissions, please"
1598
0
              " restart as root or with CAP_NET_RAW\n");
1599
0
          goto error;
1600
0
        }
1601
0
        default_core_cfg.udp4_raw = 0; /* disabled */
1602
0
      } else {
1603
0
        register_fds(1);
1604
0
        if(default_core_cfg.udp4_raw < 0) {
1605
          /* auto-detect => use it */
1606
0
          default_core_cfg.udp4_raw = 1; /* enabled */
1607
0
          LM_DBG("raw socket possible => turning it on\n");
1608
0
        }
1609
0
        if(default_core_cfg.udp4_raw_ttl < 0) {
1610
          /* auto-detect */
1611
0
          default_core_cfg.udp4_raw_ttl =
1612
0
              sock_get_ttl(sendipv4->socket);
1613
0
          if(default_core_cfg.udp4_raw_ttl < 0)
1614
            /* error, use some default value */
1615
0
            default_core_cfg.udp4_raw_ttl = 63;
1616
0
        }
1617
0
      }
1618
0
    }
1619
#else
1620
    default_core_cfg.udp4_raw = 0;
1621
#endif /* USE_RAW_SOCKS */
1622
0
#ifdef USE_SCTP
1623
0
    if(!sctp_disable) {
1624
0
      for(si = sctp_listen; si; si = si->next) {
1625
0
        if(sctp_core_init_sock(si) == -1)
1626
0
          goto error;
1627
        /* get first ipv4/ipv6 socket*/
1628
0
        if((si->address.af == AF_INET)
1629
0
            && ((sendipv4_sctp == 0)
1630
0
                || (sendipv4_sctp->flags
1631
0
                    & (SI_IS_LO | SI_IS_MCAST))))
1632
0
          sendipv4_sctp = si;
1633
0
        if(((sendipv6_sctp == 0)
1634
0
               || (sendipv6_sctp->flags & (SI_IS_LO | SI_IS_MCAST)))
1635
0
            && (si->address.af == AF_INET6))
1636
0
          sendipv6_sctp = si;
1637
        /* sctp_children_no per each socket */
1638
0
        cfg_register_child(
1639
0
            (si->workers > 0) ? si->workers : sctp_children_no);
1640
0
      }
1641
0
    }
1642
0
#endif /* USE_SCTP */
1643
0
#ifdef USE_TCP
1644
0
    if(!tcp_disable) {
1645
0
      for(si = tcp_listen; si; si = si->next) {
1646
        /* same thing for tcp */
1647
0
        if(tcp_init(si) == -1)
1648
0
          goto error;
1649
        /* get first ipv4/ipv6 socket*/
1650
0
        if((si->address.af == AF_INET)
1651
0
            && ((sendipv4_tcp == 0)
1652
0
                || (sendipv4_tcp->flags
1653
0
                    & (SI_IS_LO | SI_IS_MCAST))))
1654
0
          sendipv4_tcp = si;
1655
0
        if(((sendipv6_tcp == 0)
1656
0
               || (sendipv6_tcp->flags & (SI_IS_LO | SI_IS_MCAST)))
1657
0
            && (si->address.af == AF_INET6))
1658
0
          sendipv6_tcp = si;
1659
0
      }
1660
      /* the number of sockets does not matter */
1661
0
      cfg_register_child(tcp_children_no + 1 /* tcp main */);
1662
0
    }
1663
0
#ifdef USE_TLS
1664
0
    if(!tls_disable && tls_has_init_si()) {
1665
0
      for(si = tls_listen; si; si = si->next) {
1666
        /* same as for tcp*/
1667
0
        if(tls_init(si) == -1)
1668
0
          goto error;
1669
        /* get first ipv4/ipv6 socket*/
1670
0
        if((si->address.af == AF_INET)
1671
0
            && ((sendipv4_tls == 0)
1672
0
                || (sendipv4_tls->flags
1673
0
                    & (SI_IS_LO | SI_IS_MCAST)))) {
1674
0
          sendipv4_tls = si;
1675
0
          if(sendipv4_tcp == 0) {
1676
0
            sendipv4_tcp = si;
1677
0
          }
1678
0
        }
1679
0
        if(((sendipv6_tls == 0)
1680
0
               || (sendipv6_tls->flags & (SI_IS_LO | SI_IS_MCAST)))
1681
0
            && (si->address.af == AF_INET6)) {
1682
0
          sendipv6_tls = si;
1683
0
          if(sendipv6_tcp == 0) {
1684
0
            sendipv6_tcp = si;
1685
0
          }
1686
0
        }
1687
0
      }
1688
0
    }
1689
0
#endif /* USE_TLS */
1690
0
#endif /* USE_TCP */
1691
1692
    /* all processes should have access to all the sockets (for
1693
       * sending) so we open all first*/
1694
0
    if(do_suid() == -1)
1695
0
      goto error; /* try to drop privileges */
1696
1697
    /* delay cfg_shmize to the last moment (it must be called _before_
1698
       forking). Changes to default cfgs after this point will be
1699
       ignored (cfg_shmize() will copy the default cfgs into shmem).
1700
    */
1701
0
    if(cfg_shmize() < 0) {
1702
0
      LM_CRIT("could not initialize shared configuration\n");
1703
0
      goto error;
1704
0
    }
1705
1706
    /* Temporary set the local configuration of the main process
1707
     * to make the group instances available in PROC_INIT.
1708
     */
1709
0
    cfg_main_set_local();
1710
1711
    /* init log prefix format */
1712
0
    log_prefix_init();
1713
1714
    /* init childs with rank==PROC_INIT before forking any process,
1715
     * this is a place for delayed (after mod_init) initializations
1716
     * (e.g. shared vars that depend on the total number of processes
1717
     * that is known only after all mod_inits have been executed )
1718
     * WARNING: the same init_child will be called latter, a second time
1719
     * for the "main" process with rank PROC_MAIN (make sure things are
1720
     * not initialized twice)*/
1721
0
    if(init_child(PROC_INIT) < 0) {
1722
0
      LM_ERR("error in init_child(PROC_INT) -- exiting\n");
1723
0
      cfg_main_reset_local();
1724
0
      goto error;
1725
0
    }
1726
0
    cfg_main_reset_local();
1727
1728
0
#ifdef USE_TCP
1729
0
    if(!tcp_disable) {
1730
0
      if(ksr_tcp_check_timer == -1) {
1731
0
        if(ksr_tcp_msg_data_timeout > 0 && ksr_tcp_msg_read_timeout > 0)
1732
0
          ksr_tcp_check_timer = MIN(ksr_tcp_msg_data_timeout,
1733
0
                          ksr_tcp_msg_read_timeout)
1734
0
                      / 2;
1735
0
        else
1736
0
          ksr_tcp_check_timer =
1737
0
              ksr_tcp_msg_data_timeout > 0
1738
0
                  ? ksr_tcp_msg_data_timeout / 2
1739
0
                  : ksr_tcp_msg_read_timeout / 2;
1740
0
      }
1741
0
      if(ksr_tcp_check_timer > 0) {
1742
0
        if(sr_wtimer_add(tcp_timer_check_connections, NULL,
1743
0
               ksr_tcp_check_timer)
1744
0
            < 0) {
1745
0
          LM_CRIT("cannot add timer for tcp connection checks\n");
1746
0
          goto error;
1747
0
        }
1748
0
      }
1749
0
    }
1750
0
#endif
1751
1752
0
    if(counters_prefork_init(get_max_procs()) == -1)
1753
0
      goto error;
1754
1755
1756
0
    woneinit = 0;
1757
0
    if(ksr_wait_worker1_mode != 0) {
1758
0
      ksr_wait_worker1_done = (int *)shm_malloc(sizeof(int));
1759
0
      if(ksr_wait_worker1_done == 0) {
1760
0
        SHM_MEM_ERROR;
1761
0
        goto error;
1762
0
      }
1763
0
      *ksr_wait_worker1_done = 0;
1764
0
    }
1765
    /* udp processes */
1766
0
    for(si = udp_listen; si; si = si->next) {
1767
0
      nrprocs = (si->workers > 0) ? si->workers : children_no;
1768
0
      for(i = 0; i < nrprocs; i++) {
1769
0
        if(si->address.af == AF_INET6) {
1770
0
          if(si->useinfo.name.s)
1771
0
            snprintf(si_desc, MAX_PT_DESC,
1772
0
                "udp receiver child=%d "
1773
0
                "sock=[%s]:%s (%s:%s)",
1774
0
                i, si->name.s, si->port_no_str.s,
1775
0
                si->useinfo.name.s, si->useinfo.port_no_str.s);
1776
0
          else
1777
0
            snprintf(si_desc, MAX_PT_DESC,
1778
0
                "udp receiver child=%d "
1779
0
                "sock=[%s]:%s",
1780
0
                i, si->name.s, si->port_no_str.s);
1781
0
        } else {
1782
0
          if(si->useinfo.name.s)
1783
0
            snprintf(si_desc, MAX_PT_DESC,
1784
0
                "udp receiver child=%d "
1785
0
                "sock=%s:%s (%s:%s)",
1786
0
                i, si->name.s, si->port_no_str.s,
1787
0
                si->useinfo.name.s, si->useinfo.port_no_str.s);
1788
0
          else
1789
0
            snprintf(si_desc, MAX_PT_DESC,
1790
0
                "udp receiver child=%d "
1791
0
                "sock=%s:%s",
1792
0
                i, si->name.s, si->port_no_str.s);
1793
0
        }
1794
0
        child_rank++;
1795
0
        pid = fork_process(child_rank, si_desc, 1);
1796
0
        if(pid < 0) {
1797
0
          LM_CRIT("Cannot fork\n");
1798
0
          goto error;
1799
0
        } else if(pid == 0) {
1800
          /* child */
1801
0
          bind_address = si; /* shortcut */
1802
1803
0
          if(woneinit == 0) {
1804
0
            if(run_child_one_init_route() < 0)
1805
0
              goto error;
1806
0
          }
1807
0
          if(ksr_wait_worker1_mode != 0) {
1808
0
            *ksr_wait_worker1_done = 1;
1809
0
            LM_DBG("child one finished initialization\n");
1810
0
          }
1811
0
          return udp_rcv_loop();
1812
0
        }
1813
        /* main process */
1814
0
        if(woneinit == 0 && ksr_wait_worker1_mode != 0) {
1815
0
          int wcount = 0;
1816
0
          while(*ksr_wait_worker1_done == 0) {
1817
0
            sleep_us(ksr_wait_worker1_usleep);
1818
0
            wcount++;
1819
0
            if(ksr_wait_worker1_time
1820
0
                <= wcount * ksr_wait_worker1_usleep) {
1821
0
              LM_ERR("waiting for child one too long - wait "
1822
0
                   "time: %d\n",
1823
0
                  ksr_wait_worker1_time);
1824
0
              goto error;
1825
0
            }
1826
0
          }
1827
0
          LM_DBG("child one initialized after %d wait steps\n",
1828
0
              wcount);
1829
0
        }
1830
0
        woneinit = 1;
1831
0
      }
1832
      /*parent*/
1833
0
      /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
1834
0
    }
1835
0
#ifdef USE_SCTP
1836
    /* sctp processes */
1837
0
    if(!sctp_disable) {
1838
0
      for(si = sctp_listen; si; si = si->next) {
1839
0
        nrprocs = (si->workers > 0) ? si->workers : sctp_children_no;
1840
0
        for(i = 0; i < nrprocs; i++) {
1841
0
          if(si->address.af == AF_INET6) {
1842
0
            snprintf(si_desc, MAX_PT_DESC,
1843
0
                "sctp receiver child=%d "
1844
0
                "sock=[%s]:%s",
1845
0
                i, si->name.s, si->port_no_str.s);
1846
0
          } else {
1847
0
            snprintf(si_desc, MAX_PT_DESC,
1848
0
                "sctp receiver child=%d "
1849
0
                "sock=%s:%s",
1850
0
                i, si->name.s, si->port_no_str.s);
1851
0
          }
1852
0
          child_rank++;
1853
0
          pid = fork_process(child_rank, si_desc, 1);
1854
0
          if(pid < 0) {
1855
0
            LM_CRIT("Cannot fork\n");
1856
0
            goto error;
1857
0
          } else if(pid == 0) {
1858
            /* child */
1859
0
            bind_address = si; /* shortcut */
1860
1861
0
            if(woneinit == 0) {
1862
0
              if(run_child_one_init_route() < 0)
1863
0
                goto error;
1864
0
            }
1865
0
            if(ksr_wait_worker1_mode != 0) {
1866
0
              *ksr_wait_worker1_done = 1;
1867
0
              LM_DBG("child one finished initialization\n");
1868
0
            }
1869
0
            return sctp_core_rcv_loop();
1870
0
          }
1871
          /* main process */
1872
0
          if(woneinit == 0 && ksr_wait_worker1_mode != 0) {
1873
0
            int wcount = 0;
1874
0
            while(*ksr_wait_worker1_done == 0) {
1875
0
              sleep_us(ksr_wait_worker1_usleep);
1876
0
              wcount++;
1877
0
              if(ksr_wait_worker1_time
1878
0
                  <= wcount * ksr_wait_worker1_usleep) {
1879
0
                LM_ERR("waiting for child one too long - wait "
1880
0
                     "time: %d\n",
1881
0
                    ksr_wait_worker1_time);
1882
0
                goto error;
1883
0
              }
1884
0
            }
1885
0
            LM_DBG("child one initialized after %d wait steps\n",
1886
0
                wcount);
1887
0
          }
1888
0
          woneinit = 1;
1889
0
        }
1890
        /*parent*/
1891
0
        /*close(sctp_sock)*/; /*if closed=>sendto invalid fd errors?*/
1892
0
      }
1893
0
    }
1894
0
#endif /* USE_SCTP */
1895
1896
    /*this is the main process*/
1897
0
    bind_address = 0; /* main proc -> it shouldn't send anything, */
1898
1899
0
#ifdef USE_SLOW_TIMER
1900
    /* fork again for the "slow" timer process*/
1901
0
    pid = fork_process(PROC_TIMER, "slow timer", 1);
1902
0
    if(pid < 0) {
1903
0
      LM_CRIT("cannot fork \"slow\" timer process\n");
1904
0
      goto error;
1905
0
    } else if(pid == 0) {
1906
      /* child */
1907
0
      if(real_time & 2)
1908
0
        set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1909
0
      if(arm_slow_timer() < 0)
1910
0
        goto error;
1911
0
      slow_timer_main();
1912
0
    } else {
1913
0
      slow_timer_pid = pid;
1914
0
    }
1915
0
#endif /* USE_SLOW_TIMER */
1916
1917
    /* fork again for the "main" timer process*/
1918
0
    pid = fork_process(PROC_TIMER, "timer", 1);
1919
0
    if(pid < 0) {
1920
0
      LM_CRIT("cannot fork timer process\n");
1921
0
      goto error;
1922
0
    } else if(pid == 0) {
1923
      /* child */
1924
0
      if(real_time & 1)
1925
0
        set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1926
0
      if(arm_timer() < 0)
1927
0
        goto error;
1928
0
      timer_main();
1929
0
    }
1930
0
    if(sr_wtimer_start() < 0) {
1931
0
      LM_CRIT("Cannot start wtimer\n");
1932
0
      goto error;
1933
0
    }
1934
1935
    /* init childs with rank==MAIN before starting tcp main (in case they want
1936
   * to fork  a tcp capable process, the corresponding tcp. comm. fds in
1937
   * pt[] must be set before calling tcp_main_loop()) */
1938
0
    if(init_child(PROC_MAIN) < 0) {
1939
0
      LM_ERR("error in init_child\n");
1940
0
      goto error;
1941
0
    }
1942
1943
0
#ifdef USE_TCP
1944
0
    if(!tcp_disable) {
1945
      /* start tcp  & tls receivers */
1946
0
      if(tcp_init_children(&woneinit) < 0)
1947
0
        goto error;
1948
      /* start tcp+tls main attendant proc */
1949
0
      pid = fork_process(PROC_TCP_MAIN, "tcp main process", 0);
1950
0
      if(pid < 0) {
1951
0
        LM_CRIT("cannot fork tcp main process: %s\n", strerror(errno));
1952
0
        goto error;
1953
0
      } else if(pid == 0) {
1954
        /* child */
1955
0
        tcp_main_loop();
1956
0
      } else {
1957
0
        tcp_main_pid = pid;
1958
0
        unix_tcp_sock = -1;
1959
0
      }
1960
0
    }
1961
0
#endif
1962
    /* main */
1963
0
    strncpy(pt[0].desc, "main process - attendant", MAX_PT_DESC);
1964
0
#ifdef USE_TCP
1965
0
    close_extra_socks(PROC_ATTENDANT, get_proc_no());
1966
0
    if(!tcp_disable) {
1967
      /* main's tcp sockets are disabled by default from init_pt() */
1968
0
      unix_tcp_sock = -1;
1969
0
    }
1970
0
#endif
1971
0
    if(init_child(PROC_POSTCHILDINIT) < 0) {
1972
0
      LM_ERR("error in init_child for rank PROC_POSTCHILDINIT\n");
1973
0
      goto error;
1974
0
    }
1975
1976
    /* init cfg, but without per child callbacks support */
1977
0
    cfg_child_no_cb_init();
1978
0
    cfg_ok = 1;
1979
1980
0
    *_sr_instance_started = 1;
1981
0
    sr_corecb_void_exec(app_ready);
1982
1983
#ifdef EXTRA_DEBUG
1984
    for(r = 0; r < *process_count; r++) {
1985
      fprintf(stderr, "% 3d   % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1986
    }
1987
#endif
1988
0
    LM_DBG("Expect maximum %d  open fds\n", get_max_open_fds());
1989
    /* in daemonize mode send the exit code back to the parent process */
1990
0
    if(!dont_daemonize) {
1991
0
      if(daemon_status_send(0) < 0) {
1992
0
        ERR("error sending daemon status: %s [%d]\n", strerror(errno),
1993
0
            errno);
1994
0
        goto error;
1995
0
      }
1996
0
    }
1997
0
    for(;;) {
1998
0
      handle_sigs();
1999
0
      pause();
2000
0
      cfg_update();
2001
0
    }
2002
0
  }
2003
2004
  /*return 0; */
2005
0
error:
2006
  /* if we are here, we are the "main process",
2007
          any forked children should exit with exit(-1) and not
2008
          ever use return */
2009
0
  return -1;
2010
0
}
2011
2012
/*
2013
 * Calculate number of processes, this does not
2014
 * include processes created by modules
2015
 */
2016
static int calc_proc_no(void)
2017
0
{
2018
0
  int udp_listeners;
2019
0
  struct socket_info *si;
2020
0
#ifdef USE_TCP
2021
0
  int tcp_listeners;
2022
0
  int tcp_e_listeners;
2023
0
#endif
2024
0
#ifdef USE_SCTP
2025
0
  int sctp_listeners;
2026
0
#endif
2027
2028
0
  for(si = udp_listen, udp_listeners = 0; si; si = si->next)
2029
0
    udp_listeners += (si->workers > 0) ? si->workers : children_no;
2030
0
#ifdef USE_TCP
2031
0
  for(si = tcp_listen, tcp_listeners = 0, tcp_e_listeners = 0; si;
2032
0
      si = si->next) {
2033
0
    if(si->workers > 0)
2034
0
      tcp_listeners += si->workers;
2035
0
    else
2036
0
      tcp_e_listeners = tcp_cfg_children_no;
2037
0
  }
2038
0
  tcp_listeners += tcp_e_listeners;
2039
0
#ifdef USE_TLS
2040
0
  tcp_e_listeners = 0;
2041
0
  for(si = tls_listen, tcp_e_listeners = 0; si; si = si->next) {
2042
0
    if(si->workers > 0)
2043
0
      tcp_listeners += si->workers;
2044
0
    else {
2045
0
      if(tcp_listeners == 0)
2046
0
        tcp_e_listeners = tcp_cfg_children_no;
2047
0
    }
2048
0
  }
2049
0
  tcp_listeners += tcp_e_listeners;
2050
0
#endif
2051
0
  tcp_children_no = tcp_listeners;
2052
0
#endif
2053
0
#ifdef USE_SCTP
2054
0
  for(si = sctp_listen, sctp_listeners = 0; si; si = si->next)
2055
0
    sctp_listeners += (si->workers > 0) ? si->workers : sctp_children_no;
2056
0
#endif
2057
0
  return
2058
      /* receivers and attendant */
2059
0
      (dont_fork ? 1 : udp_listeners + 1)
2060
      /* timer process */
2061
0
      + 1 /* always, we need it in most cases, and we can't tell here
2062
           & now if we don't need it */
2063
0
#ifdef USE_SLOW_TIMER
2064
0
      + 1 /* slow timer process */
2065
0
#endif
2066
0
#ifdef USE_TCP
2067
0
      + ((!tcp_disable) ? (1 /* tcp main */ + tcp_listeners) : 0)
2068
0
#endif
2069
0
#ifdef USE_SCTP
2070
0
      + ((!sctp_disable) ? sctp_listeners : 0)
2071
0
#endif
2072
0
          ;
2073
0
}
2074
2075
int main2(int argc, char **argv)
2076
0
{
2077
2078
0
  FILE *cfg_stream;
2079
0
  int c, r;
2080
0
  char *tmp;
2081
0
  int tmp_len;
2082
0
  int port;
2083
0
  int proto;
2084
0
  int aproto;
2085
0
  char *ahost = NULL;
2086
0
  int aport = 0;
2087
0
  char *options;
2088
0
  int ret;
2089
0
  unsigned int seed;
2090
0
  int rfd;
2091
0
  int debug_save, debug_flag;
2092
0
  int dont_fork_cnt;
2093
0
  struct name_lst *n_lst;
2094
0
  char *p;
2095
0
  struct stat st = {0};
2096
2097
0
#define KSR_TBUF_SIZE 512
2098
0
  char tbuf[KSR_TBUF_SIZE];
2099
2100
0
  int option_index = 0;
2101
2102
0
#define KARGOPTVAL 1024
2103
0
  static struct option long_options[] = {/* long options with short variant */
2104
0
      {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'},
2105
      /* long options without short variant */
2106
0
      {"alias", required_argument, 0, KARGOPTVAL},
2107
0
      {"subst", required_argument, 0, KARGOPTVAL + 1},
2108
0
      {"substdef", required_argument, 0, KARGOPTVAL + 2},
2109
0
      {"substdefs", required_argument, 0, KARGOPTVAL + 3},
2110
0
      {"server-id", required_argument, 0, KARGOPTVAL + 4},
2111
0
      {"loadmodule", required_argument, 0, KARGOPTVAL + 5},
2112
0
      {"modparam", required_argument, 0, KARGOPTVAL + 6},
2113
0
      {"log-engine", required_argument, 0, KARGOPTVAL + 7},
2114
0
      {"debug", required_argument, 0, KARGOPTVAL + 8},
2115
0
      {"cfg-print", no_argument, 0, KARGOPTVAL + 9},
2116
0
      {"atexit", required_argument, 0, KARGOPTVAL + 10},
2117
0
      {"all-errors", no_argument, 0, KARGOPTVAL + 11}, {0, 0, 0, 0}};
2118
2119
0
  if(argc > 1) {
2120
    /* checks for common wrong arguments */
2121
0
    if(strcasecmp(argv[1], "start") == 0) {
2122
0
      fprintf(stderr, "error: 'start' is not a supported argument\n");
2123
0
      fprintf(stderr, "error: stopping " NAME " ...\n\n");
2124
0
      exit(-1);
2125
0
    }
2126
0
    if(strcasecmp(argv[1], "stop") == 0) {
2127
0
      fprintf(stderr, "error: 'stop' is not a supported argument\n");
2128
0
      fprintf(stderr, "error: stopping " NAME " ...\n\n");
2129
0
      exit(-1);
2130
0
    }
2131
0
    if(strcasecmp(argv[1], "restart") == 0) {
2132
0
      fprintf(stderr, "error: 'restart' is not a supported argument\n");
2133
0
      fprintf(stderr, "error: stopping " NAME " ...\n\n");
2134
0
      exit(-1);
2135
0
    }
2136
0
  }
2137
2138
  /*init*/
2139
0
  time(&up_since);
2140
0
  creator_pid = getpid();
2141
0
  ret = -1;
2142
0
  my_argc = argc;
2143
0
  my_argv = argv;
2144
0
  debug_flag = 0;
2145
0
  dont_fork_cnt = 0;
2146
2147
0
  ksr_hname_init_index();
2148
0
  sr_cfgenv_init();
2149
0
  daemon_status_init();
2150
2151
0
  log_init();
2152
2153
  /* command line options */
2154
0
  options = ":f:cm:M:dVIhEeb:B:l:L:n:vKrRDTN:W:w:t:u:g:P:G:SQ:O:a:A:x:X:Y:";
2155
  /* Handle special command line arguments, that must be treated before
2156
   * initializing the various subsystem or before parsing other arguments:
2157
   *  - get the startup debug and log_stderr values
2158
   *  - look if pkg mem size is overridden on the command line (-M) and get
2159
   *    the new value here (before initializing pkg_mem).
2160
   *  - look if there is a -h, e.g. -f -h construction won't be caught
2161
   *    later
2162
   */
2163
0
  opterr = 0;
2164
0
  option_index = 0;
2165
0
  while((c = getopt_long(argc, argv, options, long_options, &option_index))
2166
0
      != -1) {
2167
0
    switch(c) {
2168
0
      case 'd':
2169
0
        debug_flag = 1;
2170
0
        default_core_cfg.debug++;
2171
0
        break;
2172
0
      case 'E':
2173
0
        log_stderr = 1;
2174
0
        break;
2175
0
      case 'e':
2176
0
        log_color = 1;
2177
0
        break;
2178
0
      case 'M':
2179
0
        if(optarg == NULL) {
2180
0
          fprintf(stderr, "bad private mem size\n");
2181
0
          goto error;
2182
0
        }
2183
0
        pkg_mem_size = strtol(optarg, &tmp, 10) * 1024 * 1024;
2184
0
        if(tmp && (*tmp)) {
2185
0
          fprintf(stderr, "bad private mem size number: -M %s\n",
2186
0
              optarg);
2187
0
          goto error;
2188
0
        };
2189
0
        break;
2190
0
      case 'x':
2191
0
        sr_memmng_shm = optarg;
2192
0
        break;
2193
0
      case 'X':
2194
0
        sr_memmng_pkg = optarg;
2195
0
        break;
2196
0
      case KARGOPTVAL + 7:
2197
0
        ksr_slog_init(optarg);
2198
0
        break;
2199
0
      case KARGOPTVAL + 8:
2200
0
        if(optarg == NULL) {
2201
0
          fprintf(stderr, "bad debug level value\n");
2202
0
          goto error;
2203
0
        }
2204
0
        debug_flag = 1;
2205
0
        default_core_cfg.debug = (int)strtol(optarg, &tmp, 10);
2206
0
        if((tmp == 0) || (*tmp)) {
2207
0
          LM_ERR("bad debug level value: %s\n", optarg);
2208
0
          goto error;
2209
0
        }
2210
0
        break;
2211
0
      case KARGOPTVAL + 9:
2212
0
        ksr_cfg_print_mode = 1;
2213
0
        break;
2214
0
      case KARGOPTVAL + 10:
2215
0
        if(optarg == NULL) {
2216
0
          fprintf(stderr, "bad atexit value\n");
2217
0
          goto error;
2218
0
        }
2219
0
        if(optarg[0] == 'y' || optarg[0] == '1') {
2220
0
          ksr_atexit_mode = 1;
2221
0
        } else if(optarg[0] == 'n' || optarg[0] == '0') {
2222
0
          ksr_atexit_mode = 0;
2223
0
        } else {
2224
0
          LM_ERR("bad atexit value: %s\n", optarg);
2225
0
          goto error;
2226
0
        }
2227
0
        break;
2228
0
      case KARGOPTVAL + 11:
2229
0
        ksr_all_errors = 1;
2230
0
        break;
2231
2232
0
      default:
2233
0
        if(c == 'h' || (optarg && strcmp(optarg, "-h") == 0)) {
2234
0
          printf("version: %s\n", full_version);
2235
0
          printf("%s", help_msg);
2236
0
          exit(0);
2237
0
        }
2238
0
        break;
2239
0
    }
2240
0
  }
2241
2242
0
  if(sr_memmng_pkg == NULL) {
2243
0
    if(sr_memmng_shm != NULL) {
2244
0
      sr_memmng_pkg = sr_memmng_shm;
2245
0
    } else {
2246
0
      sr_memmng_pkg = SR_MEMMNG_DEFAULT;
2247
0
    }
2248
0
  }
2249
0
  if(sr_memmng_shm == NULL) {
2250
0
    sr_memmng_shm = SR_MEMMNG_DEFAULT;
2251
0
  }
2252
0
  shm_set_mname(sr_memmng_shm);
2253
0
  if(pkg_mem_size == 0) {
2254
0
    pkg_mem_size = PKG_MEM_POOL_SIZE;
2255
0
  }
2256
2257
  /*init pkg mallocs (before parsing cfg or the rest of the cmd line !)*/
2258
0
  if(pkg_mem_size)
2259
0
    LM_INFO("private (per process) memory: %ld bytes\n", pkg_mem_size);
2260
0
  if(pkg_init_manager(sr_memmng_pkg) < 0)
2261
0
    goto error;
2262
2263
#ifdef DBG_MSG_QA
2264
  fprintf(stderr, "WARNING: ser startup: "
2265
          "DBG_MSG_QA enabled, ser may exit abruptly\n");
2266
#endif
2267
2268
  /* init counters / stats */
2269
0
  if(init_counters() == -1)
2270
0
    goto error;
2271
0
#ifdef USE_TCP
2272
0
  init_tcp_options(); /* set the defaults before the config */
2273
0
#endif
2274
2275
0
  if(pv_init_buffer() < 0) {
2276
0
    goto error;
2277
0
  }
2278
2279
0
  pp_define_core();
2280
2281
  /* process command line (cfg. file path etc) */
2282
0
  optind = 1; /* reset getopt index */
2283
0
  option_index = 0;
2284
  /* switches required before script processing */
2285
0
  while((c = getopt_long(argc, argv, options, long_options, &option_index))
2286
0
      != -1) {
2287
0
    switch(c) {
2288
0
      case 'M':
2289
0
      case 'x':
2290
0
      case 'X':
2291
        /* ignore, they were parsed immediately after startup */
2292
0
        break;
2293
0
      case 'f':
2294
0
        if(optarg == NULL) {
2295
0
          fprintf(stderr, "bad -f parameter\n");
2296
0
          goto error;
2297
0
        }
2298
0
        cfg_file = optarg;
2299
0
        break;
2300
0
      case 'c':
2301
0
        config_check = 1;
2302
0
        log_stderr = 1; /* force stderr logging */
2303
0
        break;
2304
0
      case 'L':
2305
0
        if(optarg == NULL) {
2306
0
          fprintf(stderr, "bad -L parameter\n");
2307
0
          goto error;
2308
0
        }
2309
0
        mods_dir = optarg;
2310
0
        mods_dir_cmd = 1;
2311
0
        break;
2312
0
      case 'm':
2313
0
        if(optarg == NULL) {
2314
0
          fprintf(stderr, "bad shared mem size\n");
2315
0
          goto error;
2316
0
        }
2317
0
        shm_mem_size = strtol(optarg, &tmp, 10) * 1024 * 1024;
2318
0
        if(tmp && (*tmp)) {
2319
0
          fprintf(stderr, "bad shmem size number: -m %s\n", optarg);
2320
0
          goto error;
2321
0
        };
2322
0
        LM_INFO("shared memory: %ld bytes\n", shm_mem_size);
2323
0
        break;
2324
0
      case 'd':
2325
        /* ignore it, was parsed immediately after startup */
2326
0
        break;
2327
0
      case 'v':
2328
0
      case 'V':
2329
0
        printf("version: %s\n", full_version);
2330
0
        printf("flags: %s\n", ver_flags);
2331
0
        print_ct_constants();
2332
0
        printf("id: %s\n", ver_id);
2333
0
        if(strlen(ver_compiled_time) > 0)
2334
0
          printf("compiled on %s with %s\n", ver_compiled_time,
2335
0
              ver_compiler);
2336
0
        else
2337
0
          printf("compiled with %s\n", ver_compiler);
2338
2339
0
        exit(0);
2340
0
        break;
2341
0
      case 'I':
2342
0
        print_internals();
2343
0
        exit(0);
2344
0
        break;
2345
0
      case 'E':
2346
        /* ignore it, was parsed immediately after startup */
2347
0
        break;
2348
0
      case 'e':
2349
        /* ignore it, was parsed immediately after startup */
2350
0
        break;
2351
0
      case 'O':
2352
0
        if(optarg == NULL) {
2353
0
          fprintf(stderr, "bad -O parameter\n");
2354
0
          goto error;
2355
0
        }
2356
0
        scr_opt_lev = strtol(optarg, &tmp, 10);
2357
0
        if(tmp && (*tmp)) {
2358
0
          fprintf(stderr, "bad optimization level: -O %s\n", optarg);
2359
0
          goto error;
2360
0
        };
2361
0
        break;
2362
0
      case 'u':
2363
0
        if(optarg == NULL) {
2364
0
          fprintf(stderr, "bad -u parameter\n");
2365
0
          goto error;
2366
0
        }
2367
        /* user needed for possible shm. pre-init */
2368
0
        user = optarg;
2369
0
        break;
2370
0
      case 'A':
2371
0
        if(optarg == NULL) {
2372
0
          fprintf(stderr, "bad -A parameter\n");
2373
0
          goto error;
2374
0
        }
2375
0
        p = strchr(optarg, '=');
2376
0
        if(p) {
2377
0
          tmp_len = p - optarg;
2378
0
        } else {
2379
0
          tmp_len = strlen(optarg);
2380
0
        }
2381
0
        pp_define_set_type(KSR_PPDEF_DEFINE);
2382
0
        if(pp_define(tmp_len, optarg) < 0) {
2383
0
          fprintf(stderr, "error at define param: -A %s\n", optarg);
2384
0
          goto error;
2385
0
        }
2386
0
        if(p) {
2387
0
          p++;
2388
0
          if(pp_define_set(strlen(p), p, KSR_PPDEF_NORMAL) < 0) {
2389
0
            fprintf(stderr, "error at define value: -A %s\n",
2390
0
                optarg);
2391
0
            goto error;
2392
0
          }
2393
0
        }
2394
0
        break;
2395
0
      case 'b':
2396
0
      case 'B':
2397
0
      case 'l':
2398
0
      case 'n':
2399
0
      case 'K':
2400
0
      case 'r':
2401
0
      case 'R':
2402
0
      case 'D':
2403
0
      case 'T':
2404
0
      case 'N':
2405
0
      case 'W':
2406
0
      case 'w':
2407
0
      case 't':
2408
0
      case 'g':
2409
0
      case 'P':
2410
0
      case 'G':
2411
0
      case 'S':
2412
0
      case 'Q':
2413
0
      case 'a':
2414
0
      case 's':
2415
0
      case 'Y':
2416
0
      case KARGOPTVAL + 5:
2417
0
      case KARGOPTVAL + 6:
2418
0
      case KARGOPTVAL + 7:
2419
0
      case KARGOPTVAL + 8:
2420
0
      case KARGOPTVAL + 9:
2421
0
      case KARGOPTVAL + 10:
2422
0
      case KARGOPTVAL + 11:
2423
0
        break;
2424
2425
      /* long options */
2426
0
      case KARGOPTVAL:
2427
0
        if(optarg == NULL) {
2428
0
          fprintf(stderr, "bad alias parameter\n");
2429
0
          goto error;
2430
0
        }
2431
0
        if(parse_phostport(optarg, &tmp, &tmp_len, &port, &proto)
2432
0
            != 0) {
2433
0
          fprintf(stderr, "Invalid alias value '%s'\n", optarg);
2434
0
          goto error;
2435
0
        }
2436
0
        if(add_alias(tmp, tmp_len, port, proto) < 0) {
2437
0
          fprintf(stderr, "Failed to add alias value '%s'\n", optarg);
2438
0
          goto error;
2439
0
        }
2440
0
        break;
2441
0
      case KARGOPTVAL + 1:
2442
0
        if(optarg == NULL) {
2443
0
          fprintf(stderr, "bad subst parameter\n");
2444
0
          goto error;
2445
0
        }
2446
0
        if(pp_subst_add(optarg) < 0) {
2447
0
          LM_ERR("failed to add subst expression: %s\n", optarg);
2448
0
          goto error;
2449
0
        }
2450
0
        break;
2451
0
      case KARGOPTVAL + 2:
2452
0
        if(optarg == NULL) {
2453
0
          fprintf(stderr, "bad substdef parameter\n");
2454
0
          goto error;
2455
0
        }
2456
0
        if(pp_substdef_add(optarg, KSR_PPDEF_NORMAL) < 0) {
2457
0
          LM_ERR("failed to add substdef expression: %s\n", optarg);
2458
0
          goto error;
2459
0
        }
2460
0
        break;
2461
0
      case KARGOPTVAL + 3:
2462
0
        if(optarg == NULL) {
2463
0
          fprintf(stderr, "bad substdefs parameter\n");
2464
0
          goto error;
2465
0
        }
2466
0
        if(pp_substdef_add(optarg, KSR_PPDEF_QUOTED) < 0) {
2467
0
          LM_ERR("failed to add substdefs expression: %s\n", optarg);
2468
0
          goto error;
2469
0
        }
2470
0
        break;
2471
0
      case KARGOPTVAL + 4:
2472
0
        if(optarg == NULL) {
2473
0
          fprintf(stderr, "bad server if parameter\n");
2474
0
          goto error;
2475
0
        }
2476
0
        server_id = (int)strtol(optarg, &tmp, 10);
2477
0
        if((tmp == 0) || (*tmp)) {
2478
0
          LM_ERR("bad server_id value: %s\n", optarg);
2479
0
          goto error;
2480
0
        }
2481
0
        break;
2482
2483
      /* special cases */
2484
0
      case '?':
2485
0
        if(isprint(optopt)) {
2486
0
          fprintf(stderr,
2487
0
              "Unknown option '-%c'."
2488
0
              " Use -h for help.\n",
2489
0
              optopt);
2490
0
        } else {
2491
0
          fprintf(stderr,
2492
0
              "Unknown option code '0x%x' (%d)."
2493
0
              " Use -h for help.\n",
2494
0
              optopt, option_index);
2495
0
        }
2496
0
        goto error;
2497
0
      case ':':
2498
0
        if(isprint(optopt)) {
2499
0
          fprintf(stderr,
2500
0
              "Option '-%c' requires an argument."
2501
0
              " Use -h for help.\n",
2502
0
              optopt);
2503
0
        } else {
2504
0
          fprintf(stderr,
2505
0
              "Option code '0x%x' (%d) requires an argument."
2506
0
              " Use -h for help.\n",
2507
0
              optopt, option_index);
2508
0
        }
2509
0
        goto error;
2510
2511
0
      default:
2512
0
        fprintf(stderr, "Invalid option code '0x%x'", c);
2513
0
        return -1;
2514
0
    }
2515
0
  }
2516
0
  if(shm_mem_size == 0) {
2517
0
    shm_mem_size = SHM_MEM_POOL_SIZE;
2518
0
  }
2519
2520
0
  if(endianness_sanity_check() != 0) {
2521
0
    fprintf(stderr, "BUG: endianness sanity tests failed\n");
2522
0
    goto error;
2523
0
  }
2524
0
  if(init_routes() < 0)
2525
0
    goto error;
2526
0
  if(init_nonsip_hooks() < 0)
2527
0
    goto error;
2528
0
  if(init_script_cb() < 0)
2529
0
    goto error;
2530
0
  if(pv_init_api() < 0)
2531
0
    goto error;
2532
0
  if(pv_register_core_vars() != 0)
2533
0
    goto error;
2534
0
  if(init_rpcs() < 0)
2535
0
    goto error;
2536
2537
  /* Fix the value of cfg_file variable.*/
2538
0
  if(fix_cfg_file() < 0)
2539
0
    goto error;
2540
2541
  /* process command line parameters that require initialized basic environment */
2542
0
  optind = 1; /* reset getopt index */
2543
0
  option_index = 0;
2544
  /* switches required before config parsing and processing */
2545
0
  while((c = getopt_long(argc, argv, options, long_options, &option_index))
2546
0
      != -1) {
2547
0
    switch(c) {
2548
0
      case KARGOPTVAL + 5:
2549
0
        if(optarg == NULL) {
2550
0
          fprintf(stderr, "bad load module parameter\n");
2551
0
          goto error;
2552
0
        }
2553
0
        if(ksr_load_module(optarg, NULL) != 0) {
2554
0
          LM_ERR("failed to load the module: %s\n", optarg);
2555
0
          goto error;
2556
0
        }
2557
0
        break;
2558
0
      case KARGOPTVAL + 6:
2559
0
        if(optarg == NULL) {
2560
0
          fprintf(stderr, "bad modparam parameter\n");
2561
0
          goto error;
2562
0
        }
2563
0
        if(set_mod_param_serialized(optarg) < 0) {
2564
0
          LM_ERR("failed to set modparam: %s\n", optarg);
2565
0
          goto error;
2566
0
        }
2567
0
        break;
2568
0
      default:
2569
0
        break;
2570
0
    }
2571
0
  }
2572
2573
  /* load config file or die */
2574
0
  if(cfg_file[0] == '-' && strlen(cfg_file) == 1) {
2575
0
    cfg_stream = stdin;
2576
0
  } else {
2577
0
    cfg_stream = fopen(cfg_file, "r");
2578
0
  }
2579
0
  if(cfg_stream == 0) {
2580
0
    fprintf(stderr,
2581
0
        "ERROR: loading config file(%s): %s,"
2582
0
        " check file and directory permissions\n",
2583
0
        cfg_file, strerror(errno));
2584
0
    goto error;
2585
0
  }
2586
2587
  /* seed the prng */
2588
  /* try to use /dev/urandom if possible */
2589
0
  seed = 0;
2590
0
  if((rfd = open("/dev/urandom", O_RDONLY)) != -1) {
2591
0
  try_again:
2592
0
    if(read(rfd, (void *)&seed, sizeof(seed)) == -1) {
2593
0
      if(errno == EINTR)
2594
0
        goto try_again; /* interrupted by signal */
2595
0
      LM_WARN("could not read from /dev/urandom (%d)\n", errno);
2596
0
    }
2597
0
    LM_DBG("read %u from /dev/urandom\n", seed);
2598
0
    close(rfd);
2599
0
  } else {
2600
0
    LM_WARN("could not open /dev/urandom (%d)\n", errno);
2601
0
  }
2602
0
  seed += getpid() + time(0);
2603
0
  LM_DBG("seeding PRNG with %u\n", seed);
2604
0
  cryptorand_seed(seed);
2605
0
  fastrand_seed(cryptorand());
2606
0
  kam_srand(cryptorand());
2607
0
  srandom(cryptorand());
2608
0
  LM_DBG("test random numbers %u %lu %u %u\n", kam_rand(), random(),
2609
0
      fastrand(), cryptorand());
2610
2611
  /*register builtin  modules*/
2612
0
  register_builtin_modules();
2613
2614
  /* init named flags */
2615
0
  init_named_flags();
2616
2617
0
  yyin = cfg_stream;
2618
0
  debug_save = default_core_cfg.debug;
2619
0
  ksr_cfg_print_initial_state();
2620
0
  r = yyparse();
2621
0
  if(ksr_cfg_print_mode == 1) {
2622
    /* printed evaluated content of config file based on include and ifdef */
2623
0
    return 0;
2624
0
  }
2625
0
  if((r != 0) || (cfg_errors) || (pp_ifdef_level_check() < 0)) {
2626
0
    fprintf(stderr,
2627
0
        "ERROR: bad config file (%d errors) (parsing code: %d)\n",
2628
0
        cfg_errors, r);
2629
0
    if(debug_flag)
2630
0
      default_core_cfg.debug = debug_save;
2631
0
    pp_ifdef_level_error();
2632
2633
0
    goto error;
2634
0
  }
2635
2636
0
  if(cfg_warnings) {
2637
0
    fprintf(stderr, "%d config warnings\n", cfg_warnings);
2638
0
  }
2639
0
  if(debug_flag)
2640
0
    default_core_cfg.debug = debug_save;
2641
0
  print_rls();
2642
2643
0
  if(init_dst_set() < 0) {
2644
0
    LM_ERR("failed to initialize destination set structure\n");
2645
0
    goto error;
2646
0
  }
2647
  /* options with higher priority than cfg file */
2648
0
  optind = 1; /* reset getopt index */
2649
0
  option_index = 0;
2650
0
  while((c = getopt_long(argc, argv, options, long_options, &option_index))
2651
0
      != -1) {
2652
0
    switch(c) {
2653
0
      case 'f':
2654
0
      case 'c':
2655
0
      case 'm':
2656
0
      case 'M':
2657
0
      case 'd':
2658
0
      case 'v':
2659
0
      case 'V':
2660
0
      case 'I':
2661
0
      case 'h':
2662
0
      case 'O':
2663
0
      case 'A':
2664
0
        break;
2665
0
      case 'E':
2666
0
        log_stderr = 1; /* use in both getopt switches,
2667
                     takes priority over config */
2668
0
        break;
2669
0
      case 'e':
2670
0
        log_color = 1; /* use in both getopt switches,
2671
                     takes priority over config */
2672
0
        break;
2673
0
      case 'b':
2674
0
        if(optarg == NULL) {
2675
0
          fprintf(stderr, "bad -b parameter\n");
2676
0
          goto error;
2677
0
        }
2678
0
        maxbuffer = strtol(optarg, &tmp, 10);
2679
0
        if(tmp && (*tmp)) {
2680
0
          fprintf(stderr, "bad max buffer size number: -b %s\n",
2681
0
              optarg);
2682
0
          goto error;
2683
0
        }
2684
0
        break;
2685
0
      case 'B':
2686
0
        if(optarg == NULL) {
2687
0
          fprintf(stderr, "bad -B parameter\n");
2688
0
          goto error;
2689
0
        }
2690
0
        maxsndbuffer = strtol(optarg, &tmp, 10);
2691
0
        if(tmp && (*tmp)) {
2692
0
          fprintf(stderr, "bad max buffer size number: -B %s\n",
2693
0
              optarg);
2694
0
          goto error;
2695
0
        }
2696
0
        break;
2697
0
      case 'T':
2698
0
#ifdef USE_TCP
2699
0
        tcp_disable = 1;
2700
#else
2701
        fprintf(stderr, "WARNING: tcp support not compiled in\n");
2702
#endif
2703
0
        break;
2704
0
      case 'S':
2705
0
#ifdef USE_SCTP
2706
0
        sctp_disable = 1;
2707
#else
2708
        fprintf(stderr, "WARNING: sctp support not compiled in\n");
2709
#endif
2710
0
        break;
2711
0
      case 'l':
2712
0
        if(optarg == NULL) {
2713
0
          fprintf(stderr, "bad -l parameter\n");
2714
0
          goto error;
2715
0
        }
2716
0
        p = strrchr(optarg, '/');
2717
0
        if(p == NULL) {
2718
0
          p = optarg;
2719
0
        } else {
2720
0
          if(strlen(optarg) >= KSR_TBUF_SIZE - 1) {
2721
0
            fprintf(stderr, "listen value too long: %s\n", optarg);
2722
0
            goto error;
2723
0
          }
2724
0
          strcpy(tbuf, optarg);
2725
0
          p = strrchr(tbuf, '/');
2726
0
          if(p == NULL) {
2727
0
            fprintf(stderr, "unexpected bug for listen: %s\n",
2728
0
                optarg);
2729
0
            goto error;
2730
0
          }
2731
0
          *p = '\0';
2732
0
          p++;
2733
0
          tmp_len = 0;
2734
0
          if(parse_phostport(p, &ahost, &tmp_len, &aport, &aproto)
2735
0
              < 0) {
2736
0
            fprintf(stderr,
2737
0
                "listen value with invalid advertise: %s\n",
2738
0
                optarg);
2739
0
            goto error;
2740
0
          }
2741
0
          if(ahost) {
2742
0
            ahost[tmp_len] = '\0';
2743
0
          }
2744
0
          p = tbuf;
2745
0
        }
2746
0
        if((n_lst = parse_phostport_mh(
2747
0
              p, &tmp, &tmp_len, &port, &proto))
2748
0
            == 0) {
2749
0
          fprintf(stderr,
2750
0
              "bad -l address specifier: %s\n"
2751
0
              "Check disabled protocols\n",
2752
0
              optarg);
2753
0
          goto error;
2754
0
        }
2755
        /* add a new addr. to our address list */
2756
0
        if(add_listen_advertise_iface(n_lst->name, n_lst->next, port,
2757
0
               proto, aproto, ahost, aport, n_lst->flags)
2758
0
            != 0) {
2759
0
          fprintf(stderr, "failed to add new listen address: %s\n",
2760
0
              optarg);
2761
0
          free_name_lst(n_lst);
2762
0
          goto error;
2763
0
        }
2764
0
        free_name_lst(n_lst);
2765
0
        break;
2766
0
      case 'n':
2767
0
        if(optarg == NULL) {
2768
0
          fprintf(stderr, "bad -n parameter\n");
2769
0
          goto error;
2770
0
        }
2771
0
        children_no = strtol(optarg, &tmp, 10);
2772
0
        if((tmp == 0) || (*tmp)) {
2773
0
          fprintf(stderr, "bad process number: -n %s\n", optarg);
2774
0
          goto error;
2775
0
        }
2776
0
        break;
2777
0
      case 'K':
2778
0
        check_via = 1;
2779
0
        break;
2780
0
      case 'r':
2781
0
        received_dns |= DO_DNS;
2782
0
        break;
2783
0
      case 'R':
2784
0
        received_dns |= DO_REV_DNS;
2785
0
        break;
2786
0
      case 'D':
2787
0
        dont_fork_cnt++;
2788
0
        break;
2789
0
      case 'N':
2790
0
#ifdef USE_TCP
2791
0
        if(tcp_disable) {
2792
0
          fprintf(stderr,
2793
0
              "could not configure TCP children: -N %s\n"
2794
0
              "TCP support disabled\n",
2795
0
              optarg);
2796
0
          goto error;
2797
0
        }
2798
0
        if(optarg == NULL) {
2799
0
          fprintf(stderr, "bad -N parameter\n");
2800
0
          goto error;
2801
0
        }
2802
0
        tcp_cfg_children_no = strtol(optarg, &tmp, 10);
2803
0
        if((tmp == 0) || (*tmp)) {
2804
0
          fprintf(stderr, "bad process number: -N %s\n", optarg);
2805
0
          goto error;
2806
0
        }
2807
#else
2808
        fprintf(stderr, "WARNING: tcp support not compiled in\n");
2809
#endif
2810
0
        break;
2811
0
      case 'W':
2812
0
#ifdef USE_TCP
2813
0
        if(optarg == NULL) {
2814
0
          fprintf(stderr, "bad -W parameter\n");
2815
0
          goto error;
2816
0
        }
2817
0
        tcp_poll_method = get_poll_type(optarg);
2818
0
        if(tcp_poll_method == POLL_NONE) {
2819
0
          fprintf(stderr,
2820
0
              "bad poll method name: -W %s\ntry "
2821
0
              "one of %s.\n",
2822
0
              optarg, poll_support);
2823
0
          goto error;
2824
0
        }
2825
#else
2826
        fprintf(stderr, "WARNING: tcp support not compiled in\n");
2827
#endif
2828
0
        break;
2829
0
      case 'Q':
2830
0
#ifdef USE_SCTP
2831
0
        if(sctp_disable) {
2832
0
          fprintf(stderr,
2833
0
              "could not configure SCTP children: -Q %s\n"
2834
0
              "SCTP support disabled\n",
2835
0
              optarg);
2836
0
          goto error;
2837
0
        }
2838
0
        if(optarg == NULL) {
2839
0
          fprintf(stderr, "bad -Q parameter\n");
2840
0
          goto error;
2841
0
        }
2842
0
        sctp_children_no = strtol(optarg, &tmp, 10);
2843
0
        if((tmp == 0) || (*tmp)) {
2844
0
          fprintf(stderr, "bad process number: -O %s\n", optarg);
2845
0
          goto error;
2846
0
        }
2847
#else
2848
        fprintf(stderr, "WARNING: sctp support not compiled in\n");
2849
#endif
2850
0
        break;
2851
0
      case 'w':
2852
0
        working_dir = optarg;
2853
0
        break;
2854
0
      case 'Y':
2855
0
        runtime_dir = optarg;
2856
0
        break;
2857
0
      case 't':
2858
0
        chroot_dir = optarg;
2859
0
        break;
2860
0
      case 'u':
2861
0
        user = optarg;
2862
0
        break;
2863
0
      case 'g':
2864
0
        group = optarg;
2865
0
        break;
2866
0
      case 'P':
2867
0
        pid_file = optarg;
2868
0
        break;
2869
0
      case 'G':
2870
0
        pgid_file = optarg;
2871
0
        break;
2872
0
      case 'a':
2873
0
        if(strcmp(optarg, "on") == 0 || strcmp(optarg, "yes") == 0)
2874
0
          sr_auto_aliases = 1;
2875
0
        else if(strcmp(optarg, "off") == 0 || strcmp(optarg, "no") == 0)
2876
0
          sr_auto_aliases = 0;
2877
0
        else {
2878
0
          fprintf(stderr,
2879
0
              "bad auto aliases parameter: %s (valid on, off, "
2880
0
              "yes, no)\n",
2881
0
              optarg);
2882
0
          goto error;
2883
0
        }
2884
0
        break;
2885
0
      default:
2886
0
        break;
2887
0
    }
2888
0
  }
2889
2890
  /* reinit if pv buffer size has been set in config */
2891
0
  if(pv_reinit_buffer() < 0)
2892
0
    goto error;
2893
2894
0
  if(register_core_rpcs() != 0)
2895
0
    goto error;
2896
2897
0
  if(ksr_route_locks_set_init() < 0)
2898
0
    goto error;
2899
2900
0
  ksr_shutdown_phase_init();
2901
2902
  /* init lookup for core event routes */
2903
0
  sr_core_ert_init();
2904
2905
0
  ksr_hname_init_config();
2906
2907
0
  if(dont_fork_cnt)
2908
0
    dont_fork = dont_fork_cnt; /* override by command line */
2909
2910
0
  if(dont_fork > 0) {
2911
0
    dont_daemonize = dont_fork == 2;
2912
0
    dont_fork = dont_fork == 1;
2913
0
  }
2914
  /* init locks first */
2915
0
  if(init_lock_ops() != 0)
2916
0
    goto error;
2917
0
#ifdef USE_TCP
2918
0
#ifdef USE_TLS
2919
0
  if(tcp_disable)
2920
0
    tls_disable = 1; /* if no tcp => no tls */
2921
0
#endif           /* USE_TLS */
2922
0
#endif           /* USE_TCP */
2923
0
#ifdef USE_SCTP
2924
0
  if(sctp_disable != 1) {
2925
    /* fix it */
2926
0
    if(sctp_core_check_support() == -1) {
2927
      /* check if sctp support is auto, if not warn about disabling it */
2928
0
      if(sctp_disable != 2) {
2929
0
        fprintf(stderr, "ERROR: "
2930
0
                "sctp enabled, but not supported by"
2931
0
                " the OS\n");
2932
0
        goto error;
2933
0
      }
2934
0
      sctp_disable = 1;
2935
0
    } else {
2936
      /* sctp_disable!=1 and sctp supported => enable sctp */
2937
0
      sctp_disable = 0;
2938
0
    }
2939
0
  }
2940
0
#endif /* USE_SCTP */
2941
  /* initialize the configured proto list */
2942
0
  init_proto_order();
2943
  /* init the resolver, before fixing the config */
2944
0
  resolv_init();
2945
  /* fix parameters */
2946
0
  if(port_no <= 0)
2947
0
    port_no = SIP_PORT;
2948
0
#ifdef USE_TLS
2949
0
  if(tls_port_no <= 0)
2950
0
    tls_port_no = SIPS_PORT;
2951
0
#endif
2952
2953
2954
0
  if(children_no <= 0)
2955
0
    children_no = CHILD_NO;
2956
0
#ifdef USE_TCP
2957
0
  if(!tcp_disable) {
2958
0
    if(tcp_cfg_children_no <= 0)
2959
0
      tcp_cfg_children_no = children_no;
2960
0
    tcp_children_no = tcp_cfg_children_no;
2961
0
  }
2962
0
#endif
2963
0
#ifdef USE_SCTP
2964
0
  if(!sctp_disable) {
2965
0
    if(sctp_children_no <= 0)
2966
0
      sctp_children_no = children_no;
2967
0
  }
2968
0
#endif
2969
2970
0
  if(working_dir == 0)
2971
0
    working_dir = "/";
2972
2973
  /* get uid/gid */
2974
0
  if(user) {
2975
0
    if(user2uid(&uid, &gid, user) < 0) {
2976
0
      fprintf(stderr, "bad user name/uid number: -u %s\n", user);
2977
0
      goto error;
2978
0
    }
2979
0
    sock_uid = uid;
2980
0
    sock_gid = gid;
2981
0
  }
2982
0
  if(group) {
2983
0
    if(group2gid(&gid, group) < 0) {
2984
0
      fprintf(stderr, "bad group name/gid number: -u %s\n", group);
2985
0
      goto error;
2986
0
    }
2987
0
    sock_gid = gid;
2988
0
  }
2989
  /* create runtime dir if doesn't exist */
2990
0
  if(stat(runtime_dir, &st) == -1) {
2991
0
    if(mkdir(runtime_dir, 0700) == -1) {
2992
0
      LM_ERR("failed to create runtime dir %s, check directory "
2993
0
           "permissions\n",
2994
0
          runtime_dir);
2995
0
      fprintf(stderr,
2996
0
          "failed to create runtime dir %s, check directory "
2997
0
          "permissions\n",
2998
0
          runtime_dir);
2999
0
      goto error;
3000
0
    }
3001
0
    if(sock_uid != -1 || sock_gid != -1) {
3002
0
      if(chown(runtime_dir, sock_uid, sock_gid) == -1) {
3003
0
        LM_ERR("failed to change owner of runtime dir %s\n",
3004
0
            runtime_dir);
3005
0
        fprintf(stderr, "failed to change owner of runtime dir %s\n",
3006
0
            runtime_dir);
3007
0
        goto error;
3008
0
      }
3009
0
    }
3010
0
  }
3011
0
  if(fix_all_socket_lists() != 0) {
3012
0
    fprintf(stderr, "failed to initialize list addresses\n");
3013
0
    goto error;
3014
0
  }
3015
0
  ksr_sockets_index();
3016
0
  if(default_core_cfg.dns_try_ipv6 && !(socket_types & SOCKET_T_IPV6)) {
3017
    /* if we are not listening on any ipv6 address => no point
3018
     * to try to resolve ipv6 addresses */
3019
0
    default_core_cfg.dns_try_ipv6 = 0;
3020
0
  }
3021
  /* print all the listen addresses */
3022
0
  printf("Listening on \n");
3023
0
  print_all_socket_lists();
3024
0
  printf("Aliases: \n");
3025
  /*print_aliases();*/
3026
0
  print_aliases();
3027
0
  printf("\n");
3028
3029
0
  if(dont_fork) {
3030
0
    fprintf(stderr, "WARNING: no fork mode %s\n",
3031
0
        (udp_listen) ? (
3032
0
            (udp_listen->next)
3033
0
                ? "and more than one listen address found "
3034
0
                  "(will use only the first one)"
3035
0
                : "")
3036
0
               : "and no udp listen address found");
3037
0
  }
3038
0
  if(config_check) {
3039
0
    fprintf(stderr, "config file ok, exiting...\n");
3040
0
    return 0;
3041
0
  }
3042
3043
3044
  /*init shm mallocs
3045
   *  this must be here
3046
   *     -to allow setting shm mem size from the command line
3047
   *       => if shm_mem should be settable from the cfg file move
3048
   *       everything after
3049
   *     -it must be also before init_timer and init_tcp
3050
   *     -it must be after we know uid (so that in the SYSV sems case,
3051
   *        the sems will have the correct euid)
3052
   *  Note: shm can now be initialized when parsing the config script, that's
3053
   *  why checking for a prior initialization is needed.
3054
   * --andrei */
3055
0
  if(!shm_initialized() && init_shm() < 0)
3056
0
    goto error;
3057
0
  pkg_print_manager();
3058
0
  shm_print_manager();
3059
0
  if(init_atomic_ops() == -1)
3060
0
    goto error;
3061
0
  if(init_basex() != 0) {
3062
0
    LM_CRIT("could not initialize base* framework\n");
3063
0
    goto error;
3064
0
  }
3065
0
  if(sr_cfg_init() < 0) {
3066
0
    LM_CRIT("could not initialize configuration framework\n");
3067
0
    goto error;
3068
0
  }
3069
  /* declare the core cfg before the module configs */
3070
0
  if(cfg_declare("core", core_cfg_def, &default_core_cfg, cfg_sizeof(core),
3071
0
         &core_cfg)) {
3072
0
    LM_CRIT("could not declare the core configuration\n");
3073
0
    goto error;
3074
0
  }
3075
0
#ifdef USE_TCP
3076
0
  if(tcp_register_cfg()) {
3077
0
    LM_CRIT("could not register the tcp configuration\n");
3078
0
    goto error;
3079
0
  }
3080
0
#endif /* USE_TCP */
3081
  /*init timer, before parsing the cfg!*/
3082
0
  if(init_timer() < 0) {
3083
0
    LM_CRIT("could not initialize timer, exiting...\n");
3084
0
    goto error;
3085
0
  }
3086
  /* init wtimer */
3087
0
  if(sr_wtimer_init() < 0) {
3088
0
    LM_CRIT("could not initialize wtimer, exiting...\n");
3089
0
    goto error;
3090
0
  }
3091
3092
0
#ifdef USE_DNS_CACHE
3093
0
  if(init_dns_cache() < 0) {
3094
0
    LM_CRIT("could not initialize the dns cache, exiting...\n");
3095
0
    goto error;
3096
0
  }
3097
#ifdef USE_DNS_CACHE_STATS
3098
  /* preinitializing before the nubmer of processes is determined */
3099
  if(init_dns_cache_stats(1) < 0) {
3100
    LM_CRIT("could not initialize the dns cache measurement\n");
3101
    goto error;
3102
  }
3103
#endif /* USE_DNS_CACHE_STATS */
3104
0
#endif
3105
0
#ifdef USE_DST_BLOCKLIST
3106
0
  if(init_dst_blocklist() < 0) {
3107
0
    LM_CRIT("could not initialize the dst blocklist, exiting...\n");
3108
0
    goto error;
3109
0
  }
3110
#ifdef USE_DST_BLOCKLIST_STATS
3111
  /* preinitializing before the number of processes is determined */
3112
  if(init_dst_blocklist_stats(1) < 0) {
3113
    LM_CRIT("could not initialize the dst blocklist measurement\n");
3114
    goto error;
3115
  }
3116
#endif /* USE_DST_BLOCKLIST_STATS */
3117
0
#endif
3118
0
  if(init_avps() < 0)
3119
0
    goto error;
3120
0
  if(rpc_init_time() < 0)
3121
0
    goto error;
3122
3123
0
#ifdef USE_TCP
3124
0
  if(!tcp_disable) {
3125
    /*init tcp*/
3126
0
    if(init_tcp() < 0) {
3127
0
      LM_CRIT("could not initialize tcp, exiting...\n");
3128
0
      goto error;
3129
0
    }
3130
0
  }
3131
0
#endif /* USE_TCP */
3132
0
#ifdef USE_SCTP
3133
0
  if(!sctp_disable) {
3134
0
    if(sctp_core_init() < 0) {
3135
0
      LM_CRIT("Could not initialize sctp, exiting...\n");
3136
0
      goto error;
3137
0
    }
3138
0
  }
3139
0
#endif /* USE_SCTP */
3140
  /* init_daemon? */
3141
0
  if(!dont_fork && daemonize((log_name == 0) ? argv[0] : log_name, 1) < 0)
3142
0
    goto error;
3143
0
  if(install_sigs() != 0) {
3144
0
    fprintf(stderr, "ERROR: could not install the signal handlers\n");
3145
0
    goto error;
3146
0
  }
3147
3148
0
  if(disable_core_dump)
3149
0
    set_core_dump(0, 0);
3150
0
  else
3151
0
    set_core_dump(1, shm_mem_size + pkg_mem_size + 4 * 1024 * 1024);
3152
0
  if(open_files_limit > 0) {
3153
0
    if(increase_open_fds(open_files_limit) < 0) {
3154
0
      fprintf(stderr, "ERROR: error could not increase file limits\n");
3155
0
      goto error;
3156
0
    }
3157
0
  }
3158
0
  if(mlock_pages)
3159
0
    mem_lock_pages();
3160
3161
0
  if(real_time & 4)
3162
0
    set_rt_prio(rt_prio, rt_policy);
3163
3164
0
#ifdef USE_TCP
3165
0
#ifdef USE_TLS
3166
0
  if(!tls_disable) {
3167
0
    if(!tls_loaded()) {
3168
0
      LM_WARN("tls support enabled, but no tls engine "
3169
0
          " available (forgot to load the tls module?)\n");
3170
0
      LM_WARN("disabling tls...\n");
3171
0
      tls_disable = 1;
3172
0
    } else {
3173
0
      if(pre_init_tls() < 0) {
3174
0
        LM_CRIT("could not pre-initialize tls, exiting...\n");
3175
0
        goto error;
3176
0
      }
3177
0
    }
3178
0
  }
3179
0
#endif /* USE_TLS */
3180
0
#endif /* USE_TCP */
3181
3182
0
  if(init_modules() != 0) {
3183
0
    fprintf(stderr, "ERROR: error while initializing modules\n");
3184
0
    goto error;
3185
0
  }
3186
3187
  /* initialize process_table, add core process no. (calc_proc_no()) to the
3188
   * processes registered from the modules*/
3189
0
  if(init_pt(calc_proc_no()) == -1)
3190
0
    goto error;
3191
0
#ifdef USE_TCP
3192
0
#ifdef USE_TLS
3193
0
  if(!tls_disable) {
3194
0
    if(!tls_loaded()) {
3195
0
      LM_WARN("tls support enabled, but no tls engine "
3196
0
          " available (forgot to load the tls module?)\n");
3197
0
      LM_WARN("disabling tls...\n");
3198
0
      tls_disable = 1;
3199
0
    }
3200
    /* init tls*/
3201
0
    if(init_tls() < 0) {
3202
0
      LM_CRIT("could not initialize tls, exiting...\n");
3203
0
      goto error;
3204
0
    }
3205
0
  }
3206
0
#endif /* USE_TLS */
3207
0
#endif /* USE_TCP */
3208
3209
  /* The total number of processes is now known, note that no
3210
   * function being called before this point may rely on the
3211
   * number of processes !
3212
   */
3213
0
  LM_INFO("processes (at least): %d - shm size: %lu - pkg size: %lu\n",
3214
0
      get_max_procs(), shm_mem_size, pkg_mem_size);
3215
3216
#if defined USE_DNS_CACHE && defined USE_DNS_CACHE_STATS
3217
  if(init_dns_cache_stats(get_max_procs()) < 0) {
3218
    LM_CRIT("could not initialize the dns cache measurement\n");
3219
    goto error;
3220
  }
3221
#endif
3222
#if defined USE_DST_BLOCKLIST && defined USE_DST_BLOCKLIST_STATS
3223
  if(init_dst_blocklist_stats(get_max_procs()) < 0) {
3224
    LM_CRIT("could not initialize the dst blocklist measurement\n");
3225
    goto error;
3226
  }
3227
#endif
3228
3229
  /* fix routing lists */
3230
0
  if((r = fix_rls()) != 0) {
3231
0
    fprintf(stderr, "error %d while trying to fix configuration\n", r);
3232
0
    goto error;
3233
0
  };
3234
0
  fixup_complete = 1;
3235
3236
0
  ret = main_loop();
3237
0
  if(ret < 0)
3238
0
    goto error;
3239
  /*kill everything*/
3240
0
  if(_ksr_is_main)
3241
0
    shutdown_children(SIGTERM, 0);
3242
0
  if(!dont_daemonize) {
3243
0
    if(daemon_status_send(0) < 0)
3244
0
      fprintf(stderr, "error sending exit status: %s [%d]\n",
3245
0
          strerror(errno), errno);
3246
0
  }
3247
  /* else terminate process */
3248
0
  ksr_exit(ret);
3249
3250
0
error:
3251
  /*kill everything*/
3252
0
  if(_ksr_is_main)
3253
0
    shutdown_children(SIGTERM, 0);
3254
0
  if(!dont_daemonize) {
3255
0
    if(daemon_status_send((char)-1) < 0)
3256
0
      fprintf(stderr, "error sending exit status: %s [%d]\n",
3257
0
          strerror(errno), errno);
3258
0
  }
3259
0
  ksr_exit(-1);
3260
0
}
3261
3262
3263
#ifdef KSR_PTHREAD_MUTEX_SHARED
3264
3265
/**
3266
 * code to set PTHREAD_PROCESS_SHARED attribute for pthread mutex to cope
3267
 * with libssl 1.1+ thread-only mutex initialization
3268
 */
3269
3270
#define SYMBOL_EXPORT __attribute__((visibility("default")))
3271
3272
int SYMBOL_EXPORT pthread_mutex_init(
3273
    pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr)
3274
4
{
3275
4
  static int (*real_pthread_mutex_init)(pthread_mutex_t * __mutex,
3276
4
      const pthread_mutexattr_t *__mutexattr) = 0;
3277
4
  pthread_mutexattr_t attr;
3278
4
  int ret;
3279
3280
4
  if(!real_pthread_mutex_init) {
3281
4
    real_pthread_mutex_init = dlsym(RTLD_NEXT, "pthread_mutex_init");
3282
4
    if(!real_pthread_mutex_init) {
3283
0
      return -1;
3284
0
    }
3285
4
  }
3286
3287
4
  if(__mutexattr) {
3288
4
    pthread_mutexattr_t attr = *__mutexattr;
3289
4
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
3290
4
    return real_pthread_mutex_init(__mutex, &attr);
3291
4
  }
3292
3293
0
  pthread_mutexattr_init(&attr);
3294
0
  pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
3295
0
  ret = real_pthread_mutex_init(__mutex, &attr);
3296
0
  pthread_mutexattr_destroy(&attr);
3297
3298
0
  return ret;
3299
4
}
3300
3301
int SYMBOL_EXPORT pthread_rwlock_init(pthread_rwlock_t *__restrict __rwlock,
3302
    const pthread_rwlockattr_t *__restrict __attr)
3303
0
{
3304
0
  static int (*real_pthread_rwlock_init)(
3305
0
      pthread_rwlock_t *__restrict __rwlock,
3306
0
      const pthread_rwlockattr_t *__restrict __attr) = 0;
3307
0
  pthread_rwlockattr_t attr;
3308
0
  int ret;
3309
3310
0
  if(!real_pthread_rwlock_init) {
3311
0
    real_pthread_rwlock_init = dlsym(RTLD_NEXT, "pthread_rwlock_init");
3312
0
    if(!real_pthread_rwlock_init) {
3313
0
      return -1;
3314
0
    }
3315
0
  }
3316
3317
0
  if(__attr) {
3318
0
    pthread_rwlockattr_t attr = *__attr;
3319
0
    pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
3320
0
    return real_pthread_rwlock_init(__rwlock, &attr);
3321
0
  }
3322
3323
0
  pthread_rwlockattr_init(&attr);
3324
0
  pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
3325
0
  ret = real_pthread_rwlock_init(__rwlock, &attr);
3326
0
  pthread_rwlockattr_destroy(&attr);
3327
3328
0
  return ret;
3329
0
}
3330
#endif