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