Coverage Report

Created: 2023-11-27 07:05

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