- applied patch from Dragos Vingarzan <vingarzan@fokus.fraunhofer.de> which
[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
250 struct process_table *pt=0;             /*array with children pids, 0= main proc,
251                                                                         alloc'ed in shared mem if possible*/
252 int *process_count = 0;                 /* Total number of SER processes currently 
253                                                                    running */
254 gen_lock_t* process_lock;               /* lock on the process table */
255 int process_no = 0;                             /* index of process in the pt */
256
257 int sig_flag = 0;              /* last signal received */
258 int debug = L_DEFAULT; /* print only msg. < L_WARN */
259 int dont_fork = 0;
260 int dont_daemonize = 0;
261 int log_stderr = 0;
262 pid_t creator_pid = (pid_t) -1;
263 /* log facility (see syslog(3)) */
264 int log_facility = LOG_DAEMON;
265 int config_check = 0;
266 /* check if reply first via host==us */
267 int check_via =  0;
268 /* shall use stateful synonym branches? faster but not reboot-safe */
269 int syn_branch = 1;
270 /* debugging level for memory stats */
271 int memlog = L_DBG;
272 /* debugging level for the malloc debug messages */
273 int memdbg = L_DBG;
274 /* debugging level for timer debugging */
275 int timerlog = L_WARN;
276 /* should replies include extensive warnings? by default yes,
277    good for trouble-shooting
278 */
279 int sip_warning = 1;
280 /* should localy-generated messages include server's signature?
281    be default yes, good for trouble-shooting
282 */
283 int server_signature=1;
284 /* should ser try to locate outbound interface on multihomed
285  * host? by default not -- too expensive
286  */
287 int mhomed=0;
288 /* use dns and/or rdns or to see if we need to add
289    a ;received=x.x.x.x to via: */
290 int received_dns = 0;
291 char* working_dir = 0;
292 char* chroot_dir = 0;
293 char* user=0;
294 char* group=0;
295 int uid = 0;
296 int gid = 0;
297 char* sock_user=0;
298 char* sock_group=0;
299 int sock_uid= -1;
300 int sock_gid= -1;
301 int sock_mode= S_IRUSR| S_IWUSR| S_IRGRP| S_IWGRP; /* rw-rw---- */
302
303 /* more config stuff */
304 int disable_core_dump=0; /* by default enabled */
305 int open_files_limit=-1; /* don't touch it by default */
306 /* a hint to reply modules whether they should send reply
307    to IP advertised in Via or IP from which a request came
308 */
309 int reply_to_via=0;
310
311 #ifdef USE_MCAST
312 int mcast_loopback = 0;
313 int mcast_ttl = -1; /* if -1, don't touch it, use the default (usually 1) */
314 #endif /* USE_MCAST */
315 #ifdef USE_DNS_CACHE
316 int use_dns_cache=1; /* 1 if the cache is enabled, 0 otherwise */
317 int use_dns_failover=0; /* 1 if failover is enabled, 0 otherwise */
318 #endif
319 #ifdef USE_DST_BLACKLIST
320 int use_dst_blacklist=0; /* 1 if the blacklist is enabled */
321 #endif
322
323 int tos = IPTOS_LOWDELAY;
324
325 #if 0
326 char* names[MAX_LISTEN];              /* our names */
327 int names_len[MAX_LISTEN];            /* lengths of the names*/
328 struct ip_addr addresses[MAX_LISTEN]; /* our ips */
329 int addresses_no=0;                   /* number of names/ips */
330 #endif
331 struct socket_info* udp_listen=0;
332 #ifdef USE_TCP
333 struct socket_info* tcp_listen=0;
334 #endif
335 #ifdef USE_TLS
336 struct socket_info* tls_listen=0;
337 #endif
338 struct socket_info* bind_address=0; /* pointer to the crt. proc.
339                                                                          listening address*/
340 struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
341 struct socket_info* sendipv6; /* same as above for ipv6 */
342 #ifdef USE_TCP
343 struct socket_info* sendipv4_tcp;
344 struct socket_info* sendipv6_tcp;
345 #endif
346 #ifdef USE_TLS
347 struct socket_info* sendipv4_tls;
348 struct socket_info* sendipv6_tls;
349 #endif
350
351 unsigned short port_no=0; /* default port*/
352 #ifdef USE_TLS
353 unsigned short tls_port_no=0; /* default port */
354 #endif
355
356 struct host_alias* aliases=0; /* name aliases list */
357
358 /* Parameter to child_init */
359 int child_rank = 0;
360
361 /* process_bm_t process_bit = 0; */
362 #ifdef ROUTE_SRV
363 #endif
364
365 /* cfg parsing */
366 int cfg_errors=0;
367 int cfg_warnings=0;
368
369
370 /* shared memory (in MB) */
371 unsigned long shm_mem_size=SHM_MEM_SIZE * 1024 * 1024;
372
373 /* export command-line to anywhere else */
374 int my_argc;
375 char **my_argv;
376
377 #define MAX_FD 32 /* maximum number of inherited open file descriptors,
378                     (normally it shouldn't  be bigger  than 3) */
379
380
381 extern FILE* yyin;
382 extern int yyparse();
383
384
385 int is_main=1; /* flag = is this the  "main" process? */
386
387 char* pid_file = 0; /* filename as asked by use */
388 char* pgid_file = 0;
389
390
391 /* call it before exiting; if show_status==1, mem status is displayed */
392 void cleanup(show_status)
393 {
394         /*clean-up*/
395         if (mem_lock)
396                 shm_unlock(); /* hack: force-unlock the shared memory lock in case
397                                          some process crashed and let it locked; this will
398                                          allow an almost gracious shutdown */
399         destroy_modules();
400 #ifdef USE_DNS_CACHE
401         destroy_dns_cache();
402 #endif
403 #ifdef USE_DST_BLACKLIST
404         destroy_dst_blacklist();
405 #endif
406 #ifdef USE_TCP
407         destroy_tcp();
408 #endif
409 #ifdef USE_TLS
410         destroy_tls();
411 #endif
412         destroy_timer();
413         destroy_script_cb();
414         destroy_routes();
415         destroy_atomic_ops();
416 #ifdef PKG_MALLOC
417         if (show_status){
418                 LOG(memlog, "Memory status (pkg):\n");
419                 pkg_status();
420         }
421 #endif
422 #ifdef SHM_MEM
423         if (pt) shm_free(pt);
424         pt=0;
425         if (show_status){
426                         LOG(memlog, "Memory status (shm):\n");
427                         shm_status();
428         }
429         /* zero all shmem alloc vars that we still use */
430         shm_mem_destroy();
431 #endif
432         if (pid_file) unlink(pid_file);
433         if (pgid_file) unlink(pgid_file);
434 }
435
436
437 /* tries to send a signal to all our processes
438  * if daemonized  is ok to send the signal to all the process group,
439  * however if not daemonized we might end up sending the signal also
440  * to the shell which launched us => most signals will kill it if
441  * it's not in interactive mode and we don't want this. The non-daemonized
442  * case can occur when an error is encountered before daemonize is called
443  * (e.g. when parsing the config file) or when ser is started in "dont-fork"
444  *  mode. Sending the signal to all the processes in pt[] will not work
445  *  for processes forked from modules (which have no correspondent entry in
446  *  pt), but this can happen only in dont_fork mode (which is only for
447  *  debugging). So in the worst case + "dont-fork" we might leave some
448  *  zombies. -- andrei */
449 static void kill_all_children(int signum)
450 {
451         int r;
452
453         if (own_pgid) kill(0, signum);
454         else if (pt){
455                 lock_get(process_lock);
456                 for (r=1; r<*process_count; r++){
457                         if (pt[r].pid) {
458                                 kill(pt[r].pid, signum);
459                         }
460                         else LOG(L_CRIT, "BUG: killing: %s > %d no pid!!!\n",
461                                                         pt[r].desc, pt[r].pid);
462                 }
463                 lock_release(process_lock);
464         }
465 }
466
467
468
469 /* if this handler is called, a critical timeout has occured while
470  * waiting for the children to finish => we should kill everything and exit */
471 static void sig_alarm_kill(int signo)
472 {
473         kill_all_children(SIGKILL); /* this will kill the whole group
474                                                                   including "this" process;
475                                                                   for debugging replace with SIGABRT
476                                                                   (but warning: it might generate lots
477                                                                    of cores) */
478 }
479
480
481 /* like sig_alarm_kill, but the timeout has occured when cleaning up
482  * => try to leave a core for future diagnostics */
483 static void sig_alarm_abort(int signo)
484 {
485         /* LOG is not signal safe, but who cares, we are abort-ing anyway :-) */
486         LOG(L_CRIT, "BUG: shutdown timeout triggered, dying...");
487         abort();
488 }
489
490
491
492 void handle_sigs()
493 {
494         pid_t   chld;
495         int     chld_status;
496
497         switch(sig_flag){
498                 case 0: break; /* do nothing*/
499                 case SIGPIPE:
500                                 /* SIGPIPE might be rarely received on use of
501                                    exec module; simply ignore it
502                                  */
503                                 LOG(L_WARN, "WARNING: SIGPIPE received and ignored\n");
504                                 break;
505                 case SIGINT:
506                 case SIGTERM:
507                         /* we end the program in all these cases */
508                         if (sig_flag==SIGINT)
509                                 DBG("INT received, program terminates\n");
510                         else
511                                 DBG("SIGTERM received, program terminates\n");
512
513                         /* first of all, kill the children also */
514                         kill_all_children(SIGTERM);
515
516                              /* Wait for all the children to die */
517                         while(wait(0) > 0);
518
519                         cleanup(1); /* cleanup & show status*/
520                         dprint("Thank you for flying " NAME "\n");
521                         exit(0);
522                         break;
523
524                 case SIGUSR1:
525 #ifdef STATS
526                         dump_all_statistic();
527 #endif
528 #ifdef PKG_MALLOC
529                         LOG(memlog, "Memory status (pkg):\n");
530                         pkg_status();
531 #endif
532 #ifdef SHM_MEM
533                         LOG(memlog, "Memory status (shm):\n");
534                         shm_status();
535 #endif
536                         break;
537
538                 case SIGCHLD:
539                         while ((chld=waitpid( -1, &chld_status, WNOHANG ))>0) {
540                                 if (WIFEXITED(chld_status))
541                                         LOG(L_INFO, "child process %d exited normally,"
542                                                         " status=%d\n", chld,
543                                                         WEXITSTATUS(chld_status));
544                                 else if (WIFSIGNALED(chld_status)) {
545                                         LOG(L_INFO, "child process %d exited by a signal"
546                                                         " %d\n", chld, WTERMSIG(chld_status));
547 #ifdef WCOREDUMP
548                                         LOG(L_INFO, "core was %sgenerated\n",
549                                                          WCOREDUMP(chld_status) ?  "" : "not " );
550 #endif
551                                 }else if (WIFSTOPPED(chld_status))
552                                         LOG(L_INFO, "child process %d stopped by a"
553                                                                 " signal %d\n", chld,
554                                                                  WSTOPSIG(chld_status));
555                         }
556 #ifndef STOP_JIRIS_CHANGES
557                         if (dont_fork) {
558                                 LOG(L_INFO, "INFO: dont_fork turned on, living on\n");
559                                 break;
560                         }
561                         LOG(L_INFO, "INFO: terminating due to SIGCHLD\n");
562 #endif
563                         /* exit */
564                         kill_all_children(SIGTERM);
565                         if (set_sig_h(SIGALRM, sig_alarm_kill) == SIG_ERR ) {
566                                 LOG(L_ERR, "ERROR: could not install SIGALARM handler\n");
567                                 /* continue, the process will die anyway if no
568                                  * alarm is installed which is exactly what we want */
569                         }
570                         alarm(60); /* 1 minute close timeout */
571                         while(wait(0) > 0); /* wait for all the children to terminate*/
572                         set_sig_h(SIGALRM, sig_alarm_abort);
573                         cleanup(1); /* cleanup & show status*/
574                         alarm(0);
575                         set_sig_h(SIGALRM, SIG_IGN);
576                         DBG("terminating due to SIGCHLD\n");
577                         exit(0);
578                         break;
579
580                 case SIGHUP: /* ignoring it*/
581                                         DBG("SIGHUP received, ignoring it\n");
582                                         break;
583                 default:
584                         LOG(L_CRIT, "WARNING: unhandled signal %d\n", sig_flag);
585         }
586         sig_flag=0;
587 }
588
589
590
591 /* added by jku; allows for regular exit on a specific signal;
592    good for profiling which only works if exited regularly and
593    not by default signal handlers
594     - modified by andrei: moved most of the stuff to handle_sigs,
595        made it safer for the "fork" case
596 */
597 static void sig_usr(int signo)
598 {
599
600
601         if (is_main){
602                 if (sig_flag==0) sig_flag=signo;
603                 else /*  previous sig. not processed yet, ignoring? */
604                         return; ;
605                 if (dont_fork)
606                                 /* only one proc, doing everything from the sig handler,
607                                 unsafe, but this is only for debugging mode*/
608                         handle_sigs();
609         }else{
610                 /* process the important signals */
611                 switch(signo){
612                         case SIGPIPE:
613                                         LOG(L_INFO, "INFO: signal %d received\n", signo);
614                                 break;
615                         case SIGINT:
616                         case SIGTERM:
617                                         LOG(L_INFO, "INFO: signal %d received\n", signo);
618                                         /* print memory stats for non-main too */
619                                         #ifdef PKG_MALLOC
620                                         LOG(memlog, "Memory status (pkg):\n");
621                                         pkg_status();
622                                         #endif
623                                         exit(0);
624                                         break;
625                         case SIGUSR1:
626                                 /* statistics, do nothing, printed only from the main proc */
627                                         break;
628                                 /* ignored*/
629                         case SIGUSR2:
630                         case SIGHUP:
631                                         break;
632                         case SIGCHLD:
633 #ifndef                         STOP_JIRIS_CHANGES
634                                         DBG("SIGCHLD received: "
635                                                 "we do not worry about grand-children\n");
636 #else
637                                         exit(0); /* terminate if one child died */
638 #endif
639                 }
640         }
641 }
642
643
644
645 /* install the signal handlers, returns 0 on success, -1 on error */
646 int install_sigs()
647 {
648         /* added by jku: add exit handler */
649         if (set_sig_h(SIGINT, sig_usr) == SIG_ERR ) {
650                 DPrint("ERROR: no SIGINT signal handler can be installed\n");
651                 goto error;
652         }
653         /* if we debug and write to a pipe, we want to exit nicely too */
654         if (set_sig_h(SIGPIPE, sig_usr) == SIG_ERR ) {
655                 DPrint("ERROR: no SIGINT signal handler can be installed\n");
656                 goto error;
657         }
658         if (set_sig_h(SIGUSR1, sig_usr)  == SIG_ERR ) {
659                 DPrint("ERROR: no SIGUSR1 signal handler can be installed\n");
660                 goto error;
661         }
662         if (set_sig_h(SIGCHLD , sig_usr)  == SIG_ERR ) {
663                 DPrint("ERROR: no SIGCHLD signal handler can be installed\n");
664                 goto error;
665         }
666         if (set_sig_h(SIGTERM , sig_usr)  == SIG_ERR ) {
667                 DPrint("ERROR: no SIGTERM signal handler can be installed\n");
668                 goto error;
669         }
670         if (set_sig_h(SIGHUP , sig_usr)  == SIG_ERR ) {
671                 DPrint("ERROR: no SIGHUP signal handler can be installed\n");
672                 goto error;
673         }
674         if (set_sig_h(SIGUSR2 , sig_usr)  == SIG_ERR ) {
675                 DPrint("ERROR: no SIGUSR2 signal handler can be installed\n");
676                 goto error;
677         }
678         return 0;
679 error:
680         return -1;
681 }
682
683 /* returns -1 on error, 0 on success
684  * sets proto */
685 static int parse_proto(unsigned char* s, long len, int* proto)
686 {
687 #define PROTO2UINT(a, b, c) ((  (((unsigned int)(a))<<16)+ \
688                                                                 (((unsigned int)(b))<<8)+  \
689                                                                 ((unsigned int)(c)) ) | 0x20202020)
690         unsigned int i;
691         if (len!=3) return -1;
692         i=PROTO2UINT(s[0], s[1], s[2]);
693         switch(i){
694                 case PROTO2UINT('u', 'd', 'p'):
695                         *proto=PROTO_UDP;
696                         break;
697 #ifdef USE_TCP
698                 case PROTO2UINT('t', 'c', 'p'):
699                         *proto=PROTO_TCP;
700                         break;
701 #ifdef USE_TLS
702                 case PROTO2UINT('t', 'l', 's'):
703                         *proto=PROTO_TLS;
704                         break;
705 #endif
706 #endif
707                 default:
708                         return -1;
709         }
710         return 0;
711 }
712
713
714
715 /*
716  * parses [proto:]host[:port]
717  * where proto= udp|tcp|tls
718  * returns 0 on success and -1 on failure
719  */
720 static int parse_phostport(char* s, char** host, int* hlen, int* port,
721                                                         int* proto)
722 {
723         char* first; /* first ':' occurrence */
724         char* second; /* second ':' occurrence */
725         char* p;
726         int bracket;
727         char* tmp;
728
729         first=second=0;
730         bracket=0;
731
732         /* find the first 2 ':', ignoring possible ipv6 addresses
733          * (substrings between [])
734          */
735         for(p=s; *p; p++){
736                 switch(*p){
737                         case '[':
738                                 bracket++;
739                                 if (bracket>1) goto error_brackets;
740                                 break;
741                         case ']':
742                                 bracket--;
743                                 if (bracket<0) goto error_brackets;
744                                 break;
745                         case ':':
746                                 if (bracket==0){
747                                         if (first==0) first=p;
748                                         else if( second==0) second=p;
749                                         else goto error_colons;
750                                 }
751                                 break;
752                 }
753         }
754         if (p==s) return -1;
755         if (*(p-1)==':') goto error_colons;
756
757         if (first==0){ /* no ':' => only host */
758                 *host=s;
759                 *hlen=(int)(p-s);
760                 *port=0;
761                 *proto=0;
762                 return 0;
763         }
764         if (second){ /* 2 ':' found => check if valid */
765                 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
766                 *port=strtol(second+1, &tmp, 10);
767                 if ((tmp==0)||(*tmp)||(tmp==second+1)) goto error_port;
768                 *host=first+1;
769                 *hlen=(int)(second-*host);
770                 return 0;
771         }
772         /* only 1 ':' found => it's either proto:host or host:port */
773         *port=strtol(first+1, &tmp, 10);
774         if ((tmp==0)||(*tmp)||(tmp==first+1)){
775                 /* invalid port => it's proto:host */
776                 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
777                 *port=0;
778                 *host=first+1;
779                 *hlen=(int)(p-*host);
780         }else{
781                 /* valid port => its host:port */
782                 *proto=0;
783                 *host=s;
784                 *hlen=(int)(first-*host);
785         }
786         return 0;
787 error_brackets:
788         LOG(L_ERR, "ERROR: parse_phostport: too many brackets in %s\n", s);
789         return -1;
790 error_colons:
791         LOG(L_ERR, "ERROR: parse_phostport: too many colons in %s\n", s);
792         return -1;
793 error_proto:
794         LOG(L_ERR, "ERROR: parse_phostport: bad protocol in %s\n", s);
795         return -1;
796 error_port:
797         LOG(L_ERR, "ERROR: parse_phostport: bad port number in %s\n", s);
798         return -1;
799 }
800
801
802
803 /* main loop */
804 int main_loop()
805 {
806         int  i;
807         pid_t pid;
808         struct socket_info* si;
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                                 pid = fork_process(PROC_TIMER, "slow timer", 0);
842                                 if (pid<0){
843                                         LOG(L_CRIT,  "ERROR: main_loop: Cannot fork\n");
844                                         goto error;
845                                 }
846                                 if (pid==0){
847                                         /* child */
848                                         /* timer!*/
849                                         /* process_bit = 0; */
850                                         if (arm_slow_timer()<0) goto error;
851                                         slow_timer_main();
852                                 }else{
853                                         slow_timer_pid=pid;
854                                 }
855 #endif
856                                 /* we need another process to act as the "main" timer*/
857                                 pid = fork_process(PROC_TIMER, "timer", 0);
858                                 if (pid<0){
859                                         LOG(L_CRIT,  "ERROR: main_loop: Cannot fork\n");
860                                         goto error;
861                                 }
862                                 if (pid==0){
863                                         /* child */
864                                         /* timer!*/
865                                         /* process_bit = 0; */
866                                         if (arm_timer()<0) goto error;
867                                         timer_main();
868                                 }else{
869                                 }
870
871                 /* main process, receive loop */
872                 process_no=0; /*main process number*/
873                 pt[process_no].pid=getpid();
874                 snprintf(pt[process_no].desc, MAX_PT_DESC,
875                         "stand-alone receiver @ %s:%s",
876                          bind_address->name.s, bind_address->port_no_str.s );
877
878
879                      /* We will call child_init even if we
880                       * do not fork - and it will be called with rank 1 because
881                       * in fact we behave like a child, not like main process
882                       */
883
884                 if (init_child(1) < 0) {
885                         LOG(L_ERR, "main_dontfork: init_child failed\n");
886                         goto error;
887                 }
888
889                 is_main=1; /* hack 42: call init_child with is_main=0 in case
890                                          some modules wants to fork a child */
891
892                 return udp_rcv_loop();
893         }else{
894
895                 for(si=udp_listen;si;si=si->next){
896                         /* create the listening socket (for each address)*/
897                         /* udp */
898                         if (udp_init(si)==-1) goto error;
899                         /* get first ipv4/ipv6 socket*/
900                         if ((si->address.af==AF_INET)&&
901                                         ((sendipv4==0)||(sendipv4->flags&SI_IS_LO)))
902                                 sendipv4=si;
903         #ifdef USE_IPV6
904                         if((sendipv6==0)&&(si->address.af==AF_INET6))
905                                 sendipv6=si;
906         #endif
907                 }
908 #ifdef USE_TCP
909                 if (!tcp_disable){
910                         for(si=tcp_listen; si; si=si->next){
911                                 /* same thing for tcp */
912                                 if (tcp_init(si)==-1)  goto error;
913                                 /* get first ipv4/ipv6 socket*/
914                                 if ((si->address.af==AF_INET)&&
915                                                 ((sendipv4_tcp==0)||(sendipv4_tcp->flags&SI_IS_LO)))
916                                         sendipv4_tcp=si;
917                 #ifdef USE_IPV6
918                                 if((sendipv6_tcp==0)&&(si->address.af==AF_INET6))
919                                         sendipv6_tcp=si;
920                 #endif
921                         }
922                 }
923 #ifdef USE_TLS
924                 if (!tls_disable){
925                         for(si=tls_listen; si; si=si->next){
926                                 /* same as for tcp*/
927                                 if (tls_init(si)==-1)  goto error;
928                                 /* get first ipv4/ipv6 socket*/
929                                 if ((si->address.af==AF_INET)&&
930                                                 ((sendipv4_tls==0)||(sendipv4_tls->flags&SI_IS_LO)))
931                                         sendipv4_tls=si;
932                 #ifdef USE_IPV6
933                                 if((sendipv6_tls==0)&&(si->address.af==AF_INET6))
934                                         sendipv6_tls=si;
935                 #endif
936                         }
937                 }
938 #endif /* USE_TLS */
939 #endif /* USE_TCP */
940
941                         /* all processes should have access to all the sockets (for sending)
942                          * so we open all first*/
943                 if (do_suid()==-1) goto error; /* try to drop privileges */
944
945                 /* udp processes */
946                 for(si=udp_listen; si; si=si->next){
947                         for(i=0;i<children_no;i++){
948                                 child_rank++;
949                                 pid = fork_process(child_rank, "udp", 1);
950                                 if (pid<0){
951                                         LOG(L_CRIT,  "main_loop: Cannot fork\n");
952                                         goto error;
953                                 }else if (pid==0){
954                                         /* child */
955                                         bind_address=si; /* shortcut */
956 #ifdef STATS
957                                         setstats( i+r*children_no );
958 #endif
959                                         return udp_rcv_loop();
960                                 }else{
961                                                 snprintf(pt[process_no].desc, MAX_PT_DESC,
962                                                         "receiver child=%d sock= %s:%s", i,
963                                                         si->name.s, si->port_no_str.s );
964                                 }
965                         }
966                         /*parent*/
967                         /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
968                 }
969         }
970
971         /*this is the main process*/
972         bind_address=0;                         /* main proc -> it shouldn't send anything, */
973
974
975         {
976 #ifdef USE_SLOW_TIMER
977                 /* fork again for the "slow" timer process*/
978                 pid = fork_process(PROC_TIMER, "slow timer", 1);
979                 if (pid<0){
980                         LOG(L_CRIT, "main_loop: cannot fork \"slow\" timer process\n");
981                         goto error;
982                 }else if (pid==0){
983                         /* child */
984                         /* is_main=0; */
985                         if (arm_slow_timer()<0) goto error;
986                         slow_timer_main();
987                 }else{
988                         slow_timer_pid=pid;
989                 }
990 #endif /* USE_SLOW_TIMER */
991
992                 /* fork again for the "main" timer process*/
993                 pid = fork_process(PROC_TIMER, "timer", 1);
994                 if (pid<0){
995                         LOG(L_CRIT, "main_loop: cannot fork timer process\n");
996                         goto error;
997                 }else if (pid==0){
998                         /* child */
999                         /* is_main=0; */
1000                         if (arm_timer()<0) goto error;
1001                         timer_main();
1002                 }else{
1003                 }
1004         }
1005 #ifdef USE_TCP
1006                 if (!tcp_disable){
1007                                 /* start tcp  & tls receivers */
1008                         if (tcp_init_children()<0) goto error;
1009                                 /* start tcp+tls master proc */
1010                         pid = fork_process(PROC_TCP_MAIN, "tcp main process", 0);
1011                         if (pid<0){
1012                                 LOG(L_CRIT, "main_loop: cannot fork tcp main process: %s\n",
1013                                                         strerror(errno));
1014                                 goto error;
1015                         }else if (pid==0){
1016                                 /* child */
1017                                 tcp_main_loop();
1018                         }else{
1019                                 unix_tcp_sock=-1;
1020                         }
1021                 }
1022 #endif
1023         /* main */
1024         strncpy(pt[0].desc, "attendant", MAX_PT_DESC );
1025 #ifdef USE_TCP
1026         if(!tcp_disable){
1027                 pt[process_no].unix_sock=-1;
1028                 pt[process_no].idx=-1; /* this is not a "tcp" process*/
1029                 unix_tcp_sock=-1;
1030         }
1031 #endif
1032         /*DEBUG- remove it*/
1033
1034         /* process_bit = 0; */
1035         is_main=1;
1036
1037         if (init_child(PROC_MAIN) < 0) {
1038                 LOG(L_ERR, "main: error in init_child\n");
1039                 goto error;
1040         }
1041
1042         /*DEBUG- remove it*/
1043 #ifdef EXTRA_DEBUG
1044         for (r=0; r<*process_count; r++){
1045                 fprintf(stderr, "% 3d   % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1046         }
1047 #endif
1048
1049         for(;;){
1050                         pause();
1051                         handle_sigs();
1052         }
1053
1054
1055         /*return 0; */
1056  error:
1057         is_main=1;  /* if we are here, we are the "main process",
1058                                   any forked children should exit with exit(-1) and not
1059                                   ever use return */
1060         return -1;
1061
1062 }
1063
1064 /*
1065  * Calculate number of processes, this does not
1066  * include processes created by modules
1067  */
1068 static int calc_proc_no(void)
1069 {
1070         int udp_listeners;
1071         struct socket_info* si;
1072
1073         for (si=udp_listen, udp_listeners=0; si; si=si->next, udp_listeners++);
1074         return
1075                      /* receivers and attendant */
1076                 (dont_fork ? 1 : children_no * udp_listeners + 1)
1077                      /* timer process */
1078                 + 1 /* always, we need it in most cases, and we can't tell here
1079                        & now if we don't need it */
1080 #ifdef USE_SLOW_TIMER
1081                 + 1 /* slow timer process */
1082 #endif
1083 #ifdef USE_TCP
1084                 +((!tcp_disable)?( 1/* tcp main */ + tcp_children_no ):0)
1085 #endif
1086                 ;
1087 }
1088
1089 int main(int argc, char** argv)
1090 {
1091
1092         FILE* cfg_stream;
1093         int c,r;
1094         char *tmp;
1095         int tmp_len;
1096         int port;
1097         int proto;
1098         char *options;
1099         int ret;
1100         unsigned int seed;
1101         int rfd;
1102         int debug_save, debug_flag;
1103         int dont_fork_cnt;
1104         int socket_types;
1105
1106         /*init*/
1107         creator_pid = getpid();
1108         ret=-1;
1109         my_argc=argc; my_argv=argv;
1110         debug_flag=0;
1111         dont_fork_cnt=0;
1112
1113         /*init pkg mallocs (before parsing cfg or cmd line !)*/
1114         if (init_pkg_mallocs()==-1)
1115                 goto error;
1116
1117 #ifdef DBG_MSG_QA
1118         fprintf(stderr, "WARNING: ser startup: "
1119                 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1120 #endif
1121
1122         options=  "f:cm:dVhEb:l:n:vrRDTN:W:w:t:u:g:P:G:"
1123 #ifdef STATS
1124                 "s:"
1125 #endif
1126         ;
1127         /* look if there is a -h, e.g. -f -h construction won't catch it later */
1128         opterr = 0;
1129         while((c=getopt(argc,argv,options))!=-1) {
1130                 if (c == 'h' || (optarg && strcmp(optarg, "-h") == 0)) {
1131                         printf("version: %s\n", version);
1132                         printf("%s",help_msg);
1133                         exit(0);
1134                         break;
1135                 }
1136         }
1137         /* process command line (get port no, cfg. file path etc) */
1138         optind = 1;  /* reset getopt */
1139         /* switches required before script processing */
1140         while((c=getopt(argc,argv,options))!=-1) {
1141                 switch(c) {
1142                         case 'f':
1143                                         cfg_file=optarg;
1144                                         break;
1145                         case 'c':
1146                                         config_check=1;
1147                                         log_stderr=1; /* force stderr logging */
1148                                         break;
1149                         case 'm':
1150                                         shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1151                                         if (tmp &&(*tmp)){
1152                                                 fprintf(stderr, "bad shmem size number: -m %s\n",
1153                                                                                 optarg);
1154                                                 goto error;
1155                                         };
1156                                         LOG(L_INFO, "ser: shared memory: %ld bytes\n",
1157                                                                         shm_mem_size );
1158                                         break;
1159                         case 'd':
1160                                         debug_flag = 1;
1161                                         debug++;
1162                                         break;
1163                         case 'V':
1164                                         printf("version: %s\n", version);
1165                                         printf("flags: %s\n", flags );
1166                                         print_ct_constants();
1167                                         printf("%s\n",id);
1168                                         printf("%s compiled on %s with %s\n", __FILE__,
1169                                                         compiled, COMPILER );
1170
1171                                         exit(0);
1172                                         break;
1173                         case 'E':
1174                                         log_stderr=1;
1175                                         break;
1176                         case 'b':
1177                         case 'l':
1178                         case 'n':
1179                         case 'v':
1180                         case 'r':
1181                         case 'R':
1182                         case 'D':
1183                         case 'T':
1184                         case 'N':
1185                         case 'W':
1186                         case 'w':
1187                         case 't':
1188                         case 'u':
1189                         case 'g':
1190                         case 'P':
1191                         case 'G':
1192                         case 's':
1193                                         break;
1194                         case '?':
1195                                         if (isprint(optopt))
1196                                                 fprintf(stderr, "Unknown option `-%c. Use -h for help.\n", optopt);
1197                                         else
1198                                                 fprintf(stderr,
1199                                                                 "Unknown option character `\\x%x. Use -h for help.\n",
1200                                                                 optopt);
1201                                         goto error;
1202                         case ':':
1203                                         fprintf(stderr,
1204                                                                 "Option `-%c requires an argument. Use -h for help.\n",
1205                                                                 optopt);
1206                                         goto error;
1207                         default:
1208                                         abort();
1209                 }
1210         }
1211         
1212         if (init_routes()<0) goto error;
1213         /* fill missing arguments with the default values*/
1214         if (cfg_file==0) cfg_file=CFG_FILE;
1215
1216         /* load config file or die */
1217         cfg_stream=fopen (cfg_file, "r");
1218         if (cfg_stream==0){
1219                 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
1220                                 strerror(errno));
1221                 goto error;
1222         }
1223
1224         /* seed the prng */
1225         /* try to use /dev/urandom if possible */
1226         seed=0;
1227         if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
1228 try_again:
1229                 if (read(rfd, (void*)&seed, sizeof(seed))==-1){
1230                         if (errno==EINTR) goto try_again; /* interrupted by signal */
1231                         LOG(L_WARN, "WARNING: could not read from /dev/urandom (%d)\n",
1232                                                 errno);
1233                 }
1234                 DBG("read %u from /dev/urandom\n", seed);
1235                         close(rfd);
1236         }else{
1237                 LOG(L_WARN, "WARNING: could not open /dev/urandom (%d)\n", errno);
1238         }
1239         seed+=getpid()+time(0);
1240         DBG("seeding PRNG with %u\n", seed);
1241         srand(seed);
1242         DBG("test random number %u\n", rand());
1243
1244         /*register builtin  modules*/
1245         register_builtin_modules();
1246
1247         /* init named flags */
1248         init_named_flags();
1249
1250         yyin=cfg_stream;
1251         debug_save = debug;
1252         if ((yyparse()!=0)||(cfg_errors)){
1253                 fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
1254                 goto error;
1255         }
1256         if (cfg_warnings){
1257                 fprintf(stderr, "%d config warnings\n", cfg_warnings);
1258         }
1259         if (debug_flag) debug = debug_save;
1260         print_rls();
1261
1262         /* options with higher priority than cfg file */
1263         optind = 1;  /* reset getopt */
1264         while((c=getopt(argc,argv,options))!=-1) {
1265                 switch(c) {
1266                         case 'f':
1267                         case 'c':
1268                         case 'm':
1269                         case 'd':
1270                         case 'V':
1271                         case 'h':
1272                                         break;
1273                         case 'E':
1274                                         log_stderr=1;   // use in both getopt switches
1275                                         break;
1276                         case 'b':
1277                                         maxbuffer=strtol(optarg, &tmp, 10);
1278                                         if (tmp &&(*tmp)){
1279                                                 fprintf(stderr, "bad max buffer size number: -p %s\n",
1280                                                                                         optarg);
1281                                                 goto error;
1282                                         }
1283                                         break;
1284                         case 'l':
1285                                         if (parse_phostport(optarg, &tmp, &tmp_len,
1286                                                                                         &port, &proto)<0){
1287                                                 fprintf(stderr, "bad -l address specifier: %s\n",
1288                                                                                 optarg);
1289                                                 goto error;
1290                                         }
1291                                         tmp[tmp_len]=0; /* null terminate the host */
1292                                         /* add a new addr. to our address list */
1293                                         if (add_listen_iface(tmp, port, proto, 0)!=0){
1294                                                 fprintf(stderr, "failed to add new listen address\n");
1295                                                 goto error;
1296                                         }
1297                                         break;
1298                         case 'n':
1299                                         children_no=strtol(optarg, &tmp, 10);
1300                                         if ((tmp==0) ||(*tmp)){
1301                                                 fprintf(stderr, "bad process number: -n %s\n",
1302                                                                         optarg);
1303                                                 goto error;
1304                                         }
1305                                         break;
1306                         case 'v':
1307                                         check_via=1;
1308                                         break;
1309                         case 'r':
1310                                         received_dns|=DO_DNS;
1311                                         break;
1312                         case 'R':
1313                                         received_dns|=DO_REV_DNS;
1314                                         break;
1315                         case 'D':
1316                                         dont_fork_cnt++;
1317                                         break;
1318                         case 'T':
1319                                 #ifdef USE_TCP
1320                                         tcp_disable=1;
1321                                 #else
1322                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1323                                 #endif
1324                                         break;
1325                         case 'N':
1326                                 #ifdef USE_TCP
1327                                         tcp_children_no=strtol(optarg, &tmp, 10);
1328                                         if ((tmp==0) ||(*tmp)){
1329                                                 fprintf(stderr, "bad process number: -N %s\n",
1330                                                                         optarg);
1331                                                 goto error;
1332                                         }
1333                                 #else
1334                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1335                                 #endif
1336                                         break;
1337                         case 'W':
1338                                 #ifdef USE_TCP
1339                                         tcp_poll_method=get_poll_type(optarg);
1340                                         if (tcp_poll_method==POLL_NONE){
1341                                                 fprintf(stderr, "bad poll method name: -W %s\ntry "
1342                                                                                 "one of %s.\n", optarg, poll_support);
1343                                                 goto error;
1344                                         }
1345                                 #else
1346                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1347                                 #endif
1348                                         break;
1349                         case 'w':
1350                                         working_dir=optarg;
1351                                         break;
1352                         case 't':
1353                                         chroot_dir=optarg;
1354                                         break;
1355                         case 'u':
1356                                         user=optarg;
1357                                         break;
1358                         case 'g':
1359                                         group=optarg;
1360                                         break;
1361                         case 'P':
1362                                         pid_file=optarg;
1363                                         break;
1364                         case 'G':
1365                                         pgid_file=optarg;
1366                                         break;
1367                         case 's':
1368                                 #ifdef STATS
1369                                         stat_file=optarg;
1370                                 #endif
1371                                         break;
1372                         default:
1373                                         break;
1374                 }
1375         }
1376
1377         if (dont_fork_cnt)
1378                 dont_fork = dont_fork_cnt;      /* override by command line */
1379
1380         if (dont_fork > 0) {
1381                 dont_daemonize = dont_fork == 2;
1382                 dont_fork = dont_fork == 1;
1383         }
1384         /* init the resolver, before fixing the config */
1385         resolv_init();
1386         /* fix parameters */
1387         if (port_no<=0) port_no=SIP_PORT;
1388 #ifdef USE_TLS
1389         if (tls_port_no<=0) tls_port_no=SIPS_PORT;
1390 #endif
1391
1392
1393         if (children_no<=0) children_no=CHILD_NO;
1394 #ifdef USE_TCP
1395         if (!tcp_disable){
1396                 if (tcp_children_no<=0) tcp_children_no=children_no;
1397         }
1398 #endif
1399
1400         if (working_dir==0) working_dir="/";
1401
1402         /* get uid/gid */
1403         if (user){
1404                 if (user2uid(&uid, &gid, user)<0){
1405                         fprintf(stderr, "bad user name/uid number: -u %s\n", user);
1406                         goto error;
1407                 }
1408         }
1409         if (group){
1410                 if (group2gid(&gid, group)<0){
1411                                 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
1412                         goto error;
1413                 }
1414         }
1415         if (fix_all_socket_lists(&socket_types)!=0){
1416                 fprintf(stderr,  "failed to initialize list addresses\n");
1417                 goto error;
1418         }
1419         if (dns_try_ipv6 && !(socket_types & SOCKET_T_IPV6)){
1420                 /* if we are not listening on any ipv6 address => no point
1421                  * to try to resovle ipv6 addresses */
1422                 dns_try_ipv6=0;
1423         }
1424         /* print all the listen addresses */
1425         printf("Listening on \n");
1426         print_all_socket_lists();
1427         printf("Aliases: \n");
1428         /*print_aliases();*/
1429         print_aliases();
1430         printf("\n");
1431
1432         if (dont_fork){
1433                 fprintf(stderr, "WARNING: no fork mode %s\n",
1434                                 (udp_listen)?(
1435                                 (udp_listen->next)?"and more than one listen address found "
1436                                 "(will use only the the first one)":""
1437                                 ):"and no udp listen address found" );
1438         }
1439         if (config_check){
1440                 fprintf(stderr, "config file ok, exiting...\n");
1441                 goto error;
1442         }
1443
1444
1445         /*init shm mallocs
1446          *  this must be here
1447          *     -to allow setting shm mem size from the command line
1448          *       => if shm_mem should be settable from the cfg file move
1449          *       everything after
1450          *     -it must be also before init_timer and init_tcp
1451          *     -it must be after we know uid (so that in the SYSV sems case,
1452          *        the sems will have the correct euid)
1453          * --andrei */
1454         if (init_shm_mallocs()==-1)
1455                 goto error;
1456         if (init_atomic_ops()==-1)
1457                 goto error;
1458         /*init timer, before parsing the cfg!*/
1459         if (init_timer()<0){
1460                 LOG(L_CRIT, "could not initialize timer, exiting...\n");
1461                 goto error;
1462         }
1463 #ifdef USE_DNS_CACHE
1464         if (init_dns_cache()<0){
1465                 LOG(L_CRIT, "could not initialize the dns cache, exiting...\n");
1466                 goto error;
1467         }
1468         if (use_dns_cache==0)
1469                 use_dns_failover=0; /* cannot work w/o dns_cache support */
1470 #endif
1471 #ifdef USE_DST_BLACKLIST
1472         if (init_dst_blacklist()<0){
1473                 LOG(L_CRIT, "could not initialize the dst blacklist, exiting...\n");
1474                 goto error;
1475         }
1476 #endif
1477         if (init_avps()<0) goto error;
1478         if (rpc_init_time() < 0) goto error;
1479
1480 #ifdef USE_TCP
1481         if (!tcp_disable){
1482                 /*init tcp*/
1483                 if (init_tcp()<0){
1484                         LOG(L_CRIT, "could not initialize tcp, exiting...\n");
1485                         goto error;
1486                 }
1487         }
1488 #ifdef USE_TLS
1489         if (!tls_disable){
1490                 /* init tls*/
1491                 if (init_tls()<0){
1492                         LOG(L_CRIT, "could not initialize tls, exiting...\n");
1493                         goto error;
1494                 }
1495         }
1496 #endif /* USE_TLS */
1497 #endif /* USE_TCP */
1498         /* init_daemon? */
1499         if (!dont_fork){
1500                 if ( daemonize(argv[0]) <0 ) goto error;
1501         }
1502         if (install_sigs() != 0){
1503                 fprintf(stderr, "ERROR: could not install the signal handlers\n");
1504                 goto error;
1505         }
1506
1507         if (disable_core_dump) set_core_dump(0, 0);
1508         else set_core_dump(1, shm_mem_size+PKG_MEM_POOL_SIZE+4*1024*1024);
1509         if (open_files_limit>0){
1510                 if(increase_open_fds(open_files_limit)<0){
1511                         fprintf(stderr, "ERROR: error could not increase file limits\n");
1512                         goto error;
1513                 }
1514         }
1515         
1516         if (init_modules() != 0) {
1517                 fprintf(stderr, "ERROR: error while initializing modules\n");
1518                 goto error;
1519         }
1520         /* initialize process_table, add core process no. (calc_proc_no()) to the 
1521          * processes registered from the modules*/
1522         if (init_pt(calc_proc_no())==-1)
1523                 goto error;
1524         
1525         /* The total number of processes is now known, note that no
1526          * function being called before this point may rely on the
1527          * number of processes !
1528          */
1529         DBG("Expect (at least) %d SER processes in your process list\n",
1530                         get_max_procs());
1531
1532         /* fix routing lists */
1533         if ( (r=fix_rls())!=0){
1534                 fprintf(stderr, "ERROR: error %d while trying to fix configuration\n",
1535                                                 r);
1536                 goto error;
1537         };
1538
1539 #ifdef STATS
1540         if (init_stats(  dont_fork ? 1 : children_no  )==-1) goto error;
1541 #endif
1542
1543         ret=main_loop();
1544         /*kill everything*/
1545         kill_all_children(SIGTERM);
1546         /*clean-up*/
1547         cleanup(0);
1548         return ret;
1549
1550 error:
1551         /*kill everything*/
1552         kill_all_children(SIGTERM);
1553         /*clean-up*/
1554         cleanup(0);
1555         return -1;
1556
1557 }