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