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