- moved daemonize in its own file
[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 (needed on solaris) (andrei)
39  *  2003-06-11  moved all signal handlers init. in install_sigs and moved it
40  *               after daemonize (so that we won't catch anymore our own
41  *               SIGCHLD generated when becoming session leader) (andrei)
42  *              changed is_main default value to 1 (andrei)
43  *  2003-06-28  kill_all_children is now used instead of kill(0, sig)
44  *                see comment above it for explanations. (andrei)
45  *  2003-06-29  replaced port_no_str snprintf w/ int2str (andrei)
46  *  2003-10-10  added switch for config check (-c) (andrei)
47  *  2003-10-24  converted to the new socket_info lists (andrei)
48  *  2004-02-06  added support for user pref. - init_avp_child() (bogdan)
49  *
50  */
51
52
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <errno.h>
56 #include <ctype.h>
57 #include <string.h>
58 #include <netdb.h>
59 #include <unistd.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
62 #include <arpa/inet.h>
63 #include <sys/utsname.h>
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <sys/mman.h>
67 #include <fcntl.h>
68 #include <sys/time.h>
69 #include <sys/wait.h>
70 #include <pwd.h>
71 #include <grp.h>
72 #include <signal.h>
73
74 #include <sys/ioctl.h>
75 #include <net/if.h>
76 #ifdef HAVE_SYS_SOCKIO_H
77 #include <sys/sockio.h>
78 #endif
79
80 #include "config.h"
81 #include "dprint.h"
82 #include "daemonize.h"
83 #include "route.h"
84 #include "udp_server.h"
85 #include "globals.h"
86 #include "mem/mem.h"
87 #ifdef SHM_MEM
88 #include "mem/shm_mem.h"
89 #endif
90 #include "sr_module.h"
91 #include "timer.h"
92 #include "parser/msg_parser.h"
93 #include "ip_addr.h"
94 #include "resolve.h"
95 #include "parser/parse_hname2.h"
96 #include "parser/digest/digest_parser.h"
97 #include "fifo_server.h"
98 #include "unixsock_server.h"
99 #include "usr_avp.h"
100 #include "name_alias.h"
101 #include "hash_func.h"
102 #include "pt.h"
103 #include "script_cb.h"
104 #include "ut.h"
105 #ifdef USE_TCP
106 #include "tcp_init.h"
107 #ifdef USE_TLS
108 #include "tls/tls_init.h"
109 #endif
110 #endif
111
112
113
114 #include "stats.h"
115
116 #ifdef DEBUG_DMALLOC
117 #include <dmalloc.h>
118 #endif
119
120 static char id[]="@(#) $Id$";
121 static char version[]=  NAME " " VERSION " (" ARCH "/" OS ")" ;
122 static char compiled[]= __TIME__ " " __DATE__ ;
123 static char flags[]=
124 "STATS:"
125 #ifdef STATS
126 "On"
127 #else
128 "Off"
129 #endif
130 #ifdef USE_IPV6
131 ", USE_IPV6"
132 #endif
133 #ifdef USE_TCP
134 ", USE_TCP"
135 #endif
136 #ifdef USE_TLS
137 ", USE_TLS"
138 #endif
139 #ifdef DISABLE_NAGLE
140 ", DISABLE_NAGLE"
141 #endif
142 #ifdef NO_DEBUG
143 ", NO_DEBUG"
144 #endif
145 #ifdef NO_LOG
146 ", NO_LOG"
147 #endif
148 #ifdef EXTRA_DEBUG
149 ", EXTRA_DEBUG"
150 #endif
151 #ifdef DNS_IP_HACK
152 ", DNS_IP_HACK"
153 #endif
154 #ifdef SHM_MEM
155 ", SHM_MEM"
156 #endif
157 #ifdef SHM_MMAP
158 ", SHM_MMAP"
159 #endif
160 #ifdef PKG_MALLOC
161 ", PKG_MALLOC"
162 #endif
163 #ifdef VQ_MALLOC
164 ", VQ_MALLOC"
165 #endif
166 #ifdef F_MALLOC
167 ", F_MALLOC"
168 #endif
169 #ifdef USE_SHM_MEM
170 ", USE_SHM_MEM"
171 #endif
172 #ifdef DBG_QM_MALLOC
173 ", DBG_QM_MALLOC"
174 #endif
175 #ifdef DEBUG_DMALLOC
176 ", DEBUG_DMALLOC"
177 #endif
178 #ifdef FAST_LOCK
179 ", FAST_LOCK"
180 #ifdef BUSY_WAIT
181 "-BUSY_WAIT"
182 #endif
183 #ifdef USE_PTHREAD_MUTEX
184 ", USE_PTHREAD_MUTEX"
185 #endif
186 #ifdef USE_POSIX_SEM
187 ", USE_POSIX_SEM"
188 #endif
189 #ifdef USE_SYSV_SEM
190 ", USE_SYSV_SEM"
191 #endif
192 #ifdef ADAPTIVE_WAIT
193 "-ADAPTIVE_WAIT"
194 #endif
195 #ifdef NOSMP
196 "-NOSMP"
197 #endif
198 #endif /*FAST_LOCK*/
199 ;
200
201 static char help_msg[]= "\
202 Usage: " NAME " -l address [-p port] [-l address [-p port]...] [options]\n\
203 Options:\n\
204     -f file      Configuration file (default " CFG_FILE ")\n\
205     -c           Check configuration file for errors\n\
206     -p port      Listen on the specified port (default: 5060)\n\
207                   applies to the last address in -l and to all \n\
208                   following that do not have a corespponding -p\n\
209     -l address   Listen on the specified address/interface (multiple -l\n\
210                   mean listening on more addresses). The default behaviour\n\
211                   is to listen on all the interfaces\n\
212     -n processes Number of child processes to fork per interface\n\
213                   (default: 8)\n\
214     -r           Use dns to check if is necessary to add a \"received=\"\n\
215                   field to a via\n\
216     -R           Same as `-r` but use reverse dns;\n\
217                   (to use both use `-rR`)\n\
218     -v           Turn on \"via:\" host checking when forwarding replies\n\
219     -d           Debugging mode (multiple -d increase the level)\n\
220     -D           Do not fork into daemon mode\n\
221     -E           Log to stderr\n"
222 #ifdef USE_TCP
223 "    -T           Disable tcp\n\
224     -N           Number of tcp child processes (default: equal to `-n`)\n"
225 #endif
226 "    -V           Version number\n\
227     -h           This help message\n\
228     -b nr        Maximum receive buffer size which will not be exceeded by\n\
229                   auto-probing procedure even if  OS allows\n\
230     -m nr        Size of shared memory allocated in Megabytes\n\
231     -w dir       Change the working directory to \"dir\" (default \"/\")\n\
232     -t dir       Chroot to \"dir\"\n\
233     -u uid       Change uid \n\
234     -g gid       Change gid \n\
235     -P file      Create a pid file\n\
236     -i fifo_path Create a fifo (usefull for monitoring " NAME ") \n\
237     -x socket    Create a unix domain socket \n"
238 #ifdef STATS
239 "    -s file     File to which statistics is dumped (disabled otherwise)\n"
240 #endif
241 ;
242
243 /* print compile-time constants */
244 void print_ct_constants()
245 {
246 #ifdef ADAPTIVE_WAIT
247         printf("ADAPTIVE_WAIT_LOOPS=%d, ", ADAPTIVE_WAIT_LOOPS);
248 #endif
249 /*
250 #ifdef SHM_MEM
251         printf("SHM_MEM_SIZE=%d, ", SHM_MEM_SIZE);
252 #endif
253 */
254         printf("MAX_RECV_BUFFER_SIZE %d, MAX_LISTEN %d,"
255                         " MAX_URI_SIZE %d, BUF_SIZE %d\n",
256                 MAX_RECV_BUFFER_SIZE, MAX_LISTEN, MAX_URI_SIZE, 
257                 BUF_SIZE );
258 }
259
260 /* debuging function */
261 /*
262 void receive_stdin_loop()
263 {
264         #define BSIZE 1024
265         char buf[BSIZE+1];
266         int len;
267
268         while(1){
269                 len=fread(buf,1,BSIZE,stdin);
270                 buf[len+1]=0;
271                 receive_msg(buf, len);
272                 printf("-------------------------\n");
273         }
274 }
275 */
276
277 /* global vars */
278
279 int own_pgid = 0; /* whether or not we have our own pgid (and it's ok
280                                          to use kill(0, sig) */
281 char* cfg_file = 0;
282 unsigned int maxbuffer = MAX_RECV_BUFFER_SIZE; /* maximum buffer size we do
283                                                                                                   not want to exceed durig the
284                                                                                                   auto-probing procedure; may 
285                                                                                                   be re-configured */
286 int children_no = 0;                    /* number of children processing requests */
287 #ifdef USE_TCP
288 int tcp_children_no = 0;
289 int tcp_disable = 0; /* 1 if tcp is disabled */
290 #endif
291 #ifdef USE_TLS
292 int tls_disable = 0; /* 1 if tls is disabled */
293 #endif
294 struct process_table *pt=0;             /*array with childrens pids, 0= main proc,
295                                                                         alloc'ed in shared mem if possible*/
296 int sig_flag = 0;              /* last signal received */
297 int debug = L_NOTICE;
298 int dont_fork = 0;
299 int log_stderr = 0;
300 /* log facility (see syslog(3)) */
301 int log_facility = LOG_DAEMON;
302 int config_check = 0;
303 /* check if reply first via host==us */
304 int check_via =  0;        
305 /* shall use stateful synonym branches? faster but not reboot-safe */
306 int syn_branch = 1;
307 /* debugging level for memory stats */
308 int memlog = L_DBG;
309 /* should replies include extensive warnings? by default yes,
310    good for trouble-shooting
311 */
312 int sip_warning = 1;
313 /* should localy-generated messages include server's signature?
314    be default yes, good for trouble-shooting
315 */
316 int server_signature=1;
317 /* should ser try to locate outbound interface on multihomed
318  * host? by default not -- too expensive
319  */
320 int mhomed=0;
321 /* use dns and/or rdns or to see if we need to add 
322    a ;received=x.x.x.x to via: */
323 int received_dns = 0;      
324 char* working_dir = 0;
325 char* chroot_dir = 0;
326 char* user=0;
327 char* group=0;
328 int uid = 0;
329 int gid = 0;
330 /* a hint to reply modules whether they should send reply
331    to IP advertised in Via or IP from which a request came
332 */
333 int reply_to_via=0;
334
335 #if 0
336 char* names[MAX_LISTEN];              /* our names */
337 int names_len[MAX_LISTEN];            /* lengths of the names*/
338 struct ip_addr addresses[MAX_LISTEN]; /* our ips */
339 int addresses_no=0;                   /* number of names/ips */
340 #endif
341 struct socket_info* udp_listen=0;
342 #ifdef USE_TCP
343 struct socket_info* tcp_listen=0;
344 #endif
345 #ifdef USE_TLS
346 struct socket_info* tls_listen=0;
347 #endif
348 struct socket_info* bind_address=0; /* pointer to the crt. proc.
349                                                                          listening address*/
350 struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
351 struct socket_info* sendipv6; /* same as above for ipv6 */
352 #ifdef USE_TCP
353 struct socket_info* sendipv4_tcp; 
354 struct socket_info* sendipv6_tcp; 
355 #endif
356 #ifdef USE_TLS
357 struct socket_info* sendipv4_tls;
358 struct socket_info* sendipv6_tls;
359 #endif
360
361 unsigned short port_no=0; /* default port*/
362 #ifdef USE_TLS
363 unsigned short tls_port_no=0; /* default port */
364 #endif
365
366 struct host_alias* aliases=0; /* name aliases list */
367
368 /* ipc related globals */
369 int process_no = 0;
370 /* process_bm_t process_bit = 0; */
371 #ifdef ROUTE_SRV
372 #endif
373
374 /* cfg parsing */
375 int cfg_errors=0;
376
377 /* shared memory (in MB) */
378 unsigned int shm_mem_size=SHM_MEM_SIZE * 1024 * 1024;
379
380 /* export command-line to anywhere else */
381 int my_argc;
382 char **my_argv;
383
384 #define MAX_FD 32 /* maximum number of inherited open file descriptors,
385                     (normally it shouldn't  be bigger  than 3) */
386
387
388 extern FILE* yyin;
389 extern int yyparse();
390
391
392 int is_main=1; /* flag = is this the  "main" process? */
393
394 char* pid_file = 0; /* filename as asked by use */
395
396
397
398 /* callit before exiting; if show_status==1, mem status is displayed */
399 void cleanup(show_status)
400 {
401         /*clean-up*/
402         destroy_modules();
403 #ifdef USE_TCP
404         destroy_tcp();
405 #endif
406 #ifdef USE_TLS
407         destroy_tls();
408 #endif
409         destroy_timer();
410         close_unixsock_server();
411         destroy_fifo();
412         destroy_script_cb();
413 #ifdef PKG_MALLOC
414         if (show_status){
415                 LOG(memlog, "Memory status (pkg):\n");
416                 pkg_status();
417         }
418 #endif
419 #ifdef SHM_MEM
420         if (pt) shm_free(pt);
421         pt=0;
422         if (show_status){
423                         LOG(memlog, "Memory status (shm):\n");
424                         shm_status();
425         }
426         /* zero all shmem alloc vars that we still use */
427         shm_mem_destroy();
428 #endif
429         if (pid_file) unlink(pid_file);
430 }
431
432
433
434 /* tries to send a signal to all our processes
435  * if daemonized  is ok to send the signal to all the process group,
436  * however if not daemonized we might end up sending the signal also
437  * to the shell which launched us => most signals will kill it if 
438  * it's not in interactive mode and we don't want this. The non-daemonized 
439  * case can occur when an error is encountered before daemonize is called 
440  * (e.g. when parsing the config file) or when ser is started in "dont-fork"
441  *  mode. Sending the signal to all the processes in pt[] will not work
442  *  for processes forked from modules (which have no correspondent entry in 
443  *  pt), but this can happen only in dont_fork mode (which is only for
444  *  debugging). So in the worst case + "dont-fork" we might leave some
445  *  zombies. -- andrei */
446 static void kill_all_children(int signum)
447 {
448         int r;
449         if (own_pgid) kill(0, signum);
450         else if (pt)
451                 for (r=1; r<process_count(); r++)
452                         if (pt[r].pid) kill(pt[r].pid, signum);
453 }
454
455
456
457 void handle_sigs()
458 {
459         pid_t   chld;
460         int     chld_status;
461
462         switch(sig_flag){
463                 case 0: break; /* do nothing*/
464                 case SIGPIPE:
465                                 /* SIGPIPE might be rarely received on use of
466                                    exec module; simply ignore it
467                                  */
468                                 LOG(L_WARN, "WARNING: SIGPIPE received and ignored\n");
469                                 break;
470                 case SIGINT:
471                 case SIGTERM:
472                         /* we end the program in all these cases */
473                         if (sig_flag==SIGINT)
474                                 DBG("INT received, program terminates\n");
475                         else
476                                 DBG("SIGTERM received, program terminates\n");
477                                 
478                         /* first of all, kill the children also */
479                         kill_all_children(SIGTERM);
480
481                              /* Wait for all the children to die */
482                         while(wait(0) > 0);
483                         
484                         cleanup(1); /* cleanup & show status*/
485                         dprint("Thank you for flying " NAME "\n");
486                         exit(0);
487                         break;
488                         
489                 case SIGUSR1:
490 #ifdef STATS
491                         dump_all_statistic();
492 #endif
493 #ifdef PKG_MALLOC
494                         LOG(memlog, "Memory status (pkg):\n");
495                         pkg_status();
496 #endif
497 #ifdef SHM_MEM
498                         LOG(memlog, "Memory status (shm):\n");
499                         shm_status();
500 #endif
501                         break;
502                         
503                 case SIGCHLD:
504                         while ((chld=waitpid( -1, &chld_status, WNOHANG ))>0) {
505                                 if (WIFEXITED(chld_status)) 
506                                         LOG(L_INFO, "child process %d exited normally,"
507                                                         " status=%d\n", chld, 
508                                                         WEXITSTATUS(chld_status));
509                                 else if (WIFSIGNALED(chld_status)) {
510                                         LOG(L_INFO, "child process %d exited by a signal"
511                                                         " %d\n", chld, WTERMSIG(chld_status));
512 #ifdef WCOREDUMP
513                                         LOG(L_INFO, "core was %sgenerated\n",
514                                                          WCOREDUMP(chld_status) ?  "" : "not " );
515 #endif
516                                 }else if (WIFSTOPPED(chld_status)) 
517                                         LOG(L_INFO, "child process %d stopped by a"
518                                                                 " signal %d\n", chld,
519                                                                  WSTOPSIG(chld_status));
520                         }
521 #ifndef STOP_JIRIS_CHANGES
522                         if (dont_fork) {
523                                 LOG(L_INFO, "INFO: dont_fork turned on, living on\n");
524                                 break;
525                         } 
526                         LOG(L_INFO, "INFO: terminating due to SIGCHLD\n");
527 #endif
528                         /* exit */
529                         kill_all_children(SIGTERM);
530                         while(wait(0) > 0); /* wait for all the children to terminate*/
531                         cleanup(1); /* cleanup & show status*/
532                         DBG("terminating due to SIGCHLD\n");
533                         exit(0);
534                         break;
535                 
536                 case SIGHUP: /* ignoring it*/
537                                         DBG("SIGHUP received, ignoring it\n");
538                                         break;
539                 default:
540                         LOG(L_CRIT, "WARNING: unhandled signal %d\n", sig_flag);
541         }
542         sig_flag=0;
543 }
544
545
546
547 /* added by jku; allows for regular exit on a specific signal;
548    good for profiling which only works if exited regularly and
549    not by default signal handlers
550     - modified by andrei: moved most of the stuff to handle_sigs, 
551        made it safer for the "fork" case
552 */
553 static void sig_usr(int signo)
554 {
555
556
557         if (is_main){
558                 if (sig_flag==0) sig_flag=signo;
559                 else /*  previous sig. not processed yet, ignoring? */
560                         return; ;
561                 if (dont_fork) 
562                                 /* only one proc, doing everything from the sig handler,
563                                 unsafe, but this is only for debugging mode*/
564                         handle_sigs();
565         }else{
566                 /* process the important signals */
567                 switch(signo){
568                         case SIGPIPE:
569                                         LOG(L_INFO, "INFO: signal %d received\n", signo);
570                                 break;
571                         case SIGINT:
572                         case SIGTERM:
573                                         LOG(L_INFO, "INFO: signal %d received\n", signo);
574                                         /* print memory stats for non-main too */
575                                         #ifdef PKG_MALLOC
576                                         LOG(memlog, "Memory status (pkg):\n");
577                                         pkg_status();
578                                         #endif
579                                         exit(0);
580                                         break;
581                         case SIGUSR1:
582                                 /* statistics, do nothing, printed only from the main proc */
583                                         break;
584                                 /* ignored*/
585                         case SIGUSR2:
586                         case SIGHUP:
587                                         break;
588                         case SIGCHLD:
589 #ifndef                         STOP_JIRIS_CHANGES
590                                         DBG("SIGCHLD received: "
591                                                 "we do not worry about grand-children\n");
592 #else
593                                         exit(0); /* terminate if one child died */
594 #endif
595                 }
596         }
597 }
598
599
600
601 /* install the signal handlers, returns 0 on success, -1 on error */
602 int install_sigs()
603 {
604         /* added by jku: add exit handler */
605         if (signal(SIGINT, sig_usr) == SIG_ERR ) {
606                 DPrint("ERROR: no SIGINT signal handler can be installed\n");
607                 goto error;
608         }
609         /* if we debug and write to a pipe, we want to exit nicely too */
610         if (signal(SIGPIPE, sig_usr) == SIG_ERR ) {
611                 DPrint("ERROR: no SIGINT signal handler can be installed\n");
612                 goto error;
613         }
614         
615         if (signal(SIGUSR1, sig_usr)  == SIG_ERR ) {
616                 DPrint("ERROR: no SIGUSR1 signal handler can be installed\n");
617                 goto error;
618         }
619         if (signal(SIGCHLD , sig_usr)  == SIG_ERR ) {
620                 DPrint("ERROR: no SIGCHLD signal handler can be installed\n");
621                 goto error;
622         }
623         if (signal(SIGTERM , sig_usr)  == SIG_ERR ) {
624                 DPrint("ERROR: no SIGTERM signal handler can be installed\n");
625                 goto error;
626         }
627         if (signal(SIGHUP , sig_usr)  == SIG_ERR ) {
628                 DPrint("ERROR: no SIGHUP signal handler can be installed\n");
629                 goto error;
630         }
631         if (signal(SIGUSR2 , sig_usr)  == SIG_ERR ) {
632                 DPrint("ERROR: no SIGUSR2 signal handler can be installed\n");
633                 goto error;
634         }
635         return 0;
636 error:
637         return -1;
638 }
639
640
641
642 /* main loop */
643 int main_loop()
644 {
645         int  i;
646         pid_t pid;
647         struct socket_info* si;
648 #ifdef USE_TCP
649         int sockfd[2];
650 #endif
651
652         /* one "main" process and n children handling i/o */
653
654         is_main=0;
655         if (dont_fork){
656 #ifdef STATS
657                 setstats( 0 );
658 #endif
659                 if (udp_listen==0){
660                         LOG(L_ERR, "ERROR: no fork mode requires at least one"
661                                         " udp listen address, exiting...\n");
662                         goto error;
663                 }
664                 /* only one address, we ignore all the others */
665                 if (udp_init(udp_listen)==-1) goto error;
666                 bind_address=udp_listen;
667                 sendipv4=bind_address;
668                 sendipv6=bind_address; /*FIXME*/
669                 if (udp_listen->next){
670                         LOG(L_WARN, "WARNING: using only the first listen address"
671                                                 " (no fork)\n");
672                 }
673                 if (do_suid()==-1) goto error; /* try to drop priviledges */
674                 /* process_no now initialized to zero -- increase from now on
675                    as new processes are forked (while skipping 0 reserved for main 
676                 */
677
678                 /* we need another process to act as the timer*/
679 #ifdef USE_TCP
680                 /* if we are using tcp we always need a timer process,
681                  * we cannot count on select timeout to measure time
682                  * (it works only on linux)
683                  */
684                 if ((!tcp_disable)||(timer_list))
685 #else
686                 if (timer_list)
687 #endif
688                 {
689                                 process_no++;
690                                 if ((pid=fork())<0){
691                                         LOG(L_CRIT,  "ERROR: main_loop: Cannot fork\n");
692                                         goto error;
693                                 }
694                                 
695                                 if (pid==0){
696                                         /* child */
697                                         /* timer!*/
698                                         /* process_bit = 0; */
699                                         if (init_child(PROC_TIMER) < 0) {
700                                                 LOG(L_ERR, "timer: init_child failed\n");
701                                                 goto error;
702                                         }
703                                         for(;;){
704                                                 sleep(TIMER_TICK);
705                                                 timer_ticker();
706                                         }
707                                 }else{
708                                                 pt[process_no].pid=pid; /*should be shared mem anway*/
709                                                 strncpy(pt[process_no].desc, "timer", MAX_PT_DESC );
710                                 }
711                 }
712
713                 /* if configured to do so, start a server for accepting FIFO commands */
714                 if (open_fifo_server()<0) {
715                         LOG(L_ERR, "opening fifo server failed\n");
716                         goto error;
717                 }
718
719                      /* Initialize Unix domain socket server */
720                 if (init_unixsock_server()<0) {
721                         LOG(L_ERR, "Error while initializing Unix domain socket server\n");
722                         goto error;
723                 }
724
725                 /* main process, receive loop */
726                 process_no=0; /*main process number*/
727                 pt[process_no].pid=getpid();
728                 snprintf(pt[process_no].desc, MAX_PT_DESC, 
729                         "stand-alone receiver @ %s:%s", 
730                          bind_address->name.s, bind_address->port_no_str.s );
731                 
732                 
733                      /* We will call child_init even if we
734                       * do not fork - and it will be called with rank 1 because
735                       * in fact we behave like a child, not like main process
736                       */
737
738                 if (init_child(1) < 0) {
739                         LOG(L_ERR, "main_dontfork: init_child failed\n");
740                         goto error;
741                 }
742                 if (init_avp_child(1)<0) {
743                         LOG(L_ERR, "init_avp_child failed\n");
744                         goto error;
745                 }
746
747                 is_main=1; /* hack 42: call init_child with is_main=0 in case
748                                          some modules wants to fork a child */
749                 
750                 return udp_rcv_loop();
751         }else{
752                 /* process_no now initialized to zero -- increase from now on
753                    as new processes are forked (while skipping 0 reserved for main )
754                 */
755                 for(si=udp_listen;si;si=si->next){
756                         /* create the listening socket (for each address)*/
757                         /* udp */
758                         if (udp_init(si)==-1) goto error;
759                         /* get first ipv4/ipv6 socket*/
760                         if ((si->address.af==AF_INET)&&
761                                         ((sendipv4==0)||(sendipv4->flags&SI_IS_LO)))
762                                 sendipv4=si;
763         #ifdef USE_IPV6
764                         if((sendipv6==0)&&(si->address.af==AF_INET6))
765                                 sendipv6=si;
766         #endif
767                 }
768 #ifdef USE_TCP
769                 if (!tcp_disable){
770                         for(si=tcp_listen; si; si=si->next){
771                                 /* same thing for tcp */
772                                 if (tcp_init(si)==-1)  goto error;
773                                 /* get first ipv4/ipv6 socket*/
774                                 if ((si->address.af==AF_INET)&&
775                                                 ((sendipv4_tcp==0)||(sendipv4_tcp->flags&SI_IS_LO)))
776                                         sendipv4_tcp=si;
777                 #ifdef USE_IPV6
778                                 if((sendipv6_tcp==0)&&(si->address.af==AF_INET6))
779                                         sendipv6_tcp=si;
780                 #endif
781                         }
782                 }
783 #ifdef USE_TLS
784                 if (!tls_disable){
785                         for(si=tls_listen; si; si=si->next){
786                                 /* same as for tcp*/
787                                 if (tls_init(si)==-1)  goto error;
788                                 /* get first ipv4/ipv6 socket*/
789                                 if ((si->address.af==AF_INET)&&
790                                                 ((sendipv4_tls==0)||(sendipv4_tls->flags&SI_IS_LO)))
791                                         sendipv4_tls=si;
792                 #ifdef USE_IPV6
793                                 if((sendipv6_tls==0)&&(si->address.af==AF_INET6))
794                                         sendipv6_tls=si;
795                 #endif
796                         }
797                 }
798 #endif /* USE_TLS */
799 #endif /* USE_TCP */
800                         /* all procs should have access to all the sockets (for sending)
801                          * so we open all first*/
802                 if (do_suid()==-1) goto error; /* try to drop priviledges */
803                 /* udp processes */
804                 for(si=udp_listen; si; si=si->next){
805                         for(i=0;i<children_no;i++){
806                                 process_no++;
807 #ifdef USE_TCP
808                                 if(!tcp_disable){
809                                         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfd)<0){
810                                                 LOG(L_ERR, "ERROR: main_loop: socketpair failed: %s\n",
811                                                         strerror(errno));
812                                                 goto error;
813                                         }
814                                 }
815 #endif
816                                 if ((pid=fork())<0){
817                                         LOG(L_CRIT,  "main_loop: Cannot fork\n");
818                                         goto error;
819                                 }else if (pid==0){
820                                              /* child */
821 #ifdef USE_TCP
822                                         if (!tcp_disable){
823                                                 close(sockfd[0]);
824                                                 unix_tcp_sock=sockfd[1];
825                                         }
826 #endif
827                                         bind_address=si; /* shortcut */
828                                         if (init_avp_child(i + 1)<0) {
829                                                 LOG(L_ERR, "init_avp_child failed\n");
830                                                 goto error;
831                                         }
832                                         if (init_child(i + 1) < 0) {
833                                                 LOG(L_ERR, "init_child failed\n");
834                                                 goto error;
835                                         }
836 #ifdef STATS
837                                         setstats( i+r*children_no );
838 #endif
839                                         return udp_rcv_loop();
840                                 }else{
841                                                 pt[process_no].pid=pid; /*should be in shared mem.*/
842                                                 snprintf(pt[process_no].desc, MAX_PT_DESC,
843                                                         "receiver child=%d sock= %s:%s", i,     
844                                                         si->name.s, si->port_no_str.s );
845 #ifdef USE_TCP
846                                                 if (!tcp_disable){
847                                                         close(sockfd[1]);
848                                                         pt[process_no].unix_sock=sockfd[0];
849                                                         pt[process_no].idx=-1; /* this is not a "tcp"
850                                                                                                           process*/
851                                                 }
852 #endif
853                                 }
854                         }
855                         /*parent*/
856                         /*close(udp_sock)*/; /*if it's closed=>sendto invalid fd errors?*/
857                 }
858         }
859
860         /*this is the main process*/
861         bind_address=0;                         /* main proc -> it shouldn't send anything, */
862         
863         /* if configured to do so, start a server for accepting FIFO commands */
864         if (open_fifo_server()<0) {
865                 LOG(L_ERR, "opening fifo server failed\n");
866                 goto error;
867         }
868
869              /* Initialize Unix domain socket server */
870         if (init_unixsock_server()<0) {
871                 LOG(L_ERR, "Error while initializing Unix domain socket server\n");
872                 goto error;
873         }
874
875 #ifdef USE_TCP
876         /* if we are using tcp we always need the timer */
877         if ((!tcp_disable)||(timer_list))
878 #else
879         if (timer_list)
880 #endif
881         {
882 #ifdef USE_TCP
883                 if (!tcp_disable){
884                         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfd)<0){
885                                 LOG(L_ERR, "ERROR: main_loop: socketpair failed: %s\n",
886                                         strerror(errno));
887                                 goto error;
888                         }
889                 }
890 #endif
891                 /* fork again for the attendant process*/
892                 process_no++;
893                 if ((pid=fork())<0){
894                         LOG(L_CRIT, "main_loop: cannot fork timer process\n");
895                         goto error;
896                 }else if (pid==0){
897                         /* child */
898                         /* is_main=0; */
899 #ifdef USE_TCP
900                         if (!tcp_disable){
901                                 close(sockfd[0]);
902                                 unix_tcp_sock=sockfd[1];
903                         }
904 #endif
905                         if (init_child(PROC_TIMER) < 0) {
906                                 LOG(L_ERR, "timer: init_child failed\n");
907                                 goto error;
908                         }
909                         
910                         for(;;){
911                                 /* debug:  instead of doing something usefull */
912                                 /* (placeholder for timers, etc.) */
913                                 sleep(TIMER_TICK);
914                                 /* if we received a signal => TIMER_TICK may have not elapsed*/
915                                 timer_ticker();
916                         }
917                 }else{
918                         pt[process_no].pid=pid;
919                         strncpy(pt[process_no].desc, "timer", MAX_PT_DESC );
920 #ifdef USE_TCP
921                         if(!tcp_disable){
922                                                 close(sockfd[1]);
923                                                 pt[process_no].unix_sock=sockfd[0];
924                                                 pt[process_no].idx=-1; /* this is not a "tcp" process*/
925                         }
926 #endif
927                 }
928         }
929 #ifdef USE_TCP
930                 if (!tcp_disable){
931                                 /* start tcp  & tls receivers */
932                         if (tcp_init_children()<0) goto error;
933                                 /* start tcp+tls master proc */
934                         process_no++;
935                         if ((pid=fork())<0){
936                                 LOG(L_CRIT, "main_loop: cannot fork tcp main process\n");
937                                 goto error;
938                         }else if (pid==0){
939                                 /* child */
940                                 /* is_main=0; */
941                                 if (init_child(PROC_TCP_MAIN) < 0) {
942                                         LOG(L_ERR, "tcp_main: error in init_child\n");
943                                         goto error;
944                                 }
945                                 tcp_main_loop();
946                         }else{
947                                 pt[process_no].pid=pid;
948                                 strncpy(pt[process_no].desc, "tcp main process", MAX_PT_DESC );
949                                 pt[process_no].unix_sock=-1;
950                                 pt[process_no].idx=-1; /* this is not a "tcp" process*/
951                                 unix_tcp_sock=-1;
952                         }
953                 }
954 #endif
955         /* main */
956         pt[0].pid=getpid();
957         strncpy(pt[0].desc, "attendant", MAX_PT_DESC );
958 #ifdef USE_TCP
959         if(!tcp_disable){
960                 pt[process_no].unix_sock=-1;
961                 pt[process_no].idx=-1; /* this is not a "tcp" process*/
962                 unix_tcp_sock=-1;
963         }
964 #endif
965         /*DEBUG- remove it*/
966 #ifdef DEBUG
967         fprintf(stderr, "\n% 3d processes (%3d), % 3d children * "
968                         "listening addresses + tcp listeners + tls listeners"
969                         "+ main + fifo %s\n", process_no+1, process_count(), children_no,
970                         (timer_list)?"+ timer":"");
971         for (r=0; r<=process_no; r++){
972                 fprintf(stderr, "% 3d   % 5d - %s\n", r, pt[r].pid, pt[r].desc);
973         }
974 #endif
975         process_no=0; 
976         /* process_bit = 0; */
977         is_main=1;
978         
979         if (init_child(PROC_MAIN) < 0) {
980                 LOG(L_ERR, "main: error in init_child\n");
981                 goto error;
982         }
983         for(;;){
984                         pause();
985                         handle_sigs();
986         }
987         
988         
989         /*return 0; */
990  error:
991         return -1;
992
993 }
994
995
996
997
998 int main(int argc, char** argv)
999 {
1000
1001         FILE* cfg_stream;
1002         int c,r;
1003         char *tmp;
1004         char *options;
1005         int ret;
1006         struct passwd *pw_entry;
1007         struct group  *gr_entry;
1008         unsigned int seed;
1009         int rfd;
1010
1011         /*init*/
1012         ret=-1;
1013         my_argc=argc; my_argv=argv;
1014         
1015         /*init pkg mallocs (before parsing cfg or cmd line !)*/
1016         if (init_pkg_mallocs()==-1)
1017                 goto error;
1018
1019 #ifdef DBG_MSG_QA
1020         fprintf(stderr, "WARNING: ser startup: "
1021                 "DBG_MSG_QA enabled, ser may exit abruptly\n");
1022 #endif
1023
1024
1025
1026         /* process command line (get port no, cfg. file path etc) */
1027         opterr=0;
1028         options=
1029 #ifdef STATS
1030         "s:"
1031 #endif
1032         "f:cp:m:b:l:n:N:rRvdDETVhw:t:u:g:P:i:x:";
1033         
1034         while((c=getopt(argc,argv,options))!=-1){
1035                 switch(c){
1036                         case 'f':
1037                                         cfg_file=optarg;
1038                                         break;
1039                         case 'c':
1040                                         config_check=1;
1041                                         log_stderr=1; /* force stderr logging */
1042                                         break;
1043                         case 's':
1044                                 #ifdef STATS
1045                                         stat_file=optarg;
1046                                 #endif
1047                                         break;
1048                         case 'p':
1049                                         port_no=strtol(optarg, &tmp, 10);
1050                                         if (tmp &&(*tmp)){
1051                                                 fprintf(stderr, "bad port number: -p %s\n", optarg);
1052                                                 goto error;
1053                                         }
1054                                         break;
1055                         case 'm':
1056                                         shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
1057                                         if (tmp &&(*tmp)){
1058                                                 fprintf(stderr, "bad shmem size number: -m %s\n",
1059                                                                                 optarg);
1060                                                 goto error;
1061                                         };
1062                                         LOG(L_INFO, "ser: shared memory allocated: %d MByte\n",
1063                                                                         shm_mem_size );
1064                                         break;
1065
1066                         case 'b':
1067                                         maxbuffer=strtol(optarg, &tmp, 10);
1068                                         if (tmp &&(*tmp)){
1069                                                 fprintf(stderr, "bad max buffer size number: -p %s\n",
1070                                                                                         optarg);
1071                                                 goto error;
1072                                         }
1073                                         break;
1074                         case 'l':
1075                                         /* add a new addr. to our address list */
1076                                         if (add_listen_iface(optarg, 0, 0, 0)!=0){
1077                                                 fprintf(stderr, "failed to add new listen address\n");
1078                                                 goto error;
1079                                         }
1080                                         break;
1081                         case 'n':
1082                                         children_no=strtol(optarg, &tmp, 10);
1083                                         if ((tmp==0) ||(*tmp)){
1084                                                 fprintf(stderr, "bad process number: -n %s\n",
1085                                                                         optarg);
1086                                                 goto error;
1087                                         }
1088                                         break;
1089                         case 'v':
1090                                         check_via=1;
1091                                         break;
1092                         case 'r':
1093                                         received_dns|=DO_DNS;
1094                                         break;
1095                         case 'R':
1096                                         received_dns|=DO_REV_DNS;
1097                         case 'd':
1098                                         debug++;
1099                                         break;
1100                         case 'D':
1101                                         dont_fork=1;
1102                                         break;
1103                         case 'E':
1104                                         log_stderr=1;
1105                                         break;
1106                         case 'T':
1107 #ifdef USE_TCP
1108                                         tcp_disable=1;
1109 #else
1110                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1111 #endif
1112                                         break;
1113                         case 'N':
1114 #ifdef USE_TCP
1115                                         tcp_children_no=strtol(optarg, &tmp, 10);
1116                                         if ((tmp==0) ||(*tmp)){
1117                                                 fprintf(stderr, "bad process number: -N %s\n",
1118                                                                         optarg);
1119                                                 goto error;
1120                                         }
1121 #else
1122                                         fprintf(stderr,"WARNING: tcp support not compiled in\n");
1123 #endif
1124                                         break;
1125                         case 'V':
1126                                         printf("version: %s\n", version);
1127                                         printf("flags: %s\n", flags );
1128                                         print_ct_constants();
1129                                         printf("%s\n",id);
1130                                         printf("%s compiled on %s with %s\n", __FILE__,
1131                                                         compiled, COMPILER );
1132                                         
1133                                         exit(0);
1134                                         break;
1135                         case 'h':
1136                                         printf("version: %s\n", version);
1137                                         printf("%s",help_msg);
1138                                         exit(0);
1139                                         break;
1140                         case 'w':
1141                                         working_dir=optarg;
1142                                         break;
1143                         case 't':
1144                                         chroot_dir=optarg;
1145                                         break;
1146                         case 'u':
1147                                         user=optarg;
1148                                         break;
1149                         case 'g':
1150                                         group=optarg;
1151                                         break;
1152                         case 'P':
1153                                         pid_file=optarg;
1154                                         break;
1155                         case 'i':
1156                                         fifo=optarg;
1157                                         break;
1158                         case 'x':
1159                                         unixsock_name=optarg;
1160                                         break;
1161                         case '?':
1162                                         if (isprint(optopt))
1163                                                 fprintf(stderr, "Unknown option `-%c´.\n", optopt);
1164                                         else
1165                                                 fprintf(stderr, 
1166                                                                 "Unknown option character `\\x%x´.\n",
1167                                                                 optopt);
1168                                         goto error;
1169                         case ':':
1170                                         fprintf(stderr, 
1171                                                                 "Option `-%c´ requires an argument.\n",
1172                                                                 optopt);
1173                                         goto error;
1174                         default:
1175                                         abort();
1176                 }
1177         }
1178         
1179         /* fill missing arguments with the default values*/
1180         if (cfg_file==0) cfg_file=CFG_FILE;
1181
1182         /* load config file or die */
1183         cfg_stream=fopen (cfg_file, "r");
1184         if (cfg_stream==0){
1185                 fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file,
1186                                 strerror(errno));
1187                 goto error;
1188         }
1189
1190         /* seed the prng */
1191         /* try to use /dev/random if possible */
1192         seed=0;
1193         if ((rfd=open("/dev/random", O_RDONLY))!=-1){
1194 try_again:
1195                 if (read(rfd, (void*)&seed, sizeof(seed))==-1){
1196                         if (errno==EINTR) goto try_again; /* interrupted by signal */
1197                         LOG(L_WARN, "WARNING: could not read from /dev/random (%d)\n",
1198                                                 errno);
1199                 }
1200                 DBG("read %u from /dev/random\n", seed);
1201                         close(rfd);
1202         }else{
1203                 LOG(L_WARN, "WARNING: could not open /dev/random (%d)\n", errno);
1204         }
1205         seed+=getpid()+time(0);
1206         DBG("seeding PRNG with %u\n", seed);
1207         srand(seed);
1208         DBG("test random number %u\n", rand());
1209         
1210         
1211
1212
1213         /*init shm mallocs (before parsing cfg !)
1214          *  this must be here to allow setting shm mem size from the command line
1215          *  and it must also be before init_timer and init_tcp
1216          *  => if shm_mem should be settable from the cfg file move everything
1217          *  after --andrei */
1218         if (init_shm_mallocs()==-1)
1219                 goto error;
1220         /*init timer, before parsing the cfg!*/
1221         if (init_timer()<0){
1222                 LOG(L_CRIT, "could not initialize timer, exiting...\n");
1223                 goto error;
1224         }
1225         
1226         /* register a diagnostic FIFO command  - moved to fifo server - bogdan
1227         if (register_core_fifo()<0) {
1228                 LOG(L_CRIT, "unable to register core FIFO commands\n");
1229                 goto error;
1230         }*/
1231
1232         /*register builtin  modules*/
1233         register_builtin_modules();
1234
1235         yyin=cfg_stream;
1236         if ((yyparse()!=0)||(cfg_errors)){
1237                 fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
1238                 goto error;
1239         }
1240         
1241         
1242         
1243         print_rl();
1244         
1245         /* fix parameters */
1246         if (port_no<=0) port_no=SIP_PORT;
1247 #ifdef USE_TLS
1248         if (tls_port_no<=0) tls_port_no=SIPS_PORT;
1249 #endif
1250         
1251         
1252         if (children_no<=0) children_no=CHILD_NO;
1253 #ifdef USE_TCP
1254         if (!tcp_disable){
1255                 if (tcp_children_no<=0) tcp_children_no=children_no;
1256         }
1257 #endif
1258         
1259         if (working_dir==0) working_dir="/";
1260         
1261         /* get uid/gid */
1262         if (user){
1263                 uid=strtol(user, &tmp, 10);
1264                 if ((tmp==0) ||(*tmp)){
1265                         /* maybe it's a string */
1266                         pw_entry=getpwnam(user);
1267                         if (pw_entry==0){
1268                                 fprintf(stderr, "bad user name/uid number: -u %s\n", user);
1269                                 goto error;
1270                         }
1271                         uid=pw_entry->pw_uid;
1272                         gid=pw_entry->pw_gid;
1273                 }
1274         }
1275         if (group){
1276                 gid=strtol(group, &tmp, 10);
1277                 if ((tmp==0) ||(*tmp)){
1278                         /* maybe it's a string */
1279                         gr_entry=getgrnam(group);
1280                         if (gr_entry==0){
1281                                 fprintf(stderr, "bad group name/gid number: -u %s\n", group);
1282                                 goto error;
1283                         }
1284                         gid=gr_entry->gr_gid;
1285                 }
1286         }
1287         
1288         if (fix_all_socket_lists()!=0){
1289                 fprintf(stderr,  "failed to initialize liste addresses\n");
1290                 goto error;
1291         }
1292         /* print all the listen addresses */
1293         printf("Listening on \n");
1294         print_all_socket_lists();
1295         printf("Aliases: \n");
1296         /*print_aliases();*/
1297         print_aliases();
1298         printf("\n");
1299         
1300         if (dont_fork){
1301                 fprintf(stderr, "WARNING: no fork mode %s\n", 
1302                                 (udp_listen)?(
1303                                 (udp_listen->next)?" and more than one listen address found"
1304                                 "(will use only the the first one)":""
1305                                 ):"and no udp listen address found" );
1306         }
1307         if (config_check){
1308                 fprintf(stderr, "config file ok, exiting...\n");
1309                 goto error;
1310         }
1311         
1312 #ifdef USE_TCP
1313         if (!tcp_disable){
1314                 /*init tcp*/
1315                 if (init_tcp()<0){
1316                         LOG(L_CRIT, "could not initialize tcp, exiting...\n");
1317                         goto error;
1318                 }
1319         }
1320 #ifdef USE_TLS
1321         if (!tls_disable){
1322                 /* init tls*/
1323                 if (init_tls()<0){
1324                         LOG(L_CRIT, "could not initialize tls, exiting...\n");
1325                         goto error;
1326                 }
1327         }
1328 #endif /* USE_TLS */
1329 #endif /* USE_TCP */
1330         /* init_daemon? */
1331         if (!dont_fork){
1332                 if ( daemonize(argv[0]) <0 ) goto error;
1333         }
1334         if (install_sigs() != 0){
1335                 fprintf(stderr, "ERROR: could not install the signal handlers\n");
1336                 goto error;
1337         }
1338         
1339         if (init_modules() != 0) {
1340                 fprintf(stderr, "ERROR: error while initializing modules\n");
1341                 goto error;
1342         }
1343         
1344         /*alloc pids*/
1345 #ifdef SHM_MEM
1346         pt=shm_malloc(sizeof(struct process_table)*process_count());
1347 #else
1348         pt=pkg_malloc(sizeof(struct process_table)*process_count());
1349 #endif
1350         if (pt==0){
1351                 fprintf(stderr, "ERROR: out  of memory\n");
1352                 goto error;
1353         }
1354         memset(pt, 0, sizeof(struct process_table)*process_count());
1355         /* fix routing lists */
1356         if ( (r=fix_rls())!=0){
1357                 fprintf(stderr, "ERROR: error %x while trying to fix configuration\n",
1358                                                 r);
1359                 goto error;
1360         };
1361
1362 #ifdef STATS
1363         if (init_stats(  dont_fork ? 1 : children_no  )==-1) goto error;
1364 #endif
1365         
1366         ret=main_loop();
1367         /*kill everything*/
1368         kill_all_children(SIGTERM);
1369         /*clean-up*/
1370         cleanup(0);
1371         return ret;
1372
1373 error:
1374         /*kill everything*/
1375         kill_all_children(SIGTERM);
1376         /*clean-up*/
1377         cleanup(0);
1378         return -1;
1379
1380 }
1381