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