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