2 * Copyright (C) 2001-2003 FhG Fokus
4 * This file is part of Kamailio, a free SIP server.
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
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.
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
22 /** Kamailio core :: main file (init, daemonize, startup)
28 /*! @defgroup core Kamailio core
30 * sip router core part.
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #if defined(HAVE_NETINET_IN_SYSTM)
43 #include <netinet/in_systm.h>
45 #include <netinet/in.h>
46 #include <netinet/ip.h>
47 #include <arpa/inet.h>
48 #include <sys/utsname.h>
58 #include <sys/ioctl.h>
60 #ifdef HAVE_SYS_SOCKIO_H
61 #include <sys/sockio.h>
64 #include "core/config.h"
65 #include "core/dprint.h"
66 #include "core/daemonize.h"
67 #include "core/route.h"
68 #include "core/udp_server.h"
69 #include "core/globals.h"
70 #include "core/mem/mem.h"
72 #include "core/mem/shm_mem.h"
73 #include "core/shm_init.h"
75 #include "core/sr_module.h"
76 #include "core/timer.h"
77 #include "core/parser/msg_parser.h"
78 #include "core/ip_addr.h"
79 #include "core/resolve.h"
80 #include "core/parser/parse_hname2.h"
81 #include "core/parser/digest/digest_parser.h"
82 #include "core/name_alias.h"
83 #include "core/hash_func.h"
85 #include "core/script_cb.h"
86 #include "core/nonsip_hooks.h"
88 #include "core/events.h"
89 #include "core/signals.h"
91 #include "core/raw_sock.h"
92 #endif /* USE_RAW_SOCKS */
94 #include "core/poll_types.h"
95 #include "core/tcp_init.h"
96 #include "core/tcp_options.h"
98 #include "core/tls/tls_init.h"
99 #define tls_has_init_si() 1
100 #define tls_loaded() 1
102 #include "core/tls_hooks_init.h"
103 #endif /* CORE_TLS */
106 #include "core/sctp_core.h"
108 #include "core/usr_avp.h"
109 #include "core/rpc_lookup.h"
110 #include "core/core_cmd.h"
111 #include "core/flags.h"
112 #include "core/lock_ops_init.h"
113 #include "core/atomic_ops_init.h"
115 #include "core/dns_cache.h"
117 #ifdef USE_DST_BLACKLIST
118 #include "core/dst_blacklist.h"
120 #include "core/rand/fastrand.h" /* seed */
121 #include "core/rand/kam_rand.h"
123 #include "core/stats.h"
124 #include "core/counters.h"
125 #include "core/cfg/cfg.h"
126 #include "core/cfg/cfg_struct.h"
127 #include "core/cfg_core.h"
128 #include "core/endianness.h" /* init */
129 #include "core/basex.h" /* init */
130 #include "core/pvapi.h" /* init PV api */
131 #include "core/pv_core.h" /* register core pvars */
132 #include "core/ppcfg.h"
133 #include "core/sock_ut.h"
134 #include "core/async_task.h"
135 #include "core/dset.h"
136 #include "core/timer_proc.h"
137 #include "core/srapi.h"
138 #include "core/receive.h"
143 #include "core/ver.h"
145 /* define SIG_DEBUG by default */
154 static char help_msg[]= "\
155 Usage: " NAME " [options]\n\
157 -f file Configuration file (default: " CFG_FILE ")\n\
158 -L path Modules search path (default: " MODS_DIR ")\n\
159 -c Check configuration file for errors\n\
160 -l address Listen on the specified address/interface (multiple -l\n\
161 mean listening on more addresses). The address format is\n\
162 [proto:]addr_lst[:port], where proto=udp|tcp|tls|sctp, \n\
163 addr_lst= addr|(addr, addr_lst) and \n\
164 addr= host|ip_address|interface_name. \n\
165 E.g: -l localhost, -l udp:127.0.0.1:5080, -l eth0:5062,\n\
166 -l \"sctp:(eth0)\", -l \"(eth0, eth1, 127.0.0.1):5065\".\n\
167 The default behaviour is to listen on all the interfaces.\n\
168 -n processes Number of child processes to fork per interface\n\
170 -r Use dns to check if is necessary to add a \"received=\"\n\
172 -R Same as `-r` but use reverse dns;\n\
173 (to use both use `-rR`)\n\
174 -K Turn on \"via:\" host checking when forwarding replies\n\
175 -d Debugging mode (multiple -d increase the level)\n\
176 -D Control how daemonize is done:\n\
177 -D..do not fork (almost) anyway;\n\
178 -DD..do not daemonize creator;\n\
179 -DDD..daemonize (default)\n\
181 -e Log messages printed in terminal colors (requires -E)\n"
184 -N Number of tcp child processes (default: equal to `-n')\n\
185 -W type poll method (depending on support in OS, it can be: poll,\n\
186 epoll_lt, epoll_et, sigio_rt, select, kqueue, /dev/poll)\n"
190 -Q Number of sctp child processes (default: equal to `-n')\n"
191 #endif /* USE_SCTP */
192 " -v (-V) Version number\n\
193 -h This help message\n\
194 -I Print more internal compile flags and options\n\
195 -b nr Maximum receive buffer size which will not be exceeded by\n\
196 auto-probing procedure even if OS allows\n\
197 -m nr Size of shared memory allocated in Megabytes\n\
198 -M nr Size of private memory allocated, in Megabytes\n\
199 -w dir Change the working directory to \"dir\" (default: \"/\")\n\
200 -t dir Chroot to \"dir\"\n\
201 -u uid Change uid (user id)\n\
202 -g gid Change gid (group id)\n\
203 -P file Create a pid file\n\
204 -G file Create a pgid file\n\
205 -Y dir Runtime dir path\n\
206 -O nr Script optimization level (debugging option)\n\
207 -a mode Auto aliases mode: enable with yes or on,\n\
208 disable with no or off\n\
209 -A define Add config pre-processor define (e.g., -A WITH_AUTH)\n\
210 -x name Specify internal manager for shared memory (shm)\n\
211 - can be: fm, qm or tlsf\n\
212 -X name Specify internal manager for private memory (pkg)\n\
213 - if omitted, the one for shm is used\n"
215 " -s file File where to write internal statistics on SIGUSR1\n"
220 /* print compile-time constants */
221 void print_ct_constants(void)
224 printf("ADAPTIVE_WAIT_LOOPS=%d, ", ADAPTIVE_WAIT_LOOPS);
228 printf("SHM_MEM_SIZE=%d, ", SHM_MEM_SIZE);
231 printf("MAX_RECV_BUFFER_SIZE %d"
232 " MAX_URI_SIZE %d, BUF_SIZE %d, DEFAULT PKG_SIZE %uMB\n",
233 MAX_RECV_BUFFER_SIZE, MAX_URI_SIZE,
234 BUF_SIZE, PKG_MEM_SIZE);
236 printf("poll method support: %s.\n", poll_support);
240 /* print compile-time constants */
241 void print_internals(void)
243 printf("Print out of %s internals\n", NAME);
244 printf(" Version: %s\n", full_version);
245 printf(" Default config: %s\n", CFG_FILE);
246 printf(" Default paths to modules: %s\n", MODS_DIR);
247 printf(" Compile flags: %s\n", ver_flags );
248 printf(" MAX_RECV_BUFFER_SIZE=%d\n", MAX_RECV_BUFFER_SIZE);
249 printf(" MAX_URI_SIZE=%d\n", MAX_URI_SIZE);
250 printf(" BUF_SIZE=%d\n", BUF_SIZE);
251 printf(" DEFAULT PKG_SIZE=%uMB\n", PKG_MEM_SIZE);
253 printf(" DEFAULT SHM_SIZE=%uMB\n", SHM_MEM_SIZE);
256 printf(" ADAPTIVE_WAIT_LOOPS=%d\n", ADAPTIVE_WAIT_LOOPS);
259 printf(" TCP poll methods: %s\n", poll_support);
261 printf(" Source code revision ID: %s\n", ver_id);
262 printf(" Compiled with: %s\n", ver_compiler);
263 printf(" Compiled on: %s\n", ver_compiled_time);
264 printf("Thank you for flying %s!\n", NAME);
267 /* debugging function */
269 void receive_stdin_loop(void)
276 len=fread(buf,1,BSIZE,stdin);
278 receive_msg(buf, len);
279 printf("-------------------------\n");
286 int own_pgid = 0; /* whether or not we have our own pgid (and it's ok
287 to use kill(0, sig) */
289 char* mods_dir = MODS_DIR; /* search path for dyn. loadable modules */
290 int mods_dir_cmd = 0; /* mods dir path set in command lin e*/
293 unsigned int maxbuffer = MAX_RECV_BUFFER_SIZE; /* maximum buffer size we do
294 not want to exceed during the
295 auto-probing procedure; may
297 unsigned int sql_buffer_size = 65535; /* Size for the SQL buffer. Defaults to 64k.
298 This may be re-configured */
299 int socket_workers = 0; /* number of workers processing requests for a socket
300 - it's reset everytime with a new listen socket */
301 int children_no = 0; /* number of children processing requests */
303 int tcp_cfg_children_no = 0; /* set via config or command line option */
304 int tcp_children_no = 0; /* based on socket_workers and tcp_cfg_children_no */
305 int tcp_disable = 0; /* 1 if tcp is disabled */
309 int tls_disable = 0; /* tls enabled by default */
311 int tls_disable = 1; /* tls disabled by default */
312 #endif /* CORE_TLS */
315 int sctp_children_no = 0;
316 int sctp_disable = 2; /* 1 if sctp is disabled, 2 if auto mode, 0 enabled */
317 #endif /* USE_SCTP */
319 struct process_table *pt=0; /*array with children pids, 0= main proc,
320 alloc'ed in shared mem if possible*/
321 int *process_count = 0; /* Total number of SER processes currently
323 gen_lock_t* process_lock; /* lock on the process table */
324 int process_no = 0; /* index of process in the pt */
327 int sig_flag = 0; /* last signal received */
329 int dont_daemonize = 0;
332 /* set custom app name for syslog printing */
334 char *log_prefix_fmt = 0;
335 pid_t creator_pid = (pid_t) -1;
336 int config_check = 0;
337 /* check if reply first via host==us */
339 /* translate user=phone URIs to TEL URIs */
341 /* debugging level for timer debugging */
342 int timerlog = L_WARN;
343 /* should replies include extensive warnings? by default no,
344 good for trouble-shooting
347 /* should localy-generated messages include server's signature?
348 be default yes, good for trouble-shooting
350 int server_signature=1;
351 str server_hdr = {SERVER_HDR, SERVER_HDR_LEN};
352 str user_agent_hdr = {USER_AGENT, USER_AGENT_LEN};
353 str version_table = {VERSION_TABLE, VERSION_TABLE_LEN};
354 /* should ser try to locate outbound interface on multihomed
355 * host? by default not -- too expensive
358 /* use dns and/or rdns or to see if we need to add
359 a ;received=x.x.x.x to via: */
360 int received_dns = 0;
361 /* add or not the rev dns names to aliases list */
362 int sr_auto_aliases=1;
363 char* working_dir = 0;
364 char* chroot_dir = 0;
365 char* runtime_dir = "" RUN_DIR;
374 int sock_mode= S_IRUSR| S_IWUSR| S_IRGRP| S_IWGRP; /* rw-rw---- */
376 int server_id = 0; /* Configurable unique ID of the server */
378 /* maximum number of branches for transaction */
379 unsigned int sr_dst_max_branches = MAX_BRANCHES_DEFAULT;
381 /* set timeval for each received sip message */
384 /* onsend_route is executed for replies*/
385 int onsend_route_reply = 0;
387 /* more config stuff */
388 int disable_core_dump=0; /* by default enabled */
389 int open_files_limit=-1; /* don't touch it by default */
392 int shm_force_alloc=0; /* force immediate (on startup) page allocation
393 (by writting 0 in the pages), useful if
394 mlock_pages is also 1 */
395 int mlock_pages=0; /* default off, try to disable swapping */
397 /* real time options */
398 int real_time=0; /* default off, flags: 1 on only timer, 2 slow timer,
399 4 all procs (7=all) */
401 int rt_policy=0; /* SCHED_OTHER */
402 int rt_timer1_prio=0; /* "fast" timer */
403 int rt_timer2_prio=0; /* "slow" timer */
404 int rt_timer1_policy=0; /* "fast" timer, SCHED_OTHER */
405 int rt_timer2_policy=0; /* "slow" timer, SCHED_OTHER */
408 /* a hint to reply modules whether they should send reply
409 to IP advertised in Via or IP from which a request came
414 int mcast_loopback = 0;
415 int mcast_ttl = -1; /* if -1, don't touch it, use the default (usually 1) */
417 #endif /* USE_MCAST */
419 int tos = IPTOS_LOWDELAY;
420 int pmtu_discovery = 0;
422 int auto_bind_ipv6 = 0;
424 struct socket_info* udp_listen=0;
426 int tcp_main_pid=0; /* set after the tcp main process is started */
427 struct socket_info* tcp_listen=0;
430 struct socket_info* tls_listen=0;
433 struct socket_info* sctp_listen=0;
435 struct socket_info* bind_address=0; /* pointer to the crt. proc.
437 struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
438 struct socket_info* sendipv6; /* same as above for ipv6 */
440 int raw_udp4_send_sock = -1; /* raw socket used for sending udp4 packets */
441 #endif /* USE_RAW_SOCKS */
443 struct socket_info* sendipv4_tcp;
444 struct socket_info* sendipv6_tcp;
447 struct socket_info* sendipv4_tls;
448 struct socket_info* sendipv6_tls;
451 struct socket_info* sendipv4_sctp;
452 struct socket_info* sendipv6_sctp;
455 unsigned short port_no=0; /* default port*/
457 unsigned short tls_port_no=0; /* default port */
460 struct host_alias* aliases=0; /* name aliases list */
462 /* Parameter to child_init */
465 /* how much to wait for children to terminate, before taking extreme measures*/
466 int ser_kill_timeout=DEFAULT_SER_KILL_TIMEOUT;
468 int ksr_verbose_startup = 0;
475 /* shared memory (in MB) */
476 unsigned long shm_mem_size=0;
477 /* private (pkg) memory (in MB) */
478 unsigned long pkg_mem_size=0;
480 /* export command-line to anywhere else */
484 /* set to 1 when the cfg framework and core cfg is initialized/registered */
487 #define MAX_FD 32 /* maximum number of inherited open file descriptors,
488 (normally it shouldn't be bigger than 3) */
492 extern int yyparse(void);
495 int is_main=1; /* flag = is this the "main" process? */
496 int fixup_complete=0; /* flag = is the fixup complete ? */
498 char* pid_file = 0; /* filename as asked by use */
503 #define SR_MEMMNG_DEFAULT "qm"
505 char *sr_memmng_pkg = NULL;
506 char *sr_memmng_shm = NULL;
508 /* call it before exiting; if show_status==1, mem status is displayed */
509 void cleanup(int show_status)
514 #ifndef SHM_SAFE_MALLOC
515 if(shm_initialized()) {
516 /* force-unlock the shared memory lock in case some process crashed
517 * and let it locked; this will allow an almost gracious shutdown */
526 #ifdef USE_DST_BLACKLIST
527 destroy_dst_blacklist();
529 /* restore the original core configuration before the
530 * config block is freed, otherwise even logging is unusable,
531 * it can case segfault */
534 /* copy current config into default_core_cfg */
536 default_core_cfg=*((struct cfg_group_core*)core_cfg);
538 core_cfg = &default_core_cfg;
551 ksr_route_locks_set_destroy();
553 destroy_nonsip_hooks();
555 destroy_atomic_ops();
557 memlog=cfg_get(core, core_cfg, memlog);
559 if (show_status && memlog <= cfg_get(core, core_cfg, debug)){
560 if (cfg_get(core, core_cfg, mem_summary) & 1) {
561 LOG(memlog, "Memory status (pkg):\n");
564 if (cfg_get(core, core_cfg, mem_summary) & 4) {
565 LOG(memlog, "Memory still-in-use summary (pkg):\n");
571 if (pt) shm_free(pt);
573 if (show_status && memlog <= cfg_get(core, core_cfg, debug)){
574 if (cfg_get(core, core_cfg, mem_summary) & 2) {
575 LOG(memlog, "Memory status (shm):\n");
578 if (cfg_get(core, core_cfg, mem_summary) & 8) {
579 LOG(memlog, "Memory still-in-use summary (shm):\n");
583 /* zero all shmem alloc vars that we still use */
584 shm_destroy_manager();
587 if (pid_file) unlink(pid_file);
588 if (pgid_file) unlink(pgid_file);
589 pkg_destroy_manager();
593 /* tries to send a signal to all our processes
594 * if daemonized is ok to send the signal to all the process group,
595 * however if not daemonized we might end up sending the signal also
596 * to the shell which launched us => most signals will kill it if
597 * it's not in interactive mode and we don't want this. The non-daemonized
598 * case can occur when an error is encountered before daemonize is called
599 * (e.g. when parsing the config file) or when ser is started in "dont-fork"
600 * mode. Sending the signal to all the processes in pt[] will not work
601 * for processes forked from modules (which have no correspondent entry in
602 * pt), but this can happen only in dont_fork mode (which is only for
603 * debugging). So in the worst case + "dont-fork" we might leave some
604 * zombies. -- andrei */
605 static void kill_all_children(int signum)
609 if (own_pgid) kill(0, signum);
611 /* lock processes table only if this is a child process
612 * (only main can add processes, so from main is safe not to lock
613 * and moreover it avoids the lock-holding suicidal children problem)
615 if (!is_main) lock_get(process_lock);
616 for (r=1; r<*process_count; r++){
617 if (r==process_no) continue; /* try not to be suicidal */
619 kill(pt[r].pid, signum);
621 else LM_CRIT("killing: %s > %d no pid!!!\n",
622 pt[r].desc, pt[r].pid);
624 if (!is_main) lock_release(process_lock);
630 /* if this handler is called, a critical timeout has occurred while
631 * waiting for the children to finish => we should kill everything and exit */
632 static void sig_alarm_kill(int signo)
634 kill_all_children(SIGKILL); /* this will kill the whole group
635 including "this" process;
636 for debugging replace with SIGABRT
637 (but warning: it might generate lots
642 /* like sig_alarm_kill, but the timeout has occurred when cleaning up
643 * => try to leave a core for future diagnostics */
644 static void sig_alarm_abort(int signo)
646 /* LOG is not signal safe, but who cares, we are abort-ing anyway :-) */
647 LM_CRIT("shutdown timeout triggered, dying...");
653 static void shutdown_children(int sig, int show_status)
655 kill_all_children(sig);
656 if (set_sig_h(SIGALRM, sig_alarm_kill) == SIG_ERR ) {
657 LM_ERR("could not install SIGALARM handler\n");
658 /* continue, the process will die anyway if no
659 * alarm is installed which is exactly what we want */
661 alarm(ser_kill_timeout);
662 while((wait(0) > 0) || (errno==EINTR)); /* wait for all the
663 children to terminate*/
664 set_sig_h(SIGALRM, sig_alarm_abort);
665 cleanup(show_status); /* cleanup & show status*/
667 set_sig_h(SIGALRM, SIG_IGN);
672 void handle_sigs(void)
676 int any_chld_stopped;
680 case 0: break; /* do nothing*/
682 /* SIGPIPE might be rarely received on use of
683 exec module; simply ignore it
685 LM_WARN("SIGPIPE received and ignored\n");
689 /* we end the program in all these cases */
690 if (sig_flag==SIGINT)
691 LM_DBG("INT received, program terminates\n");
693 LM_DBG("SIGTERM received, program terminates\n");
694 LM_NOTICE("Thank you for flying " NAME "!!!\n");
695 /* shutdown/kill all the children */
696 shutdown_children(SIGTERM, 1);
702 dump_all_statistic();
704 memlog=cfg_get(core, core_cfg, memlog);
706 if (memlog <= cfg_get(core, core_cfg, debug)){
707 if (cfg_get(core, core_cfg, mem_summary) & 1) {
708 LOG(memlog, "Memory status (pkg):\n");
711 if (cfg_get(core, core_cfg, mem_summary) & 4) {
712 LOG(memlog, "Memory still-in-use summary (pkg):\n");
718 if (memlog <= cfg_get(core, core_cfg, debug)){
719 if (cfg_get(core, core_cfg, mem_summary) & 2) {
720 LOG(memlog, "Memory status (shm):\n");
723 if (cfg_get(core, core_cfg, mem_summary) & 8) {
724 LOG(memlog, "Memory still-in-use summary (shm):\n");
733 while ((chld=waitpid( -1, &chld_status, WNOHANG ))>0) {
735 if (WIFEXITED(chld_status))
736 LM_ALERT("child process %ld exited normally,"
737 " status=%d\n", (long)chld,
738 WEXITSTATUS(chld_status));
739 else if (WIFSIGNALED(chld_status)) {
740 LM_ALERT("child process %ld exited by a signal"
741 " %d\n", (long)chld, WTERMSIG(chld_status));
743 LM_ALERT("core was %sgenerated\n",
744 WCOREDUMP(chld_status) ? "" : "not " );
746 }else if (WIFSTOPPED(chld_status))
747 LM_ALERT("child process %ld stopped by a"
748 " signal %d\n", (long)chld,
749 WSTOPSIG(chld_status));
752 /* If it appears that no child process has stopped, then do not terminate on SIGCHLD.
753 Certain modules like app_python can run external scripts which cause child processes to be started and
754 stopped. That can result in SIGCHLD being received here even though there is no real problem. Therefore,
755 we do not terminate Kamailio unless we can find the child process which has stopped. */
756 if (!any_chld_stopped) {
757 LM_INFO("SIGCHLD received, but no child has stopped, ignoring it\n");
761 #ifndef STOP_JIRIS_CHANGES
763 LM_INFO("dont_fork turned on, living on\n");
766 LM_INFO("terminating due to SIGCHLD\n");
768 LM_DBG("terminating due to SIGCHLD\n");
770 shutdown_children(SIGTERM, 1);
771 if (WIFSIGNALED(chld_status)) {
778 case SIGHUP: /* ignoring it*/
779 LM_DBG("SIGHUP received, ignoring it\n");
782 LM_CRIT("unhandled signal %d\n", sig_flag);
789 /* added by jku; allows for regular exit on a specific signal;
790 good for profiling which only works if exited regularly and
791 not by default signal handlers
792 - modified by andrei: moved most of the stuff to handle_sigs,
793 made it safer for the "fork" case
795 void sig_usr(int signo)
803 if (sig_flag==0) sig_flag=signo;
804 else /* previous sig. not processed yet, ignoring? */
807 /* only one proc, doing everything from the sig handler,
808 unsafe, but this is only for debugging mode*/
811 /* process the important signals */
814 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
815 LM_INFO("signal %d received\n", signo);
820 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
821 LM_INFO("signal %d received\n", signo);
822 /* print memory stats for non-main too */
824 /* make sure we have current cfg values, but update only
825 the safe part (values not requiring callbacks), to
826 account for processes that might not have registered
829 memlog=cfg_get(core, core_cfg, memlog);
830 if (memlog <= cfg_get(core, core_cfg, debug)){
831 if (cfg_get(core, core_cfg, mem_summary) & 1) {
832 LOG(memlog, "Memory status (pkg):\n");
835 if (cfg_get(core, core_cfg, mem_summary) & 4) {
836 LOG(memlog, "Memory still-in-use summary (pkg):"
848 memlog=cfg_get(core, core_cfg, memlog);
849 if (memlog <= cfg_get(core, core_cfg, debug)){
850 if (cfg_get(core, core_cfg, mem_summary) & 1) {
851 LOG(memlog, "Memory status (pkg):\n");
854 if (cfg_get(core, core_cfg, mem_summary) & 4) {
855 LOG(memlog, "Memory still-in-use summary (pkg):\n");
866 #ifndef STOP_JIRIS_CHANGES
867 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
868 LM_DBG("SIGCHLD received: "
869 "we do not worry about grand-children\n");
872 _exit(0); /* terminate if one child died */
881 /* install the signal handlers, returns 0 on success, -1 on error */
882 int install_sigs(void)
884 /* added by jku: add exit handler */
885 if (set_sig_h(SIGINT, sig_usr) == SIG_ERR ) {
886 ERR("no SIGINT signal handler can be installed\n");
889 /* if we debug and write to a pipe, we want to exit nicely too */
890 if (set_sig_h(SIGPIPE, sig_usr) == SIG_ERR ) {
891 ERR("no SIGINT signal handler can be installed\n");
894 if (set_sig_h(SIGUSR1, sig_usr) == SIG_ERR ) {
895 ERR("no SIGUSR1 signal handler can be installed\n");
898 if (set_sig_h(SIGCHLD , sig_usr) == SIG_ERR ) {
899 ERR("no SIGCHLD signal handler can be installed\n");
902 if (set_sig_h(SIGTERM , sig_usr) == SIG_ERR ) {
903 ERR("no SIGTERM signal handler can be installed\n");
906 if (set_sig_h(SIGHUP , sig_usr) == SIG_ERR ) {
907 ERR("no SIGHUP signal handler can be installed\n");
910 if (set_sig_h(SIGUSR2 , sig_usr) == SIG_ERR ) {
911 ERR("no SIGUSR2 signal handler can be installed\n");
919 /* returns -1 on error, 0 on success
921 int parse_proto(unsigned char* s, long len, int* proto)
923 #define PROTO2UINT3(a, b, c) (( (((unsigned int)(a))<<16)+ \
924 (((unsigned int)(b))<<8)+ \
925 ((unsigned int)(c)) ) | 0x20202020)
926 #define PROTO2UINT4(a, b ,c ,d) (( (((unsigned int)(a))<<24)+ \
927 (((unsigned int)(b))<<16)+ \
928 (((unsigned int)(c))<< 8)+ \
929 (((unsigned int)(d))) \
933 i=PROTO2UINT3(s[0], s[1], s[2]);
935 case PROTO2UINT3('u', 'd', 'p'):
939 case PROTO2UINT3('t', 'c', 'p'):
943 case PROTO2UINT3('t', 'l', 's'):
953 else if (likely(len==4)){
954 i=PROTO2UINT4(s[0], s[1], s[2], s[3]);
955 if (i==PROTO2UINT4('s', 'c', 't', 'p'))
960 #endif /* USE_SCTP */
962 /* Deliberately leaving out PROTO_WS and PROTO_WSS as these are just
963 upgraded TCP/TLS connections. */
970 static struct name_lst* mk_name_lst_elem(char* name, int name_len, int flags)
974 l=pkg_malloc(sizeof(struct name_lst)+name_len+1/* 0 */);
976 l->name=((char*)l)+sizeof(struct name_lst);
977 memcpy(l->name, name, name_len);
987 /* free a name_lst list with elements allocated with mk_name_lst_elem
988 * (single block both for the structure and for the name) */
989 static void free_name_lst(struct name_lst* lst)
1002 /* parse h and returns a name lst (flags are set to SI_IS_MHOMED if
1003 * h contains more then one name or contains a name surrounded by '(' ')' )
1004 * valid formats: "hostname"
1005 * "(hostname, hostname1, hostname2)"
1006 * "(hostname hostname1 hostname2)"
1009 static struct name_lst* parse_name_lst(char* h, int h_len)
1013 struct name_lst* n_lst;
1015 struct name_lst** tail;
1022 /* eat whitespace */
1023 for(; h<=last && ((*h==' ') || (*h=='\t')); h++);
1024 for(; last>h && ((*last==' ') || (*last=='\t')); last--);
1025 /* catch empty strings and invalid lens */
1026 if (h>last) goto error;
1030 if (*last!=')' || ((h+1)>(last-1)))
1035 for(p=h; p<=last; p++)
1042 l=mk_name_lst_elem(h, (int)(p-h), flags);
1052 /* single addr. mode */
1057 l=mk_name_lst_elem(h, (int)(p-h), flags);
1065 if (n_lst) free_name_lst(n_lst);
1072 * parses [proto:]host[:port] or
1073 * [proto:](host_1, host_2, ... host_n)[:port]
1074 * where proto= udp|tcp|tls
1075 * returns fills proto, port, host and returns list of addresses on success
1076 * (pkg malloc'ed) and 0 on failure
1078 /** get protocol host and port from a string representation.
1079 * parses [proto:]host[:port] or
1080 * [proto:](host_1, host_2, ... host_n)[:port]
1081 * where proto= udp|tcp|tls|sctp
1082 * @param s - string (like above)
1083 * @param host - will be filled with the host part
1084 * Note: for multi-homing it wil contain all the addresses
1085 * (e.g.: "sctp:(1.2.3.4, 5.6.7.8)" => host="(1.2.3.4, 5.6.7.8)")
1086 * @param hlen - will be filled with the length of the host part.
1087 * @param port - will be filled with the port if present or 0 if it's not.
1088 * @param proto - will be filled with the protocol if present or PROTO_NONE
1090 * @return fills proto, port, host and returns 0 on success and -1 on failure.
1092 int parse_phostport(char* s, char** host, int* hlen,
1093 int* port, int* proto)
1095 char* first; /* first ':' occurrence */
1096 char* second; /* second ':' occurrence */
1104 /* find the first 2 ':', ignoring possible ipv6 addresses
1105 * (substrings between [])
1111 if (bracket>1) goto error_brackets;
1115 if (bracket<0) goto error_brackets;
1119 if (first==0) first=p;
1120 else if( second==0) second=p;
1121 else goto error_colons;
1126 if (p==s) return -1;
1127 if (*(p-1)==':') goto error_colons;
1129 if (first==0){ /* no ':' => only host */
1136 if (second){ /* 2 ':' found => check if valid */
1137 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
1138 *port=strtol(second+1, &tmp, 10);
1139 if ((tmp==0)||(*tmp)||(tmp==second+1)) goto error_port;
1141 *hlen=(int)(second-*host);
1144 /* only 1 ':' found => it's either proto:host or host:port */
1145 *port=strtol(first+1, &tmp, 10);
1146 if ((tmp==0)||(*tmp)||(tmp==first+1)){
1147 /* invalid port => it's proto:host */
1148 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
1151 *hlen=(int)(p-*host);
1153 /* valid port => its host:port */
1156 *hlen=(int)(first-*host);
1161 LM_ERR("too many brackets in %s\n", s);
1164 LM_ERR("too many colons in %s\n", s);
1167 LM_ERR("bad protocol in %s\n", s);
1170 LM_ERR("bad port number in %s\n", s);
1176 /** get protocol host, port and MH addresses list from a string representation.
1177 * parses [proto:]host[:port] or
1178 * [proto:](host_1, host_2, ... host_n)[:port]
1179 * where proto= udp|tcp|tls|sctp
1180 * @param s - string (like above)
1181 * @param host - will be filled with the host part
1182 * Note: for multi-homing it wil contain all the addresses
1183 * (e.g.: "sctp:(1.2.3.4, 5.6.7.8)" => host="(1.2.3.4, 5.6.7.8)")
1184 * @param hlen - will be filled with the length of the host part.
1185 * @param port - will be filled with the port if present or 0 if it's not.
1186 * @param proto - will be filled with the protocol if present or PROTO_NONE
1188 * @return fills proto, port, host and returns list of addresses on success
1189 * (pkg malloc'ed) and 0 on failure
1191 static struct name_lst* parse_phostport_mh(char* s, char** host, int* hlen,
1192 int* port, int* proto)
1194 if (parse_phostport(s, host, hlen, port, proto)==0)
1195 return parse_name_lst(*host, *hlen);
1201 /** Update \c cfg_file variable to contain full pathname. The function updates
1202 * the value of \c cfg_file global variable to contain full absolute pathname
1203 * to the main configuration file of SER. The function uses CFG_FILE macro to
1204 * determine the default path to the configuration file if the user did not
1205 * specify one using the command line option. If \c cfg_file contains an
1206 * absolute pathname then it is used unmodified, if it contains a relative
1207 * pathanme than the value returned by \c getcwd function will be added at the
1208 * beginning. This function must be run before SER changes its current working
1209 * directory to / (in daemon mode).
1210 * @return Zero on success, negative number
1213 int fix_cfg_file(void)
1216 size_t max_len, cwd_len, cfg_len;
1218 if (cfg_file == NULL) cfg_file = CFG_FILE;
1219 if (cfg_file[0] == '/') return 0;
1220 if (cfg_file[0] == '-' && strlen(cfg_file)==1) return 0;
1222 /* cfg_file contains a relative pathname, get the current
1223 * working directory and add it at the beginning
1225 cfg_len = strlen(cfg_file);
1227 max_len = pathmax();
1228 if ((res = malloc(max_len)) == NULL) goto error;
1230 if (getcwd(res, max_len) == NULL) goto error;
1231 cwd_len = strlen(res);
1233 /* Make sure that the buffer is big enough */
1234 if (cwd_len + 1 + cfg_len >= max_len) goto error;
1237 memcpy(res + cwd_len + 1, cfg_file, cfg_len);
1239 res[cwd_len + 1 + cfg_len] = '\0'; /* Add terminating zero */
1244 fprintf(stderr, "ERROR: Unable to fix cfg_file to contain full pathname\n");
1255 struct socket_info* si;
1256 char si_desc[MAX_PT_DESC];
1263 /* one "main" process and n children handling i/o */
1269 LM_ERR("no fork mode requires at least one"
1270 " udp listen address, exiting...\n");
1273 /* only one address, we ignore all the others */
1274 if (udp_init(udp_listen)==-1) goto error;
1275 bind_address=udp_listen;
1276 if (bind_address->address.af==AF_INET) {
1277 sendipv4=bind_address;
1278 #ifdef USE_RAW_SOCKS
1279 /* always try to have a raw socket opened if we are using ipv4 */
1280 raw_udp4_send_sock = raw_socket(IPPROTO_RAW, 0, 0, 1);
1281 if (raw_udp4_send_sock < 0) {
1282 if ( default_core_cfg.udp4_raw > 0) {
1283 /* force use raw socket failed */
1284 ERR("could not initialize raw udp send socket (ipv4):"
1285 " %s (%d)\n", strerror(errno), errno);
1287 ERR("could not initialize raw socket on startup"
1288 " due to inadequate permissions, please"
1289 " restart as root or with CAP_NET_RAW\n");
1292 default_core_cfg.udp4_raw = 0; /* disabled */
1295 if (default_core_cfg.udp4_raw < 0) {
1296 /* auto-detect => use it */
1297 default_core_cfg.udp4_raw = 1; /* enabled */
1298 LM_DBG("raw socket possible => turning it on\n");
1300 if (default_core_cfg.udp4_raw_ttl < 0) {
1302 default_core_cfg.udp4_raw_ttl = sock_get_ttl(sendipv4->socket);
1303 if (default_core_cfg.udp4_raw_ttl < 0)
1304 /* error, use some default value */
1305 default_core_cfg.udp4_raw_ttl = 63;
1309 default_core_cfg.udp4_raw = 0;
1310 #endif /* USE_RAW_SOCKS */
1312 sendipv6=bind_address;
1313 if (udp_listen->next){
1314 LM_WARN("using only the first listen address (no fork)\n");
1317 /* delay cfg_shmize to the last moment (it must be called _before_
1318 forking). Changes to default cfgs after this point will be
1321 if (cfg_shmize() < 0) {
1322 LM_CRIT("could not initialize shared configuration\n");
1326 /* Register the children that will keep updating their
1327 * local configuration */
1329 1 /* main = udp listener */
1331 #ifdef USE_SLOW_TIMER
1332 + 1 /* slow timer */
1335 if (do_suid()==-1) goto error; /* try to drop privileges */
1336 /* process_no now initialized to zero -- increase from now on
1337 as new processes are forked (while skipping 0 reserved for main
1340 /* Temporary set the local configuration of the main process
1341 * to make the group instances available in PROC_INIT.
1343 cfg_main_set_local();
1345 /* init log prefix format */
1348 /* init childs with rank==PROC_INIT before forking any process,
1349 * this is a place for delayed (after mod_init) initializations
1350 * (e.g. shared vars that depend on the total number of processes
1351 * that is known only after all mod_inits have been executed )
1352 * WARNING: the same init_child will be called latter, a second time
1353 * for the "main" process with rank PROC_MAIN (make sure things are
1354 * not initialized twice)*/
1355 if (init_child(PROC_INIT) < 0) {
1356 LM_ERR("init_child(PROC_INT) -- exiting\n");
1357 cfg_main_reset_local();
1360 cfg_main_reset_local();
1361 if (counters_prefork_init(get_max_procs()) == -1) goto error;
1363 #ifdef USE_SLOW_TIMER
1364 /* we need another process to act as the "slow" timer*/
1365 pid = fork_process(PROC_TIMER, "slow timer", 0);
1367 LM_CRIT("Cannot fork\n");
1374 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1376 if (arm_slow_timer()<0) goto error;
1382 /* we need another process to act as the "main" timer*/
1383 pid = fork_process(PROC_TIMER, "timer", 0);
1385 LM_CRIT("Cannot fork\n");
1392 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1393 if (arm_timer()<0) goto error;
1398 if(sr_wtimer_start()<0) {
1399 LM_CRIT("Cannot start wtimer\n");
1402 /* main process, receive loop */
1403 process_no=0; /*main process number*/
1404 pt[process_no].pid=getpid();
1405 snprintf(pt[process_no].desc, MAX_PT_DESC,
1406 "stand-alone receiver @ %s:%s",
1407 bind_address->name.s, bind_address->port_no_str.s );
1409 /* call it also w/ PROC_MAIN to make sure modules that init things
1410 * only in PROC_MAIN get a chance to run */
1411 if (init_child(PROC_MAIN) < 0) {
1412 LM_ERR("init_child(PROC_MAIN) -- exiting\n");
1416 /* We will call child_init even if we
1417 * do not fork - and it will be called with rank 1 because
1418 * in fact we behave like a child, not like main process
1421 if (init_child(PROC_SIPINIT) < 0) {
1422 LM_ERR("init_child failed\n");
1425 return udp_rcv_loop();
1428 /* Register the children that will keep updating their
1429 * local configuration. (udp/tcp/sctp listeneres
1430 * will be added later.) */
1433 #ifdef USE_SLOW_TIMER
1434 + 1 /* slow timer */
1438 for(si=udp_listen;si;si=si->next){
1439 /* create the listening socket (for each address)*/
1441 if (udp_init(si)==-1) goto error;
1442 /* get first ipv4/ipv6 socket*/
1443 if ((si->address.af==AF_INET)&&
1444 ((sendipv4==0)||(sendipv4->flags&(SI_IS_LO|SI_IS_MCAST))))
1446 if ( ((sendipv6==0)||(sendipv6->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1447 (si->address.af==AF_INET6))
1449 /* children_no per each socket */
1450 cfg_register_child((si->workers>0)?si->workers:children_no);
1452 #ifdef USE_RAW_SOCKS
1453 /* always try to have a raw socket opened if we are using ipv4 */
1455 raw_udp4_send_sock = raw_socket(IPPROTO_RAW, 0, 0, 1);
1456 if (raw_udp4_send_sock < 0) {
1457 if ( default_core_cfg.udp4_raw > 0) {
1458 /* force use raw socket failed */
1459 ERR("could not initialize raw udp send socket (ipv4):"
1460 " %s (%d)\n", strerror(errno), errno);
1462 ERR("could not initialize raw socket on startup"
1463 " due to inadequate permissions, please"
1464 " restart as root or with CAP_NET_RAW\n");
1467 default_core_cfg.udp4_raw = 0; /* disabled */
1470 if (default_core_cfg.udp4_raw < 0) {
1471 /* auto-detect => use it */
1472 default_core_cfg.udp4_raw = 1; /* enabled */
1473 LM_DBG("raw socket possible => turning it on\n");
1475 if (default_core_cfg.udp4_raw_ttl < 0) {
1477 default_core_cfg.udp4_raw_ttl =
1478 sock_get_ttl(sendipv4->socket);
1479 if (default_core_cfg.udp4_raw_ttl < 0)
1480 /* error, use some default value */
1481 default_core_cfg.udp4_raw_ttl = 63;
1486 default_core_cfg.udp4_raw = 0;
1487 #endif /* USE_RAW_SOCKS */
1490 for(si=sctp_listen; si; si=si->next){
1491 if (sctp_core_init_sock(si)==-1) goto error;
1492 /* get first ipv4/ipv6 socket*/
1493 if ((si->address.af==AF_INET) &&
1494 ((sendipv4_sctp==0) ||
1495 (sendipv4_sctp->flags&(SI_IS_LO|SI_IS_MCAST))))
1497 if( ((sendipv6_sctp==0) ||
1498 (sendipv6_sctp->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1499 (si->address.af==AF_INET6))
1501 /* sctp_children_no per each socket */
1502 cfg_register_child((si->workers>0)?si->workers:sctp_children_no);
1505 #endif /* USE_SCTP */
1508 for(si=tcp_listen; si; si=si->next){
1509 /* same thing for tcp */
1510 if (tcp_init(si)==-1) goto error;
1511 /* get first ipv4/ipv6 socket*/
1512 if ((si->address.af==AF_INET)&&
1513 ((sendipv4_tcp==0) ||
1514 (sendipv4_tcp->flags&(SI_IS_LO|SI_IS_MCAST))))
1516 if( ((sendipv6_tcp==0) ||
1517 (sendipv6_tcp->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1518 (si->address.af==AF_INET6))
1521 /* the number of sockets does not matter */
1522 cfg_register_child(tcp_children_no + 1 /* tcp main */);
1525 if (!tls_disable && tls_has_init_si()){
1526 for(si=tls_listen; si; si=si->next){
1527 /* same as for tcp*/
1528 if (tls_init(si)==-1) goto error;
1529 /* get first ipv4/ipv6 socket*/
1530 if ((si->address.af==AF_INET)&&
1531 ((sendipv4_tls==0) ||
1532 (sendipv4_tls->flags&(SI_IS_LO|SI_IS_MCAST))))
1534 if( ((sendipv6_tls==0) ||
1535 (sendipv6_tls->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1536 (si->address.af==AF_INET6))
1540 #endif /* USE_TLS */
1541 #endif /* USE_TCP */
1543 /* all processes should have access to all the sockets (for
1544 * sending) so we open all first*/
1545 if (do_suid()==-1) goto error; /* try to drop privileges */
1547 /* delay cfg_shmize to the last moment (it must be called _before_
1548 forking). Changes to default cfgs after this point will be
1549 ignored (cfg_shmize() will copy the default cfgs into shmem).
1551 if (cfg_shmize() < 0) {
1552 LM_CRIT("could not initialize shared configuration\n");
1556 /* Temporary set the local configuration of the main process
1557 * to make the group instances available in PROC_INIT.
1559 cfg_main_set_local();
1561 /* init log prefix format */
1564 /* init childs with rank==PROC_INIT before forking any process,
1565 * this is a place for delayed (after mod_init) initializations
1566 * (e.g. shared vars that depend on the total number of processes
1567 * that is known only after all mod_inits have been executed )
1568 * WARNING: the same init_child will be called latter, a second time
1569 * for the "main" process with rank PROC_MAIN (make sure things are
1570 * not initialized twice)*/
1571 if (init_child(PROC_INIT) < 0) {
1572 LM_ERR("error in init_child(PROC_INT) -- exiting\n");
1573 cfg_main_reset_local();
1576 cfg_main_reset_local();
1577 if (counters_prefork_init(get_max_procs()) == -1) goto error;
1582 for(si=udp_listen; si; si=si->next){
1583 nrprocs = (si->workers>0)?si->workers:children_no;
1584 for(i=0;i<nrprocs;i++){
1585 if(si->address.af==AF_INET6) {
1586 if(si->useinfo.name.s)
1587 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1588 "sock=[%s]:%s (%s:%s)",
1589 i, si->name.s, si->port_no_str.s,
1590 si->useinfo.name.s, si->useinfo.port_no_str.s);
1592 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1594 i, si->name.s, si->port_no_str.s);
1596 if(si->useinfo.name.s)
1597 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1598 "sock=%s:%s (%s:%s)",
1599 i, si->name.s, si->port_no_str.s,
1600 si->useinfo.name.s, si->useinfo.port_no_str.s);
1602 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1604 i, si->name.s, si->port_no_str.s);
1607 pid = fork_process(child_rank, si_desc, 1);
1609 LM_CRIT("Cannot fork\n");
1613 bind_address=si; /* shortcut */
1615 setstats( i+r*children_no );
1618 if(run_child_one_init_route()<0)
1621 return udp_rcv_loop();
1626 /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
1629 /* sctp processes */
1631 for(si=sctp_listen; si; si=si->next){
1632 nrprocs = (si->workers>0)?si->workers:sctp_children_no;
1633 for(i=0;i<nrprocs;i++){
1634 if(si->address.af==AF_INET6) {
1635 snprintf(si_desc, MAX_PT_DESC, "sctp receiver child=%d "
1637 i, si->name.s, si->port_no_str.s);
1639 snprintf(si_desc, MAX_PT_DESC, "sctp receiver child=%d "
1641 i, si->name.s, si->port_no_str.s);
1644 pid = fork_process(child_rank, si_desc, 1);
1646 LM_CRIT("Cannot fork\n");
1650 bind_address=si; /* shortcut */
1652 setstats( i+r*children_no );
1654 return sctp_core_rcv_loop();
1658 /*close(sctp_sock)*/; /*if closed=>sendto invalid fd errors?*/
1661 #endif /* USE_SCTP */
1663 /*this is the main process*/
1664 bind_address=0; /* main proc -> it shouldn't send anything, */
1666 #ifdef USE_SLOW_TIMER
1667 /* fork again for the "slow" timer process*/
1668 pid = fork_process(PROC_TIMER, "slow timer", 1);
1670 LM_CRIT("cannot fork \"slow\" timer process\n");
1675 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1676 if (arm_slow_timer()<0) goto error;
1681 #endif /* USE_SLOW_TIMER */
1683 /* fork again for the "main" timer process*/
1684 pid = fork_process(PROC_TIMER, "timer", 1);
1686 LM_CRIT("cannot fork timer process\n");
1691 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1692 if (arm_timer()<0) goto error;
1695 if(sr_wtimer_start()<0) {
1696 LM_CRIT("Cannot start wtimer\n");
1700 /* init childs with rank==MAIN before starting tcp main (in case they want
1701 * to fork a tcp capable process, the corresponding tcp. comm. fds in
1702 * pt[] must be set before calling tcp_main_loop()) */
1703 if (init_child(PROC_MAIN) < 0) {
1704 LM_ERR("error in init_child\n");
1710 /* start tcp & tls receivers */
1711 if (tcp_init_children()<0) goto error;
1712 /* start tcp+tls master proc */
1713 pid = fork_process(PROC_TCP_MAIN, "tcp main process", 0);
1715 LM_CRIT("cannot fork tcp main process: %s\n", strerror(errno));
1727 strncpy(pt[0].desc, "main process - attendant", MAX_PT_DESC );
1729 close_extra_socks(PROC_ATTENDANT, get_proc_no());
1731 /* main's tcp sockets are disabled by default from init_pt() */
1735 /* init cfg, but without per child callbacks support */
1736 cfg_child_no_cb_init();
1740 for (r=0; r<*process_count; r++){
1741 fprintf(stderr, "% 3d % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1744 LM_DBG("Expect maximum %d open fds\n", get_max_open_fds());
1745 /* in daemonize mode send the exit code back to the parent process */
1746 if (!dont_daemonize) {
1747 if (daemon_status_send(0) < 0) {
1748 ERR("error sending daemon status: %s [%d]\n",
1749 strerror(errno), errno);
1763 /* if we are here, we are the "main process",
1764 any forked children should exit with exit(-1) and not
1771 * Calculate number of processes, this does not
1772 * include processes created by modules
1774 static int calc_proc_no(void)
1777 struct socket_info* si;
1780 int tcp_e_listeners;
1786 for (si=udp_listen, udp_listeners=0; si; si=si->next)
1787 udp_listeners += (si->workers>0)?si->workers:children_no;
1789 for (si=tcp_listen, tcp_listeners=0, tcp_e_listeners=0; si; si=si->next) {
1791 tcp_listeners += si->workers;
1793 tcp_e_listeners = tcp_cfg_children_no;
1795 tcp_listeners += tcp_e_listeners;
1797 tcp_e_listeners = 0;
1798 for (si=tls_listen, tcp_e_listeners=0; si; si=si->next) {
1800 tcp_listeners += si->workers;
1802 if(tcp_listeners==0)
1803 tcp_e_listeners = tcp_cfg_children_no;
1806 tcp_listeners += tcp_e_listeners;
1808 tcp_children_no = tcp_listeners;
1811 for (si=sctp_listen, sctp_listeners=0; si; si=si->next)
1812 sctp_listeners += (si->workers>0)?si->workers:sctp_children_no;
1815 /* receivers and attendant */
1816 (dont_fork ? 1 : udp_listeners + 1)
1818 + 1 /* always, we need it in most cases, and we can't tell here
1819 & now if we don't need it */
1820 #ifdef USE_SLOW_TIMER
1821 + 1 /* slow timer process */
1824 +((!tcp_disable)?( 1/* tcp main */ + tcp_listeners ):0)
1827 +((!sctp_disable)?sctp_listeners:0)
1832 int main(int argc, char** argv)
1845 int debug_save, debug_flag;
1847 struct name_lst* n_lst;
1849 struct stat st = {0};
1853 creator_pid = getpid();
1855 my_argc=argc; my_argv=argv;
1860 daemon_status_init();
1862 dprint_init_colors();
1864 /* command line options */
1865 options= ":f:cm:M:dVIhEeb:l:L:n:vKrRDTN:W:w:t:u:g:P:G:SQ:O:a:A:x:X:Y:"
1870 /* Handle special command line arguments, that must be treated before
1871 * intializing the various subsystem or before parsing other arguments:
1872 * - get the startup debug and log_stderr values
1873 * - look if pkg mem size is overriden on the command line (-M) and get
1874 * the new value here (before intializing pkg_mem).
1875 * - look if there is a -h, e.g. -f -h construction won't be caught
1879 while((c=getopt(argc,argv,options))!=-1) {
1883 default_core_cfg.debug++;
1892 pkg_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1894 fprintf(stderr, "bad private mem size number: -M %s\n",
1900 sr_memmng_shm = optarg;
1903 sr_memmng_pkg = optarg;
1906 if (c == 'h' || (optarg && strcmp(optarg, "-h") == 0)) {
1907 printf("version: %s\n", full_version);
1908 printf("%s",help_msg);
1915 if(sr_memmng_pkg==NULL) {
1916 if(sr_memmng_shm!=NULL) {
1917 sr_memmng_pkg = sr_memmng_shm;
1919 sr_memmng_pkg = SR_MEMMNG_DEFAULT;
1922 if(sr_memmng_shm==NULL) {
1923 sr_memmng_shm = SR_MEMMNG_DEFAULT;
1925 shm_set_mname(sr_memmng_shm);
1926 if (pkg_mem_size == 0) {
1927 pkg_mem_size = PKG_MEM_POOL_SIZE;
1930 /*init pkg mallocs (before parsing cfg or the rest of the cmd line !)*/
1932 LM_INFO("private (per process) memory: %ld bytes\n", pkg_mem_size );
1933 if (pkg_init_manager(sr_memmng_pkg)<0)
1937 fprintf(stderr, "WARNING: ser startup: "
1938 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1941 /* init counters / stats */
1942 if (init_counters() == -1)
1945 init_tcp_options(); /* set the defaults before the config */
1950 /* process command line (cfg. file path etc) */
1951 optind = 1; /* reset getopt */
1952 /* switches required before script processing */
1953 while((c=getopt(argc,argv,options))!=-1) {
1958 /* ignore, they were parsed immediately after startup */
1965 log_stderr=1; /* force stderr logging */
1972 shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1974 fprintf(stderr, "bad shmem size number: -m %s\n",
1978 LM_INFO("shared memory: %ld bytes\n", shm_mem_size );
1981 /* ignore it, was parsed immediately after startup */
1985 printf("version: %s\n", full_version);
1986 printf("flags: %s\n", ver_flags );
1987 print_ct_constants();
1988 printf("id: %s\n", ver_id);
1989 if(strlen(ver_compiled_time)>0)
1990 printf("compiled on %s with %s\n",
1991 ver_compiled_time, ver_compiler );
1993 printf("compiled with %s\n",
2003 /* ignore it, was parsed immediately after startup */
2006 /* ignore it, was parsed immediately after startup */
2009 scr_opt_lev=strtol(optarg, &tmp, 10);
2011 fprintf(stderr, "bad optimization level: -O %s\n",
2017 /* user needed for possible shm. pre-init */
2021 p = strchr(optarg, '=');
2025 pp_define_set_type(0);
2026 if(pp_define(strlen(optarg), optarg)<0) {
2027 fprintf(stderr, "error at define param: -A %s\n",
2034 if(pp_define_set(strlen(p), p)<0) {
2035 fprintf(stderr, "error at define value: -A %s\n",
2063 if (isprint(optopt)) {
2064 fprintf(stderr, "Unknown option `-%c'."
2065 " Use -h for help.\n", optopt);
2067 fprintf(stderr, "Unknown option character `\\x%x'."
2068 " Use -h for help.\n",
2073 fprintf(stderr, "Option `-%c' requires an argument."
2074 " Use -h for help.\n",
2081 if (shm_mem_size == 0) {
2082 shm_mem_size = SHM_MEM_POOL_SIZE;
2085 if (endianness_sanity_check() != 0){
2086 fprintf(stderr, "BUG: endianness sanity tests failed\n");
2089 if (init_routes()<0) goto error;
2090 if (init_nonsip_hooks()<0) goto error;
2091 if (init_script_cb()<0) goto error;
2092 if (pv_init_api()<0) goto error;
2093 if (pv_register_core_vars()!=0) goto error;
2094 if (init_rpcs()<0) goto error;
2095 if (register_core_rpcs()!=0) goto error;
2097 /* Fix the value of cfg_file variable.*/
2098 if (fix_cfg_file() < 0) goto error;
2100 /* load config file or die */
2101 if (cfg_file[0] == '-' && strlen(cfg_file)==1) {
2104 cfg_stream=fopen (cfg_file, "r");
2107 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
2113 /* try to use /dev/urandom if possible */
2115 if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
2117 if (read(rfd, (void*)&seed, sizeof(seed))==-1){
2118 if (errno==EINTR) goto try_again; /* interrupted by signal */
2119 LM_WARN("could not read from /dev/urandom (%d)\n", errno);
2121 LM_DBG("read %u from /dev/urandom\n", seed);
2124 LM_WARN("could not open /dev/urandom (%d)\n", errno);
2126 seed+=getpid()+time(0);
2127 LM_DBG("seeding PRNG with %u\n", seed);
2129 fastrand_seed(kam_rand());
2130 srandom(kam_rand()+time(0));
2131 LM_DBG("test random numbers %u %lu %u\n", kam_rand(), random(), fastrand());
2133 /*register builtin modules*/
2134 register_builtin_modules();
2136 /* init named flags */
2140 debug_save = default_core_cfg.debug;
2141 if ((yyparse()!=0)||(cfg_errors)){
2142 fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
2143 if (debug_flag) default_core_cfg.debug = debug_save;
2144 pp_ifdef_level_check();
2149 fprintf(stderr, "%d config warnings\n", cfg_warnings);
2151 if (debug_flag) default_core_cfg.debug = debug_save;
2152 pp_ifdef_level_check();
2155 if(init_dst_set()<0) {
2156 LM_ERR("failed to initialize destination set structure\n");
2159 /* options with higher priority than cfg file */
2160 optind = 1; /* reset getopt */
2161 while((c=getopt(argc,argv,options))!=-1) {
2176 log_stderr=1; /* use in both getopt switches,
2177 takes priority over config */
2180 log_color=1; /* use in both getopt switches,
2181 takes priority over config */
2184 maxbuffer=strtol(optarg, &tmp, 10);
2186 fprintf(stderr, "bad max buffer size number: -b %s\n",
2192 if ((n_lst=parse_phostport_mh(optarg, &tmp, &tmp_len,
2193 &port, &proto))==0){
2194 fprintf(stderr, "bad -l address specifier: %s\n",
2198 /* add a new addr. to our address list */
2199 if (add_listen_iface(n_lst->name, n_lst->next, port,
2200 proto, n_lst->flags)!=0){
2201 fprintf(stderr, "failed to add new listen address\n");
2202 free_name_lst(n_lst);
2205 free_name_lst(n_lst);
2208 children_no=strtol(optarg, &tmp, 10);
2209 if ((tmp==0) ||(*tmp)){
2210 fprintf(stderr, "bad process number: -n %s\n",
2219 received_dns|=DO_DNS;
2222 received_dns|=DO_REV_DNS;
2231 fprintf(stderr,"WARNING: tcp support not compiled in\n");
2236 tcp_cfg_children_no=strtol(optarg, &tmp, 10);
2237 if ((tmp==0) ||(*tmp)){
2238 fprintf(stderr, "bad process number: -N %s\n",
2243 fprintf(stderr,"WARNING: tcp support not compiled in\n");
2248 tcp_poll_method=get_poll_type(optarg);
2249 if (tcp_poll_method==POLL_NONE){
2250 fprintf(stderr, "bad poll method name: -W %s\ntry "
2251 "one of %s.\n", optarg, poll_support);
2255 fprintf(stderr,"WARNING: tcp support not compiled in\n");
2262 fprintf(stderr,"WARNING: sctp support not compiled in\n");
2267 sctp_children_no=strtol(optarg, &tmp, 10);
2268 if ((tmp==0) ||(*tmp)){
2269 fprintf(stderr, "bad process number: -O %s\n",
2274 fprintf(stderr,"WARNING: sctp support not compiled in\n");
2299 if(strcmp(optarg, "on")==0 || strcmp(optarg, "yes")==0)
2300 sr_auto_aliases = 1;
2301 else if(strcmp(optarg, "off")==0 || strcmp(optarg, "no")==0)
2302 sr_auto_aliases = 0;
2305 "bad auto aliases parameter: %s (valid on, off, yes, no)\n",
2320 /* reinit if pv buffer size has been set in config */
2321 if (pv_reinit_buffer()<0)
2324 if (ksr_route_locks_set_init()<0)
2327 /* init lookup for core event routes */
2331 dont_fork = dont_fork_cnt; /* override by command line */
2333 if (dont_fork > 0) {
2334 dont_daemonize = dont_fork == 2;
2335 dont_fork = dont_fork == 1;
2337 /* init locks first */
2338 if (init_lock_ops()!=0)
2343 tls_disable=1; /* if no tcp => no tls */
2344 #endif /* USE_TLS */
2345 #endif /* USE_TCP */
2347 if (sctp_disable!=1){
2349 if (sctp_core_check_support()==-1){
2350 /* check if sctp support is auto, if not warn about disabling it */
2351 if (sctp_disable!=2){
2352 fprintf(stderr, "ERROR: " "sctp enabled, but not supported by"
2358 /* sctp_disable!=1 and sctp supported => enable sctp */
2362 #endif /* USE_SCTP */
2363 /* initialize the configured proto list */
2365 /* init the resolver, before fixing the config */
2367 /* fix parameters */
2368 if (port_no<=0) port_no=SIP_PORT;
2370 if (tls_port_no<=0) tls_port_no=SIPS_PORT;
2374 if (children_no<=0) children_no=CHILD_NO;
2377 if (tcp_cfg_children_no<=0) tcp_cfg_children_no=children_no;
2378 tcp_children_no = tcp_cfg_children_no;
2383 if (sctp_children_no<=0) sctp_children_no=children_no;
2387 if (working_dir==0) working_dir="/";
2391 if (user2uid(&uid, &gid, user)<0){
2392 fprintf(stderr, "bad user name/uid number: -u %s\n", user);
2399 if (group2gid(&gid, group)<0){
2400 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
2405 /* create runtime dir if doesn't exist */
2406 if (stat(runtime_dir, &st) == -1) {
2407 if(mkdir(runtime_dir, 0700) == -1) {
2408 LM_ERR("failed to create runtime dir %s\n", runtime_dir);
2409 fprintf(stderr, "failed to create runtime dir %s\n", runtime_dir);
2412 if(sock_uid!=-1 || sock_gid!=-1) {
2413 if(chown(runtime_dir, sock_uid, sock_gid) == -1) {
2414 LM_ERR("failed to change owner of runtime dir %s\n", runtime_dir);
2415 fprintf(stderr, "failed to change owner of runtime dir %s\n", runtime_dir);
2420 if (fix_all_socket_lists()!=0){
2421 fprintf(stderr, "failed to initialize list addresses\n");
2424 if (default_core_cfg.dns_try_ipv6 && !(socket_types & SOCKET_T_IPV6)){
2425 /* if we are not listening on any ipv6 address => no point
2426 * to try to resovle ipv6 addresses */
2427 default_core_cfg.dns_try_ipv6=0;
2429 /* print all the listen addresses */
2430 printf("Listening on \n");
2431 print_all_socket_lists();
2432 printf("Aliases: \n");
2433 /*print_aliases();*/
2438 fprintf(stderr, "WARNING: no fork mode %s\n",
2440 (udp_listen->next)?"and more than one listen address found "
2441 "(will use only the first one)":""
2442 ):"and no udp listen address found" );
2445 fprintf(stderr, "config file ok, exiting...\n");
2452 * -to allow setting shm mem size from the command line
2453 * => if shm_mem should be settable from the cfg file move
2455 * -it must be also before init_timer and init_tcp
2456 * -it must be after we know uid (so that in the SYSV sems case,
2457 * the sems will have the correct euid)
2458 * Note: shm can now be initialized when parsing the config script, that's
2459 * why checking for a prior initialization is needed.
2462 if (!shm_initialized() && init_shm()<0)
2464 #endif /* SHM_MEM */
2465 pkg_print_manager();
2466 shm_print_manager();
2467 if (init_atomic_ops()==-1)
2469 if (init_basex() != 0){
2470 LM_CRIT("could not initialize base* framework\n");
2473 if (sr_cfg_init() < 0) {
2474 LM_CRIT("could not initialize configuration framework\n");
2477 /* declare the core cfg before the module configs */
2478 if (cfg_declare("core", core_cfg_def, &default_core_cfg, cfg_sizeof(core),
2481 LM_CRIT("could not declare the core configuration\n");
2485 if (tcp_register_cfg()){
2486 LM_CRIT("could not register the tcp configuration\n");
2489 #endif /* USE_TCP */
2490 /*init timer, before parsing the cfg!*/
2491 if (init_timer()<0){
2492 LM_CRIT("could not initialize timer, exiting...\n");
2496 if(sr_wtimer_init()<0) {
2497 LM_CRIT("could not initialize wtimer, exiting...\n");
2501 #ifdef USE_DNS_CACHE
2502 if (init_dns_cache()<0){
2503 LM_CRIT("could not initialize the dns cache, exiting...\n");
2506 #ifdef USE_DNS_CACHE_STATS
2507 /* preinitializing before the nubmer of processes is determined */
2508 if (init_dns_cache_stats(1)<0){
2509 LM_CRIT("could not initialize the dns cache measurement\n");
2512 #endif /* USE_DNS_CACHE_STATS */
2514 #ifdef USE_DST_BLACKLIST
2515 if (init_dst_blacklist()<0){
2516 LM_CRIT("could not initialize the dst blacklist, exiting...\n");
2519 #ifdef USE_DST_BLACKLIST_STATS
2520 /* preinitializing before the number of processes is determined */
2521 if (init_dst_blacklist_stats(1)<0){
2522 LM_CRIT("could not initialize the dst blacklist measurement\n");
2525 #endif /* USE_DST_BLACKLIST_STATS */
2527 if (init_avps()<0) goto error;
2528 if (rpc_init_time() < 0) goto error;
2534 LM_CRIT("could not initialize tcp, exiting...\n");
2538 #endif /* USE_TCP */
2541 if (sctp_core_init()<0){
2542 LM_CRIT("Could not initialize sctp, exiting...\n");
2546 #endif /* USE_SCTP */
2548 if( !dont_fork && daemonize((log_name==0)?argv[0]:log_name, 1) < 0)
2550 if (install_sigs() != 0){
2551 fprintf(stderr, "ERROR: could not install the signal handlers\n");
2555 if (disable_core_dump) set_core_dump(0, 0);
2556 else set_core_dump(1, shm_mem_size+pkg_mem_size+4*1024*1024);
2557 if (open_files_limit>0){
2558 if(increase_open_fds(open_files_limit)<0){
2559 fprintf(stderr, "ERROR: error could not increase file limits\n");
2567 set_rt_prio(rt_prio, rt_policy);
2573 LM_WARN("tls support enabled, but no tls engine "
2574 " available (forgot to load the tls module?)\n");
2575 LM_WARN("disabling tls...\n");
2578 if (pre_init_tls()<0){
2579 LM_CRIT("could not pre-initialize tls, exiting...\n");
2584 #endif /* USE_TLS */
2585 #endif /* USE_TCP */
2587 if (init_modules() != 0) {
2588 fprintf(stderr, "ERROR: error while initializing modules\n");
2592 /* initialize process_table, add core process no. (calc_proc_no()) to the
2593 * processes registered from the modules*/
2594 if (init_pt(calc_proc_no())==-1)
2600 LM_WARN("tls support enabled, but no tls engine "
2601 " available (forgot to load the tls module?)\n");
2602 LM_WARN("disabling tls...\n");
2607 LM_CRIT("could not initialize tls, exiting...\n");
2611 #endif /* USE_TLS */
2612 #endif /* USE_TCP */
2614 /* The total number of processes is now known, note that no
2615 * function being called before this point may rely on the
2616 * number of processes !
2618 LM_DBG("Expect (at least) %d kamailio processes in your process list\n",
2621 #if defined USE_DNS_CACHE && defined USE_DNS_CACHE_STATS
2622 if (init_dns_cache_stats(get_max_procs())<0){
2623 LM_CRIT("could not initialize the dns cache measurement\n");
2627 #if defined USE_DST_BLACKLIST && defined USE_DST_BLACKLIST_STATS
2628 if (init_dst_blacklist_stats(get_max_procs())<0){
2629 LM_CRIT("could not initialize the dst blacklist measurement\n");
2634 /* fix routing lists */
2635 if ( (r=fix_rls())!=0){
2636 fprintf(stderr, "error %d while trying to fix configuration\n", r);
2642 if (init_stats( dont_fork ? 1 : children_no )==-1) goto error;
2649 if (is_main) shutdown_children(SIGTERM, 0);
2650 if (!dont_daemonize) {
2651 if (daemon_status_send(0) < 0)
2652 fprintf(stderr, "error sending exit status: %s [%d]\n",
2653 strerror(errno), errno);
2655 /* else terminate process */
2660 if (is_main) shutdown_children(SIGTERM, 0);
2661 if (!dont_daemonize) {
2662 if (daemon_status_send((char)-1) < 0)
2663 fprintf(stderr, "error sending exit status: %s [%d]\n",
2664 strerror(errno), errno);