- use_dns_cache can be enabled/disabled runtime
[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
375 int tos = IPTOS_LOWDELAY;
376 int pmtu_discovery = 0;
377
378 #if 0
379 char* names[MAX_LISTEN];              /* our names */
380 int names_len[MAX_LISTEN];            /* lengths of the names*/
381 struct ip_addr addresses[MAX_LISTEN]; /* our ips */
382 int addresses_no=0;                   /* number of names/ips */
383 #endif
384 struct socket_info* udp_listen=0;
385 #ifdef USE_TCP
386 int tcp_main_pid=0; /* set after the tcp main process is started */
387 struct socket_info* tcp_listen=0;
388 #endif
389 #ifdef USE_TLS
390 struct socket_info* tls_listen=0;
391 #endif
392 struct socket_info* bind_address=0; /* pointer to the crt. proc.
393                                                                          listening address*/
394 struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
395 struct socket_info* sendipv6; /* same as above for ipv6 */
396 #ifdef USE_TCP
397 struct socket_info* sendipv4_tcp;
398 struct socket_info* sendipv6_tcp;
399 #endif
400 #ifdef USE_TLS
401 struct socket_info* sendipv4_tls;
402 struct socket_info* sendipv6_tls;
403 #endif
404
405 unsigned short port_no=0; /* default port*/
406 #ifdef USE_TLS
407 unsigned short tls_port_no=0; /* default port */
408 #endif
409
410 #ifdef USE_STUN
411 /* refresh interval in miliseconds */
412 unsigned int stun_refresh_interval=0;
413 /* stun can be switch off even if it is compiled */
414 int stun_allow_stun=1;
415 /* use or don't use fingerprint */
416 int stun_allow_fp=1;
417 #endif
418
419 struct host_alias* aliases=0; /* name aliases list */
420
421 /* Parameter to child_init */
422 int child_rank = 0;
423
424 /* how much to wait for children to terminate, before taking extreme measures*/
425 int ser_kill_timeout=DEFAULT_SER_KILL_TIMEOUT;
426
427 /* process_bm_t process_bit = 0; */
428 #ifdef ROUTE_SRV
429 #endif
430
431 /* cfg parsing */
432 int cfg_errors=0;
433 int cfg_warnings=0;
434
435
436 /* shared memory (in MB) */
437 unsigned long shm_mem_size=SHM_MEM_SIZE * 1024 * 1024;
438
439 /* export command-line to anywhere else */
440 int my_argc;
441 char **my_argv;
442
443 #define MAX_FD 32 /* maximum number of inherited open file descriptors,
444                     (normally it shouldn't  be bigger  than 3) */
445
446
447 extern FILE* yyin;
448 extern int yyparse();
449
450
451 int is_main=1; /* flag = is this the  "main" process? */
452 int fixup_complete=0; /* flag = is the fixup complete ? */
453
454 char* pid_file = 0; /* filename as asked by use */
455 char* pgid_file = 0;
456
457
458 /* call it before exiting; if show_status==1, mem status is displayed */
459 void cleanup(show_status)
460 {
461         /*clean-up*/
462 #ifndef SHM_SAFE_MALLOC
463         if (mem_lock)
464                 shm_unlock(); /* hack: force-unlock the shared memory lock in case
465                                          some process crashed and let it locked; this will
466                                          allow an almost gracious shutdown */
467 #endif
468         destroy_modules();
469 #ifdef USE_DNS_CACHE
470         destroy_dns_cache();
471 #endif
472 #ifdef USE_DST_BLACKLIST
473         destroy_dst_blacklist();
474 #endif
475         /* restore the original core configuration before the
476          * config block is freed, otherwise even logging is unusable,
477          * it can case segfault */
478         core_cfg = &default_core_cfg;
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 /** Update \c cfg_file variable to contain full pathname. The function updates
893  * the value of \c cfg_file global variable to contain full absolute pathname
894  * to the main configuration file of SER. The function uses CFG_FILE macro to
895  * determine the default path to the configuration file if the user did not
896  * specify one using the command line option. If \c cfg_file contains an
897  * absolute pathname then it is used unmodified, if it contains a relative
898  * pathanme than the value returned by \c getcwd function will be added at the
899  * beginning. This function must be run before SER changes its current working
900  * directory to / (in daemon mode).
901  * @return Zero on success, negative number
902  * on error.
903  */
904 int fix_cfg_file(void)
905 {
906         char* res = NULL;
907         size_t max_len, cwd_len, cfg_len;
908         
909         if (cfg_file == NULL) cfg_file = CFG_FILE;
910         if (cfg_file[0] == '/') return 0;
911         
912         /* cfg_file contains a relative pathname, get the current
913          * working directory and add it at the beginning
914          */
915         cfg_len = strlen(cfg_file);
916         
917         max_len = pathmax();
918         if ((res = malloc(max_len)) == NULL) goto error;
919         
920         if (getcwd(res, max_len) == NULL) goto error;
921         cwd_len = strlen(res);
922         
923         /* Make sure that the buffer is big enough */
924         if (cwd_len + 1 + cfg_len >= max_len) goto error;
925         
926         res[cwd_len] = '/';
927         memcpy(res + cwd_len + 1, cfg_file, cfg_len);
928         
929         res[cwd_len + 1 + cfg_len] = '\0'; /* Add terminating zero */
930         cfg_file = res;
931         return 0;
932         
933  error:
934         fprintf(stderr, "ERROR: Unable to fix cfg_file to contain full pathname\n");
935         if (res) free(res);
936         return -1;
937 }
938
939
940 /* main loop */
941 int main_loop()
942 {
943         int  i;
944         pid_t pid;
945         struct socket_info* si;
946         char si_desc[MAX_PT_DESC];
947 #ifdef EXTRA_DEBUG
948         int r;
949 #endif
950
951         /* one "main" process and n children handling i/o */
952         if (dont_fork){
953 #ifdef STATS
954                 setstats( 0 );
955 #endif
956                 if (udp_listen==0){
957                         LOG(L_ERR, "ERROR: no fork mode requires at least one"
958                                         " udp listen address, exiting...\n");
959                         goto error;
960                 }
961                 /* only one address, we ignore all the others */
962                 if (udp_init(udp_listen)==-1) goto error;
963                 bind_address=udp_listen;
964                 sendipv4=bind_address;
965                 sendipv6=bind_address; /*FIXME*/
966                 if (udp_listen->next){
967                         LOG(L_WARN, "WARNING: using only the first listen address"
968                                                 " (no fork)\n");
969                 }
970                 if (do_suid()==-1) goto error; /* try to drop privileges */
971                 /* process_no now initialized to zero -- increase from now on
972                    as new processes are forked (while skipping 0 reserved for main
973                 */
974
975                 /* init childs with rank==PROC_INIT before forking any process,
976                  * this is a place for delayed (after mod_init) initializations
977                  * (e.g. shared vars that depend on the total number of processes
978                  * that is known only after all mod_inits have been executed )
979                  * WARNING: the same init_child will be called latter, a second time
980                  * for the "main" process with rank PROC_MAIN (make sure things are
981                  * not initialized twice)*/
982                 if (init_child(PROC_INIT) < 0) {
983                         LOG(L_ERR, "ERROR: main_dontfork: init_child(PROC_INT) --"
984                                                 " exiting\n");
985                         goto error;
986                 }
987
988 #ifdef USE_SLOW_TIMER
989                 /* we need another process to act as the "slow" timer*/
990                                 pid = fork_process(PROC_TIMER, "slow timer", 0);
991                                 if (pid<0){
992                                         LOG(L_CRIT,  "ERROR: main_loop: Cannot fork\n");
993                                         goto error;
994                                 }
995                                 if (pid==0){
996                                         /* child */
997                                         /* timer!*/
998                                         /* process_bit = 0; */
999                                         if (real_time&2)
1000                                                 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1001
1002                                         if (arm_slow_timer()<0) goto error;
1003                                         slow_timer_main();
1004                                 }else{
1005                                         slow_timer_pid=pid;
1006                                 }
1007 #endif
1008                                 /* we need another process to act as the "main" timer*/
1009                                 pid = fork_process(PROC_TIMER, "timer", 0);
1010                                 if (pid<0){
1011                                         LOG(L_CRIT,  "ERROR: main_loop: Cannot fork\n");
1012                                         goto error;
1013                                 }
1014                                 if (pid==0){
1015                                         /* child */
1016                                         /* timer!*/
1017                                         /* process_bit = 0; */
1018                                         if (real_time&1)
1019                                                 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1020                                         if (arm_timer()<0) goto error;
1021                                         timer_main();
1022                                 }else{
1023                                 }
1024
1025                 /* main process, receive loop */
1026                 process_no=0; /*main process number*/
1027                 pt[process_no].pid=getpid();
1028                 snprintf(pt[process_no].desc, MAX_PT_DESC,
1029                         "stand-alone receiver @ %s:%s",
1030                          bind_address->name.s, bind_address->port_no_str.s );
1031
1032         /* call it also w/ PROC_MAIN to make sure modules that init things only
1033          * in PROC_MAIN get a chance to run */
1034         if (init_child(PROC_MAIN) < 0) {
1035                 LOG(L_ERR, "ERROR: main_dontfork: init_child(PROC_MAIN) -- exiting\n");
1036                 goto error;
1037         }
1038
1039                 /* We will call child_init even if we
1040                  * do not fork - and it will be called with rank 1 because
1041                  * in fact we behave like a child, not like main process
1042                  */
1043
1044                 if (init_child(1) < 0) {
1045                         LOG(L_ERR, "main_dontfork: init_child failed\n");
1046                         goto error;
1047                 }
1048                 return udp_rcv_loop();
1049         }else{ /* fork: */
1050
1051                 for(si=udp_listen;si;si=si->next){
1052                         /* create the listening socket (for each address)*/
1053                         /* udp */
1054                         if (udp_init(si)==-1) goto error;
1055                         /* get first ipv4/ipv6 socket*/
1056                         if ((si->address.af==AF_INET)&&
1057                                         ((sendipv4==0)||(sendipv4->flags&(SI_IS_LO|SI_IS_MCAST))))
1058                                 sendipv4=si;
1059         #ifdef USE_IPV6
1060                         if((sendipv6==0)&&(si->address.af==AF_INET6))
1061                                 sendipv6=si;
1062         #endif
1063                 }
1064 #ifdef USE_TCP
1065                 if (!tcp_disable){
1066                         for(si=tcp_listen; si; si=si->next){
1067                                 /* same thing for tcp */
1068                                 if (tcp_init(si)==-1)  goto error;
1069                                 /* get first ipv4/ipv6 socket*/
1070                                 if ((si->address.af==AF_INET)&&
1071                                                 ((sendipv4_tcp==0)||
1072                                                         (sendipv4_tcp->flags&(SI_IS_LO|SI_IS_MCAST))))
1073                                         sendipv4_tcp=si;
1074                 #ifdef USE_IPV6
1075                                 if((sendipv6_tcp==0)&&(si->address.af==AF_INET6))
1076                                         sendipv6_tcp=si;
1077                 #endif
1078                         }
1079                 }
1080 #ifdef USE_TLS
1081                 if (!tls_disable && tls_has_init_si()){
1082                         for(si=tls_listen; si; si=si->next){
1083                                 /* same as for tcp*/
1084                                 if (tls_init(si)==-1)  goto error;
1085                                 /* get first ipv4/ipv6 socket*/
1086                                 if ((si->address.af==AF_INET)&&
1087                                                 ((sendipv4_tls==0)||
1088                                                         (sendipv4_tls->flags&(SI_IS_LO|SI_IS_MCAST))))
1089                                         sendipv4_tls=si;
1090                 #ifdef USE_IPV6
1091                                 if((sendipv6_tls==0)&&(si->address.af==AF_INET6))
1092                                         sendipv6_tls=si;
1093                 #endif
1094                         }
1095                 }
1096 #endif /* USE_TLS */
1097 #endif /* USE_TCP */
1098
1099                         /* all processes should have access to all the sockets (for sending)
1100                          * so we open all first*/
1101                 if (do_suid()==-1) goto error; /* try to drop privileges */
1102
1103                 /* init childs with rank==PROC_INIT before forking any process,
1104                  * this is a place for delayed (after mod_init) initializations
1105                  * (e.g. shared vars that depend on the total number of processes
1106                  * that is known only after all mod_inits have been executed )
1107                  * WARNING: the same init_child will be called latter, a second time
1108                  * for the "main" process with rank PROC_MAIN (make sure things are
1109                  * not initialized twice)*/
1110                 if (init_child(PROC_INIT) < 0) {
1111                         LOG(L_ERR, "ERROR: main: error in init_child(PROC_INT) --"
1112                                         " exiting\n");
1113                         goto error;
1114                 }
1115
1116
1117                 /* udp processes */
1118                 for(si=udp_listen; si; si=si->next){
1119                         for(i=0;i<children_no;i++){
1120                                 snprintf(si_desc, MAX_PT_DESC, "receiver child=%d sock=%s:%s",
1121                                         i, si->name.s, si->port_no_str.s);
1122                                 child_rank++;
1123                                 pid = fork_process(child_rank, si_desc, 1);
1124                                 if (pid<0){
1125                                         LOG(L_CRIT,  "main_loop: Cannot fork\n");
1126                                         goto error;
1127                                 }else if (pid==0){
1128                                         /* child */
1129                                         bind_address=si; /* shortcut */
1130 #ifdef STATS
1131                                         setstats( i+r*children_no );
1132 #endif
1133                                         return udp_rcv_loop();
1134                                 }
1135                         }
1136                         /*parent*/
1137                         /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
1138                 }
1139         }
1140
1141         /*this is the main process*/
1142         bind_address=0;                         /* main proc -> it shouldn't send anything, */
1143
1144         {
1145 #ifdef USE_SLOW_TIMER
1146                 /* fork again for the "slow" timer process*/
1147                 pid = fork_process(PROC_TIMER, "slow timer", 1);
1148                 if (pid<0){
1149                         LOG(L_CRIT, "main_loop: cannot fork \"slow\" timer process\n");
1150                         goto error;
1151                 }else if (pid==0){
1152                         /* child */
1153                         if (real_time&2)
1154                                 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1155                         if (arm_slow_timer()<0) goto error;
1156                         slow_timer_main();
1157                 }else{
1158                         slow_timer_pid=pid;
1159                 }
1160 #endif /* USE_SLOW_TIMER */
1161
1162                 /* fork again for the "main" timer process*/
1163                 pid = fork_process(PROC_TIMER, "timer", 1);
1164                 if (pid<0){
1165                         LOG(L_CRIT, "main_loop: cannot fork timer process\n");
1166                         goto error;
1167                 }else if (pid==0){
1168                         /* child */
1169                         if (real_time&1)
1170                                 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1171                         if (arm_timer()<0) goto error;
1172                         timer_main();
1173                 }else{
1174                 }
1175         }
1176
1177 /* init childs with rank==MAIN before starting tcp main (in case they want to
1178  *  fork  a tcp capable process, the corresponding tcp. comm. fds in pt[] must
1179  *  be set before calling tcp_main_loop()) */
1180         if (init_child(PROC_MAIN) < 0) {
1181                 LOG(L_ERR, "ERROR: main: error in init_child\n");
1182                 goto error;
1183         }
1184
1185 #ifdef USE_TCP
1186                 if (!tcp_disable){
1187                                 /* start tcp  & tls receivers */
1188                         if (tcp_init_children()<0) goto error;
1189                                 /* start tcp+tls master proc */
1190                         pid = fork_process(PROC_TCP_MAIN, "tcp main process", 0);
1191                         if (pid<0){
1192                                 LOG(L_CRIT, "main_loop: cannot fork tcp main process: %s\n",
1193                                                         strerror(errno));
1194                                 goto error;
1195                         }else if (pid==0){
1196                                 /* child */
1197                                 tcp_main_loop();
1198                         }else{
1199                                 tcp_main_pid=pid;
1200                                 unix_tcp_sock=-1;
1201                         }
1202                 }
1203 #endif
1204         /* main */
1205         strncpy(pt[0].desc, "attendant", MAX_PT_DESC );
1206 #ifdef USE_TCP
1207         close_extra_socks(PROC_ATTENDANT, get_proc_no());
1208         if(!tcp_disable){
1209                 /* main's tcp sockets are disabled by default from init_pt() */
1210                 unix_tcp_sock=-1;
1211         }
1212 #endif
1213
1214         /*DEBUG- remove it*/
1215 #ifdef EXTRA_DEBUG
1216         for (r=0; r<*process_count; r++){
1217                 fprintf(stderr, "% 3d   % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1218         }
1219 #endif
1220         DBG("Expect maximum %d  open fds\n", get_max_open_fds());
1221
1222         for(;;){
1223                         handle_sigs();
1224                         pause();
1225         }
1226
1227
1228         /*return 0; */
1229  error:
1230                                  /* if we are here, we are the "main process",
1231                                   any forked children should exit with exit(-1) and not
1232                                   ever use return */
1233         return -1;
1234
1235 }
1236
1237 /*
1238  * Calculate number of processes, this does not
1239  * include processes created by modules
1240  */
1241 static int calc_proc_no(void)
1242 {
1243         int udp_listeners;
1244         struct socket_info* si;
1245
1246         for (si=udp_listen, udp_listeners=0; si; si=si->next, udp_listeners++);
1247         return
1248                      /* receivers and attendant */
1249                 (dont_fork ? 1 : children_no * udp_listeners + 1)
1250                      /* timer process */
1251                 + 1 /* always, we need it in most cases, and we can't tell here
1252                        & now if we don't need it */
1253 #ifdef USE_SLOW_TIMER
1254                 + 1 /* slow timer process */
1255 #endif
1256 #ifdef USE_TCP
1257                 +((!tcp_disable)?( 1/* tcp main */ + tcp_children_no ):0)
1258 #endif
1259                 ;
1260 }
1261
1262 int main(int argc, char** argv)
1263 {
1264
1265         FILE* cfg_stream;
1266         int c,r;
1267         char *tmp;
1268         int tmp_len;
1269         int port;
1270         int proto;
1271         char *options;
1272         int ret;
1273         unsigned int seed;
1274         int rfd;
1275         int debug_save, debug_flag;
1276         int dont_fork_cnt;
1277
1278         /*init*/
1279         creator_pid = getpid();
1280         ret=-1;
1281         my_argc=argc; my_argv=argv;
1282         debug_flag=0;
1283         dont_fork_cnt=0;
1284
1285         /*init pkg mallocs (before parsing cfg or cmd line !)*/
1286         if (init_pkg_mallocs()==-1)
1287                 goto error;
1288
1289 #ifdef DBG_MSG_QA
1290         fprintf(stderr, "WARNING: ser startup: "
1291                 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1292 #endif
1293
1294         options=  ":f:cm:dVhEb:l:L:n:vrRDTN:W:w:t:u:g:P:G:"
1295 #ifdef STATS
1296                 "s:"
1297 #endif
1298         ;
1299         
1300 #ifdef USE_TCP
1301         init_tcp_options(); /* set the defaults before the config */
1302 #endif
1303         /* look if there is a -h, e.g. -f -h construction won't catch it later */
1304         opterr = 0;
1305         while((c=getopt(argc,argv,options))!=-1) {
1306                 if (c == 'h' || (optarg && strcmp(optarg, "-h") == 0)) {
1307                         printf("version: %s\n", version);
1308                         printf("%s",help_msg);
1309                         exit(0);
1310                         break;
1311                 }
1312         }
1313         /* process command line (cfg. file path etc) */
1314         optind = 1;  /* reset getopt */
1315         /* switches required before script processing */
1316         while((c=getopt(argc,argv,options))!=-1) {
1317                 switch(c) {
1318                         case 'f':
1319                                         cfg_file=optarg;
1320                                         break;
1321                         case 'c':
1322                                         config_check=1;
1323                                         log_stderr=1; /* force stderr logging */
1324                                         break;
1325                         case 'L':
1326                                         mods_dir = optarg;
1327                                         break;
1328                         case 'm':
1329                                         shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1330                                         if (tmp &&(*tmp)){
1331                                                 fprintf(stderr, "bad shmem size number: -m %s\n",
1332                                                                                 optarg);
1333                                                 goto error;
1334                                         };
1335                                         LOG(L_INFO, "ser: shared memory: %ld bytes\n",
1336                                                                         shm_mem_size );
1337                                         break;
1338                         case 'd':
1339                                         debug_flag = 1;
1340                                         default_core_cfg.debug++;
1341                                         break;
1342                         case 'V':
1343                                         printf("version: %s\n", version);
1344                                         printf("flags: %s\n", flags );
1345                                         print_ct_constants();
1346                                         printf("%s\n",id);
1347                                         printf("%s compiled on %s with %s\n", __FILE__,
1348                                                         compiled, COMPILER );
1349
1350                                         exit(0);
1351                                         break;
1352                         case 'E':
1353                                         log_stderr=1;
1354                                         break;
1355                         case 'b':
1356                         case 'l':
1357                         case 'n':
1358                         case 'v':
1359                         case 'r':
1360                         case 'R':
1361                         case 'D':
1362                         case 'T':
1363                         case 'N':
1364                         case 'W':
1365                         case 'w':
1366                         case 't':
1367                         case 'u':
1368                         case 'g':
1369                         case 'P':
1370                         case 'G':
1371                         case 's':
1372                                         break;
1373                         case '?':
1374                                         if (isprint(optopt)) {
1375                                                 fprintf(stderr, "Unknown option `-%c'."
1376                                                                                 " Use -h for help.\n", optopt);
1377                                         } else {
1378                                                 fprintf(stderr, "Unknown option character `\\x%x'."
1379                                                                                 " Use -h for help.\n",
1380                                                         optopt);
1381                                         }
1382                                         goto error;
1383                         case ':':
1384                                         fprintf(stderr, "Option `-%c' requires an argument."
1385                                                                         " Use -h for help.\n",
1386                                                 optopt);
1387                                         goto error;
1388                         default:
1389                                         abort();
1390                 }
1391         }
1392
1393         if (init_routes()<0) goto error;
1394         if (init_nonsip_hooks()<0) goto error;
1395
1396         /* Fix the value of cfg_file variable.*/
1397         if (fix_cfg_file() < 0) goto error;
1398
1399         /* load config file or die */
1400         cfg_stream=fopen (cfg_file, "r");
1401         if (cfg_stream==0){
1402                 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
1403                                 strerror(errno));
1404                 goto error;
1405         }
1406
1407         /* seed the prng */
1408         /* try to use /dev/urandom if possible */
1409         seed=0;
1410         if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
1411 try_again:
1412                 if (read(rfd, (void*)&seed, sizeof(seed))==-1){
1413                         if (errno==EINTR) goto try_again; /* interrupted by signal */
1414                         LOG(L_WARN, "WARNING: could not read from /dev/urandom (%d)\n",
1415                                                 errno);
1416                 }
1417                 DBG("read %u from /dev/urandom\n", seed);
1418                         close(rfd);
1419         }else{
1420                 LOG(L_WARN, "WARNING: could not open /dev/urandom (%d)\n", errno);
1421         }
1422         seed+=getpid()+time(0);
1423         DBG("seeding PRNG with %u\n", seed);
1424         srand(seed);
1425         fastrand_seed(rand());
1426         srandom(rand()+time(0));
1427         DBG("test random numbers %u %lu %u\n", rand(), random(), fastrand());
1428
1429         /*register builtin  modules*/
1430         register_builtin_modules();
1431
1432         /* init named flags */
1433         init_named_flags();
1434
1435         yyin=cfg_stream;
1436         debug_save = default_core_cfg.debug;
1437         if ((yyparse()!=0)||(cfg_errors)){
1438                 fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
1439                 goto error;
1440         }
1441         if (cfg_warnings){
1442                 fprintf(stderr, "%d config warnings\n", cfg_warnings);
1443         }
1444         if (debug_flag) default_core_cfg.debug = debug_save;
1445         print_rls();
1446
1447         /* options with higher priority than cfg file */
1448         optind = 1;  /* reset getopt */
1449         while((c=getopt(argc,argv,options))!=-1) {
1450                 switch(c) {
1451                         case 'f':
1452                         case 'c':
1453                         case 'm':
1454                         case 'd':
1455                         case 'V':
1456                         case 'h':
1457                                         break;
1458                         case 'E':
1459                                         log_stderr=1;   // use in both getopt switches
1460                                         break;
1461                         case 'b':
1462                                         maxbuffer=strtol(optarg, &tmp, 10);
1463                                         if (tmp &&(*tmp)){
1464                                                 fprintf(stderr, "bad max buffer size number: -b %s\n",
1465                                                                                         optarg);
1466                                                 goto error;
1467                                         }
1468                                         break;
1469                         case 'l':
1470                                         if (parse_phostport(optarg, &tmp, &tmp_len,
1471                                                                                         &port, &proto)<0){
1472                                                 fprintf(stderr, "bad -l address specifier: %s\n",
1473                                                                                 optarg);
1474                                                 goto error;
1475                                         }
1476                                         tmp[tmp_len]=0; /* null terminate the host */
1477                                         /* add a new addr. to our address list */
1478                                         if (add_listen_iface(tmp, port, proto, 0)!=0){
1479                                                 fprintf(stderr, "failed to add new listen address\n");
1480                                                 goto error;
1481                                         }
1482                                         break;
1483                         case 'n':
1484                                         children_no=strtol(optarg, &tmp, 10);
1485                                         if ((tmp==0) ||(*tmp)){
1486                                                 fprintf(stderr, "bad process number: -n %s\n",
1487                                                                         optarg);
1488                                                 goto error;
1489                                         }
1490                                         break;
1491                         case 'v':
1492                                         check_via=1;
1493                                         break;
1494                         case 'r':
1495                                         received_dns|=DO_DNS;
1496                                         break;
1497                         case 'R':
1498                                         received_dns|=DO_REV_DNS;
1499                                         break;
1500                         case 'D':
1501                                         dont_fork_cnt++;
1502                                         break;
1503                         case 'T':
1504                                 #ifdef USE_TCP
1505                                         tcp_disable=1;
1506                                 #else
1507                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1508                                 #endif
1509                                         break;
1510                         case 'N':
1511                                 #ifdef USE_TCP
1512                                         tcp_children_no=strtol(optarg, &tmp, 10);
1513                                         if ((tmp==0) ||(*tmp)){
1514                                                 fprintf(stderr, "bad process number: -N %s\n",
1515                                                                         optarg);
1516                                                 goto error;
1517                                         }
1518                                 #else
1519                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1520                                 #endif
1521                                         break;
1522                         case 'W':
1523                                 #ifdef USE_TCP
1524                                         tcp_poll_method=get_poll_type(optarg);
1525                                         if (tcp_poll_method==POLL_NONE){
1526                                                 fprintf(stderr, "bad poll method name: -W %s\ntry "
1527                                                                                 "one of %s.\n", optarg, poll_support);
1528                                                 goto error;
1529                                         }
1530                                 #else
1531                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1532                                 #endif
1533                                         break;
1534                         case 'w':
1535                                         working_dir=optarg;
1536                                         break;
1537                         case 't':
1538                                         chroot_dir=optarg;
1539                                         break;
1540                         case 'u':
1541                                         user=optarg;
1542                                         break;
1543                         case 'g':
1544                                         group=optarg;
1545                                         break;
1546                         case 'P':
1547                                         pid_file=optarg;
1548                                         break;
1549                         case 'G':
1550                                         pgid_file=optarg;
1551                                         break;
1552                         case 's':
1553                                 #ifdef STATS
1554                                         stat_file=optarg;
1555                                 #endif
1556                                         break;
1557                         default:
1558                                         break;
1559                 }
1560         }
1561
1562         if (dont_fork_cnt)
1563                 dont_fork = dont_fork_cnt;      /* override by command line */
1564
1565         if (dont_fork > 0) {
1566                 dont_daemonize = dont_fork == 2;
1567                 dont_fork = dont_fork == 1;
1568         }
1569         /* init locks first */
1570         if (init_lock_ops()!=0)
1571                 goto error;
1572         /* init the resolver, before fixing the config */
1573         resolv_init();
1574         /* fix parameters */
1575         if (port_no<=0) port_no=SIP_PORT;
1576 #ifdef USE_TLS
1577         if (tls_port_no<=0) tls_port_no=SIPS_PORT;
1578 #endif
1579
1580
1581         if (children_no<=0) children_no=CHILD_NO;
1582 #ifdef USE_TCP
1583         if (!tcp_disable){
1584                 if (tcp_children_no<=0) tcp_children_no=children_no;
1585         }
1586 #endif
1587
1588         if (working_dir==0) working_dir="/";
1589
1590         /* get uid/gid */
1591         if (user){
1592                 if (user2uid(&uid, &gid, user)<0){
1593                         fprintf(stderr, "bad user name/uid number: -u %s\n", user);
1594                         goto error;
1595                 }
1596         }
1597         if (group){
1598                 if (group2gid(&gid, group)<0){
1599                                 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
1600                         goto error;
1601                 }
1602         }
1603         if (fix_all_socket_lists()!=0){
1604                 fprintf(stderr,  "failed to initialize list addresses\n");
1605                 goto error;
1606         }
1607         if (default_core_cfg.dns_try_ipv6 && !(socket_types & SOCKET_T_IPV6)){
1608                 /* if we are not listening on any ipv6 address => no point
1609                  * to try to resovle ipv6 addresses */
1610                 default_core_cfg.dns_try_ipv6=0;
1611         }
1612         /* print all the listen addresses */
1613         printf("Listening on \n");
1614         print_all_socket_lists();
1615         printf("Aliases: \n");
1616         /*print_aliases();*/
1617         print_aliases();
1618         printf("\n");
1619
1620         if (dont_fork){
1621                 fprintf(stderr, "WARNING: no fork mode %s\n",
1622                                 (udp_listen)?(
1623                                 (udp_listen->next)?"and more than one listen address found "
1624                                 "(will use only the the first one)":""
1625                                 ):"and no udp listen address found" );
1626         }
1627         if (config_check){
1628                 fprintf(stderr, "config file ok, exiting...\n");
1629                 goto error;
1630         }
1631
1632
1633         /*init shm mallocs
1634          *  this must be here
1635          *     -to allow setting shm mem size from the command line
1636          *       => if shm_mem should be settable from the cfg file move
1637          *       everything after
1638          *     -it must be also before init_timer and init_tcp
1639          *     -it must be after we know uid (so that in the SYSV sems case,
1640          *        the sems will have the correct euid)
1641          * --andrei */
1642         if (init_shm_mallocs(shm_force_alloc)==-1)
1643                 goto error;
1644         if (init_atomic_ops()==-1)
1645                 goto error;
1646         /*init timer, before parsing the cfg!*/
1647         if (init_timer()<0){
1648                 LOG(L_CRIT, "could not initialize timer, exiting...\n");
1649                 goto error;
1650         }
1651 #ifdef USE_DNS_CACHE
1652         if (init_dns_cache()<0){
1653                 LOG(L_CRIT, "could not initialize the dns cache, exiting...\n");
1654                 goto error;
1655         }
1656 #ifdef USE_DNS_CACHE_STATS
1657         /* preinitializing before the nubmer of processes is determined */
1658         if (init_dns_cache_stats(1)<0){
1659                 LOG(L_CRIT, "could not initialize the dns cache measurement\n");
1660                 goto error;
1661         }
1662 #endif /* USE_DNS_CACHE_STATS */
1663 #endif
1664 #ifdef USE_DST_BLACKLIST
1665         if (init_dst_blacklist()<0){
1666                 LOG(L_CRIT, "could not initialize the dst blacklist, exiting...\n");
1667                 goto error;
1668         }
1669 #ifdef USE_DST_BLACKLIST_STATS
1670         /* preinitializing before the nubmer of processes is determined */
1671         if (init_dst_blacklist_stats(1)<0){
1672                 LOG(L_CRIT, "could not initialize the dst blacklist measurement\n");
1673                 goto error;
1674         }
1675 #endif /* USE_DST_BLACKLIST_STATS */
1676 #endif
1677         if (init_avps()<0) goto error;
1678         if (rpc_init_time() < 0) goto error;
1679
1680 #ifdef USE_TCP
1681         if (!tcp_disable){
1682                 /*init tcp*/
1683                 if (init_tcp()<0){
1684                         LOG(L_CRIT, "could not initialize tcp, exiting...\n");
1685                         goto error;
1686                 }
1687         }
1688 #endif /* USE_TCP */
1689         /* init_daemon? */
1690         if (!dont_fork){
1691                 if ( daemonize(argv[0]) <0 ) goto error;
1692         }
1693         if (install_sigs() != 0){
1694                 fprintf(stderr, "ERROR: could not install the signal handlers\n");
1695                 goto error;
1696         }
1697
1698         if (disable_core_dump) set_core_dump(0, 0);
1699         else set_core_dump(1, shm_mem_size+PKG_MEM_POOL_SIZE+4*1024*1024);
1700         if (open_files_limit>0){
1701                 if(increase_open_fds(open_files_limit)<0){
1702                         fprintf(stderr, "ERROR: error could not increase file limits\n");
1703                         goto error;
1704                 }
1705         }
1706         if (mlock_pages)
1707                 mem_lock_pages();
1708
1709         if (real_time&4)
1710                         set_rt_prio(rt_prio, rt_policy);
1711
1712         
1713         if (cfg_init() < 0) {
1714                 LOG(L_CRIT, "could not initialize configuration framework\n");
1715                 goto error;
1716         }
1717         /* declare the core cfg before the module configs */
1718         if (cfg_declare("core", core_cfg_def, &default_core_cfg, cfg_size(core),
1719                         &core_cfg)
1720         ) {
1721                 LOG(L_CRIT, "could not declare the core configuration\n");
1722                 goto error;
1723         }
1724         
1725         if (init_modules() != 0) {
1726                 fprintf(stderr, "ERROR: error while initializing modules\n");
1727                 goto error;
1728         }
1729         
1730         if (cfg_shmize() < 0) {
1731                 LOG(L_CRIT, "could not initialize shared configuration\n");
1732                 goto error;
1733         }
1734         
1735         /* initialize process_table, add core process no. (calc_proc_no()) to the
1736          * processes registered from the modules*/
1737         if (init_pt(calc_proc_no())==-1)
1738                 goto error;
1739 #ifdef USE_TCP
1740 #ifdef USE_TLS
1741         if (!tls_disable){
1742                 if (!tls_loaded()){
1743                         LOG(L_WARN, "WARNING: tls support enabled, but no tls engine "
1744                                                 " available (forgot to load the tls module?)\n");
1745                         LOG(L_WARN, "WARNING: disabling tls...\n");
1746                         tls_disable=1;
1747                 }
1748                 /* init tls*/
1749                 if (init_tls()<0){
1750                         LOG(L_CRIT, "could not initialize tls, exiting...\n");
1751                         goto error;
1752                 }
1753         }
1754 #endif /* USE_TLS */
1755 #endif /* USE_TCP */
1756
1757         /* The total number of processes is now known, note that no
1758          * function being called before this point may rely on the
1759          * number of processes !
1760          */
1761         DBG("Expect (at least) %d SER processes in your process list\n",
1762                         get_max_procs());
1763
1764 #if defined USE_DNS_CACHE && defined USE_DNS_CACHE_STATS
1765         if (init_dns_cache_stats(get_max_procs())<0){
1766                 LOG(L_CRIT, "could not initialize the dns cache measurement\n");
1767                 goto error;
1768         }
1769 #endif
1770 #if defined USE_DST_BLACKLIST && defined USE_DST_BLACKLIST_STATS
1771         if (init_dst_blacklist_stats(get_max_procs())<0){
1772                 LOG(L_CRIT, "could not initialize the dst blacklist measurement\n");
1773                 goto error;
1774         }
1775 #endif
1776
1777         /* fix routing lists */
1778         if ( (r=fix_rls())!=0){
1779                 fprintf(stderr, "ERROR: error %d while trying to fix configuration\n",
1780                                                 r);
1781                 goto error;
1782         };
1783         fixup_complete=1;
1784
1785 #ifdef STATS
1786         if (init_stats(  dont_fork ? 1 : children_no  )==-1) goto error;
1787 #endif
1788
1789         ret=main_loop();
1790         /*kill everything*/
1791         if (is_main) shutdown_children(SIGTERM, 0);
1792         /* else terminate process */
1793         return ret;
1794
1795 error:
1796         /*kill everything*/
1797         if (is_main) shutdown_children(SIGTERM, 0);
1798         return -1;
1799
1800 }