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