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