sipcapture: updated to the new mod interface
[sip-router] / src / main.c
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 #include <stdio.h>
34 #include <stdlib.h>
35 #include <errno.h>
36 #include <ctype.h>
37 #include <string.h>
38 #include <netdb.h>
39 #include <unistd.h>
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #if defined(HAVE_NETINET_IN_SYSTM)
43 #include <netinet/in_systm.h>
44 #endif
45 #include <netinet/in.h>
46 #include <netinet/ip.h>
47 #include <arpa/inet.h>
48 #include <sys/utsname.h>
49 #include <sys/stat.h>
50 #include <sys/mman.h>
51 #include <fcntl.h>
52 #include <sys/time.h>
53 #include <sys/wait.h>
54 #include <pwd.h>
55 #include <grp.h>
56 #include <signal.h>
57
58 #include <sys/ioctl.h>
59 #include <net/if.h>
60 #ifdef HAVE_SYS_SOCKIO_H
61 #include <sys/sockio.h>
62 #endif
63
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"
71 #ifdef SHM_MEM
72 #include "core/mem/shm_mem.h"
73 #include "core/shm_init.h"
74 #endif /* SHM_MEM */
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"
84 #include "core/pt.h"
85 #include "core/script_cb.h"
86 #include "core/nonsip_hooks.h"
87 #include "core/ut.h"
88 #include "core/events.h"
89 #include "core/signals.h"
90 #ifdef USE_RAW_SOCKS
91 #include "core/raw_sock.h"
92 #endif /* USE_RAW_SOCKS */
93 #ifdef USE_TCP
94 #include "core/poll_types.h"
95 #include "core/tcp_init.h"
96 #include "core/tcp_options.h"
97 #ifdef CORE_TLS
98 #include "core/tls/tls_init.h"
99 #define tls_has_init_si() 1
100 #define tls_loaded() 1
101 #else
102 #include "core/tls_hooks_init.h"
103 #endif /* CORE_TLS */
104 #endif /* USE_TCP */
105 #ifdef USE_SCTP
106 #include "core/sctp_core.h"
107 #endif
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"
114 #ifdef USE_DNS_CACHE
115 #include "core/dns_cache.h"
116 #endif
117 #ifdef USE_DST_BLACKLIST
118 #include "core/dst_blacklist.h"
119 #endif
120 #include "core/rand/fastrand.h" /* seed */
121 #include "core/rand/kam_rand.h"
122
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"
139
140 #ifdef DEBUG_DMALLOC
141 #include <dmalloc.h>
142 #endif
143 #include "core/ver.h"
144
145 /* define SIG_DEBUG by default */
146 #ifdef NO_SIG_DEBUG
147 #undef SIG_DEBUG
148 #else
149 #define SIG_DEBUG
150 #endif
151
152
153
154 static char help_msg[]= "\
155 Usage: " NAME " [options]\n\
156 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\
169                   (default: 8)\n\
170     -r           Use dns to check if is necessary to add a \"received=\"\n\
171                   field to a via\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\
180     -E           Log to stderr\n\
181     -e           Log messages printed in terminal colors (requires -E)\n"
182 #ifdef USE_TCP
183 "    -T           Disable tcp\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"
187 #endif
188 #ifdef USE_SCTP
189 "    -S           disable sctp\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"
214 #ifdef STATS
215 "    -s file     File where to write internal statistics on SIGUSR1\n"
216 #endif
217 ;
218
219
220 /* print compile-time constants */
221 void print_ct_constants(void)
222 {
223 #ifdef ADAPTIVE_WAIT
224         printf("ADAPTIVE_WAIT_LOOPS=%d, ", ADAPTIVE_WAIT_LOOPS);
225 #endif
226 /*
227 #ifdef SHM_MEM
228         printf("SHM_MEM_SIZE=%d, ", SHM_MEM_SIZE);
229 #endif
230 */
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);
235 #ifdef USE_TCP
236         printf("poll method support: %s.\n", poll_support);
237 #endif
238 }
239
240 /* print compile-time constants */
241 void print_internals(void)
242 {
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);
252 #ifdef SHM_MEM
253         printf("  DEFAULT SHM_SIZE=%uMB\n", SHM_MEM_SIZE);
254 #endif
255 #ifdef ADAPTIVE_WAIT
256         printf("  ADAPTIVE_WAIT_LOOPS=%d\n", ADAPTIVE_WAIT_LOOPS);
257 #endif
258 #ifdef USE_TCP
259         printf("  TCP poll methods: %s\n", poll_support);
260 #endif
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);
265 }
266
267 /* debugging function */
268 /*
269 void receive_stdin_loop(void)
270 {
271         #define BSIZE 1024
272         char buf[BSIZE+1];
273         int len;
274
275         while(1){
276                 len=fread(buf,1,BSIZE,stdin);
277                 buf[len+1]=0;
278                 receive_msg(buf, len);
279                 printf("-------------------------\n");
280         }
281 }
282 */
283
284 /* global vars */
285
286 int own_pgid = 0; /* whether or not we have our own pgid (and it's ok
287                                          to use kill(0, sig) */
288
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*/
291
292 char* cfg_file = 0;
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
296                                                                                                   be re-configured */
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 */
302 #ifdef USE_TCP
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 */
306 #endif
307 #ifdef USE_TLS
308 #ifdef  CORE_TLS
309 int tls_disable = 0;  /* tls enabled by default */
310 #else
311 int tls_disable = 1;  /* tls disabled by default */
312 #endif /* CORE_TLS */
313 #endif /* USE_TLS */
314 #ifdef USE_SCTP
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 */
318
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
322                                                                    running */
323 gen_lock_t* process_lock;               /* lock on the process table */
324 int process_no = 0;                             /* index of process in the pt */
325
326 time_t up_since;
327 int sig_flag = 0;              /* last signal received */
328 int dont_fork = 0;
329 int dont_daemonize = 0;
330 int log_stderr = 0;
331 int log_color = 0;
332 /* set custom app name for syslog printing */
333 char *log_name = 0;
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 */
338 int check_via =  0;
339 /* translate user=phone URIs to TEL URIs */
340 int phone2tel = 1;
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
345 */
346 int sip_warning = 0;
347 /* should localy-generated messages include server's signature?
348    be default yes, good for trouble-shooting
349 */
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
356  */
357 int mhomed=0;
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;
366 char* user=0;
367 char* group=0;
368 int uid = 0;
369 int gid = 0;
370 char* sock_user=0;
371 char* sock_group=0;
372 int sock_uid= -1;
373 int sock_gid= -1;
374 int sock_mode= S_IRUSR| S_IWUSR| S_IRGRP| S_IWGRP; /* rw-rw---- */
375
376 int server_id = 0; /* Configurable unique ID of the server */
377
378 /* maximum number of branches for transaction */
379 unsigned int sr_dst_max_branches = MAX_BRANCHES_DEFAULT;
380
381 /* set timeval for each received sip message */
382 int sr_msg_time = 1;
383
384 /* onsend_route is executed for replies*/
385 int onsend_route_reply = 0;
386
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 */
390
391 /* memory options */
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 */
396
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) */
400 int rt_prio=0;
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 */
406
407
408 /* a hint to reply modules whether they should send reply
409    to IP advertised in Via or IP from which a request came
410 */
411 int reply_to_via=0;
412
413 #ifdef USE_MCAST
414 int mcast_loopback = 0;
415 int mcast_ttl = -1; /* if -1, don't touch it, use the default (usually 1) */
416 char* mcast = 0;
417 #endif /* USE_MCAST */
418
419 int tos = IPTOS_LOWDELAY;
420 int pmtu_discovery = 0;
421
422 int auto_bind_ipv6 = 0;
423
424 struct socket_info* udp_listen=0;
425 #ifdef USE_TCP
426 int tcp_main_pid=0; /* set after the tcp main process is started */
427 struct socket_info* tcp_listen=0;
428 #endif
429 #ifdef USE_TLS
430 struct socket_info* tls_listen=0;
431 #endif
432 #ifdef USE_SCTP
433 struct socket_info* sctp_listen=0;
434 #endif
435 struct socket_info* bind_address=0; /* pointer to the crt. proc.
436                                                                          listening address*/
437 struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
438 struct socket_info* sendipv6; /* same as above for ipv6 */
439 #ifdef USE_RAW_SOCKS
440 int raw_udp4_send_sock = -1; /* raw socket used for sending udp4 packets */
441 #endif /* USE_RAW_SOCKS */
442 #ifdef USE_TCP
443 struct socket_info* sendipv4_tcp;
444 struct socket_info* sendipv6_tcp;
445 #endif
446 #ifdef USE_TLS
447 struct socket_info* sendipv4_tls;
448 struct socket_info* sendipv6_tls;
449 #endif
450 #ifdef USE_SCTP
451 struct socket_info* sendipv4_sctp;
452 struct socket_info* sendipv6_sctp;
453 #endif
454
455 unsigned short port_no=0; /* default port*/
456 #ifdef USE_TLS
457 unsigned short tls_port_no=0; /* default port */
458 #endif
459
460 struct host_alias* aliases=0; /* name aliases list */
461
462 /* Parameter to child_init */
463 int child_rank = 0;
464
465 /* how much to wait for children to terminate, before taking extreme measures*/
466 int ser_kill_timeout=DEFAULT_SER_KILL_TIMEOUT;
467
468 int ksr_verbose_startup = 0;
469
470 /* cfg parsing */
471 int cfg_errors=0;
472 int cfg_warnings=0;
473
474
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;
479
480 /* export command-line to anywhere else */
481 int my_argc;
482 char **my_argv;
483
484 /* set to 1 when the cfg framework and core cfg is initialized/registered */
485 static int cfg_ok=0;
486
487 #define MAX_FD 32 /* maximum number of inherited open file descriptors,
488                     (normally it shouldn't  be bigger  than 3) */
489
490
491 extern FILE* yyin;
492 extern int yyparse(void);
493
494
495 int is_main=1; /* flag = is this the  "main" process? */
496 int fixup_complete=0; /* flag = is the fixup complete ? */
497
498 char* pid_file = 0; /* filename as asked by use */
499 char* pgid_file = 0;
500
501
502 /* memory manager */
503 #define SR_MEMMNG_DEFAULT       "qm"
504
505 char *sr_memmng_pkg = NULL;
506 char *sr_memmng_shm = NULL;
507
508 /* call it before exiting; if show_status==1, mem status is displayed */
509 void cleanup(int show_status)
510 {
511         int memlog;
512
513         /*clean-up*/
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 */
518                 shm_global_unlock();
519         }
520 #endif
521         destroy_rpcs();
522         destroy_modules();
523 #ifdef USE_DNS_CACHE
524         destroy_dns_cache();
525 #endif
526 #ifdef USE_DST_BLACKLIST
527         destroy_dst_blacklist();
528 #endif
529         /* restore the original core configuration before the
530          * config block is freed, otherwise even logging is unusable,
531          * it can case segfault */
532         if (cfg_ok){
533                 cfg_update();
534                 /* copy current config into default_core_cfg */
535                 if (core_cfg)
536                         default_core_cfg=*((struct cfg_group_core*)core_cfg);
537         }
538         core_cfg = &default_core_cfg;
539         cfg_destroy();
540 #ifdef USE_TCP
541         destroy_tcp();
542 #ifdef USE_TLS
543         destroy_tls();
544 #endif /* USE_TLS */
545 #endif /* USE_TCP */
546 #ifdef USE_SCTP
547         sctp_core_destroy();
548 #endif
549         destroy_timer();
550         pv_destroy_api();
551         ksr_route_locks_set_destroy();
552         destroy_script_cb();
553         destroy_nonsip_hooks();
554         destroy_routes();
555         destroy_atomic_ops();
556         destroy_counters();
557         memlog=cfg_get(core, core_cfg, memlog);
558 #ifdef PKG_MALLOC
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");
562                         pkg_status();
563                 }
564                 if (cfg_get(core, core_cfg, mem_summary) & 4) {
565                         LOG(memlog, "Memory still-in-use summary (pkg):\n");
566                         pkg_sums();
567                 }
568         }
569 #endif
570 #ifdef SHM_MEM
571         if (pt) shm_free(pt);
572         pt=0;
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");
576                         shm_status();
577                 }
578                 if (cfg_get(core, core_cfg, mem_summary) & 8) {
579                         LOG(memlog, "Memory still-in-use summary (shm):\n");
580                         shm_sums();
581                 }
582         }
583         /* zero all shmem alloc vars that we still use */
584         shm_destroy_manager();
585 #endif
586         destroy_lock_ops();
587         if (pid_file) unlink(pid_file);
588         if (pgid_file) unlink(pgid_file);
589         pkg_destroy_manager();
590 }
591
592
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)
606 {
607         int r;
608
609         if (own_pgid) kill(0, signum);
610         else if (pt){
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)
614                   */
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 */
618                         if (pt[r].pid) {
619                                 kill(pt[r].pid, signum);
620                         }
621                         else LM_CRIT("killing: %s > %d no pid!!!\n",
622                                                         pt[r].desc, pt[r].pid);
623                 }
624                 if (!is_main) lock_release(process_lock);
625         }
626 }
627
628
629
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)
633 {
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
638                                                                    of cores) */
639 }
640
641
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)
645 {
646         /* LOG is not signal safe, but who cares, we are abort-ing anyway :-) */
647         LM_CRIT("shutdown timeout triggered, dying...");
648         abort();
649 }
650
651
652
653 static void shutdown_children(int sig, int show_status)
654 {
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 */
660         }
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*/
666         alarm(0);
667         set_sig_h(SIGALRM, SIG_IGN);
668 }
669
670
671
672 void handle_sigs(void)
673 {
674         pid_t   chld;
675         int     chld_status;
676         int     any_chld_stopped;
677         int memlog;
678
679         switch(sig_flag){
680                 case 0: break; /* do nothing*/
681                 case SIGPIPE:
682                                 /* SIGPIPE might be rarely received on use of
683                                    exec module; simply ignore it
684                                  */
685                                 LM_WARN("SIGPIPE received and ignored\n");
686                                 break;
687                 case SIGINT:
688                 case SIGTERM:
689                         /* we end the program in all these cases */
690                         if (sig_flag==SIGINT)
691                                 LM_DBG("INT received, program terminates\n");
692                         else
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);
697                         exit(0);
698                         break;
699
700                 case SIGUSR1:
701 #ifdef STATS
702                         dump_all_statistic();
703 #endif
704                 memlog=cfg_get(core, core_cfg, memlog);
705 #ifdef PKG_MALLOC
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");
709                                 pkg_status();
710                         }
711                         if (cfg_get(core, core_cfg, mem_summary) & 4) {
712                                 LOG(memlog, "Memory still-in-use summary (pkg):\n");
713                                 pkg_sums();
714                         }
715                 }
716 #endif
717 #ifdef SHM_MEM
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");
721                                 shm_status();
722                         }
723                         if (cfg_get(core, core_cfg, mem_summary) & 8) {
724                                 LOG(memlog, "Memory still-in-use summary (shm):\n");
725                                 shm_sums();
726                         }
727                 }
728 #endif
729                         break;
730
731                 case SIGCHLD:
732                         any_chld_stopped=0;
733                         while ((chld=waitpid( -1, &chld_status, WNOHANG ))>0) {
734                                 any_chld_stopped=1;
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));
742 #ifdef WCOREDUMP
743                                         LM_ALERT("core was %sgenerated\n",
744                                                          WCOREDUMP(chld_status) ?  "" : "not " );
745 #endif
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));
750                         }
751
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");
758                                 break;
759                         }
760
761 #ifndef STOP_JIRIS_CHANGES
762                         if (dont_fork) {
763                                 LM_INFO("dont_fork turned on, living on\n");
764                                 break;
765                         }
766                         LM_INFO("terminating due to SIGCHLD\n");
767 #endif
768                         LM_DBG("terminating due to SIGCHLD\n");
769                         /* exit */
770                         shutdown_children(SIGTERM, 1);
771                         if (WIFSIGNALED(chld_status)) {
772                                 exit(1);
773                         } else {
774                                 exit(0);
775                         }
776                         break;
777
778                 case SIGHUP: /* ignoring it*/
779                                         LM_DBG("SIGHUP received, ignoring it\n");
780                                         break;
781                 default:
782                         LM_CRIT("unhandled signal %d\n", sig_flag);
783         }
784         sig_flag=0;
785 }
786
787
788
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
794 */
795 void sig_usr(int signo)
796 {
797
798 #ifdef PKG_MALLOC
799         int memlog;
800 #endif
801
802         if (is_main){
803                 if (sig_flag==0) sig_flag=signo;
804                 else /*  previous sig. not processed yet, ignoring? */
805                         return; ;
806                 if (dont_fork)
807                                 /* only one proc, doing everything from the sig handler,
808                                 unsafe, but this is only for debugging mode*/
809                         handle_sigs();
810         }else{
811                 /* process the important signals */
812                 switch(signo){
813                         case SIGPIPE:
814 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
815                                         LM_INFO("signal %d received\n", signo);
816 #endif
817                                 break;
818                         case SIGINT:
819                         case SIGTERM:
820 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
821                                         LM_INFO("signal %d received\n", signo);
822                                         /* print memory stats for non-main too */
823                                         #ifdef PKG_MALLOC
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
827                                           config support */
828                                         cfg_update_no_cbs();
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");
833                                                         pkg_status();
834                                                 }
835                                                 if (cfg_get(core, core_cfg, mem_summary) & 4) {
836                                                         LOG(memlog, "Memory still-in-use summary (pkg):"
837                                                                         "\n");
838                                                         pkg_sums();
839                                                 }
840                                         }
841                                         #endif
842 #endif
843                                         _exit(0);
844                                         break;
845                         case SIGUSR1:
846 #ifdef PKG_MALLOC
847                                         cfg_update_no_cbs();
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");
852                                                         pkg_status();
853                                                 }
854                                                 if (cfg_get(core, core_cfg, mem_summary) & 4) {
855                                                         LOG(memlog, "Memory still-in-use summary (pkg):\n");
856                                                         pkg_sums();
857                                                 }
858                                         }
859 #endif
860                                         break;
861                                 /* ignored*/
862                         case SIGUSR2:
863                         case SIGHUP:
864                                         break;
865                         case SIGCHLD:
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");
870 #endif
871 #else
872                                         _exit(0); /* terminate if one child died */
873 #endif
874                                         break;
875                 }
876         }
877 }
878
879
880
881 /* install the signal handlers, returns 0 on success, -1 on error */
882 int install_sigs(void)
883 {
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");
887                 goto error;
888         }
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");
892                 goto error;
893         }
894         if (set_sig_h(SIGUSR1, sig_usr)  == SIG_ERR ) {
895                 ERR("no SIGUSR1 signal handler can be installed\n");
896                 goto error;
897         }
898         if (set_sig_h(SIGCHLD , sig_usr)  == SIG_ERR ) {
899                 ERR("no SIGCHLD signal handler can be installed\n");
900                 goto error;
901         }
902         if (set_sig_h(SIGTERM , sig_usr)  == SIG_ERR ) {
903                 ERR("no SIGTERM signal handler can be installed\n");
904                 goto error;
905         }
906         if (set_sig_h(SIGHUP , sig_usr)  == SIG_ERR ) {
907                 ERR("no SIGHUP signal handler can be installed\n");
908                 goto error;
909         }
910         if (set_sig_h(SIGUSR2 , sig_usr)  == SIG_ERR ) {
911                 ERR("no SIGUSR2 signal handler can be installed\n");
912                 goto error;
913         }
914         return 0;
915 error:
916         return -1;
917 }
918
919 /* returns -1 on error, 0 on success
920  * sets proto */
921 int parse_proto(unsigned char* s, long len, int* proto)
922 {
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))) \
930                                                                   )| 0x20202020 )
931         unsigned int i;
932         if (likely(len==3)){
933                 i=PROTO2UINT3(s[0], s[1], s[2]);
934                 switch(i){
935                         case PROTO2UINT3('u', 'd', 'p'):
936                                 *proto=PROTO_UDP;
937                                 break;
938 #ifdef USE_TCP
939                         case PROTO2UINT3('t', 'c', 'p'):
940                                 *proto=PROTO_TCP;
941                                 break;
942 #ifdef USE_TLS
943                         case PROTO2UINT3('t', 'l', 's'):
944                                 *proto=PROTO_TLS;
945                                 break;
946 #endif
947 #endif
948                         default:
949                                 return -1;
950                 }
951         }
952 #ifdef USE_SCTP
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'))
956                         *proto=PROTO_SCTP;
957                 else
958                         return -1;
959         }
960 #endif /* USE_SCTP */
961         else
962         /* Deliberately leaving out PROTO_WS and PROTO_WSS as these are just
963            upgraded TCP/TLS connections. */
964                 return -1;
965         return 0;
966 }
967
968
969
970 static struct name_lst* mk_name_lst_elem(char* name, int name_len, int flags)
971 {
972         struct name_lst* l;
973         
974         l=pkg_malloc(sizeof(struct name_lst)+name_len+1/* 0 */);
975         if (l){
976                 l->name=((char*)l)+sizeof(struct name_lst);
977                 memcpy(l->name, name, name_len);
978                 l->name[name_len]=0;
979                 l->flags=flags;
980                 l->next=0;
981         }
982         return l;
983 }
984
985
986
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)
990 {
991         struct name_lst* l;
992         
993         while(lst){
994                 l=lst;
995                 lst=lst->next;
996                 pkg_free(l);
997         }
998 }
999
1000
1001
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)"
1007  *                   "(hostname)"
1008  */
1009 static struct name_lst* parse_name_lst(char* h, int h_len)
1010 {
1011         char* last;
1012         char* p;
1013         struct name_lst* n_lst;
1014         struct name_lst* l;
1015         struct name_lst** tail;
1016         int flags;
1017         
1018         n_lst=0;
1019         tail=&n_lst;
1020         last=h+h_len-1;
1021         flags=0;
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;
1027         
1028         if (*h=='('){
1029                 /* list mode */
1030                 if (*last!=')' || ((h+1)>(last-1)))
1031                         goto error;
1032                 h++;
1033                 last--;
1034                 flags=SI_IS_MHOMED;
1035                 for(p=h; p<=last; p++)
1036                         switch (*p){
1037                                 case ',':
1038                                 case ';':
1039                                 case ' ':
1040                                 case '\t':
1041                                         if ((int)(p-h)>0){
1042                                                 l=mk_name_lst_elem(h, (int)(p-h), flags);
1043                                                 if (l==0) 
1044                                                         goto error;
1045                                                 *tail=l;
1046                                                 tail=&l->next;
1047                                         }
1048                                         h=p+1;
1049                                         break;
1050                         }
1051         }else{
1052                 /* single addr. mode */
1053                 flags=0;
1054                 p=last+1;
1055         }
1056         if ((int)(p-h)>0){
1057                 l=mk_name_lst_elem(h, (int)(p-h), flags);
1058                 if (l==0) 
1059                         goto error;
1060                 *tail=l;
1061                 tail=&l->next;
1062         }
1063         return n_lst;
1064 error:
1065         if (n_lst) free_name_lst(n_lst);
1066         return 0;
1067 }
1068
1069
1070
1071 /*
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
1077  */
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
1089  *                if it's not.
1090  * @return  fills proto, port, host and returns 0 on success and -1 on failure.
1091  */
1092 int parse_phostport(char* s, char** host, int* hlen,
1093                                                                  int* port, int* proto)
1094 {
1095         char* first; /* first ':' occurrence */
1096         char* second; /* second ':' occurrence */
1097         char* p;
1098         int bracket;
1099         char* tmp;
1100
1101         first=second=0;
1102         bracket=0;
1103
1104         /* find the first 2 ':', ignoring possible ipv6 addresses
1105          * (substrings between [])
1106          */
1107         for(p=s; *p; p++){
1108                 switch(*p){
1109                         case '[':
1110                                 bracket++;
1111                                 if (bracket>1) goto error_brackets;
1112                                 break;
1113                         case ']':
1114                                 bracket--;
1115                                 if (bracket<0) goto error_brackets;
1116                                 break;
1117                         case ':':
1118                                 if (bracket==0){
1119                                         if (first==0) first=p;
1120                                         else if( second==0) second=p;
1121                                         else goto error_colons;
1122                                 }
1123                                 break;
1124                 }
1125         }
1126         if (p==s) return -1;
1127         if (*(p-1)==':') goto error_colons;
1128
1129         if (first==0){ /* no ':' => only host */
1130                 *host=s;
1131                 *hlen=(int)(p-s);
1132                 *port=0;
1133                 *proto=0;
1134                 goto end;
1135         }
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;
1140                 *host=first+1;
1141                 *hlen=(int)(second-*host);
1142                 goto end;
1143         }
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;
1149                 *port=0;
1150                 *host=first+1;
1151                 *hlen=(int)(p-*host);
1152         }else{
1153                 /* valid port => its host:port */
1154                 *proto=0;
1155                 *host=s;
1156                 *hlen=(int)(first-*host);
1157         }
1158 end:
1159         return 0;
1160 error_brackets:
1161         LM_ERR("too many brackets in %s\n", s);
1162         return -1;
1163 error_colons:
1164         LM_ERR("too many colons in %s\n", s);
1165         return -1;
1166 error_proto:
1167         LM_ERR("bad protocol in %s\n", s);
1168         return -1;
1169 error_port:
1170         LM_ERR("bad port number in %s\n", s);
1171         return -1;
1172 }
1173
1174
1175
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
1187  *                if it's not.
1188  * @return  fills proto, port, host and returns list of addresses on success
1189  * (pkg malloc'ed) and 0 on failure
1190  */
1191 static struct name_lst* parse_phostport_mh(char* s, char** host, int* hlen,
1192                                                                  int* port, int* proto)
1193 {
1194         if (parse_phostport(s, host, hlen, port, proto)==0)
1195                 return parse_name_lst(*host, *hlen);
1196         return 0;
1197 }
1198
1199
1200
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
1211  * on error.
1212  */
1213 int fix_cfg_file(void)
1214 {
1215         char* res = NULL;
1216         size_t max_len, cwd_len, cfg_len;
1217         
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;
1221         
1222         /* cfg_file contains a relative pathname, get the current
1223          * working directory and add it at the beginning
1224          */
1225         cfg_len = strlen(cfg_file);
1226         
1227         max_len = pathmax();
1228         if ((res = malloc(max_len)) == NULL) goto error;
1229         
1230         if (getcwd(res, max_len) == NULL) goto error;
1231         cwd_len = strlen(res);
1232         
1233         /* Make sure that the buffer is big enough */
1234         if (cwd_len + 1 + cfg_len >= max_len) goto error;
1235         
1236         res[cwd_len] = '/';
1237         memcpy(res + cwd_len + 1, cfg_file, cfg_len);
1238         
1239         res[cwd_len + 1 + cfg_len] = '\0'; /* Add terminating zero */
1240         cfg_file = res;
1241         return 0;
1242         
1243  error:
1244         fprintf(stderr, "ERROR: Unable to fix cfg_file to contain full pathname\n");
1245         if (res) free(res);
1246         return -1;
1247 }
1248
1249
1250 /* main loop */
1251 int main_loop(void)
1252 {
1253         int  i;
1254         pid_t pid;
1255         struct socket_info* si;
1256         char si_desc[MAX_PT_DESC];
1257 #ifdef EXTRA_DEBUG
1258         int r;
1259 #endif
1260         int nrprocs;
1261         int woneinit;
1262
1263         /* one "main" process and n children handling i/o */
1264         if (dont_fork){
1265 #ifdef STATS
1266                 setstats( 0 );
1267 #endif
1268                 if (udp_listen==0){
1269                         LM_ERR("no fork mode requires at least one"
1270                                         " udp listen address, exiting...\n");
1271                         goto error;
1272                 }
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);
1286                                 if (errno == EPERM)
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");
1290                                 goto error;
1291                         }
1292                         default_core_cfg.udp4_raw = 0; /* disabled */
1293                 } else {
1294                         register_fds(1);
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");
1299                         }
1300                         if (default_core_cfg.udp4_raw_ttl < 0) {
1301                                 /* auto-detect */
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;
1306                         }
1307                 }
1308 #else
1309                 default_core_cfg.udp4_raw = 0;
1310 #endif /* USE_RAW_SOCKS */
1311                 } else
1312                         sendipv6=bind_address;
1313                 if (udp_listen->next){
1314                         LM_WARN("using only the first listen address (no fork)\n");
1315                 }
1316
1317                 /* delay cfg_shmize to the last moment (it must be called _before_
1318                    forking). Changes to default cfgs after this point will be
1319                    ignored.
1320                 */
1321                 if (cfg_shmize() < 0) {
1322                         LM_CRIT("could not initialize shared configuration\n");
1323                         goto error;
1324                 }
1325
1326                 /* Register the children that will keep updating their
1327                  * local configuration */
1328                 cfg_register_child(
1329                                 1   /* main = udp listener */
1330                                 + 1 /* timer */
1331 #ifdef USE_SLOW_TIMER
1332                                 + 1 /* slow timer */
1333 #endif
1334                         );
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
1338                 */
1339
1340                 /* Temporary set the local configuration of the main process
1341                  * to make the group instances available in PROC_INIT.
1342                  */
1343                 cfg_main_set_local();
1344
1345                 /* init log prefix format */
1346                 log_prefix_init();
1347
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();
1358                         goto error;
1359                 }
1360                 cfg_main_reset_local();
1361                 if (counters_prefork_init(get_max_procs()) == -1) goto error;
1362
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);
1366                                 if (pid<0){
1367                                         LM_CRIT("Cannot fork\n");
1368                                         goto error;
1369                                 }
1370                                 if (pid==0){
1371                                         /* child */
1372                                         /* timer!*/
1373                                         if (real_time&2)
1374                                                 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1375
1376                                         if (arm_slow_timer()<0) goto error;
1377                                         slow_timer_main();
1378                                 }else{
1379                                         slow_timer_pid=pid;
1380                                 }
1381 #endif
1382                                 /* we need another process to act as the "main" timer*/
1383                                 pid = fork_process(PROC_TIMER, "timer", 0);
1384                                 if (pid<0){
1385                                         LM_CRIT("Cannot fork\n");
1386                                         goto error;
1387                                 }
1388                                 if (pid==0){
1389                                         /* child */
1390                                         /* timer!*/
1391                                         if (real_time&1)
1392                                                 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1393                                         if (arm_timer()<0) goto error;
1394                                         timer_main();
1395                                 }else{
1396                                 }
1397
1398                 if(sr_wtimer_start()<0) {
1399                         LM_CRIT("Cannot start wtimer\n");
1400                         goto error;
1401                 }
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 );
1408
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");
1413                         goto error;
1414                 }
1415
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
1419                  */
1420
1421                 if (init_child(PROC_SIPINIT) < 0) {
1422                         LM_ERR("init_child failed\n");
1423                         goto error;
1424                 }
1425                 return udp_rcv_loop();
1426         }else{ /* fork: */
1427
1428                 /* Register the children that will keep updating their
1429                  * local configuration. (udp/tcp/sctp listeneres
1430                  * will be added later.) */
1431                 cfg_register_child(
1432                                 1   /* timer */
1433 #ifdef USE_SLOW_TIMER
1434                                 + 1 /* slow timer */
1435 #endif
1436                         );
1437
1438                 for(si=udp_listen;si;si=si->next){
1439                         /* create the listening socket (for each address)*/
1440                         /* udp */
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))))
1445                                 sendipv4=si;
1446                         if ( ((sendipv6==0)||(sendipv6->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1447                                         (si->address.af==AF_INET6))
1448                                 sendipv6=si;
1449                         /* children_no per each socket */
1450                         cfg_register_child((si->workers>0)?si->workers:children_no);
1451                 }
1452 #ifdef USE_RAW_SOCKS
1453                 /* always try to have a raw socket opened if we are using ipv4 */
1454                 if (sendipv4) {
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);
1461                                                 if (errno == EPERM)
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");
1465                                                 goto error;
1466                                         }
1467                                         default_core_cfg.udp4_raw = 0; /* disabled */
1468                         } else {
1469                                 register_fds(1);
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");
1474                                 }
1475                                 if (default_core_cfg.udp4_raw_ttl < 0) {
1476                                         /* auto-detect */
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;
1482                                 }
1483                         }
1484                 }
1485 #else
1486                 default_core_cfg.udp4_raw = 0;
1487 #endif /* USE_RAW_SOCKS */
1488 #ifdef USE_SCTP
1489                 if (!sctp_disable){
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))))
1496                                         sendipv4_sctp=si;
1497                                 if( ((sendipv6_sctp==0) || 
1498                                                         (sendipv6_sctp->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1499                                                 (si->address.af==AF_INET6))
1500                                         sendipv6_sctp=si;
1501                                 /* sctp_children_no per each socket */
1502                                 cfg_register_child((si->workers>0)?si->workers:sctp_children_no);
1503                         }
1504                 }
1505 #endif /* USE_SCTP */
1506 #ifdef USE_TCP
1507                 if (!tcp_disable){
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))))
1515                                         sendipv4_tcp=si;
1516                                 if( ((sendipv6_tcp==0) ||
1517                                                         (sendipv6_tcp->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1518                                                 (si->address.af==AF_INET6))
1519                                         sendipv6_tcp=si;
1520                         }
1521                         /* the number of sockets does not matter */
1522                         cfg_register_child(tcp_children_no + 1 /* tcp main */);
1523                 }
1524 #ifdef USE_TLS
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))))
1533                                         sendipv4_tls=si;
1534                                 if( ((sendipv6_tls==0) ||
1535                                                         (sendipv6_tls->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1536                                                 (si->address.af==AF_INET6))
1537                                         sendipv6_tls=si;
1538                         }
1539                 }
1540 #endif /* USE_TLS */
1541 #endif /* USE_TCP */
1542
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 */
1546
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).
1550                 */
1551                 if (cfg_shmize() < 0) {
1552                         LM_CRIT("could not initialize shared configuration\n");
1553                         goto error;
1554                 }
1555
1556                 /* Temporary set the local configuration of the main process
1557                  * to make the group instances available in PROC_INIT.
1558                  */
1559                 cfg_main_set_local();
1560
1561                 /* init log prefix format */
1562                 log_prefix_init();
1563
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();
1574                         goto error;
1575                 }
1576                 cfg_main_reset_local();
1577                 if (counters_prefork_init(get_max_procs()) == -1) goto error;
1578
1579
1580                 woneinit = 0;
1581                 /* udp processes */
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);
1591                                         else
1592                                                 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1593                                                         "sock=[%s]:%s",
1594                                                         i, si->name.s, si->port_no_str.s);
1595                                 } else {
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);
1601                                         else
1602                                                 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1603                                                         "sock=%s:%s",
1604                                                         i, si->name.s, si->port_no_str.s);
1605                                 }
1606                                 child_rank++;
1607                                 pid = fork_process(child_rank, si_desc, 1);
1608                                 if (pid<0){
1609                                         LM_CRIT("Cannot fork\n");
1610                                         goto error;
1611                                 }else if (pid==0){
1612                                         /* child */
1613                                         bind_address=si; /* shortcut */
1614 #ifdef STATS
1615                                         setstats( i+r*children_no );
1616 #endif
1617                                         if(woneinit==0) {
1618                                                 if(run_child_one_init_route()<0)
1619                                                         goto error;
1620                                         }
1621                                         return udp_rcv_loop();
1622                                 }
1623                                 woneinit = 1;
1624                         }
1625                         /*parent*/
1626                         /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
1627                 }
1628 #ifdef USE_SCTP
1629                 /* sctp processes */
1630                 if (!sctp_disable){
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 "
1636                                                                 "sock=[%s]:%s",
1637                                                                 i, si->name.s, si->port_no_str.s);
1638                                         } else {
1639                                                 snprintf(si_desc, MAX_PT_DESC, "sctp receiver child=%d "
1640                                                                 "sock=%s:%s",
1641                                                                 i, si->name.s, si->port_no_str.s);
1642                                         }
1643                                         child_rank++;
1644                                         pid = fork_process(child_rank, si_desc, 1);
1645                                         if (pid<0){
1646                                                 LM_CRIT("Cannot fork\n");
1647                                                 goto error;
1648                                         }else if (pid==0){
1649                                                 /* child */
1650                                                 bind_address=si; /* shortcut */
1651 #ifdef STATS
1652                                                 setstats( i+r*children_no );
1653 #endif
1654                                                 return sctp_core_rcv_loop();
1655                                         }
1656                                 }
1657                         /*parent*/
1658                         /*close(sctp_sock)*/; /*if closed=>sendto invalid fd errors?*/
1659                         }
1660                 }
1661 #endif /* USE_SCTP */
1662
1663                 /*this is the main process*/
1664                 bind_address=0; /* main proc -> it shouldn't send anything, */
1665
1666 #ifdef USE_SLOW_TIMER
1667                 /* fork again for the "slow" timer process*/
1668                 pid = fork_process(PROC_TIMER, "slow timer", 1);
1669                 if (pid<0){
1670                         LM_CRIT("cannot fork \"slow\" timer process\n");
1671                         goto error;
1672                 }else if (pid==0){
1673                         /* child */
1674                         if (real_time&2)
1675                                 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1676                         if (arm_slow_timer()<0) goto error;
1677                         slow_timer_main();
1678                 }else{
1679                         slow_timer_pid=pid;
1680                 }
1681 #endif /* USE_SLOW_TIMER */
1682
1683                 /* fork again for the "main" timer process*/
1684                 pid = fork_process(PROC_TIMER, "timer", 1);
1685                 if (pid<0){
1686                         LM_CRIT("cannot fork timer process\n");
1687                         goto error;
1688                 }else if (pid==0){
1689                         /* child */
1690                         if (real_time&1)
1691                                 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1692                         if (arm_timer()<0) goto error;
1693                         timer_main();
1694                 }
1695                 if(sr_wtimer_start()<0) {
1696                         LM_CRIT("Cannot start wtimer\n");
1697                         goto error;
1698                 }
1699
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");
1705                         goto error;
1706                 }
1707
1708 #ifdef USE_TCP
1709                 if (!tcp_disable){
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);
1714                         if (pid<0){
1715                                 LM_CRIT("cannot fork tcp main process: %s\n", strerror(errno));
1716                                 goto error;
1717                         }else if (pid==0){
1718                                 /* child */
1719                                 tcp_main_loop();
1720                         }else{
1721                                 tcp_main_pid=pid;
1722                                 unix_tcp_sock=-1;
1723                         }
1724                 }
1725 #endif
1726                 /* main */
1727                 strncpy(pt[0].desc, "main process - attendant", MAX_PT_DESC );
1728 #ifdef USE_TCP
1729                 close_extra_socks(PROC_ATTENDANT, get_proc_no());
1730                 if(!tcp_disable){
1731                         /* main's tcp sockets are disabled by default from init_pt() */
1732                         unix_tcp_sock=-1;
1733                 }
1734 #endif
1735                 /* init cfg, but without per child callbacks support */
1736                 cfg_child_no_cb_init();
1737                 cfg_ok=1;
1738
1739 #ifdef EXTRA_DEBUG
1740                 for (r=0; r<*process_count; r++){
1741                         fprintf(stderr, "% 3d   % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1742                 }
1743 #endif
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);
1750                                 goto error;
1751                         }
1752                 }
1753                 for(;;){
1754                         handle_sigs();
1755                         pause();
1756                         cfg_update();
1757                 }
1758         
1759         }
1760
1761         /*return 0; */
1762 error:
1763                                  /* if we are here, we are the "main process",
1764                                   any forked children should exit with exit(-1) and not
1765                                   ever use return */
1766         return -1;
1767
1768 }
1769
1770 /*
1771  * Calculate number of processes, this does not
1772  * include processes created by modules
1773  */
1774 static int calc_proc_no(void)
1775 {
1776         int udp_listeners;
1777         struct socket_info* si;
1778 #ifdef USE_TCP
1779         int tcp_listeners;
1780         int tcp_e_listeners;
1781 #endif
1782 #ifdef USE_SCTP
1783         int sctp_listeners;
1784 #endif
1785
1786         for (si=udp_listen, udp_listeners=0; si; si=si->next)
1787                 udp_listeners += (si->workers>0)?si->workers:children_no;
1788 #ifdef USE_TCP
1789         for (si=tcp_listen, tcp_listeners=0, tcp_e_listeners=0; si; si=si->next) {
1790                 if(si->workers>0)
1791                         tcp_listeners += si->workers;
1792                 else
1793                          tcp_e_listeners = tcp_cfg_children_no;
1794         }
1795         tcp_listeners += tcp_e_listeners;
1796 #ifdef USE_TLS
1797         tcp_e_listeners = 0;
1798         for (si=tls_listen, tcp_e_listeners=0; si; si=si->next) {
1799                 if(si->workers>0)
1800                         tcp_listeners += si->workers;
1801                 else {
1802                         if(tcp_listeners==0)
1803                                 tcp_e_listeners = tcp_cfg_children_no;
1804                 }
1805         }
1806         tcp_listeners += tcp_e_listeners;
1807 #endif
1808         tcp_children_no = tcp_listeners;
1809 #endif
1810 #ifdef USE_SCTP
1811         for (si=sctp_listen, sctp_listeners=0; si; si=si->next)
1812                 sctp_listeners += (si->workers>0)?si->workers:sctp_children_no;
1813 #endif
1814         return
1815                      /* receivers and attendant */
1816                 (dont_fork ? 1 : udp_listeners + 1)
1817                      /* timer process */
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 */
1822 #endif
1823 #ifdef USE_TCP
1824                 +((!tcp_disable)?( 1/* tcp main */ + tcp_listeners ):0)
1825 #endif
1826 #ifdef USE_SCTP
1827                 +((!sctp_disable)?sctp_listeners:0)
1828 #endif
1829                 ;
1830 }
1831
1832 int main(int argc, char** argv)
1833 {
1834
1835         FILE* cfg_stream;
1836         int c,r;
1837         char *tmp;
1838         int tmp_len;
1839         int port;
1840         int proto;
1841         char *options;
1842         int ret;
1843         unsigned int seed;
1844         int rfd;
1845         int debug_save, debug_flag;
1846         int dont_fork_cnt;
1847         struct name_lst* n_lst;
1848         char *p;
1849         struct stat st = {0};
1850
1851         /*init*/
1852         time(&up_since);
1853         creator_pid = getpid();
1854         ret=-1;
1855         my_argc=argc; my_argv=argv;
1856         debug_flag=0;
1857         dont_fork_cnt=0;
1858
1859         sr_cfgenv_init();
1860         daemon_status_init();
1861
1862         dprint_init_colors();
1863
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:"
1866 #ifdef STATS
1867                 "s:"
1868 #endif
1869         ;
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
1876          *    later
1877          */
1878         opterr = 0;
1879         while((c=getopt(argc,argv,options))!=-1) {
1880                 switch(c) {
1881                         case 'd':
1882                                         debug_flag = 1;
1883                                         default_core_cfg.debug++;
1884                                         break;
1885                         case 'E':
1886                                         log_stderr=1;
1887                                         break;
1888                         case 'e':
1889                                         log_color=1;
1890                                         break;
1891                         case 'M':
1892                                         pkg_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1893                                         if (tmp &&(*tmp)){
1894                                                 fprintf(stderr, "bad private mem size number: -M %s\n",
1895                                                                                         optarg);
1896                                                 goto error;
1897                                         };
1898                                         break;
1899                         case 'x':
1900                                         sr_memmng_shm = optarg;
1901                                         break;
1902                         case 'X':
1903                                         sr_memmng_pkg = optarg;
1904                                         break;
1905                         default:
1906                                         if (c == 'h' || (optarg && strcmp(optarg, "-h") == 0)) {
1907                                                 printf("version: %s\n", full_version);
1908                                                 printf("%s",help_msg);
1909                                                 exit(0);
1910                                         }
1911                                         break;
1912                 }
1913         }
1914
1915         if(sr_memmng_pkg==NULL) {
1916                 if(sr_memmng_shm!=NULL) {
1917                         sr_memmng_pkg = sr_memmng_shm;
1918                 } else {
1919                         sr_memmng_pkg = SR_MEMMNG_DEFAULT;
1920                 }
1921         }
1922         if(sr_memmng_shm==NULL) {
1923                 sr_memmng_shm = SR_MEMMNG_DEFAULT;
1924         }
1925         shm_set_mname(sr_memmng_shm);
1926         if (pkg_mem_size == 0) {
1927                 pkg_mem_size = PKG_MEM_POOL_SIZE;
1928         }
1929
1930         /*init pkg mallocs (before parsing cfg or the rest of the cmd line !)*/
1931         if (pkg_mem_size)
1932                 LM_INFO("private (per process) memory: %ld bytes\n", pkg_mem_size );
1933         if (pkg_init_manager(sr_memmng_pkg)<0)
1934                 goto error;
1935
1936 #ifdef DBG_MSG_QA
1937         fprintf(stderr, "WARNING: ser startup: "
1938                 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1939 #endif
1940
1941         /* init counters / stats */
1942         if (init_counters() == -1)
1943                 goto error;
1944 #ifdef USE_TCP
1945         init_tcp_options(); /* set the defaults before the config */
1946 #endif
1947
1948         pp_define_core();
1949
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) {
1954                 switch(c) {
1955                         case 'M':
1956                         case 'x':
1957                         case 'X':
1958                                         /* ignore, they were parsed immediately after startup */
1959                                         break;
1960                         case 'f':
1961                                         cfg_file=optarg;
1962                                         break;
1963                         case 'c':
1964                                         config_check=1;
1965                                         log_stderr=1; /* force stderr logging */
1966                                         break;
1967                         case 'L':
1968                                         mods_dir = optarg;
1969                                         mods_dir_cmd = 1;
1970                                         break;
1971                         case 'm':
1972                                         shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1973                                         if (tmp &&(*tmp)){
1974                                                 fprintf(stderr, "bad shmem size number: -m %s\n",
1975                                                                                 optarg);
1976                                                 goto error;
1977                                         };
1978                                         LM_INFO("shared memory: %ld bytes\n", shm_mem_size );
1979                                         break;
1980                         case 'd':
1981                                         /* ignore it, was parsed immediately after startup */
1982                                         break;
1983                         case 'v':
1984                         case 'V':
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 );
1992                                         else
1993                                                 printf("compiled with %s\n",
1994                                                         ver_compiler );
1995
1996                                         exit(0);
1997                                         break;
1998                         case 'I':
1999                                         print_internals();
2000                                         exit(0);
2001                                         break;
2002                         case 'E':
2003                                         /* ignore it, was parsed immediately after startup */
2004                                         break;
2005                         case 'e':
2006                                         /* ignore it, was parsed immediately after startup */
2007                                         break;
2008                         case 'O':
2009                                         scr_opt_lev=strtol(optarg, &tmp, 10);
2010                                         if (tmp &&(*tmp)){
2011                                                 fprintf(stderr, "bad optimization level: -O %s\n",
2012                                                                                 optarg);
2013                                                 goto error;
2014                                         };
2015                                         break;
2016                         case 'u':
2017                                         /* user needed for possible shm. pre-init */
2018                                         user=optarg;
2019                                         break;
2020                         case 'A':
2021                                         p = strchr(optarg, '=');
2022                                         if(p) {
2023                                                 *p = '\0';
2024                                         }
2025                                         pp_define_set_type(0);
2026                                         if(pp_define(strlen(optarg), optarg)<0) {
2027                                                 fprintf(stderr, "error at define param: -A %s\n",
2028                                                                 optarg);
2029                                                 goto error;
2030                                         }
2031                                         if(p) {
2032                                                 *p = '=';
2033                                                 p++;
2034                                                 if(pp_define_set(strlen(p), p)<0) {
2035                                                         fprintf(stderr, "error at define value: -A %s\n",
2036                                                                 optarg);
2037                                                         goto error;
2038                                                 }
2039                                         }
2040                                         break;
2041                         case 'b':
2042                         case 'l':
2043                         case 'n':
2044                         case 'K':
2045                         case 'r':
2046                         case 'R':
2047                         case 'D':
2048                         case 'T':
2049                         case 'N':
2050                         case 'W':
2051                         case 'w':
2052                         case 't':
2053                         case 'g':
2054                         case 'P':
2055                         case 'G':
2056                         case 'S':
2057                         case 'Q':
2058                         case 'a':
2059                         case 's':
2060                         case 'Y':
2061                                         break;
2062                         case '?':
2063                                         if (isprint(optopt)) {
2064                                                 fprintf(stderr, "Unknown option `-%c'."
2065                                                                                 " Use -h for help.\n", optopt);
2066                                         } else {
2067                                                 fprintf(stderr, "Unknown option character `\\x%x'."
2068                                                                                 " Use -h for help.\n",
2069                                                         optopt);
2070                                         }
2071                                         goto error;
2072                         case ':':
2073                                         fprintf(stderr, "Option `-%c' requires an argument."
2074                                                                         " Use -h for help.\n",
2075                                                 optopt);
2076                                         goto error;
2077                         default:
2078                                         abort();
2079                 }
2080         }
2081         if (shm_mem_size == 0) {
2082                 shm_mem_size = SHM_MEM_POOL_SIZE;
2083         }
2084
2085         if (endianness_sanity_check() != 0){
2086                 fprintf(stderr, "BUG: endianness sanity tests failed\n");
2087                 goto error;
2088         }
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;
2096
2097         /* Fix the value of cfg_file variable.*/
2098         if (fix_cfg_file() < 0) goto error;
2099
2100         /* load config file or die */
2101         if (cfg_file[0] == '-' && strlen(cfg_file)==1) {
2102                 cfg_stream=stdin;
2103         } else {
2104                 cfg_stream=fopen (cfg_file, "r");
2105         }
2106         if (cfg_stream==0){
2107                 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
2108                                 strerror(errno));
2109                 goto error;
2110         }
2111
2112         /* seed the prng */
2113         /* try to use /dev/urandom if possible */
2114         seed=0;
2115         if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
2116 try_again:
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);
2120                 }
2121                 LM_DBG("read %u from /dev/urandom\n", seed);
2122                         close(rfd);
2123         }else{
2124                 LM_WARN("could not open /dev/urandom (%d)\n", errno);
2125         }
2126         seed+=getpid()+time(0);
2127         LM_DBG("seeding PRNG with %u\n", seed);
2128         kam_srand(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());
2132
2133         /*register builtin  modules*/
2134         register_builtin_modules();
2135
2136         /* init named flags */
2137         init_named_flags();
2138
2139         yyin=cfg_stream;
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();
2145
2146                 goto error;
2147         }
2148         if (cfg_warnings){
2149                 fprintf(stderr, "%d config warnings\n", cfg_warnings);
2150         }
2151         if (debug_flag) default_core_cfg.debug = debug_save;
2152         pp_ifdef_level_check();
2153         print_rls();
2154
2155         if(init_dst_set()<0) {
2156                 LM_ERR("failed to initialize destination set structure\n");
2157                 goto error;
2158         }
2159         /* options with higher priority than cfg file */
2160         optind = 1;  /* reset getopt */
2161         while((c=getopt(argc,argv,options))!=-1) {
2162                 switch(c) {
2163                         case 'f':
2164                         case 'c':
2165                         case 'm':
2166                         case 'M':
2167                         case 'd':
2168                         case 'v':
2169                         case 'V':
2170                         case 'I':
2171                         case 'h':
2172                         case 'O':
2173                         case 'A':
2174                                         break;
2175                         case 'E':
2176                                         log_stderr=1;   /* use in both getopt switches,
2177                                                                            takes priority over config */
2178                                         break;
2179                         case 'e':
2180                                         log_color=1;    /* use in both getopt switches,
2181                                                                            takes priority over config */
2182                                         break;
2183                         case 'b':
2184                                         maxbuffer=strtol(optarg, &tmp, 10);
2185                                         if (tmp &&(*tmp)){
2186                                                 fprintf(stderr, "bad max buffer size number: -b %s\n",
2187                                                                                         optarg);
2188                                                 goto error;
2189                                         }
2190                                         break;
2191                         case 'l':
2192                                         if ((n_lst=parse_phostport_mh(optarg, &tmp, &tmp_len,
2193                                                                                         &port, &proto))==0){
2194                                                 fprintf(stderr, "bad -l address specifier: %s\n",
2195                                                                                 optarg);
2196                                                 goto error;
2197                                         }
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);
2203                                                 goto error;
2204                                         }
2205                                         free_name_lst(n_lst);
2206                                         break;
2207                         case 'n':
2208                                         children_no=strtol(optarg, &tmp, 10);
2209                                         if ((tmp==0) ||(*tmp)){
2210                                                 fprintf(stderr, "bad process number: -n %s\n",
2211                                                                         optarg);
2212                                                 goto error;
2213                                         }
2214                                         break;
2215                         case 'K':
2216                                         check_via=1;
2217                                         break;
2218                         case 'r':
2219                                         received_dns|=DO_DNS;
2220                                         break;
2221                         case 'R':
2222                                         received_dns|=DO_REV_DNS;
2223                                         break;
2224                         case 'D':
2225                                         dont_fork_cnt++;
2226                                         break;
2227                         case 'T':
2228                                 #ifdef USE_TCP
2229                                         tcp_disable=1;
2230                                 #else
2231                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
2232                                 #endif
2233                                         break;
2234                         case 'N':
2235                                 #ifdef USE_TCP
2236                                         tcp_cfg_children_no=strtol(optarg, &tmp, 10);
2237                                         if ((tmp==0) ||(*tmp)){
2238                                                 fprintf(stderr, "bad process number: -N %s\n",
2239                                                                         optarg);
2240                                                 goto error;
2241                                         }
2242                                 #else
2243                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
2244                                 #endif
2245                                         break;
2246                         case 'W':
2247                                 #ifdef USE_TCP
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);
2252                                                 goto error;
2253                                         }
2254                                 #else
2255                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
2256                                 #endif
2257                                         break;
2258                         case 'S':
2259                                 #ifdef USE_SCTP
2260                                         sctp_disable=1;
2261                                 #else
2262                                         fprintf(stderr,"WARNING: sctp support not compiled in\n");
2263                                 #endif
2264                                         break;
2265                         case 'Q':
2266                                 #ifdef USE_SCTP
2267                                         sctp_children_no=strtol(optarg, &tmp, 10);
2268                                         if ((tmp==0) ||(*tmp)){
2269                                                 fprintf(stderr, "bad process number: -O %s\n",
2270                                                                         optarg);
2271                                                 goto error;
2272                                         }
2273                                 #else
2274                                         fprintf(stderr,"WARNING: sctp support not compiled in\n");
2275                                 #endif
2276                                         break;
2277                         case 'w':
2278                                         working_dir=optarg;
2279                                         break;
2280                         case 'Y':
2281                                         runtime_dir=optarg;
2282                                         break;
2283                         case 't':
2284                                         chroot_dir=optarg;
2285                                         break;
2286                         case 'u':
2287                                         user=optarg;
2288                                         break;
2289                         case 'g':
2290                                         group=optarg;
2291                                         break;
2292                         case 'P':
2293                                         pid_file=optarg;
2294                                         break;
2295                         case 'G':
2296                                         pgid_file=optarg;
2297                                         break;
2298                         case 'a':
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;
2303                                         else {
2304                                                 fprintf(stderr,
2305                                                         "bad auto aliases parameter: %s (valid on, off, yes, no)\n",
2306                                                         optarg);
2307                                                 goto error;
2308                                         }
2309                                         break;
2310                         case 's':
2311                                 #ifdef STATS
2312                                         stat_file=optarg;
2313                                 #endif
2314                                         break;
2315                         default:
2316                                         break;
2317                 }
2318         }
2319
2320         /* reinit if pv buffer size has been set in config */
2321         if (pv_reinit_buffer()<0)
2322                 goto error;
2323
2324         if (ksr_route_locks_set_init()<0)
2325                 goto error;
2326
2327         /* init lookup for core event routes */
2328         sr_core_ert_init();
2329
2330         if (dont_fork_cnt)
2331                 dont_fork = dont_fork_cnt;      /* override by command line */
2332
2333         if (dont_fork > 0) {
2334                 dont_daemonize = dont_fork == 2;
2335                 dont_fork = dont_fork == 1;
2336         }
2337         /* init locks first */
2338         if (init_lock_ops()!=0)
2339                 goto error;
2340 #ifdef USE_TCP
2341 #ifdef USE_TLS
2342         if (tcp_disable)
2343                 tls_disable=1; /* if no tcp => no tls */
2344 #endif /* USE_TLS */
2345 #endif /* USE_TCP */
2346 #ifdef USE_SCTP
2347         if (sctp_disable!=1){
2348                 /* fix it */
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"
2353                                                                 " the OS\n");
2354                                 goto error;
2355                         }
2356                         sctp_disable=1;
2357                 }else{
2358                         /* sctp_disable!=1 and sctp supported => enable sctp */
2359                         sctp_disable=0;
2360                 }
2361         }
2362 #endif /* USE_SCTP */
2363         /* initialize the configured proto list */
2364         init_proto_order();
2365         /* init the resolver, before fixing the config */
2366         resolv_init();
2367         /* fix parameters */
2368         if (port_no<=0) port_no=SIP_PORT;
2369 #ifdef USE_TLS
2370         if (tls_port_no<=0) tls_port_no=SIPS_PORT;
2371 #endif
2372
2373
2374         if (children_no<=0) children_no=CHILD_NO;
2375 #ifdef USE_TCP
2376         if (!tcp_disable){
2377                 if (tcp_cfg_children_no<=0) tcp_cfg_children_no=children_no;
2378                 tcp_children_no = tcp_cfg_children_no;
2379         }
2380 #endif
2381 #ifdef USE_SCTP
2382         if (!sctp_disable){
2383                 if (sctp_children_no<=0) sctp_children_no=children_no;
2384         }
2385 #endif
2386
2387         if (working_dir==0) working_dir="/";
2388
2389         /* get uid/gid */
2390         if (user){
2391                 if (user2uid(&uid, &gid, user)<0){
2392                         fprintf(stderr, "bad user name/uid number: -u %s\n", user);
2393                         goto error;
2394                 }
2395                 sock_uid = uid;
2396                 sock_gid = gid;
2397         }
2398         if (group){
2399                 if (group2gid(&gid, group)<0){
2400                                 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
2401                         goto error;
2402                 }
2403                 sock_gid = gid;
2404         }
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);
2410                         goto error;
2411                 }
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);
2416                                 goto error;
2417                         }
2418                 }
2419         }
2420         if (fix_all_socket_lists()!=0){
2421                 fprintf(stderr,  "failed to initialize list addresses\n");
2422                 goto error;
2423         }
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;
2428         }
2429         /* print all the listen addresses */
2430         printf("Listening on \n");
2431         print_all_socket_lists();
2432         printf("Aliases: \n");
2433         /*print_aliases();*/
2434         print_aliases();
2435         printf("\n");
2436
2437         if (dont_fork){
2438                 fprintf(stderr, "WARNING: no fork mode %s\n",
2439                                 (udp_listen)?(
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" );
2443         }
2444         if (config_check){
2445                 fprintf(stderr, "config file ok, exiting...\n");
2446                 return 0;
2447         }
2448
2449
2450         /*init shm mallocs
2451          *  this must be here
2452          *     -to allow setting shm mem size from the command line
2453          *       => if shm_mem should be settable from the cfg file move
2454          *       everything after
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.
2460          * --andrei */
2461 #ifdef SHM_MEM
2462         if (!shm_initialized() && init_shm()<0)
2463                 goto error;
2464 #endif /* SHM_MEM */
2465         pkg_print_manager();
2466         shm_print_manager();
2467         if (init_atomic_ops()==-1)
2468                 goto error;
2469         if (init_basex() != 0){
2470                 LM_CRIT("could not initialize base* framework\n");
2471                 goto error;
2472         }
2473         if (sr_cfg_init() < 0) {
2474                 LM_CRIT("could not initialize configuration framework\n");
2475                 goto error;
2476         }
2477         /* declare the core cfg before the module configs */
2478         if (cfg_declare("core", core_cfg_def, &default_core_cfg, cfg_sizeof(core),
2479                         &core_cfg)
2480         ) {
2481                 LM_CRIT("could not declare the core configuration\n");
2482                 goto error;
2483         }
2484 #ifdef USE_TCP
2485         if (tcp_register_cfg()){
2486                 LM_CRIT("could not register the tcp configuration\n");
2487                 goto error;
2488         }
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");
2493                 goto error;
2494         }
2495         /* init wtimer */
2496         if(sr_wtimer_init()<0) {
2497                 LM_CRIT("could not initialize wtimer, exiting...\n");
2498                 goto error;
2499         }
2500
2501 #ifdef USE_DNS_CACHE
2502         if (init_dns_cache()<0){
2503                 LM_CRIT("could not initialize the dns cache, exiting...\n");
2504                 goto error;
2505         }
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");
2510                 goto error;
2511         }
2512 #endif /* USE_DNS_CACHE_STATS */
2513 #endif
2514 #ifdef USE_DST_BLACKLIST
2515         if (init_dst_blacklist()<0){
2516                 LM_CRIT("could not initialize the dst blacklist, exiting...\n");
2517                 goto error;
2518         }
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");
2523                 goto error;
2524         }
2525 #endif /* USE_DST_BLACKLIST_STATS */
2526 #endif
2527         if (init_avps()<0) goto error;
2528         if (rpc_init_time() < 0) goto error;
2529
2530 #ifdef USE_TCP
2531         if (!tcp_disable){
2532                 /*init tcp*/
2533                 if (init_tcp()<0){
2534                         LM_CRIT("could not initialize tcp, exiting...\n");
2535                         goto error;
2536                 }
2537         }
2538 #endif /* USE_TCP */
2539 #ifdef USE_SCTP
2540         if (!sctp_disable){
2541                 if (sctp_core_init()<0){
2542                         LM_CRIT("Could not initialize sctp, exiting...\n");
2543                         goto error;
2544                 }
2545         }
2546 #endif /* USE_SCTP */
2547         /* init_daemon? */
2548         if( !dont_fork && daemonize((log_name==0)?argv[0]:log_name, 1) < 0)
2549                 goto error;
2550         if (install_sigs() != 0){
2551                 fprintf(stderr, "ERROR: could not install the signal handlers\n");
2552                 goto error;
2553         }
2554
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");
2560                         goto error;
2561                 }
2562         }
2563         if (mlock_pages)
2564                 mem_lock_pages();
2565
2566         if (real_time&4)
2567                         set_rt_prio(rt_prio, rt_policy);
2568
2569 #ifdef USE_TCP
2570 #ifdef USE_TLS
2571         if (!tls_disable){
2572                 if (!tls_loaded()){
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");
2576                         tls_disable=1;
2577                 } else {
2578                         if (pre_init_tls()<0){
2579                                 LM_CRIT("could not pre-initialize tls, exiting...\n");
2580                                 goto error;
2581                         }
2582                 }
2583         }
2584 #endif /* USE_TLS */
2585 #endif /* USE_TCP */
2586         
2587         if (init_modules() != 0) {
2588                 fprintf(stderr, "ERROR: error while initializing modules\n");
2589                 goto error;
2590         }
2591         
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)
2595                 goto error;
2596 #ifdef USE_TCP
2597 #ifdef USE_TLS
2598         if (!tls_disable){
2599                 if (!tls_loaded()){
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");
2603                         tls_disable=1;
2604                 }
2605                 /* init tls*/
2606                 if (init_tls()<0){
2607                         LM_CRIT("could not initialize tls, exiting...\n");
2608                         goto error;
2609                 }
2610         }
2611 #endif /* USE_TLS */
2612 #endif /* USE_TCP */
2613
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 !
2617          */
2618         LM_DBG("Expect (at least) %d kamailio processes in your process list\n",
2619                         get_max_procs());
2620
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");
2624                 goto error;
2625         }
2626 #endif
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");
2630                 goto error;
2631         }
2632 #endif
2633
2634         /* fix routing lists */
2635         if ( (r=fix_rls())!=0){
2636                 fprintf(stderr, "error %d while trying to fix configuration\n", r);
2637                 goto error;
2638         };
2639         fixup_complete=1;
2640
2641 #ifdef STATS
2642         if (init_stats(  dont_fork ? 1 : children_no  )==-1) goto error;
2643 #endif
2644
2645         ret=main_loop();
2646         if (ret < 0)
2647                 goto error;
2648         /*kill everything*/
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);
2654         }
2655         /* else terminate process */
2656         return ret;
2657
2658 error:
2659         /*kill everything*/
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);
2665         }
2666         return -1;
2667 }