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