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