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