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