4 * Copyright (C) 2001-2003 FhG Fokus
6 * This file is part of ser, a free SIP server.
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
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:
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.
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
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
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)
88 #include <sys/types.h>
89 #include <sys/socket.h>
90 #if defined(HAVE_NETINET_IN_SYSTM)
91 #include <netinet/in_systm.h>
93 #include <netinet/in.h>
94 #include <netinet/ip.h>
95 #include <arpa/inet.h>
96 #include <sys/utsname.h>
100 #include <sys/time.h>
101 #include <sys/wait.h>
106 #include <sys/ioctl.h>
108 #ifdef HAVE_SYS_SOCKIO_H
109 #include <sys/sockio.h>
114 #include "daemonize.h"
116 #include "udp_server.h"
120 #include "mem/shm_mem.h"
122 #include "sr_module.h"
124 #include "parser/msg_parser.h"
127 #include "parser/parse_hname2.h"
128 #include "parser/digest/digest_parser.h"
129 #include "name_alias.h"
130 #include "hash_func.h"
132 #include "script_cb.h"
133 #include "nonsip_hooks.h"
137 #include "poll_types.h"
138 #include "tcp_init.h"
139 #include "tcp_options.h"
141 #include "tls/tls_init.h"
142 #define tls_has_init_si() 1
143 #define tls_loaded() 1
145 #include "tls_hooks_init.h"
146 #endif /* CORE_TLS */
149 #include "core_cmd.h"
151 #include "lock_ops_init.h"
152 #include "atomic_ops_init.h"
154 #include "dns_cache.h"
156 #ifdef USE_DST_BLACKLIST
157 #include "dst_blacklist.h"
159 #include "rand/fastrand.h" /* seed */
163 #include "cfg/cfg_struct.h"
164 #include "cfg_core.h"
171 /* define SIG_DEBUG by default */
178 static char id[]="@(#) $Id$";
179 static char* version=SER_FULL_VERSION;
180 static char* flags=SER_COMPILE_FLAGS;
181 char compiled[]= __TIME__ " " __DATE__ ;
184 static char help_msg[]= "\
185 Usage: " NAME " [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\
198 -r Use dns to check if is necessary to add a \"received=\"\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\
209 -N Number of tcp child processes (default: equal to `-n')\n\
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"
224 " -s file File to which statistics is dumped (disabled otherwise)\n"
228 /* print compile-time constants */
229 void print_ct_constants()
232 printf("ADAPTIVE_WAIT_LOOPS=%d, ", ADAPTIVE_WAIT_LOOPS);
236 printf("SHM_MEM_SIZE=%d, ", SHM_MEM_SIZE);
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,
244 printf("poll method support: %s.\n", poll_support);
248 /* debugging function */
250 void receive_stdin_loop()
257 len=fread(buf,1,BSIZE,stdin);
259 receive_msg(buf, len);
260 printf("-------------------------\n");
267 int own_pgid = 0; /* whether or not we have our own pgid (and it's ok
268 to use kill(0, sig) */
270 char* mods_dir = MODS_DIR; /* directory with dyn. loadable modules */
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
277 int children_no = 0; /* number of children processing requests */
279 int tcp_children_no = 0;
280 int tcp_disable = 0; /* 1 if tcp is disabled */
284 int tls_disable = 0; /* tls enabled by default */
286 int tls_disable = 1; /* tls disabled by default */
287 #endif /* CORE_TLS */
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
294 gen_lock_t* process_lock; /* lock on the process table */
295 int process_no = 0; /* index of process in the pt */
297 int sig_flag = 0; /* last signal received */
299 int dont_daemonize = 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 */
307 /* translate user=phone URIs to TEL URIs */
309 /* shall use stateful synonym branches? faster but not reboot-safe */
311 /* debugging level for memory stats */
313 /* debugging level for the malloc debug messages */
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
321 /* should localy-generated messages include server's signature?
322 be default yes, good for trouble-shooting
324 int server_signature=1;
325 /* should ser try to locate outbound interface on multihomed
326 * host? by default not -- too expensive
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;
342 int sock_mode= S_IRUSR| S_IWUSR| S_IRGRP| S_IWGRP; /* rw-rw---- */
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 */
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 */
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) */
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 */
365 /* a hint to reply modules whether they should send reply
366 to IP advertised in Via or IP from which a request came
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 */
375 int tos = IPTOS_LOWDELAY;
376 int pmtu_discovery = 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 */
384 struct socket_info* udp_listen=0;
386 int tcp_main_pid=0; /* set after the tcp main process is started */
387 struct socket_info* tcp_listen=0;
390 struct socket_info* tls_listen=0;
392 struct socket_info* bind_address=0; /* pointer to the crt. proc.
394 struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
395 struct socket_info* sendipv6; /* same as above for ipv6 */
397 struct socket_info* sendipv4_tcp;
398 struct socket_info* sendipv6_tcp;
401 struct socket_info* sendipv4_tls;
402 struct socket_info* sendipv6_tls;
405 unsigned short port_no=0; /* default port*/
407 unsigned short tls_port_no=0; /* default port */
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 */
419 struct host_alias* aliases=0; /* name aliases list */
421 /* Parameter to child_init */
424 /* how much to wait for children to terminate, before taking extreme measures*/
425 int ser_kill_timeout=DEFAULT_SER_KILL_TIMEOUT;
427 /* process_bm_t process_bit = 0; */
436 /* shared memory (in MB) */
437 unsigned long shm_mem_size=SHM_MEM_SIZE * 1024 * 1024;
439 /* export command-line to anywhere else */
443 #define MAX_FD 32 /* maximum number of inherited open file descriptors,
444 (normally it shouldn't be bigger than 3) */
448 extern int yyparse();
451 int is_main=1; /* flag = is this the "main" process? */
452 int fixup_complete=0; /* flag = is the fixup complete ? */
454 char* pid_file = 0; /* filename as asked by use */
458 /* call it before exiting; if show_status==1, mem status is displayed */
459 void cleanup(show_status)
462 #ifndef SHM_SAFE_MALLOC
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 */
472 #ifdef USE_DST_BLACKLIST
473 destroy_dst_blacklist();
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;
488 destroy_nonsip_hooks();
490 destroy_atomic_ops();
493 LOG(memlog, "Memory status (pkg):\n");
498 if (pt) shm_free(pt);
501 LOG(memlog, "Memory status (shm):\n");
504 /* zero all shmem alloc vars that we still use */
508 if (pid_file) unlink(pid_file);
509 if (pgid_file) unlink(pgid_file);
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)
529 if (own_pgid) kill(0, signum);
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)
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 */
539 kill(pt[r].pid, signum);
541 else LOG(L_CRIT, "BUG: killing: %s > %d no pid!!!\n",
542 pt[r].desc, pt[r].pid);
544 if (!is_main) lock_release(process_lock);
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)
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
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)
566 /* LOG is not signal safe, but who cares, we are abort-ing anyway :-) */
567 LOG(L_CRIT, "BUG: shutdown timeout triggered, dying...");
573 static void shutdown_children(int sig, int show_status)
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 */
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*/
587 set_sig_h(SIGALRM, SIG_IGN);
598 case 0: break; /* do nothing*/
600 /* SIGPIPE might be rarely received on use of
601 exec module; simply ignore it
603 LOG(L_WARN, "WARNING: SIGPIPE received and ignored\n");
607 /* we end the program in all these cases */
608 if (sig_flag==SIGINT)
609 DBG("INT received, program terminates\n");
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");
620 dump_all_statistic();
623 LOG(memlog, "Memory status (pkg):\n");
627 LOG(memlog, "Memory status (shm):\n");
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));
642 LOG(L_ALERT, "core was %sgenerated\n",
643 WCOREDUMP(chld_status) ? "" : "not " );
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));
650 #ifndef STOP_JIRIS_CHANGES
652 LOG(L_INFO, "INFO: dont_fork turned on, living on\n");
655 LOG(L_INFO, "INFO: terminating due to SIGCHLD\n");
658 shutdown_children(SIGTERM, 1);
659 DBG("terminating due to SIGCHLD\n");
663 case SIGHUP: /* ignoring it*/
664 DBG("SIGHUP received, ignoring it\n");
667 LOG(L_CRIT, "WARNING: unhandled signal %d\n", sig_flag);
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
680 void sig_usr(int signo)
685 if (sig_flag==0) sig_flag=signo;
686 else /* previous sig. not processed yet, ignoring? */
689 /* only one proc, doing everything from the sig handler,
690 unsafe, but this is only for debugging mode*/
693 /* process the important signals */
696 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
697 LOG(L_INFO, "INFO: signal %d received\n", signo);
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 */
706 LOG(memlog, "Memory status (pkg):\n");
713 /* statistics, do nothing, printed only from the main proc */
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");
726 _exit(0); /* terminate if one child died */
735 /* install the signal handlers, returns 0 on success, -1 on error */
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");
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");
748 if (set_sig_h(SIGUSR1, sig_usr) == SIG_ERR ) {
749 DPrint("ERROR: no SIGUSR1 signal handler can be installed\n");
752 if (set_sig_h(SIGCHLD , sig_usr) == SIG_ERR ) {
753 DPrint("ERROR: no SIGCHLD signal handler can be installed\n");
756 if (set_sig_h(SIGTERM , sig_usr) == SIG_ERR ) {
757 DPrint("ERROR: no SIGTERM signal handler can be installed\n");
760 if (set_sig_h(SIGHUP , sig_usr) == SIG_ERR ) {
761 DPrint("ERROR: no SIGHUP signal handler can be installed\n");
764 if (set_sig_h(SIGUSR2 , sig_usr) == SIG_ERR ) {
765 DPrint("ERROR: no SIGUSR2 signal handler can be installed\n");
773 /* returns -1 on error, 0 on success
775 static int parse_proto(unsigned char* s, long len, int* proto)
777 #define PROTO2UINT(a, b, c) (( (((unsigned int)(a))<<16)+ \
778 (((unsigned int)(b))<<8)+ \
779 ((unsigned int)(c)) ) | 0x20202020)
781 if (len!=3) return -1;
782 i=PROTO2UINT(s[0], s[1], s[2]);
784 case PROTO2UINT('u', 'd', 'p'):
788 case PROTO2UINT('t', 'c', 'p'):
792 case PROTO2UINT('t', 'l', 's'):
806 * parses [proto:]host[:port]
807 * where proto= udp|tcp|tls
808 * returns 0 on success and -1 on failure
810 static int parse_phostport(char* s, char** host, int* hlen, int* port,
813 char* first; /* first ':' occurrence */
814 char* second; /* second ':' occurrence */
822 /* find the first 2 ':', ignoring possible ipv6 addresses
823 * (substrings between [])
829 if (bracket>1) goto error_brackets;
833 if (bracket<0) goto error_brackets;
837 if (first==0) first=p;
838 else if( second==0) second=p;
839 else goto error_colons;
845 if (*(p-1)==':') goto error_colons;
847 if (first==0){ /* no ':' => only host */
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;
859 *hlen=(int)(second-*host);
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;
869 *hlen=(int)(p-*host);
871 /* valid port => its host:port */
874 *hlen=(int)(first-*host);
878 LOG(L_ERR, "ERROR: parse_phostport: too many brackets in %s\n", s);
881 LOG(L_ERR, "ERROR: parse_phostport: too many colons in %s\n", s);
884 LOG(L_ERR, "ERROR: parse_phostport: bad protocol in %s\n", s);
887 LOG(L_ERR, "ERROR: parse_phostport: bad port number in %s\n", s);
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
904 int fix_cfg_file(void)
907 size_t max_len, cwd_len, cfg_len;
909 if (cfg_file == NULL) cfg_file = CFG_FILE;
910 if (cfg_file[0] == '/') return 0;
912 /* cfg_file contains a relative pathname, get the current
913 * working directory and add it at the beginning
915 cfg_len = strlen(cfg_file);
918 if ((res = malloc(max_len)) == NULL) goto error;
920 if (getcwd(res, max_len) == NULL) goto error;
921 cwd_len = strlen(res);
923 /* Make sure that the buffer is big enough */
924 if (cwd_len + 1 + cfg_len >= max_len) goto error;
927 memcpy(res + cwd_len + 1, cfg_file, cfg_len);
929 res[cwd_len + 1 + cfg_len] = '\0'; /* Add terminating zero */
934 fprintf(stderr, "ERROR: Unable to fix cfg_file to contain full pathname\n");
945 struct socket_info* si;
946 char si_desc[MAX_PT_DESC];
951 /* one "main" process and n children handling i/o */
957 LOG(L_ERR, "ERROR: no fork mode requires at least one"
958 " udp listen address, exiting...\n");
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"
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
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) --"
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);
992 LOG(L_CRIT, "ERROR: main_loop: Cannot fork\n");
998 /* process_bit = 0; */
1000 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1002 if (arm_slow_timer()<0) goto error;
1008 /* we need another process to act as the "main" timer*/
1009 pid = fork_process(PROC_TIMER, "timer", 0);
1011 LOG(L_CRIT, "ERROR: main_loop: Cannot fork\n");
1017 /* process_bit = 0; */
1019 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1020 if (arm_timer()<0) goto error;
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 );
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");
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
1044 if (init_child(1) < 0) {
1045 LOG(L_ERR, "main_dontfork: init_child failed\n");
1048 return udp_rcv_loop();
1051 for(si=udp_listen;si;si=si->next){
1052 /* create the listening socket (for each address)*/
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))))
1060 if((sendipv6==0)&&(si->address.af==AF_INET6))
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))))
1075 if((sendipv6_tcp==0)&&(si->address.af==AF_INET6))
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))))
1091 if((sendipv6_tls==0)&&(si->address.af==AF_INET6))
1096 #endif /* USE_TLS */
1097 #endif /* USE_TCP */
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 */
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) --"
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);
1123 pid = fork_process(child_rank, si_desc, 1);
1125 LOG(L_CRIT, "main_loop: Cannot fork\n");
1129 bind_address=si; /* shortcut */
1131 setstats( i+r*children_no );
1133 return udp_rcv_loop();
1137 /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
1141 /*this is the main process*/
1142 bind_address=0; /* main proc -> it shouldn't send anything, */
1145 #ifdef USE_SLOW_TIMER
1146 /* fork again for the "slow" timer process*/
1147 pid = fork_process(PROC_TIMER, "slow timer", 1);
1149 LOG(L_CRIT, "main_loop: cannot fork \"slow\" timer process\n");
1154 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1155 if (arm_slow_timer()<0) goto error;
1160 #endif /* USE_SLOW_TIMER */
1162 /* fork again for the "main" timer process*/
1163 pid = fork_process(PROC_TIMER, "timer", 1);
1165 LOG(L_CRIT, "main_loop: cannot fork timer process\n");
1170 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1171 if (arm_timer()<0) goto error;
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");
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);
1192 LOG(L_CRIT, "main_loop: cannot fork tcp main process: %s\n",
1205 strncpy(pt[0].desc, "attendant", MAX_PT_DESC );
1207 close_extra_socks(PROC_ATTENDANT, get_proc_no());
1209 /* main's tcp sockets are disabled by default from init_pt() */
1214 /*DEBUG- remove it*/
1216 for (r=0; r<*process_count; r++){
1217 fprintf(stderr, "% 3d % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1220 DBG("Expect maximum %d open fds\n", get_max_open_fds());
1230 /* if we are here, we are the "main process",
1231 any forked children should exit with exit(-1) and not
1238 * Calculate number of processes, this does not
1239 * include processes created by modules
1241 static int calc_proc_no(void)
1244 struct socket_info* si;
1246 for (si=udp_listen, udp_listeners=0; si; si=si->next, udp_listeners++);
1248 /* receivers and attendant */
1249 (dont_fork ? 1 : children_no * udp_listeners + 1)
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 */
1257 +((!tcp_disable)?( 1/* tcp main */ + tcp_children_no ):0)
1262 int main(int argc, char** argv)
1275 int debug_save, debug_flag;
1279 creator_pid = getpid();
1281 my_argc=argc; my_argv=argv;
1285 /*init pkg mallocs (before parsing cfg or cmd line !)*/
1286 if (init_pkg_mallocs()==-1)
1290 fprintf(stderr, "WARNING: ser startup: "
1291 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1294 options= ":f:cm:dVhEb:l:L:n:vrRDTN:W:w:t:u:g:P:G:"
1301 init_tcp_options(); /* set the defaults before the config */
1303 /* look if there is a -h, e.g. -f -h construction won't catch it later */
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);
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) {
1323 log_stderr=1; /* force stderr logging */
1329 shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1331 fprintf(stderr, "bad shmem size number: -m %s\n",
1335 LOG(L_INFO, "ser: shared memory: %ld bytes\n",
1340 default_core_cfg.debug++;
1343 printf("version: %s\n", version);
1344 printf("flags: %s\n", flags );
1345 print_ct_constants();
1347 printf("%s compiled on %s with %s\n", __FILE__,
1348 compiled, COMPILER );
1374 if (isprint(optopt)) {
1375 fprintf(stderr, "Unknown option `-%c'."
1376 " Use -h for help.\n", optopt);
1378 fprintf(stderr, "Unknown option character `\\x%x'."
1379 " Use -h for help.\n",
1384 fprintf(stderr, "Option `-%c' requires an argument."
1385 " Use -h for help.\n",
1393 if (init_routes()<0) goto error;
1394 if (init_nonsip_hooks()<0) goto error;
1396 /* Fix the value of cfg_file variable.*/
1397 if (fix_cfg_file() < 0) goto error;
1399 /* load config file or die */
1400 cfg_stream=fopen (cfg_file, "r");
1402 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
1408 /* try to use /dev/urandom if possible */
1410 if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
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",
1417 DBG("read %u from /dev/urandom\n", seed);
1420 LOG(L_WARN, "WARNING: could not open /dev/urandom (%d)\n", errno);
1422 seed+=getpid()+time(0);
1423 DBG("seeding PRNG with %u\n", seed);
1425 fastrand_seed(rand());
1426 srandom(rand()+time(0));
1427 DBG("test random numbers %u %lu %u\n", rand(), random(), fastrand());
1429 /*register builtin modules*/
1430 register_builtin_modules();
1432 /* init named flags */
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);
1442 fprintf(stderr, "%d config warnings\n", cfg_warnings);
1444 if (debug_flag) default_core_cfg.debug = debug_save;
1447 /* options with higher priority than cfg file */
1448 optind = 1; /* reset getopt */
1449 while((c=getopt(argc,argv,options))!=-1) {
1459 log_stderr=1; // use in both getopt switches
1462 maxbuffer=strtol(optarg, &tmp, 10);
1464 fprintf(stderr, "bad max buffer size number: -b %s\n",
1470 if (parse_phostport(optarg, &tmp, &tmp_len,
1472 fprintf(stderr, "bad -l address specifier: %s\n",
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");
1484 children_no=strtol(optarg, &tmp, 10);
1485 if ((tmp==0) ||(*tmp)){
1486 fprintf(stderr, "bad process number: -n %s\n",
1495 received_dns|=DO_DNS;
1498 received_dns|=DO_REV_DNS;
1507 fprintf(stderr,"WARNING: tcp support not compiled in\n");
1512 tcp_children_no=strtol(optarg, &tmp, 10);
1513 if ((tmp==0) ||(*tmp)){
1514 fprintf(stderr, "bad process number: -N %s\n",
1519 fprintf(stderr,"WARNING: tcp support not compiled in\n");
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);
1531 fprintf(stderr,"WARNING: tcp support not compiled in\n");
1563 dont_fork = dont_fork_cnt; /* override by command line */
1565 if (dont_fork > 0) {
1566 dont_daemonize = dont_fork == 2;
1567 dont_fork = dont_fork == 1;
1569 /* init locks first */
1570 if (init_lock_ops()!=0)
1572 /* init the resolver, before fixing the config */
1574 /* fix parameters */
1575 if (port_no<=0) port_no=SIP_PORT;
1577 if (tls_port_no<=0) tls_port_no=SIPS_PORT;
1581 if (children_no<=0) children_no=CHILD_NO;
1584 if (tcp_children_no<=0) tcp_children_no=children_no;
1588 if (working_dir==0) working_dir="/";
1592 if (user2uid(&uid, &gid, user)<0){
1593 fprintf(stderr, "bad user name/uid number: -u %s\n", user);
1598 if (group2gid(&gid, group)<0){
1599 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
1603 if (fix_all_socket_lists()!=0){
1604 fprintf(stderr, "failed to initialize list addresses\n");
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;
1612 /* print all the listen addresses */
1613 printf("Listening on \n");
1614 print_all_socket_lists();
1615 printf("Aliases: \n");
1616 /*print_aliases();*/
1621 fprintf(stderr, "WARNING: no fork mode %s\n",
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" );
1628 fprintf(stderr, "config file ok, exiting...\n");
1635 * -to allow setting shm mem size from the command line
1636 * => if shm_mem should be settable from the cfg file move
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)
1642 if (init_shm_mallocs(shm_force_alloc)==-1)
1644 if (init_atomic_ops()==-1)
1646 /*init timer, before parsing the cfg!*/
1647 if (init_timer()<0){
1648 LOG(L_CRIT, "could not initialize timer, exiting...\n");
1651 #ifdef USE_DNS_CACHE
1652 if (init_dns_cache()<0){
1653 LOG(L_CRIT, "could not initialize the dns cache, exiting...\n");
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");
1662 #endif /* USE_DNS_CACHE_STATS */
1664 #ifdef USE_DST_BLACKLIST
1665 if (init_dst_blacklist()<0){
1666 LOG(L_CRIT, "could not initialize the dst blacklist, exiting...\n");
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");
1675 #endif /* USE_DST_BLACKLIST_STATS */
1677 if (init_avps()<0) goto error;
1678 if (rpc_init_time() < 0) goto error;
1684 LOG(L_CRIT, "could not initialize tcp, exiting...\n");
1688 #endif /* USE_TCP */
1691 if ( daemonize(argv[0]) <0 ) goto error;
1693 if (install_sigs() != 0){
1694 fprintf(stderr, "ERROR: could not install the signal handlers\n");
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");
1710 set_rt_prio(rt_prio, rt_policy);
1713 if (cfg_init() < 0) {
1714 LOG(L_CRIT, "could not initialize configuration framework\n");
1717 /* declare the core cfg before the module configs */
1718 if (cfg_declare("core", core_cfg_def, &default_core_cfg, cfg_size(core),
1721 LOG(L_CRIT, "could not declare the core configuration\n");
1725 if (init_modules() != 0) {
1726 fprintf(stderr, "ERROR: error while initializing modules\n");
1730 if (cfg_shmize() < 0) {
1731 LOG(L_CRIT, "could not initialize shared configuration\n");
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)
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");
1750 LOG(L_CRIT, "could not initialize tls, exiting...\n");
1754 #endif /* USE_TLS */
1755 #endif /* USE_TCP */
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 !
1761 DBG("Expect (at least) %d SER processes in your process list\n",
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");
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");
1777 /* fix routing lists */
1778 if ( (r=fix_rls())!=0){
1779 fprintf(stderr, "ERROR: error %d while trying to fix configuration\n",
1786 if (init_stats( dont_fork ? 1 : children_no )==-1) goto error;
1791 if (is_main) shutdown_children(SIGTERM, 0);
1792 /* else terminate process */
1797 if (is_main) shutdown_children(SIGTERM, 0);