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