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