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