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