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