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