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