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