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 use_dns_cache=1; /* 1 if the cache is enabled, 0 otherwise */
376 int use_dns_failover=0; /* 1 if failover is enabled, 0 otherwise */
378 #ifdef USE_DST_BLACKLIST
379 int use_dst_blacklist=0; /* 1 if the blacklist is enabled */
382 int tos = IPTOS_LOWDELAY;
383 int pmtu_discovery = 0;
386 char* names[MAX_LISTEN]; /* our names */
387 int names_len[MAX_LISTEN]; /* lengths of the names*/
388 struct ip_addr addresses[MAX_LISTEN]; /* our ips */
389 int addresses_no=0; /* number of names/ips */
391 struct socket_info* udp_listen=0;
393 int tcp_main_pid=0; /* set after the tcp main process is started */
394 struct socket_info* tcp_listen=0;
397 struct socket_info* tls_listen=0;
399 struct socket_info* bind_address=0; /* pointer to the crt. proc.
401 struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
402 struct socket_info* sendipv6; /* same as above for ipv6 */
404 struct socket_info* sendipv4_tcp;
405 struct socket_info* sendipv6_tcp;
408 struct socket_info* sendipv4_tls;
409 struct socket_info* sendipv6_tls;
412 unsigned short port_no=0; /* default port*/
414 unsigned short tls_port_no=0; /* default port */
418 /* refresh interval in miliseconds */
419 unsigned int stun_refresh_interval=0;
420 /* stun can be switch off even if it is compiled */
421 int stun_allow_stun=1;
422 /* use or don't use fingerprint */
426 struct host_alias* aliases=0; /* name aliases list */
428 /* Parameter to child_init */
431 /* how much to wait for children to terminate, before taking extreme measures*/
432 int ser_kill_timeout=DEFAULT_SER_KILL_TIMEOUT;
434 /* process_bm_t process_bit = 0; */
443 /* shared memory (in MB) */
444 unsigned long shm_mem_size=SHM_MEM_SIZE * 1024 * 1024;
446 /* export command-line to anywhere else */
450 #define MAX_FD 32 /* maximum number of inherited open file descriptors,
451 (normally it shouldn't be bigger than 3) */
455 extern int yyparse();
458 int is_main=1; /* flag = is this the "main" process? */
459 int fixup_complete=0; /* flag = is the fixup complete ? */
461 char* pid_file = 0; /* filename as asked by use */
465 /* call it before exiting; if show_status==1, mem status is displayed */
466 void cleanup(show_status)
469 #ifndef SHM_SAFE_MALLOC
471 shm_unlock(); /* hack: force-unlock the shared memory lock in case
472 some process crashed and let it locked; this will
473 allow an almost gracious shutdown */
479 #ifdef USE_DST_BLACKLIST
480 destroy_dst_blacklist();
491 destroy_nonsip_hooks();
493 destroy_atomic_ops();
496 LOG(memlog, "Memory status (pkg):\n");
501 if (pt) shm_free(pt);
504 LOG(memlog, "Memory status (shm):\n");
507 /* zero all shmem alloc vars that we still use */
511 if (pid_file) unlink(pid_file);
512 if (pgid_file) unlink(pgid_file);
516 /* tries to send a signal to all our processes
517 * if daemonized is ok to send the signal to all the process group,
518 * however if not daemonized we might end up sending the signal also
519 * to the shell which launched us => most signals will kill it if
520 * it's not in interactive mode and we don't want this. The non-daemonized
521 * case can occur when an error is encountered before daemonize is called
522 * (e.g. when parsing the config file) or when ser is started in "dont-fork"
523 * mode. Sending the signal to all the processes in pt[] will not work
524 * for processes forked from modules (which have no correspondent entry in
525 * pt), but this can happen only in dont_fork mode (which is only for
526 * debugging). So in the worst case + "dont-fork" we might leave some
527 * zombies. -- andrei */
528 static void kill_all_children(int signum)
532 if (own_pgid) kill(0, signum);
534 /* lock processes table only if this is a child process
535 * (only main can add processes, so from main is safe not to lock
536 * and moreover it avoids the lock-holding suicidal children problem)
538 if (!is_main) lock_get(process_lock);
539 for (r=1; r<*process_count; r++){
540 if (r==process_no) continue; /* try not to be suicidal */
542 kill(pt[r].pid, signum);
544 else LOG(L_CRIT, "BUG: killing: %s > %d no pid!!!\n",
545 pt[r].desc, pt[r].pid);
547 if (!is_main) lock_release(process_lock);
553 /* if this handler is called, a critical timeout has occurred while
554 * waiting for the children to finish => we should kill everything and exit */
555 static void sig_alarm_kill(int signo)
557 kill_all_children(SIGKILL); /* this will kill the whole group
558 including "this" process;
559 for debugging replace with SIGABRT
560 (but warning: it might generate lots
565 /* like sig_alarm_kill, but the timeout has occurred when cleaning up
566 * => try to leave a core for future diagnostics */
567 static void sig_alarm_abort(int signo)
569 /* LOG is not signal safe, but who cares, we are abort-ing anyway :-) */
570 LOG(L_CRIT, "BUG: shutdown timeout triggered, dying...");
576 static void shutdown_children(int sig, int show_status)
578 kill_all_children(sig);
579 if (set_sig_h(SIGALRM, sig_alarm_kill) == SIG_ERR ) {
580 LOG(L_ERR, "ERROR: shutdown: could not install SIGALARM handler\n");
581 /* continue, the process will die anyway if no
582 * alarm is installed which is exactly what we want */
584 alarm(ser_kill_timeout);
585 while((wait(0) > 0) || (errno==EINTR)); /* wait for all the
586 children to terminate*/
587 set_sig_h(SIGALRM, sig_alarm_abort);
588 cleanup(show_status); /* cleanup & show status*/
590 set_sig_h(SIGALRM, SIG_IGN);
601 case 0: break; /* do nothing*/
603 /* SIGPIPE might be rarely received on use of
604 exec module; simply ignore it
606 LOG(L_WARN, "WARNING: SIGPIPE received and ignored\n");
610 /* we end the program in all these cases */
611 if (sig_flag==SIGINT)
612 DBG("INT received, program terminates\n");
614 DBG("SIGTERM received, program terminates\n");
615 /* shutdown/kill all the children */
616 shutdown_children(SIGTERM, 1);
617 dprint("Thank you for flying " NAME "\n");
623 dump_all_statistic();
626 LOG(memlog, "Memory status (pkg):\n");
630 LOG(memlog, "Memory status (shm):\n");
636 while ((chld=waitpid( -1, &chld_status, WNOHANG ))>0) {
637 if (WIFEXITED(chld_status))
638 LOG(L_ALERT, "child process %d exited normally,"
639 " status=%d\n", chld,
640 WEXITSTATUS(chld_status));
641 else if (WIFSIGNALED(chld_status)) {
642 LOG(L_ALERT, "child process %d exited by a signal"
643 " %d\n", chld, WTERMSIG(chld_status));
645 LOG(L_ALERT, "core was %sgenerated\n",
646 WCOREDUMP(chld_status) ? "" : "not " );
648 }else if (WIFSTOPPED(chld_status))
649 LOG(L_ALERT, "child process %d stopped by a"
650 " signal %d\n", chld,
651 WSTOPSIG(chld_status));
653 #ifndef STOP_JIRIS_CHANGES
655 LOG(L_INFO, "INFO: dont_fork turned on, living on\n");
658 LOG(L_INFO, "INFO: terminating due to SIGCHLD\n");
661 shutdown_children(SIGTERM, 1);
662 DBG("terminating due to SIGCHLD\n");
666 case SIGHUP: /* ignoring it*/
667 DBG("SIGHUP received, ignoring it\n");
670 LOG(L_CRIT, "WARNING: unhandled signal %d\n", sig_flag);
677 /* added by jku; allows for regular exit on a specific signal;
678 good for profiling which only works if exited regularly and
679 not by default signal handlers
680 - modified by andrei: moved most of the stuff to handle_sigs,
681 made it safer for the "fork" case
683 void sig_usr(int signo)
688 if (sig_flag==0) sig_flag=signo;
689 else /* previous sig. not processed yet, ignoring? */
692 /* only one proc, doing everything from the sig handler,
693 unsafe, but this is only for debugging mode*/
696 /* process the important signals */
699 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
700 LOG(L_INFO, "INFO: signal %d received\n", signo);
705 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
706 LOG(L_INFO, "INFO: signal %d received\n", signo);
707 /* print memory stats for non-main too */
709 LOG(memlog, "Memory status (pkg):\n");
716 /* statistics, do nothing, printed only from the main proc */
723 #ifndef STOP_JIRIS_CHANGES
724 #ifdef SIG_DEBUG /* signal unsafe stuff follows */
725 DBG("SIGCHLD received: "
726 "we do not worry about grand-children\n");
729 _exit(0); /* terminate if one child died */
738 /* install the signal handlers, returns 0 on success, -1 on error */
741 /* added by jku: add exit handler */
742 if (set_sig_h(SIGINT, sig_usr) == SIG_ERR ) {
743 DPrint("ERROR: no SIGINT signal handler can be installed\n");
746 /* if we debug and write to a pipe, we want to exit nicely too */
747 if (set_sig_h(SIGPIPE, sig_usr) == SIG_ERR ) {
748 DPrint("ERROR: no SIGINT signal handler can be installed\n");
751 if (set_sig_h(SIGUSR1, sig_usr) == SIG_ERR ) {
752 DPrint("ERROR: no SIGUSR1 signal handler can be installed\n");
755 if (set_sig_h(SIGCHLD , sig_usr) == SIG_ERR ) {
756 DPrint("ERROR: no SIGCHLD signal handler can be installed\n");
759 if (set_sig_h(SIGTERM , sig_usr) == SIG_ERR ) {
760 DPrint("ERROR: no SIGTERM signal handler can be installed\n");
763 if (set_sig_h(SIGHUP , sig_usr) == SIG_ERR ) {
764 DPrint("ERROR: no SIGHUP signal handler can be installed\n");
767 if (set_sig_h(SIGUSR2 , sig_usr) == SIG_ERR ) {
768 DPrint("ERROR: no SIGUSR2 signal handler can be installed\n");
776 /* returns -1 on error, 0 on success
778 static int parse_proto(unsigned char* s, long len, int* proto)
780 #define PROTO2UINT(a, b, c) (( (((unsigned int)(a))<<16)+ \
781 (((unsigned int)(b))<<8)+ \
782 ((unsigned int)(c)) ) | 0x20202020)
784 if (len!=3) return -1;
785 i=PROTO2UINT(s[0], s[1], s[2]);
787 case PROTO2UINT('u', 'd', 'p'):
791 case PROTO2UINT('t', 'c', 'p'):
795 case PROTO2UINT('t', 'l', 's'):
809 * parses [proto:]host[:port]
810 * where proto= udp|tcp|tls
811 * returns 0 on success and -1 on failure
813 static int parse_phostport(char* s, char** host, int* hlen, int* port,
816 char* first; /* first ':' occurrence */
817 char* second; /* second ':' occurrence */
825 /* find the first 2 ':', ignoring possible ipv6 addresses
826 * (substrings between [])
832 if (bracket>1) goto error_brackets;
836 if (bracket<0) goto error_brackets;
840 if (first==0) first=p;
841 else if( second==0) second=p;
842 else goto error_colons;
848 if (*(p-1)==':') goto error_colons;
850 if (first==0){ /* no ':' => only host */
857 if (second){ /* 2 ':' found => check if valid */
858 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
859 *port=strtol(second+1, &tmp, 10);
860 if ((tmp==0)||(*tmp)||(tmp==second+1)) goto error_port;
862 *hlen=(int)(second-*host);
865 /* only 1 ':' found => it's either proto:host or host:port */
866 *port=strtol(first+1, &tmp, 10);
867 if ((tmp==0)||(*tmp)||(tmp==first+1)){
868 /* invalid port => it's proto:host */
869 if (parse_proto((unsigned char*)s, first-s, proto)<0) goto error_proto;
872 *hlen=(int)(p-*host);
874 /* valid port => its host:port */
877 *hlen=(int)(first-*host);
881 LOG(L_ERR, "ERROR: parse_phostport: too many brackets in %s\n", s);
884 LOG(L_ERR, "ERROR: parse_phostport: too many colons in %s\n", s);
887 LOG(L_ERR, "ERROR: parse_phostport: bad protocol in %s\n", s);
890 LOG(L_ERR, "ERROR: parse_phostport: bad port number in %s\n", s);
901 struct socket_info* si;
902 char si_desc[MAX_PT_DESC];
907 /* one "main" process and n children handling i/o */
913 LOG(L_ERR, "ERROR: no fork mode requires at least one"
914 " udp listen address, exiting...\n");
917 /* only one address, we ignore all the others */
918 if (udp_init(udp_listen)==-1) goto error;
919 bind_address=udp_listen;
920 sendipv4=bind_address;
921 sendipv6=bind_address; /*FIXME*/
922 if (udp_listen->next){
923 LOG(L_WARN, "WARNING: using only the first listen address"
926 if (do_suid()==-1) goto error; /* try to drop privileges */
927 /* process_no now initialized to zero -- increase from now on
928 as new processes are forked (while skipping 0 reserved for main
931 /* init childs with rank==PROC_INIT before forking any process,
932 * this is a place for delayed (after mod_init) initializations
933 * (e.g. shared vars that depend on the total number of processes
934 * that is known only after all mod_inits have been executed )
935 * WARNING: the same init_child will be called latter, a second time
936 * for the "main" process with rank PROC_MAIN (make sure things are
937 * not initialized twice)*/
938 if (init_child(PROC_INIT) < 0) {
939 LOG(L_ERR, "ERROR: main_dontfork: init_child(PROC_INT) --"
944 #ifdef USE_SLOW_TIMER
945 /* we need another process to act as the "slow" timer*/
946 pid = fork_process(PROC_TIMER, "slow timer", 0);
948 LOG(L_CRIT, "ERROR: main_loop: Cannot fork\n");
954 /* process_bit = 0; */
956 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
958 if (arm_slow_timer()<0) goto error;
964 /* we need another process to act as the "main" timer*/
965 pid = fork_process(PROC_TIMER, "timer", 0);
967 LOG(L_CRIT, "ERROR: main_loop: Cannot fork\n");
973 /* process_bit = 0; */
975 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
976 if (arm_timer()<0) goto error;
981 /* main process, receive loop */
982 process_no=0; /*main process number*/
983 pt[process_no].pid=getpid();
984 snprintf(pt[process_no].desc, MAX_PT_DESC,
985 "stand-alone receiver @ %s:%s",
986 bind_address->name.s, bind_address->port_no_str.s );
988 /* call it also w/ PROC_MAIN to make sure modules that init things only
989 * in PROC_MAIN get a chance to run */
990 if (init_child(PROC_MAIN) < 0) {
991 LOG(L_ERR, "ERROR: main_dontfork: init_child(PROC_MAIN) -- exiting\n");
995 /* We will call child_init even if we
996 * do not fork - and it will be called with rank 1 because
997 * in fact we behave like a child, not like main process
1000 if (init_child(1) < 0) {
1001 LOG(L_ERR, "main_dontfork: init_child failed\n");
1004 return udp_rcv_loop();
1007 for(si=udp_listen;si;si=si->next){
1008 /* create the listening socket (for each address)*/
1010 if (udp_init(si)==-1) goto error;
1011 /* get first ipv4/ipv6 socket*/
1012 if ((si->address.af==AF_INET)&&
1013 ((sendipv4==0)||(sendipv4->flags&(SI_IS_LO|SI_IS_MCAST))))
1016 if((sendipv6==0)&&(si->address.af==AF_INET6))
1022 for(si=tcp_listen; si; si=si->next){
1023 /* same thing for tcp */
1024 if (tcp_init(si)==-1) goto error;
1025 /* get first ipv4/ipv6 socket*/
1026 if ((si->address.af==AF_INET)&&
1027 ((sendipv4_tcp==0)||
1028 (sendipv4_tcp->flags&(SI_IS_LO|SI_IS_MCAST))))
1031 if((sendipv6_tcp==0)&&(si->address.af==AF_INET6))
1037 if (!tls_disable && tls_has_init_si()){
1038 for(si=tls_listen; si; si=si->next){
1039 /* same as for tcp*/
1040 if (tls_init(si)==-1) goto error;
1041 /* get first ipv4/ipv6 socket*/
1042 if ((si->address.af==AF_INET)&&
1043 ((sendipv4_tls==0)||
1044 (sendipv4_tls->flags&(SI_IS_LO|SI_IS_MCAST))))
1047 if((sendipv6_tls==0)&&(si->address.af==AF_INET6))
1052 #endif /* USE_TLS */
1053 #endif /* USE_TCP */
1055 /* all processes should have access to all the sockets (for sending)
1056 * so we open all first*/
1057 if (do_suid()==-1) goto error; /* try to drop privileges */
1059 /* init childs with rank==PROC_INIT before forking any process,
1060 * this is a place for delayed (after mod_init) initializations
1061 * (e.g. shared vars that depend on the total number of processes
1062 * that is known only after all mod_inits have been executed )
1063 * WARNING: the same init_child will be called latter, a second time
1064 * for the "main" process with rank PROC_MAIN (make sure things are
1065 * not initialized twice)*/
1066 if (init_child(PROC_INIT) < 0) {
1067 LOG(L_ERR, "ERROR: main: error in init_child(PROC_INT) --"
1074 for(si=udp_listen; si; si=si->next){
1075 for(i=0;i<children_no;i++){
1076 snprintf(si_desc, MAX_PT_DESC, "receiver child=%d sock=%s:%s",
1077 i, si->name.s, si->port_no_str.s);
1079 pid = fork_process(child_rank, si_desc, 1);
1081 LOG(L_CRIT, "main_loop: Cannot fork\n");
1085 bind_address=si; /* shortcut */
1087 setstats( i+r*children_no );
1089 return udp_rcv_loop();
1093 /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
1097 /*this is the main process*/
1098 bind_address=0; /* main proc -> it shouldn't send anything, */
1101 #ifdef USE_SLOW_TIMER
1102 /* fork again for the "slow" timer process*/
1103 pid = fork_process(PROC_TIMER, "slow timer", 1);
1105 LOG(L_CRIT, "main_loop: cannot fork \"slow\" timer process\n");
1110 set_rt_prio(rt_timer2_prio, rt_timer2_policy);
1111 if (arm_slow_timer()<0) goto error;
1116 #endif /* USE_SLOW_TIMER */
1118 /* fork again for the "main" timer process*/
1119 pid = fork_process(PROC_TIMER, "timer", 1);
1121 LOG(L_CRIT, "main_loop: cannot fork timer process\n");
1126 set_rt_prio(rt_timer1_prio, rt_timer1_policy);
1127 if (arm_timer()<0) goto error;
1133 /* init childs with rank==MAIN before starting tcp main (in case they want to
1134 * fork a tcp capable process, the corresponding tcp. comm. fds in pt[] must
1135 * be set before calling tcp_main_loop()) */
1136 if (init_child(PROC_MAIN) < 0) {
1137 LOG(L_ERR, "ERROR: main: error in init_child\n");
1143 /* start tcp & tls receivers */
1144 if (tcp_init_children()<0) goto error;
1145 /* start tcp+tls master proc */
1146 pid = fork_process(PROC_TCP_MAIN, "tcp main process", 0);
1148 LOG(L_CRIT, "main_loop: cannot fork tcp main process: %s\n",
1161 strncpy(pt[0].desc, "attendant", MAX_PT_DESC );
1163 close_extra_socks(PROC_ATTENDANT, get_proc_no());
1165 /* main's tcp sockets are disabled by default from init_pt() */
1170 /*DEBUG- remove it*/
1172 for (r=0; r<*process_count; r++){
1173 fprintf(stderr, "% 3d % 5d - %s\n", r, pt[r].pid, pt[r].desc);
1176 DBG("Expect maximum %d open fds\n", get_max_open_fds());
1186 /* if we are here, we are the "main process",
1187 any forked children should exit with exit(-1) and not
1194 * Calculate number of processes, this does not
1195 * include processes created by modules
1197 static int calc_proc_no(void)
1200 struct socket_info* si;
1202 for (si=udp_listen, udp_listeners=0; si; si=si->next, udp_listeners++);
1204 /* receivers and attendant */
1205 (dont_fork ? 1 : children_no * udp_listeners + 1)
1207 + 1 /* always, we need it in most cases, and we can't tell here
1208 & now if we don't need it */
1209 #ifdef USE_SLOW_TIMER
1210 + 1 /* slow timer process */
1213 +((!tcp_disable)?( 1/* tcp main */ + tcp_children_no ):0)
1218 int main(int argc, char** argv)
1231 int debug_save, debug_flag;
1236 creator_pid = getpid();
1238 my_argc=argc; my_argv=argv;
1242 /*init pkg mallocs (before parsing cfg or cmd line !)*/
1243 if (init_pkg_mallocs()==-1)
1247 fprintf(stderr, "WARNING: ser startup: "
1248 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1251 options= ":f:cm:dVhEb:l:L:n:vrRDTN:W:w:t:u:g:P:G:"
1258 init_tcp_options(); /* set the defaults before the config */
1260 /* look if there is a -h, e.g. -f -h construction won't catch it later */
1262 while((c=getopt(argc,argv,options))!=-1) {
1263 if (c == 'h' || (optarg && strcmp(optarg, "-h") == 0)) {
1264 printf("version: %s\n", version);
1265 printf("%s",help_msg);
1270 /* process command line (cfg. file path etc) */
1271 optind = 1; /* reset getopt */
1272 /* switches required before script processing */
1273 while((c=getopt(argc,argv,options))!=-1) {
1280 log_stderr=1; /* force stderr logging */
1286 shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1288 fprintf(stderr, "bad shmem size number: -m %s\n",
1292 LOG(L_INFO, "ser: shared memory: %ld bytes\n",
1297 default_core_cfg.debug++;
1300 printf("version: %s\n", version);
1301 printf("flags: %s\n", flags );
1302 print_ct_constants();
1304 printf("%s compiled on %s with %s\n", __FILE__,
1305 compiled, COMPILER );
1331 if (isprint(optopt)) {
1332 fprintf(stderr, "Unknown option `-%c'."
1333 " Use -h for help.\n", optopt);
1335 fprintf(stderr, "Unknown option character `\\x%x'."
1336 " Use -h for help.\n",
1341 fprintf(stderr, "Option `-%c' requires an argument."
1342 " Use -h for help.\n",
1350 if (init_routes()<0) goto error;
1351 if (init_nonsip_hooks()<0) goto error;
1352 /* fill missing arguments with the default values*/
1353 if (cfg_file==0) cfg_file=CFG_FILE;
1355 /* load config file or die */
1356 cfg_stream=fopen (cfg_file, "r");
1358 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
1364 /* try to use /dev/urandom if possible */
1366 if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
1368 if (read(rfd, (void*)&seed, sizeof(seed))==-1){
1369 if (errno==EINTR) goto try_again; /* interrupted by signal */
1370 LOG(L_WARN, "WARNING: could not read from /dev/urandom (%d)\n",
1373 DBG("read %u from /dev/urandom\n", seed);
1376 LOG(L_WARN, "WARNING: could not open /dev/urandom (%d)\n", errno);
1378 seed+=getpid()+time(0);
1379 DBG("seeding PRNG with %u\n", seed);
1381 fastrand_seed(rand());
1382 srandom(rand()+time(0));
1383 DBG("test random numbers %u %lu %u\n", rand(), random(), fastrand());
1385 /*register builtin modules*/
1386 register_builtin_modules();
1388 /* init named flags */
1392 debug_save = default_core_cfg.debug;
1393 if ((yyparse()!=0)||(cfg_errors)){
1394 fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
1398 fprintf(stderr, "%d config warnings\n", cfg_warnings);
1400 if (debug_flag) default_core_cfg.debug = debug_save;
1403 /* options with higher priority than cfg file */
1404 optind = 1; /* reset getopt */
1405 while((c=getopt(argc,argv,options))!=-1) {
1415 log_stderr=1; // use in both getopt switches
1418 maxbuffer=strtol(optarg, &tmp, 10);
1420 fprintf(stderr, "bad max buffer size number: -b %s\n",
1426 if (parse_phostport(optarg, &tmp, &tmp_len,
1428 fprintf(stderr, "bad -l address specifier: %s\n",
1432 tmp[tmp_len]=0; /* null terminate the host */
1433 /* add a new addr. to our address list */
1434 if (add_listen_iface(tmp, port, proto, 0)!=0){
1435 fprintf(stderr, "failed to add new listen address\n");
1440 children_no=strtol(optarg, &tmp, 10);
1441 if ((tmp==0) ||(*tmp)){
1442 fprintf(stderr, "bad process number: -n %s\n",
1451 received_dns|=DO_DNS;
1454 received_dns|=DO_REV_DNS;
1463 fprintf(stderr,"WARNING: tcp support not compiled in\n");
1468 tcp_children_no=strtol(optarg, &tmp, 10);
1469 if ((tmp==0) ||(*tmp)){
1470 fprintf(stderr, "bad process number: -N %s\n",
1475 fprintf(stderr,"WARNING: tcp support not compiled in\n");
1480 tcp_poll_method=get_poll_type(optarg);
1481 if (tcp_poll_method==POLL_NONE){
1482 fprintf(stderr, "bad poll method name: -W %s\ntry "
1483 "one of %s.\n", optarg, poll_support);
1487 fprintf(stderr,"WARNING: tcp support not compiled in\n");
1519 dont_fork = dont_fork_cnt; /* override by command line */
1521 if (dont_fork > 0) {
1522 dont_daemonize = dont_fork == 2;
1523 dont_fork = dont_fork == 1;
1525 /* init locks first */
1526 if (init_lock_ops()!=0)
1528 /* init the resolver, before fixing the config */
1530 /* fix parameters */
1531 if (port_no<=0) port_no=SIP_PORT;
1533 if (tls_port_no<=0) tls_port_no=SIPS_PORT;
1537 if (children_no<=0) children_no=CHILD_NO;
1540 if (tcp_children_no<=0) tcp_children_no=children_no;
1544 if (working_dir==0) working_dir="/";
1548 if (user2uid(&uid, &gid, user)<0){
1549 fprintf(stderr, "bad user name/uid number: -u %s\n", user);
1554 if (group2gid(&gid, group)<0){
1555 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
1559 if (fix_all_socket_lists(&socket_types)!=0){
1560 fprintf(stderr, "failed to initialize list addresses\n");
1563 if (dns_try_ipv6 && !(socket_types & SOCKET_T_IPV6)){
1564 /* if we are not listening on any ipv6 address => no point
1565 * to try to resovle ipv6 addresses */
1568 /* print all the listen addresses */
1569 printf("Listening on \n");
1570 print_all_socket_lists();
1571 printf("Aliases: \n");
1572 /*print_aliases();*/
1577 fprintf(stderr, "WARNING: no fork mode %s\n",
1579 (udp_listen->next)?"and more than one listen address found "
1580 "(will use only the the first one)":""
1581 ):"and no udp listen address found" );
1584 fprintf(stderr, "config file ok, exiting...\n");
1591 * -to allow setting shm mem size from the command line
1592 * => if shm_mem should be settable from the cfg file move
1594 * -it must be also before init_timer and init_tcp
1595 * -it must be after we know uid (so that in the SYSV sems case,
1596 * the sems will have the correct euid)
1598 if (init_shm_mallocs(shm_force_alloc)==-1)
1600 if (init_atomic_ops()==-1)
1602 /*init timer, before parsing the cfg!*/
1603 if (init_timer()<0){
1604 LOG(L_CRIT, "could not initialize timer, exiting...\n");
1607 #ifdef USE_DNS_CACHE
1608 if (use_dns_cache && init_dns_cache()<0){
1609 LOG(L_CRIT, "could not initialize the dns cache, exiting...\n");
1612 if (use_dns_cache==0)
1613 use_dns_failover=0; /* cannot work w/o dns_cache support */
1614 #ifdef USE_DNS_CACHE_STATS
1615 /* preinitializing before the nubmer of processes is determined */
1616 if (init_dns_cache_stats(1)<0){
1617 LOG(L_CRIT, "could not initialize the dns cache measurement\n");
1620 #endif /* USE_DNS_CACHE_STATS */
1622 #ifdef USE_DST_BLACKLIST
1623 if (init_dst_blacklist()<0){
1624 LOG(L_CRIT, "could not initialize the dst blacklist, exiting...\n");
1627 #ifdef USE_DST_BLACKLIST_STATS
1628 /* preinitializing before the nubmer of processes is determined */
1629 if (init_dst_blacklist_stats(1)<0){
1630 LOG(L_CRIT, "could not initialize the dst blacklist measurement\n");
1633 #endif /* USE_DST_BLACKLIST_STATS */
1635 if (init_avps()<0) goto error;
1636 if (rpc_init_time() < 0) goto error;
1642 LOG(L_CRIT, "could not initialize tcp, exiting...\n");
1646 #endif /* USE_TCP */
1649 if ( daemonize(argv[0]) <0 ) goto error;
1651 if (install_sigs() != 0){
1652 fprintf(stderr, "ERROR: could not install the signal handlers\n");
1656 if (disable_core_dump) set_core_dump(0, 0);
1657 else set_core_dump(1, shm_mem_size+PKG_MEM_POOL_SIZE+4*1024*1024);
1658 if (open_files_limit>0){
1659 if(increase_open_fds(open_files_limit)<0){
1660 fprintf(stderr, "ERROR: error could not increase file limits\n");
1668 set_rt_prio(rt_prio, rt_policy);
1671 if (cfg_init() < 0) {
1672 LOG(L_CRIT, "could not initialize configuration framework\n");
1675 /* declare the core cfg before the module configs */
1676 if (cfg_declare("core", core_cfg_def, &default_core_cfg, cfg_size(core),
1679 LOG(L_CRIT, "could not declare the core configuration\n");
1683 if (init_modules() != 0) {
1684 fprintf(stderr, "ERROR: error while initializing modules\n");
1688 if (cfg_shmize() < 0) {
1689 LOG(L_CRIT, "could not initialize shared configuration\n");
1693 /* initialize process_table, add core process no. (calc_proc_no()) to the
1694 * processes registered from the modules*/
1695 if (init_pt(calc_proc_no())==-1)
1701 LOG(L_WARN, "WARNING: tls support enabled, but no tls engine "
1702 " available (forgot to load the tls module?)\n");
1703 LOG(L_WARN, "WARNING: disabling tls...\n");
1708 LOG(L_CRIT, "could not initialize tls, exiting...\n");
1712 #endif /* USE_TLS */
1713 #endif /* USE_TCP */
1715 /* The total number of processes is now known, note that no
1716 * function being called before this point may rely on the
1717 * number of processes !
1719 DBG("Expect (at least) %d SER processes in your process list\n",
1722 #if defined USE_DNS_CACHE && defined USE_DNS_CACHE_STATS
1723 if (init_dns_cache_stats(get_max_procs())<0){
1724 LOG(L_CRIT, "could not initialize the dns cache measurement\n");
1728 #if defined USE_DST_BLACKLIST && defined USE_DST_BLACKLIST_STATS
1729 if (init_dst_blacklist_stats(get_max_procs())<0){
1730 LOG(L_CRIT, "could not initialize the dst blacklist measurement\n");
1735 /* fix routing lists */
1736 if ( (r=fix_rls())!=0){
1737 fprintf(stderr, "ERROR: error %d while trying to fix configuration\n",
1744 if (init_stats( dont_fork ? 1 : children_no )==-1) goto error;
1749 if (is_main) shutdown_children(SIGTERM, 0);
1750 /* else terminate process */
1755 if (is_main) shutdown_children(SIGTERM, 0);