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