modules/lcr: Fixed to/from_gw tests when proto parameter is 0 (ANY)
[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                 return -1;
980         return 0;
981 }
982
983
984
985 static struct name_lst* mk_name_lst_elem(char* name, int name_len, int flags)
986 {
987         struct name_lst* l;
988         
989         l=pkg_malloc(sizeof(struct name_lst)+name_len+1/* 0 */);
990         if (l){
991                 l->name=((char*)l)+sizeof(struct name_lst);
992                 memcpy(l->name, name, name_len);
993                 l->name[name_len]=0;
994                 l->flags=flags;
995                 l->next=0;
996         }
997         return l;
998 }
999
1000
1001
1002 /* free a name_lst list with elements allocated with mk_name_lst_elem
1003  * (single block both for the structure and for the name) */
1004 static void free_name_lst(struct name_lst* lst)
1005 {
1006         struct name_lst* l;
1007         
1008         while(lst){
1009                 l=lst;
1010                 lst=lst->next;
1011                 pkg_free(l);
1012         }
1013 }
1014
1015
1016
1017 /* parse h and returns a name lst (flags are set to SI_IS_MHOMED if
1018  * h contains more then one name or contains a name surrounded by '(' ')' )
1019  * valid formats:    "hostname"
1020  *                   "(hostname, hostname1, hostname2)"
1021  *                   "(hostname hostname1 hostname2)"
1022  *                   "(hostname)"
1023  */
1024 static struct name_lst* parse_name_lst(char* h, int h_len)
1025 {
1026         char* last;
1027         char* p;
1028         struct name_lst* n_lst;
1029         struct name_lst* l;
1030         struct name_lst** tail;
1031         int flags;
1032         
1033         n_lst=0;
1034         tail=&n_lst;
1035         last=h+h_len-1;
1036         flags=0;
1037         /* eat whitespace */
1038         for(; h<=last && ((*h==' ') || (*h=='\t')); h++);
1039         for(; last>h && ((*last==' ') || (*last=='\t')); last--);
1040         /* catch empty strings and invalid lens */
1041         if (h>last) goto error;
1042         
1043         if (*h=='('){
1044                 /* list mode */
1045                 if (*last!=')' || ((h+1)>(last-1)))
1046                         goto error;
1047                 h++;
1048                 last--;
1049                 flags=SI_IS_MHOMED;
1050                 for(p=h; p<=last; p++)
1051                         switch (*p){
1052                                 case ',':
1053                                 case ';':
1054                                 case ' ':
1055                                 case '\t':
1056                                         if ((int)(p-h)>0){
1057                                                 l=mk_name_lst_elem(h, (int)(p-h), flags);
1058                                                 if (l==0) 
1059                                                         goto error;
1060                                                 *tail=l;
1061                                                 tail=&l->next;
1062                                         }
1063                                         h=p+1;
1064                                         break;
1065                         }
1066         }else{
1067                 /* single addr. mode */
1068                 flags=0;
1069                 p=last+1;
1070         }
1071         if ((int)(p-h)>0){
1072                 l=mk_name_lst_elem(h, (int)(p-h), flags);
1073                 if (l==0) 
1074                         goto error;
1075                 *tail=l;
1076                 tail=&l->next;
1077         }
1078         return n_lst;
1079 error:
1080         if (n_lst) free_name_lst(n_lst);
1081         return 0;
1082 }
1083
1084
1085
1086 /*
1087  * parses [proto:]host[:port]  or
1088  *  [proto:](host_1, host_2, ... host_n)[:port]
1089  * where proto= udp|tcp|tls
1090  * returns  fills proto, port, host and returns list of addresses on success
1091  * (pkg malloc'ed) and 0 on failure
1092  */
1093 /** get protocol host and port from a string representation.
1094  * parses [proto:]host[:port]  or
1095  *  [proto:](host_1, host_2, ... host_n)[:port]
1096  * where proto= udp|tcp|tls|sctp
1097  * @param s  - string (like above)
1098  * @param host - will be filled with the host part
1099  *               Note: for multi-homing it wil contain all the addresses
1100  *               (e.g.: "sctp:(1.2.3.4, 5.6.7.8)" => host="(1.2.3.4, 5.6.7.8)")
1101  * @param hlen - will be filled with the length of the host part.
1102  * @param port - will be filled with the port if present or 0 if it's not.
1103  * @param proto - will be filled with the protocol if present or PROTO_NONE
1104  *                if it's not.
1105  * @return  fills proto, port, host and returns 0 on success and -1 on failure.
1106  */
1107 int parse_phostport(char* s, char** host, int* hlen,
1108                                                                  int* port, int* proto)
1109 {
1110         char* first; /* first ':' occurrence */
1111         char* second; /* second ':' occurrence */
1112         char* p;
1113         int bracket;
1114         char* tmp;
1115
1116         first=second=0;
1117         bracket=0;
1118
1119         /* find the first 2 ':', ignoring possible ipv6 addresses
1120          * (substrings between [])
1121          */
1122         for(p=s; *p; p++){
1123                 switch(*p){
1124                         case '[':
1125                                 bracket++;
1126                                 if (bracket>1) goto error_brackets;
1127                                 break;
1128                         case ']':
1129                                 bracket--;
1130                                 if (bracket<0) goto error_brackets;
1131                                 break;
1132                         case ':':
1133                                 if (bracket==0){
1134                                         if (first==0) first=p;
1135                                         else if( second==0) second=p;
1136                                         else goto error_colons;
1137                                 }
1138                                 break;
1139                 }
1140         }
1141         if (p==s) return -1;
1142         if (*(p-1)==':') goto error_colons;
1143
1144         if (first==0){ /* no ':' => only host */
1145                 *host=s;
1146                 *hlen=(int)(p-s);
1147                 *port=0;
1148                 *proto=0;
1149                 goto end;
1150         }
1151         if (second){ /* 2 ':' found => check if valid */
1152                 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
1153                 *port=strtol(second+1, &tmp, 10);
1154                 if ((tmp==0)||(*tmp)||(tmp==second+1)) goto error_port;
1155                 *host=first+1;
1156                 *hlen=(int)(second-*host);
1157                 goto end;
1158         }
1159         /* only 1 ':' found => it's either proto:host or host:port */
1160         *port=strtol(first+1, &tmp, 10);
1161         if ((tmp==0)||(*tmp)||(tmp==first+1)){
1162                 /* invalid port => it's proto:host */
1163                 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
1164                 *port=0;
1165                 *host=first+1;
1166                 *hlen=(int)(p-*host);
1167         }else{
1168                 /* valid port => its host:port */
1169                 *proto=0;
1170                 *host=s;
1171                 *hlen=(int)(first-*host);
1172         }
1173 end:
1174         return 0;
1175 error_brackets:
1176         LOG(L_ERR, "ERROR: parse_phostport: too many brackets in %s\n", s);
1177         return -1;
1178 error_colons:
1179         LOG(L_ERR, "ERROR: parse_phostport: too many colons in %s\n", s);
1180         return -1;
1181 error_proto:
1182         LOG(L_ERR, "ERROR: parse_phostport: bad protocol in %s\n", s);
1183         return -1;
1184 error_port:
1185         LOG(L_ERR, "ERROR: parse_phostport: bad port number in %s\n", s);
1186         return -1;
1187 }
1188
1189
1190
1191 /** get protocol host, port and MH addresses list from a string representation.
1192  * parses [proto:]host[:port]  or
1193  *  [proto:](host_1, host_2, ... host_n)[:port]
1194  * where proto= udp|tcp|tls|sctp
1195  * @param s  - string (like above)
1196  * @param host - will be filled with the host part
1197  *               Note: for multi-homing it wil contain all the addresses
1198  *               (e.g.: "sctp:(1.2.3.4, 5.6.7.8)" => host="(1.2.3.4, 5.6.7.8)")
1199  * @param hlen - will be filled with the length of the host part.
1200  * @param port - will be filled with the port if present or 0 if it's not.
1201  * @param proto - will be filled with the protocol if present or PROTO_NONE
1202  *                if it's not.
1203  * @return  fills proto, port, host and returns list of addresses on success
1204  * (pkg malloc'ed) and 0 on failure
1205  */
1206 static struct name_lst* parse_phostport_mh(char* s, char** host, int* hlen,
1207                                                                  int* port, int* proto)
1208 {
1209         if (parse_phostport(s, host, hlen, port, proto)==0)
1210                 return parse_name_lst(*host, *hlen);
1211         return 0;
1212 }
1213
1214
1215
1216 /** Update \c cfg_file variable to contain full pathname. The function updates
1217  * the value of \c cfg_file global variable to contain full absolute pathname
1218  * to the main configuration file of SER. The function uses CFG_FILE macro to
1219  * determine the default path to the configuration file if the user did not
1220  * specify one using the command line option. If \c cfg_file contains an
1221  * absolute pathname then it is used unmodified, if it contains a relative
1222  * pathanme than the value returned by \c getcwd function will be added at the
1223  * beginning. This function must be run before SER changes its current working
1224  * directory to / (in daemon mode).
1225  * @return Zero on success, negative number
1226  * on error.
1227  */
1228 int fix_cfg_file(void)
1229 {
1230         char* res = NULL;
1231         size_t max_len, cwd_len, cfg_len;
1232         
1233         if (cfg_file == NULL) cfg_file = CFG_FILE;
1234         if (cfg_file[0] == '/') return 0;
1235         
1236         /* cfg_file contains a relative pathname, get the current
1237          * working directory and add it at the beginning
1238          */
1239         cfg_len = strlen(cfg_file);
1240         
1241         max_len = pathmax();
1242         if ((res = malloc(max_len)) == NULL) goto error;
1243         
1244         if (getcwd(res, max_len) == NULL) goto error;
1245         cwd_len = strlen(res);
1246         
1247         /* Make sure that the buffer is big enough */
1248         if (cwd_len + 1 + cfg_len >= max_len) goto error;
1249         
1250         res[cwd_len] = '/';
1251         memcpy(res + cwd_len + 1, cfg_file, cfg_len);
1252         
1253         res[cwd_len + 1 + cfg_len] = '\0'; /* Add terminating zero */
1254         cfg_file = res;
1255         return 0;
1256         
1257  error:
1258         fprintf(stderr, "ERROR: Unable to fix cfg_file to contain full pathname\n");
1259         if (res) free(res);
1260         return -1;
1261 }
1262
1263
1264 /* main loop */
1265 int main_loop(void)
1266 {
1267         int  i;
1268         pid_t pid;
1269         struct socket_info* si;
1270         char si_desc[MAX_PT_DESC];
1271 #ifdef EXTRA_DEBUG
1272         int r;
1273 #endif
1274         int nrprocs;
1275
1276         /* one "main" process and n children handling i/o */
1277         if (dont_fork){
1278 #ifdef STATS
1279                 setstats( 0 );
1280 #endif
1281                 if (udp_listen==0){
1282                         LOG(L_ERR, "ERROR: no fork mode requires at least one"
1283                                         " udp listen address, exiting...\n");
1284                         goto error;
1285                 }
1286                 /* only one address, we ignore all the others */
1287                 if (udp_init(udp_listen)==-1) goto error;
1288                 bind_address=udp_listen;
1289                 if (bind_address->address.af==AF_INET) {
1290                         sendipv4=bind_address;
1291 #ifdef USE_RAW_SOCKS
1292                 /* always try to have a raw socket opened if we are using ipv4 */
1293                 raw_udp4_send_sock = raw_socket(IPPROTO_RAW, 0, 0, 1);
1294                 if (raw_udp4_send_sock < 0) {
1295                         if ( default_core_cfg.udp4_raw > 0) {
1296                                 /* force use raw socket failed */
1297                                 ERR("could not initialize raw udp send socket (ipv4):"
1298                                                 " %s (%d)\n", strerror(errno), errno);
1299                                 if (errno == EPERM)
1300                                         ERR("could not initialize raw socket on startup"
1301                                                 " due to inadequate permissions, please"
1302                                                 " restart as root or with CAP_NET_RAW\n");
1303                                 goto error;
1304                         }
1305                         default_core_cfg.udp4_raw = 0; /* disabled */
1306                 } else {
1307                         register_fds(1);
1308                         if (default_core_cfg.udp4_raw < 0) {
1309                                 /* auto-detect => use it */
1310                                 default_core_cfg.udp4_raw = 1; /* enabled */
1311                                 DBG("raw socket possible => turning it on\n");
1312                         }
1313                         if (default_core_cfg.udp4_raw_ttl < 0) {
1314                                 /* auto-detect */
1315                                 default_core_cfg.udp4_raw_ttl = sock_get_ttl(sendipv4->socket);
1316                                 if (default_core_cfg.udp4_raw_ttl < 0)
1317                                         /* error, use some default value */
1318                                         default_core_cfg.udp4_raw_ttl = 63;
1319                         }
1320                 }
1321 #else
1322                 default_core_cfg.udp4_raw = 0;
1323 #endif /* USE_RAW_SOCKS */
1324                 } else
1325                         sendipv6=bind_address;
1326                 if (udp_listen->next){
1327                         LOG(L_WARN, "WARNING: using only the first listen address"
1328                                                 " (no fork)\n");
1329                 }
1330
1331                 /* delay cfg_shmize to the last moment (it must be called _before_
1332                    forking). Changes to default cfgs after this point will be
1333                    ignored.
1334                 */
1335                 if (cfg_shmize() < 0) {
1336                         LOG(L_CRIT, "could not initialize shared configuration\n");
1337                         goto error;
1338                 }
1339         
1340                 /* Register the children that will keep updating their
1341                  * local configuration */
1342                 cfg_register_child(
1343                                 1   /* main = udp listener */
1344                                 + 1 /* timer */
1345 #ifdef USE_SLOW_TIMER
1346                                 + 1 /* slow timer */
1347 #endif
1348                         );
1349                 if (do_suid()==-1) goto error; /* try to drop privileges */
1350                 /* process_no now initialized to zero -- increase from now on
1351                    as new processes are forked (while skipping 0 reserved for main
1352                 */
1353
1354                 /* Temporary set the local configuration of the main process
1355                  * to make the group instances available in PROC_INIT.
1356                  */
1357                 cfg_main_set_local();
1358
1359                 /* init childs with rank==PROC_INIT before forking any process,
1360                  * this is a place for delayed (after mod_init) initializations
1361                  * (e.g. shared vars that depend on the total number of processes
1362                  * that is known only after all mod_inits have been executed )
1363                  * WARNING: the same init_child will be called latter, a second time
1364                  * for the "main" process with rank PROC_MAIN (make sure things are
1365                  * not initialized twice)*/
1366                 if (init_child(PROC_INIT) < 0) {
1367                         LOG(L_ERR, "ERROR: main_dontfork: init_child(PROC_INT) --"
1368                                                 " exiting\n");
1369                         cfg_main_reset_local();
1370                         goto error;
1371                 }
1372                 cfg_main_reset_local();
1373                 if (counters_prefork_init(get_max_procs()) == -1) goto error;
1374
1375 #ifdef USE_SLOW_TIMER
1376                 /* we need another process to act as the "slow" timer*/
1377                                 pid = fork_process(PROC_TIMER, "slow timer", 0);
1378                                 if (pid<0){
1379                                         LOG(L_CRIT,  "ERROR: main_loop: Cannot fork\n");
1380                                         goto error;
1381                                 }
1382                                 if (pid==0){
1383                                         /* child */
1384                                         /* timer!*/
1385                                         /* process_bit = 0; */
1386                                         if (real_time&2)
1387                                                 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1388
1389                                         if (arm_slow_timer()<0) goto error;
1390                                         slow_timer_main();
1391                                 }else{
1392                                         slow_timer_pid=pid;
1393                                 }
1394 #endif
1395                                 /* we need another process to act as the "main" timer*/
1396                                 pid = fork_process(PROC_TIMER, "timer", 0);
1397                                 if (pid<0){
1398                                         LOG(L_CRIT,  "ERROR: main_loop: Cannot fork\n");
1399                                         goto error;
1400                                 }
1401                                 if (pid==0){
1402                                         /* child */
1403                                         /* timer!*/
1404                                         /* process_bit = 0; */
1405                                         if (real_time&1)
1406                                                 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1407                                         if (arm_timer()<0) goto error;
1408                                         timer_main();
1409                                 }else{
1410                                 }
1411
1412                 /* main process, receive loop */
1413                 process_no=0; /*main process number*/
1414                 pt[process_no].pid=getpid();
1415                 snprintf(pt[process_no].desc, MAX_PT_DESC,
1416                         "stand-alone receiver @ %s:%s",
1417                          bind_address->name.s, bind_address->port_no_str.s );
1418
1419                 /* call it also w/ PROC_MAIN to make sure modules that init things 
1420                  * only in PROC_MAIN get a chance to run */
1421                 if (init_child(PROC_MAIN) < 0) {
1422                         LOG(L_ERR, "ERROR: main_dontfork: init_child(PROC_MAIN) "
1423                                                 "-- exiting\n");
1424                         goto error;
1425                 }
1426
1427                 /* We will call child_init even if we
1428                  * do not fork - and it will be called with rank 1 because
1429                  * in fact we behave like a child, not like main process
1430                  */
1431
1432                 if (init_child(PROC_SIPINIT) < 0) {
1433                         LOG(L_ERR, "main_dontfork: init_child failed\n");
1434                         goto error;
1435                 }
1436                 return udp_rcv_loop();
1437         }else{ /* fork: */
1438
1439                 /* Register the children that will keep updating their
1440                  * local configuration. (udp/tcp/sctp listeneres
1441                  * will be added later.) */
1442                 cfg_register_child(
1443                                 1   /* timer */
1444 #ifdef USE_SLOW_TIMER
1445                                 + 1 /* slow timer */
1446 #endif
1447                         );
1448
1449                 for(si=udp_listen;si;si=si->next){
1450                         /* create the listening socket (for each address)*/
1451                         /* udp */
1452                         if (udp_init(si)==-1) goto error;
1453                         /* get first ipv4/ipv6 socket*/
1454                         if ((si->address.af==AF_INET)&&
1455                                         ((sendipv4==0)||(sendipv4->flags&(SI_IS_LO|SI_IS_MCAST))))
1456                                 sendipv4=si;
1457         #ifdef USE_IPV6
1458                         if ( ((sendipv6==0)||(sendipv6->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1459                                         (si->address.af==AF_INET6))
1460                                 sendipv6=si;
1461         #endif
1462                         /* children_no per each socket */
1463                         cfg_register_child((si->workers>0)?si->workers:children_no);
1464                 }
1465 #ifdef USE_RAW_SOCKS
1466                 /* always try to have a raw socket opened if we are using ipv4 */
1467                 if (sendipv4) {
1468                         raw_udp4_send_sock = raw_socket(IPPROTO_RAW, 0, 0, 1);
1469                         if (raw_udp4_send_sock < 0) {
1470                                 if ( default_core_cfg.udp4_raw > 0) {
1471                                                 /* force use raw socket failed */
1472                                                 ERR("could not initialize raw udp send socket (ipv4):"
1473                                                                 " %s (%d)\n", strerror(errno), errno);
1474                                                 if (errno == EPERM)
1475                                                         ERR("could not initialize raw socket on startup"
1476                                                                 " due to inadequate permissions, please"
1477                                                                 " restart as root or with CAP_NET_RAW\n");
1478                                                 goto error;
1479                                         }
1480                                         default_core_cfg.udp4_raw = 0; /* disabled */
1481                         } else {
1482                                 register_fds(1);
1483                                 if (default_core_cfg.udp4_raw < 0) {
1484                                         /* auto-detect => use it */
1485                                         default_core_cfg.udp4_raw = 1; /* enabled */
1486                                         DBG("raw socket possible => turning it on\n");
1487                                 }
1488                                 if (default_core_cfg.udp4_raw_ttl < 0) {
1489                                         /* auto-detect */
1490                                         default_core_cfg.udp4_raw_ttl =
1491                                                 sock_get_ttl(sendipv4->socket);
1492                                         if (default_core_cfg.udp4_raw_ttl < 0)
1493                                                 /* error, use some default value */
1494                                                 default_core_cfg.udp4_raw_ttl = 63;
1495                                 }
1496                         }
1497                 }
1498 #else
1499                 default_core_cfg.udp4_raw = 0;
1500 #endif /* USE_RAW_SOCKS */
1501 #ifdef USE_SCTP
1502                 if (!sctp_disable){
1503                         for(si=sctp_listen; si; si=si->next){
1504                                 if (sctp_init_sock(si)==-1)  goto error;
1505                                 /* get first ipv4/ipv6 socket*/
1506                                 if ((si->address.af==AF_INET) &&
1507                                                 ((sendipv4_sctp==0) ||
1508                                                         (sendipv4_sctp->flags&(SI_IS_LO|SI_IS_MCAST))))
1509                                         sendipv4_sctp=si;
1510                 #ifdef USE_IPV6
1511                                 if( ((sendipv6_sctp==0) || 
1512                                                         (sendipv6_sctp->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1513                                                 (si->address.af==AF_INET6))
1514                                         sendipv6_sctp=si;
1515                 #endif
1516                                 /* sctp_children_no per each socket */
1517                                 cfg_register_child((si->workers>0)?si->workers:sctp_children_no);
1518                         }
1519                 }
1520 #endif /* USE_SCTP */
1521 #ifdef USE_TCP
1522                 if (!tcp_disable){
1523                         for(si=tcp_listen; si; si=si->next){
1524                                 /* same thing for tcp */
1525                                 if (tcp_init(si)==-1)  goto error;
1526                                 /* get first ipv4/ipv6 socket*/
1527                                 if ((si->address.af==AF_INET)&&
1528                                                 ((sendipv4_tcp==0) ||
1529                                                         (sendipv4_tcp->flags&(SI_IS_LO|SI_IS_MCAST))))
1530                                         sendipv4_tcp=si;
1531                 #ifdef USE_IPV6
1532                                 if( ((sendipv6_tcp==0) ||
1533                                                         (sendipv6_tcp->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1534                                                 (si->address.af==AF_INET6))
1535                                         sendipv6_tcp=si;
1536                 #endif
1537                         }
1538                         /* the number of sockets does not matter */
1539                         cfg_register_child(tcp_children_no + 1 /* tcp main */);
1540                 }
1541 #ifdef USE_TLS
1542                 if (!tls_disable && tls_has_init_si()){
1543                         for(si=tls_listen; si; si=si->next){
1544                                 /* same as for tcp*/
1545                                 if (tls_init(si)==-1)  goto error;
1546                                 /* get first ipv4/ipv6 socket*/
1547                                 if ((si->address.af==AF_INET)&&
1548                                                 ((sendipv4_tls==0) ||
1549                                                         (sendipv4_tls->flags&(SI_IS_LO|SI_IS_MCAST))))
1550                                         sendipv4_tls=si;
1551                 #ifdef USE_IPV6
1552                                 if( ((sendipv6_tls==0) ||
1553                                                         (sendipv6_tls->flags&(SI_IS_LO|SI_IS_MCAST))) &&
1554                                                 (si->address.af==AF_INET6))
1555                                         sendipv6_tls=si;
1556                 #endif
1557                         }
1558                 }
1559 #endif /* USE_TLS */
1560 #endif /* USE_TCP */
1561
1562                         /* all processes should have access to all the sockets (for 
1563                          * sending) so we open all first*/
1564                 if (do_suid()==-1) goto error; /* try to drop privileges */
1565
1566                 /* delay cfg_shmize to the last moment (it must be called _before_
1567                    forking). Changes to default cfgs after this point will be
1568                    ignored (cfg_shmize() will copy the default cfgs into shmem).
1569                 */
1570                 if (cfg_shmize() < 0) {
1571                         LOG(L_CRIT, "could not initialize shared configuration\n");
1572                         goto error;
1573                 }
1574
1575                 /* Temporary set the local configuration of the main process
1576                  * to make the group instances available in PROC_INIT.
1577                  */
1578                 cfg_main_set_local();
1579
1580                 /* init childs with rank==PROC_INIT before forking any process,
1581                  * this is a place for delayed (after mod_init) initializations
1582                  * (e.g. shared vars that depend on the total number of processes
1583                  * that is known only after all mod_inits have been executed )
1584                  * WARNING: the same init_child will be called latter, a second time
1585                  * for the "main" process with rank PROC_MAIN (make sure things are
1586                  * not initialized twice)*/
1587                 if (init_child(PROC_INIT) < 0) {
1588                         LOG(L_ERR, "ERROR: main: error in init_child(PROC_INT) --"
1589                                         " exiting\n");
1590                         cfg_main_reset_local();
1591                         goto error;
1592                 }
1593                 cfg_main_reset_local();
1594                 if (counters_prefork_init(get_max_procs()) == -1) goto error;
1595
1596
1597                 /* udp processes */
1598                 for(si=udp_listen; si; si=si->next){
1599                         nrprocs = (si->workers>0)?si->workers:children_no;
1600                         for(i=0;i<nrprocs;i++){
1601                                 if(si->address.af==AF_INET6) {
1602                                         if(si->useinfo.name.s)
1603                                                 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1604                                                         "sock=[%s]:%s (%s:%s)",
1605                                                         i, si->name.s, si->port_no_str.s,
1606                                                         si->useinfo.name.s, si->useinfo.port_no_str.s);
1607                                         else
1608                                                 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1609                                                         "sock=[%s]:%s",
1610                                                         i, si->name.s, si->port_no_str.s);
1611                                 } else {
1612                                         if(si->useinfo.name.s)
1613                                                 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1614                                                         "sock=%s:%s (%s:%s)",
1615                                                         i, si->name.s, si->port_no_str.s,
1616                                                         si->useinfo.name.s, si->useinfo.port_no_str.s);
1617                                         else
1618                                                 snprintf(si_desc, MAX_PT_DESC, "udp receiver child=%d "
1619                                                         "sock=%s:%s",
1620                                                         i, si->name.s, si->port_no_str.s);
1621                                 }
1622                                 child_rank++;
1623                                 pid = fork_process(child_rank, si_desc, 1);
1624                                 if (pid<0){
1625                                         LOG(L_CRIT,  "main_loop: Cannot fork\n");
1626                                         goto error;
1627                                 }else if (pid==0){
1628                                         /* child */
1629                                         bind_address=si; /* shortcut */
1630 #ifdef STATS
1631                                         setstats( i+r*children_no );
1632 #endif
1633                                         return udp_rcv_loop();
1634                                 }
1635                         }
1636                         /*parent*/
1637                         /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
1638                 }
1639 #ifdef USE_SCTP
1640                 /* sctp processes */
1641                 if (!sctp_disable){
1642                         for(si=sctp_listen; si; si=si->next){
1643                                 nrprocs = (si->workers>0)?si->workers:sctp_children_no;
1644                                 for(i=0;i<nrprocs;i++){
1645                                         if(si->address.af==AF_INET6) {
1646                                                 snprintf(si_desc, MAX_PT_DESC, "sctp receiver child=%d "
1647                                                                 "sock=[%s]:%s",
1648                                                                 i, si->name.s, si->port_no_str.s);
1649                                         } else {
1650                                                 snprintf(si_desc, MAX_PT_DESC, "sctp receiver child=%d "
1651                                                                 "sock=%s:%s",
1652                                                                 i, si->name.s, si->port_no_str.s);
1653                                         }
1654                                         child_rank++;
1655                                         pid = fork_process(child_rank, si_desc, 1);
1656                                         if (pid<0){
1657                                                 LOG(L_CRIT,  "main_loop: Cannot fork\n");
1658                                                 goto error;
1659                                         }else if (pid==0){
1660                                                 /* child */
1661                                                 bind_address=si; /* shortcut */
1662 #ifdef STATS
1663                                                 setstats( i+r*children_no );
1664 #endif
1665                                                 return sctp_rcv_loop();
1666                                         }
1667                                 }
1668                         /*parent*/
1669                         /*close(sctp_sock)*/; /*if closed=>sendto invalid fd errors?*/
1670                         }
1671                 }
1672 #endif /* USE_SCTP */
1673
1674                 /*this is the main process*/
1675                 bind_address=0; /* main proc -> it shouldn't send anything, */
1676
1677 #ifdef USE_SLOW_TIMER
1678                 /* fork again for the "slow" timer process*/
1679                 pid = fork_process(PROC_TIMER, "slow timer", 1);
1680                 if (pid<0){
1681                         LOG(L_CRIT, "main_loop: cannot fork \"slow\" timer process\n");
1682                         goto error;
1683                 }else if (pid==0){
1684                         /* child */
1685                         if (real_time&2)
1686                                 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1687                         if (arm_slow_timer()<0) goto error;
1688                         slow_timer_main();
1689                 }else{
1690                         slow_timer_pid=pid;
1691                 }
1692 #endif /* USE_SLOW_TIMER */
1693
1694                 /* fork again for the "main" timer process*/
1695                 pid = fork_process(PROC_TIMER, "timer", 1);
1696                 if (pid<0){
1697                         LOG(L_CRIT, "main_loop: cannot fork timer process\n");
1698                         goto error;
1699                 }else if (pid==0){
1700                         /* child */
1701                         if (real_time&1)
1702                                 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1703                         if (arm_timer()<0) goto error;
1704                         timer_main();
1705                 }
1706
1707         /* init childs with rank==MAIN before starting tcp main (in case they want
1708          * to fork  a tcp capable process, the corresponding tcp. comm. fds in
1709          * pt[] must be set before calling tcp_main_loop()) */
1710                 if (init_child(PROC_MAIN) < 0) {
1711                         LOG(L_ERR, "ERROR: main: error in init_child\n");
1712                         goto error;
1713                 }
1714
1715 #ifdef USE_TCP
1716                 if (!tcp_disable){
1717                                 /* start tcp  & tls receivers */
1718                         if (tcp_init_children()<0) goto error;
1719                                 /* start tcp+tls master proc */
1720                         pid = fork_process(PROC_TCP_MAIN, "tcp main process", 0);
1721                         if (pid<0){
1722                                 LOG(L_CRIT, "main_loop: cannot fork tcp main process: %s\n",
1723                                                         strerror(errno));
1724                                 goto error;
1725                         }else if (pid==0){
1726                                 /* child */
1727                                 tcp_main_loop();
1728                         }else{
1729                                 tcp_main_pid=pid;
1730                                 unix_tcp_sock=-1;
1731                         }
1732                 }
1733 #endif
1734                 /* main */
1735                 strncpy(pt[0].desc, "attendant", MAX_PT_DESC );
1736 #ifdef USE_TCP
1737                 close_extra_socks(PROC_ATTENDANT, get_proc_no());
1738                 if(!tcp_disable){
1739                         /* main's tcp sockets are disabled by default from init_pt() */
1740                         unix_tcp_sock=-1;
1741                 }
1742 #endif
1743                 /* init cfg, but without per child callbacks support */
1744                 cfg_child_no_cb_init();
1745                 cfg_ok=1;
1746
1747 #ifdef EXTRA_DEBUG
1748                 for (r=0; r<*process_count; r++){
1749                         fprintf(stderr, "% 3d   % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1750                 }
1751 #endif
1752                 DBG("Expect maximum %d  open fds\n", get_max_open_fds());
1753                 /* in daemonize mode send the exit code back to the parent process */
1754                 if (!dont_daemonize) {
1755                         if (daemon_status_send(0) < 0) {
1756                                 ERR("error sending daemon status: %s [%d]\n",
1757                                                 strerror(errno), errno);
1758                                 goto error;
1759                         }
1760                 }
1761                 for(;;){
1762                         handle_sigs();
1763                         pause();
1764                         cfg_update();
1765                 }
1766         
1767         }
1768
1769         /*return 0; */
1770 error:
1771                                  /* if we are here, we are the "main process",
1772                                   any forked children should exit with exit(-1) and not
1773                                   ever use return */
1774         return -1;
1775
1776 }
1777
1778 /*
1779  * Calculate number of processes, this does not
1780  * include processes created by modules
1781  */
1782 static int calc_proc_no(void)
1783 {
1784         int udp_listeners;
1785         struct socket_info* si;
1786 #ifdef USE_TCP
1787         int tcp_listeners;
1788         int tcp_e_listeners;
1789 #endif
1790 #ifdef USE_SCTP
1791         int sctp_listeners;
1792 #endif
1793
1794         for (si=udp_listen, udp_listeners=0; si; si=si->next)
1795                 udp_listeners += (si->workers>0)?si->workers:children_no;
1796 #ifdef USE_TCP
1797         for (si=tcp_listen, tcp_listeners=0, tcp_e_listeners=0; si; si=si->next) {
1798                 if(si->workers>0)
1799                         tcp_listeners += si->workers;
1800                 else
1801                          tcp_e_listeners = tcp_cfg_children_no;
1802         }
1803         tcp_listeners += tcp_e_listeners;
1804         tcp_children_no = tcp_listeners;
1805 #endif
1806 #ifdef USE_SCTP
1807         for (si=sctp_listen, sctp_listeners=0; si; si=si->next)
1808                 sctp_listeners += (si->workers>0)?si->workers:sctp_children_no;
1809 #endif
1810         return
1811                      /* receivers and attendant */
1812                 (dont_fork ? 1 : udp_listeners + 1)
1813                      /* timer process */
1814                 + 1 /* always, we need it in most cases, and we can't tell here
1815                        & now if we don't need it */
1816 #ifdef USE_SLOW_TIMER
1817                 + 1 /* slow timer process */
1818 #endif
1819 #ifdef USE_TCP
1820                 +((!tcp_disable)?( 1/* tcp main */ + tcp_listeners ):0)
1821 #endif
1822 #ifdef USE_SCTP
1823                 +((!sctp_disable)?sctp_listeners:0)
1824 #endif
1825                 ;
1826 }
1827
1828 int main(int argc, char** argv)
1829 {
1830
1831         FILE* cfg_stream;
1832         int c,r;
1833         char *tmp;
1834         int tmp_len;
1835         int port;
1836         int proto;
1837         char *options;
1838         int ret;
1839         unsigned int seed;
1840         int rfd;
1841         int debug_save, debug_flag;
1842         int dont_fork_cnt;
1843         struct name_lst* n_lst;
1844         char *p;
1845
1846         /*init*/
1847         time(&up_since);
1848         creator_pid = getpid();
1849         ret=-1;
1850         my_argc=argc; my_argv=argv;
1851         debug_flag=0;
1852         dont_fork_cnt=0;
1853
1854         daemon_status_init();
1855         /* command line options */
1856         options=  ":f:cm:M:dVIhEb:l:L:n:vrRDTN:W:w:t:u:g:P:G:SQ:O:a:A:"
1857 #ifdef STATS
1858                 "s:"
1859 #endif
1860         ;
1861         /* Handle special command line arguments, that must be treated before
1862          * intializing the various subsystem or before parsing other arguments:
1863          *  - get the startup debug and log_stderr values
1864          *  - look if pkg mem size is overriden on the command line (-M) and get
1865          *    the new value here (before intializing pkg_mem).
1866          *  - look if there is a -h, e.g. -f -h construction won't be caught
1867          *    later
1868          */
1869         opterr = 0;
1870         while((c=getopt(argc,argv,options))!=-1) {
1871                 switch(c) {
1872                         case 'd':
1873                                         debug_flag = 1;
1874                                         default_core_cfg.debug++;
1875                                         break;
1876                         case 'E':
1877                                         log_stderr=1;
1878                                         break;
1879                         case 'M':
1880                                         pkg_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1881                                         if (tmp &&(*tmp)){
1882                                                 fprintf(stderr, "bad private mem size number: -M %s\n",
1883                                                                                         optarg);
1884                                                 goto error;
1885                                         };
1886                                         break;
1887                         default:
1888                                         if (c == 'h' || (optarg && strcmp(optarg, "-h") == 0)) {
1889                                                 printf("version: %s\n", full_version);
1890                                                 printf("%s",help_msg);
1891                                                 exit(0);
1892                                         }
1893                                         break;
1894                 }
1895         }
1896         
1897         /*init pkg mallocs (before parsing cfg or the rest of the cmd line !)*/
1898         if (pkg_mem_size)
1899                 LOG(L_INFO, " private (per process) memory: %ld bytes\n",
1900                                                                 pkg_mem_size );
1901         if (init_pkg_mallocs()==-1)
1902                 goto error;
1903
1904 #ifdef DBG_MSG_QA
1905         fprintf(stderr, "WARNING: ser startup: "
1906                 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1907 #endif
1908
1909         /* init counters / stats */
1910         if (init_counters() == -1)
1911                 goto error;
1912 #ifdef USE_TCP
1913         init_tcp_options(); /* set the defaults before the config */
1914 #endif
1915 #ifdef USE_SCTP
1916         init_sctp_options(); /* set defaults before the config */
1917 #endif
1918         /* process command line (cfg. file path etc) */
1919         optind = 1;  /* reset getopt */
1920         /* switches required before script processing */
1921         while((c=getopt(argc,argv,options))!=-1) {
1922                 switch(c) {
1923                         case 'f':
1924                                         cfg_file=optarg;
1925                                         break;
1926                         case 'c':
1927                                         config_check=1;
1928                                         log_stderr=1; /* force stderr logging */
1929                                         break;
1930                         case 'L':
1931                                         mods_dir = optarg;
1932                                         break;
1933                         case 'm':
1934                                         shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1935                                         if (tmp &&(*tmp)){
1936                                                 fprintf(stderr, "bad shmem size number: -m %s\n",
1937                                                                                 optarg);
1938                                                 goto error;
1939                                         };
1940                                         LOG(L_INFO, "ser: shared memory: %ld bytes\n",
1941                                                                         shm_mem_size );
1942                                         break;
1943                         case 'M':
1944                                         /* ignore it, it was parsed immediately after startup,
1945                                            the pkg mem. is already initialized at this point */
1946                                         break;
1947                         case 'd':
1948                                         /* ignore it, was parsed immediately after startup */
1949                                         break;
1950                         case 'V':
1951                                         printf("version: %s\n", full_version);
1952                                         printf("flags: %s\n", ver_flags );
1953                                         print_ct_constants();
1954 #ifdef USE_SCTP
1955                                         tmp=malloc(256);
1956                                         if (tmp && (sctp_check_compiled_sockopts(tmp, 256)!=0))
1957                                                 printf("sctp unsupported socket options: %s\n", tmp);
1958                                         if (tmp) free(tmp);
1959 #endif
1960                                         printf("id: %s\n", ver_id);
1961                                         printf("compiled on %s with %s\n",
1962                                                         ver_compiled_time, ver_compiler );
1963
1964                                         exit(0);
1965                                         break;
1966                         case 'I':
1967                                         print_internals();
1968                                         exit(0);
1969                                         break;
1970                         case 'E':
1971                                         /* ignore it, was parsed immediately after startup */
1972                                         break;
1973                         case 'O':
1974                                         scr_opt_lev=strtol(optarg, &tmp, 10);
1975                                         if (tmp &&(*tmp)){
1976                                                 fprintf(stderr, "bad optimization level: -O %s\n",
1977                                                                                 optarg);
1978                                                 goto error;
1979                                         };
1980                                         break;
1981                         case 'u':
1982                                         /* user needed for possible shm. pre-init */
1983                                         user=optarg;
1984                                         break;
1985                         case 'A':
1986                                         p = strchr(optarg, '=');
1987                                         if(p) {
1988                                                 *p = '\0';
1989                                         }
1990                                         pp_define_set_type(0);
1991                                         if(pp_define(strlen(optarg), optarg)<0) {
1992                                                 fprintf(stderr, "error at define param: -A %s\n",
1993                                                                 optarg);
1994                                                 goto error;
1995                                         }
1996                                         if(p) {
1997                                                 *p = '=';
1998                                                 p++;
1999                                                 if(pp_define_set(strlen(p), p)<0) {
2000                                                         fprintf(stderr, "error at define value: -A %s\n",
2001                                                                 optarg);
2002                                                         goto error;
2003                                                 }
2004                                         }
2005                                         break;
2006                         case 'b':
2007                         case 'l':
2008                         case 'n':
2009                         case 'v':
2010                         case 'r':
2011                         case 'R':
2012                         case 'D':
2013                         case 'T':
2014                         case 'N':
2015                         case 'W':
2016                         case 'w':
2017                         case 't':
2018                         case 'g':
2019                         case 'P':
2020                         case 'G':
2021                         case 'S':
2022                         case 'Q':
2023                         case 'a':
2024                         case 's':
2025                                         break;
2026                         case '?':
2027                                         if (isprint(optopt)) {
2028                                                 fprintf(stderr, "Unknown option `-%c'."
2029                                                                                 " Use -h for help.\n", optopt);
2030                                         } else {
2031                                                 fprintf(stderr, "Unknown option character `\\x%x'."
2032                                                                                 " Use -h for help.\n",
2033                                                         optopt);
2034                                         }
2035                                         goto error;
2036                         case ':':
2037                                         fprintf(stderr, "Option `-%c' requires an argument."
2038                                                                         " Use -h for help.\n",
2039                                                 optopt);
2040                                         goto error;
2041                         default:
2042                                         abort();
2043                 }
2044         }
2045
2046         if (endianness_sanity_check() != 0){
2047                 fprintf(stderr, "BUG: endianness sanity tests failed\n");
2048                 goto error;
2049         }
2050         if (init_routes()<0) goto error;
2051         if (init_nonsip_hooks()<0) goto error;
2052         if (init_script_cb()<0) goto error;
2053         if (pv_init_api()<0) goto error;
2054         if (pv_register_core_vars()!=0) goto error;
2055         if (init_rpcs()<0) goto error;
2056         if (register_core_rpcs()!=0) goto error;
2057
2058         /* Fix the value of cfg_file variable.*/
2059         if (fix_cfg_file() < 0) goto error;
2060
2061         /* load config file or die */
2062         cfg_stream=fopen (cfg_file, "r");
2063         if (cfg_stream==0){
2064                 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
2065                                 strerror(errno));
2066                 goto error;
2067         }
2068
2069         /* seed the prng */
2070         /* try to use /dev/urandom if possible */
2071         seed=0;
2072         if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
2073 try_again:
2074                 if (read(rfd, (void*)&seed, sizeof(seed))==-1){
2075                         if (errno==EINTR) goto try_again; /* interrupted by signal */
2076                         LOG(L_WARN, "WARNING: could not read from /dev/urandom (%d)\n",
2077                                                 errno);
2078                 }
2079                 DBG("read %u from /dev/urandom\n", seed);
2080                         close(rfd);
2081         }else{
2082                 LOG(L_WARN, "WARNING: could not open /dev/urandom (%d)\n", errno);
2083         }
2084         seed+=getpid()+time(0);
2085         DBG("seeding PRNG with %u\n", seed);
2086         srand(seed);
2087         fastrand_seed(rand());
2088         srandom(rand()+time(0));
2089         DBG("test random numbers %u %lu %u\n", rand(), random(), fastrand());
2090
2091         /*register builtin  modules*/
2092         register_builtin_modules();
2093
2094         /* init named flags */
2095         init_named_flags();
2096
2097         yyin=cfg_stream;
2098         debug_save = default_core_cfg.debug;
2099         if ((yyparse()!=0)||(cfg_errors)){
2100                 fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
2101
2102                 goto error;
2103         }
2104         if (cfg_warnings){
2105                 fprintf(stderr, "%d config warnings\n", cfg_warnings);
2106         }
2107         if (debug_flag) default_core_cfg.debug = debug_save;
2108         print_rls();
2109
2110         /* options with higher priority than cfg file */
2111         optind = 1;  /* reset getopt */
2112         while((c=getopt(argc,argv,options))!=-1) {
2113                 switch(c) {
2114                         case 'f':
2115                         case 'c':
2116                         case 'm':
2117                         case 'M':
2118                         case 'd':
2119                         case 'V':
2120                         case 'I':
2121                         case 'h':
2122                         case 'O':
2123                         case 'A':
2124                                         break;
2125                         case 'E':
2126                                         log_stderr=1;   /* use in both getopt switches,
2127                                                                            takes priority over config */
2128                                         break;
2129                         case 'b':
2130                                         maxbuffer=strtol(optarg, &tmp, 10);
2131                                         if (tmp &&(*tmp)){
2132                                                 fprintf(stderr, "bad max buffer size number: -b %s\n",
2133                                                                                         optarg);
2134                                                 goto error;
2135                                         }
2136                                         break;
2137                         case 'l':
2138                                         if ((n_lst=parse_phostport_mh(optarg, &tmp, &tmp_len,
2139                                                                                         &port, &proto))==0){
2140                                                 fprintf(stderr, "bad -l address specifier: %s\n",
2141                                                                                 optarg);
2142                                                 goto error;
2143                                         }
2144                                         /* add a new addr. to our address list */
2145                                         if (add_listen_iface(n_lst->name, n_lst->next,  port,
2146                                                                                         proto, n_lst->flags)!=0){
2147                                                 fprintf(stderr, "failed to add new listen address\n");
2148                                                 free_name_lst(n_lst);
2149                                                 goto error;
2150                                         }
2151                                         free_name_lst(n_lst);
2152                                         break;
2153                         case 'n':
2154                                         children_no=strtol(optarg, &tmp, 10);
2155                                         if ((tmp==0) ||(*tmp)){
2156                                                 fprintf(stderr, "bad process number: -n %s\n",
2157                                                                         optarg);
2158                                                 goto error;
2159                                         }
2160                                         break;
2161                         case 'v':
2162                                         check_via=1;
2163                                         break;
2164                         case 'r':
2165                                         received_dns|=DO_DNS;
2166                                         break;
2167                         case 'R':
2168                                         received_dns|=DO_REV_DNS;
2169                                         break;
2170                         case 'D':
2171                                         dont_fork_cnt++;
2172                                         break;
2173                         case 'T':
2174                                 #ifdef USE_TCP
2175                                         tcp_disable=1;
2176                                 #else
2177                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
2178                                 #endif
2179                                         break;
2180                         case 'N':
2181                                 #ifdef USE_TCP
2182                                         tcp_cfg_children_no=strtol(optarg, &tmp, 10);
2183                                         if ((tmp==0) ||(*tmp)){
2184                                                 fprintf(stderr, "bad process number: -N %s\n",
2185                                                                         optarg);
2186                                                 goto error;
2187                                         }
2188                                 #else
2189                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
2190                                 #endif
2191                                         break;
2192                         case 'W':
2193                                 #ifdef USE_TCP
2194                                         tcp_poll_method=get_poll_type(optarg);
2195                                         if (tcp_poll_method==POLL_NONE){
2196                                                 fprintf(stderr, "bad poll method name: -W %s\ntry "
2197                                                                                 "one of %s.\n", optarg, poll_support);
2198                                                 goto error;
2199                                         }
2200                                 #else
2201                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
2202                                 #endif
2203                                         break;
2204                         case 'S':
2205                                 #ifdef USE_SCTP
2206                                         sctp_disable=1;
2207                                 #else
2208                                         fprintf(stderr,"WARNING: sctp support not compiled in\n");
2209                                 #endif
2210                                         break;
2211                         case 'Q':
2212                                 #ifdef USE_SCTP
2213                                         sctp_children_no=strtol(optarg, &tmp, 10);
2214                                         if ((tmp==0) ||(*tmp)){
2215                                                 fprintf(stderr, "bad process number: -O %s\n",
2216                                                                         optarg);
2217                                                 goto error;
2218                                         }
2219                                 #else
2220                                         fprintf(stderr,"WARNING: sctp support not compiled in\n");
2221                                 #endif
2222                                         break;
2223                         case 'w':
2224                                         working_dir=optarg;
2225                                         break;
2226                         case 't':
2227                                         chroot_dir=optarg;
2228                                         break;
2229                         case 'u':
2230                                         user=optarg;
2231                                         break;
2232                         case 'g':
2233                                         group=optarg;
2234                                         break;
2235                         case 'P':
2236                                         pid_file=optarg;
2237                                         break;
2238                         case 'G':
2239                                         pgid_file=optarg;
2240                                         break;
2241                         case 'a':
2242                                         if(strcmp(optarg, "on")==0 || strcmp(optarg, "yes")==0)
2243                                                 sr_auto_aliases = 1;
2244                                         else if(strcmp(optarg, "off")==0 || strcmp(optarg, "no")==0)
2245                                                 sr_auto_aliases = 0;
2246                                         else {
2247                                                 fprintf(stderr,
2248                                                         "bad auto aliases parameter: %s (valid on, off, yes, no)\n",
2249                                                         optarg);
2250                                                 goto error;
2251                                         }
2252                                         break;
2253                         case 's':
2254                                 #ifdef STATS
2255                                         stat_file=optarg;
2256                                 #endif
2257                                         break;
2258                         default:
2259                                         break;
2260                 }
2261         }
2262
2263         /* reinit if pv buffer size has been set in config */
2264         if (pv_reinit_buffer()<0)
2265                 goto error;
2266
2267         if (dont_fork_cnt)
2268                 dont_fork = dont_fork_cnt;      /* override by command line */
2269
2270         if (dont_fork > 0) {
2271                 dont_daemonize = dont_fork == 2;
2272                 dont_fork = dont_fork == 1;
2273         }
2274         /* init locks first */
2275         if (init_lock_ops()!=0)
2276                 goto error;
2277 #ifdef USE_TCP
2278 #ifdef USE_TLS
2279         if (tcp_disable)
2280                 tls_disable=1; /* if no tcp => no tls */
2281 #endif /* USE_TLS */
2282 #endif /* USE_TCP */
2283 #ifdef USE_SCTP
2284         if (sctp_disable!=1){
2285                 /* fix it */
2286                 if (sctp_check_support()==-1){
2287                         /* check if sctp support is auto, if not warn about disabling it */
2288                         if (sctp_disable!=2){
2289                                 fprintf(stderr, "ERROR: " "sctp enabled, but not supported by"
2290                                                                 " the OS\n");
2291                                 goto error;
2292                         }
2293                         sctp_disable=1;
2294                 }else{
2295                         /* sctp_disable!=1 and sctp supported => enable sctp */
2296                         sctp_disable=0;
2297                 }
2298         }
2299 #endif /* USE_SCTP */
2300         /* initialize the configured proto list */
2301         init_proto_order();
2302         /* init the resolver, before fixing the config */
2303         resolv_init();
2304         /* fix parameters */
2305         if (port_no<=0) port_no=SIP_PORT;
2306 #ifdef USE_TLS
2307         if (tls_port_no<=0) tls_port_no=SIPS_PORT;
2308 #endif
2309
2310
2311         if (children_no<=0) children_no=CHILD_NO;
2312 #ifdef USE_TCP
2313         if (!tcp_disable){
2314                 if (tcp_cfg_children_no<=0) tcp_cfg_children_no=children_no;
2315                 tcp_children_no = tcp_cfg_children_no;
2316         }
2317 #endif
2318 #ifdef USE_SCTP
2319         if (!sctp_disable){
2320                 if (sctp_children_no<=0) sctp_children_no=children_no;
2321         }
2322 #endif
2323
2324         if (working_dir==0) working_dir="/";
2325
2326         /* get uid/gid */
2327         if (user){
2328                 if (user2uid(&uid, &gid, user)<0){
2329                         fprintf(stderr, "bad user name/uid number: -u %s\n", user);
2330                         goto error;
2331                 }
2332         }
2333         if (group){
2334                 if (group2gid(&gid, group)<0){
2335                                 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
2336                         goto error;
2337                 }
2338         }
2339         if (fix_all_socket_lists()!=0){
2340                 fprintf(stderr,  "failed to initialize list addresses\n");
2341                 goto error;
2342         }
2343         if (default_core_cfg.dns_try_ipv6 && !(socket_types & SOCKET_T_IPV6)){
2344                 /* if we are not listening on any ipv6 address => no point
2345                  * to try to resovle ipv6 addresses */
2346                 default_core_cfg.dns_try_ipv6=0;
2347         }
2348         /* print all the listen addresses */
2349         printf("Listening on \n");
2350         print_all_socket_lists();
2351         printf("Aliases: \n");
2352         /*print_aliases();*/
2353         print_aliases();
2354         printf("\n");
2355
2356         if (dont_fork){
2357                 fprintf(stderr, "WARNING: no fork mode %s\n",
2358                                 (udp_listen)?(
2359                                 (udp_listen->next)?"and more than one listen address found "
2360                                 "(will use only the first one)":""
2361                                 ):"and no udp listen address found" );
2362         }
2363         if (config_check){
2364                 fprintf(stderr, "config file ok, exiting...\n");
2365                 return 0;
2366         }
2367
2368
2369         /*init shm mallocs
2370          *  this must be here
2371          *     -to allow setting shm mem size from the command line
2372          *       => if shm_mem should be settable from the cfg file move
2373          *       everything after
2374          *     -it must be also before init_timer and init_tcp
2375          *     -it must be after we know uid (so that in the SYSV sems case,
2376          *        the sems will have the correct euid)
2377          *  Note: shm can now be initialized when parsing the config script, that's
2378          *  why checking for a prior initialization is needed.
2379          * --andrei */
2380 #ifdef SHM_MEM
2381         if (!shm_initialized() && init_shm()<0)
2382                 goto error;
2383 #endif /* SHM_MEM */
2384         if (init_atomic_ops()==-1)
2385                 goto error;
2386         if (init_basex() != 0){
2387                 LOG(L_CRIT, "could not initialize base* framework\n");
2388                 goto error;
2389         }
2390         if (sr_cfg_init() < 0) {
2391                 LOG(L_CRIT, "could not initialize configuration framework\n");
2392                 goto error;
2393         }
2394         /* declare the core cfg before the module configs */
2395         if (cfg_declare("core", core_cfg_def, &default_core_cfg, cfg_sizeof(core),
2396                         &core_cfg)
2397         ) {
2398                 LOG(L_CRIT, "could not declare the core configuration\n");
2399                 goto error;
2400         }
2401 #ifdef USE_TCP
2402         if (tcp_register_cfg()){
2403                 LOG(L_CRIT, "could not register the tcp configuration\n");
2404                 goto error;
2405         }
2406 #endif /* USE_TCP */
2407 #ifdef USE_SCTP
2408         if (sctp_register_cfg()){
2409                 LOG(L_CRIT, "could not register the sctp configuration\n");
2410                 goto error;
2411         }
2412 #endif /* USE_SCTP */
2413         /*init timer, before parsing the cfg!*/
2414         if (init_timer()<0){
2415                 LOG(L_CRIT, "could not initialize timer, exiting...\n");
2416                 goto error;
2417         }
2418 #ifdef USE_DNS_CACHE
2419         if (init_dns_cache()<0){
2420                 LOG(L_CRIT, "could not initialize the dns cache, exiting...\n");
2421                 goto error;
2422         }
2423 #ifdef USE_DNS_CACHE_STATS
2424         /* preinitializing before the nubmer of processes is determined */
2425         if (init_dns_cache_stats(1)<0){
2426                 LOG(L_CRIT, "could not initialize the dns cache measurement\n");
2427                 goto error;
2428         }
2429 #endif /* USE_DNS_CACHE_STATS */
2430 #endif
2431 #ifdef USE_DST_BLACKLIST
2432         if (init_dst_blacklist()<0){
2433                 LOG(L_CRIT, "could not initialize the dst blacklist, exiting...\n");
2434                 goto error;
2435         }
2436 #ifdef USE_DST_BLACKLIST_STATS
2437         /* preinitializing before the number of processes is determined */
2438         if (init_dst_blacklist_stats(1)<0){
2439                 LOG(L_CRIT, "could not initialize the dst blacklist measurement\n");
2440                 goto error;
2441         }
2442 #endif /* USE_DST_BLACKLIST_STATS */
2443 #endif
2444         if (init_avps()<0) goto error;
2445         if (rpc_init_time() < 0) goto error;
2446
2447 #ifdef USE_TCP
2448         if (!tcp_disable){
2449                 /*init tcp*/
2450                 if (init_tcp()<0){
2451                         LOG(L_CRIT, "could not initialize tcp, exiting...\n");
2452                         goto error;
2453                 }
2454         }
2455 #endif /* USE_TCP */
2456 #ifdef USE_SCTP
2457         if (!sctp_disable){
2458                 if (init_sctp()<0){
2459                         LOG(L_CRIT, "Could not initialize sctp, exiting...\n");
2460                         goto error;
2461                 }
2462         }
2463 #endif /* USE_SCTP */
2464         /* init_daemon? */
2465         if( !dont_fork && daemonize((log_name==0)?argv[0]:log_name, 1) < 0)
2466                 goto error;
2467         if (install_sigs() != 0){
2468                 fprintf(stderr, "ERROR: could not install the signal handlers\n");
2469                 goto error;
2470         }
2471
2472         if (disable_core_dump) set_core_dump(0, 0);
2473         else set_core_dump(1, shm_mem_size+pkg_mem_size+4*1024*1024);
2474         if (open_files_limit>0){
2475                 if(increase_open_fds(open_files_limit)<0){
2476                         fprintf(stderr, "ERROR: error could not increase file limits\n");
2477                         goto error;
2478                 }
2479         }
2480         if (mlock_pages)
2481                 mem_lock_pages();
2482
2483         if (real_time&4)
2484                         set_rt_prio(rt_prio, rt_policy);
2485
2486         
2487         if (init_modules() != 0) {
2488                 fprintf(stderr, "ERROR: error while initializing modules\n");
2489                 goto error;
2490         }
2491         
2492         /* initialize process_table, add core process no. (calc_proc_no()) to the
2493          * processes registered from the modules*/
2494         if (init_pt(calc_proc_no())==-1)
2495                 goto error;
2496 #ifdef USE_TCP
2497 #ifdef USE_TLS
2498         if (!tls_disable){
2499                 if (!tls_loaded()){
2500                         LOG(L_WARN, "WARNING: tls support enabled, but no tls engine "
2501                                                 " available (forgot to load the tls module?)\n");
2502                         LOG(L_WARN, "WARNING: disabling tls...\n");
2503                         tls_disable=1;
2504                 }
2505                 /* init tls*/
2506                 if (init_tls()<0){
2507                         LOG(L_CRIT, "could not initialize tls, exiting...\n");
2508                         goto error;
2509                 }
2510         }
2511 #endif /* USE_TLS */
2512 #endif /* USE_TCP */
2513
2514         /* The total number of processes is now known, note that no
2515          * function being called before this point may rely on the
2516          * number of processes !
2517          */
2518         DBG("Expect (at least) %d SER processes in your process list\n",
2519                         get_max_procs());
2520
2521 #if defined USE_DNS_CACHE && defined USE_DNS_CACHE_STATS
2522         if (init_dns_cache_stats(get_max_procs())<0){
2523                 LOG(L_CRIT, "could not initialize the dns cache measurement\n");
2524                 goto error;
2525         }
2526 #endif
2527 #if defined USE_DST_BLACKLIST && defined USE_DST_BLACKLIST_STATS
2528         if (init_dst_blacklist_stats(get_max_procs())<0){
2529                 LOG(L_CRIT, "could not initialize the dst blacklist measurement\n");
2530                 goto error;
2531         }
2532 #endif
2533
2534         /* fix routing lists */
2535         if ( (r=fix_rls())!=0){
2536                 fprintf(stderr, "ERROR: error %d while trying to fix configuration\n",
2537                                                 r);
2538                 goto error;
2539         };
2540         fixup_complete=1;
2541
2542 #ifdef STATS
2543         if (init_stats(  dont_fork ? 1 : children_no  )==-1) goto error;
2544 #endif
2545
2546         ret=main_loop();
2547         if (ret < 0)
2548                 goto error;
2549         /*kill everything*/
2550         if (is_main) shutdown_children(SIGTERM, 0);
2551         if (!dont_daemonize) {
2552                 if (daemon_status_send(0) < 0)
2553                         ERR("error sending exit status: %s [%d]\n",
2554                                         strerror(errno), errno);
2555         }
2556         /* else terminate process */
2557         return ret;
2558
2559 error:
2560         /*kill everything*/
2561         if (is_main) shutdown_children(SIGTERM, 0);
2562         if (!dont_daemonize) {
2563                 if (daemon_status_send((char)-1) < 0)
2564                         ERR("error sending exit status: %s [%d]\n",
2565                                         strerror(errno), errno);
2566         }
2567         return -1;
2568 }