SIP: Fix incoming re-invite
[lcr.git] / main.c
1 /*****************************************************************************\
2 **                                                                           **
3 ** Linux Call Router                                                         **
4 **                                                                           **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg                                              **
7 **                                                                           **
8 ** Main function                                                             **
9 **                                                                           **
10 \*****************************************************************************/ 
11
12 #include "main.h"
13 #ifdef PACKAGE_VERSION
14 #undef PACKAGE_VERSION
15 #endif
16 #include "config.h"
17
18 //MESSAGES
19
20 struct timeval now_tv;
21 struct timezone now_tz;
22 #define GET_NOW() \
23         { \
24                 gettimeofday(&now_tv, &now_tz); \
25                 now_d = ((double)(now_tv.tv_usec))/1000000 + now_tv.tv_sec; \
26         }
27
28 FILE *debug_fp = NULL;
29 int quit = 0;
30
31 #if 0
32 struct lcr_fdset lcr_fdset[FD_SETSIZE];
33 #endif
34
35 pthread_mutex_t mutexd; // debug output mutex
36 pthread_mutex_t mutext; // trace output mutex
37 pthread_mutex_t mutexe; // error output mutex
38 //pthread_mutex_t mutex_lcr; // lcr process mutex
39
40 int memuse = 0;
41 int mmemuse = 0;
42 int cmemuse = 0;
43 int ememuse = 0;
44 int pmemuse = 0;
45 int amemuse = 0;
46 int rmemuse = 0;
47 int classuse = 0;
48 int fduse = 0;
49 int fhuse = 0;
50
51 int debug_count = 0;
52 int last_debug = 0;
53 int debug_newline = 1;
54 int nooutput = 0;
55
56 void debug(const char *file, const char *function, int line, const char *prefix, char *buffer)
57 {
58         time_t now;
59         struct tm *now_tm;
60
61         /* if we have a new debug count, we add a mark */
62         if (last_debug != debug_count) {
63                 last_debug = debug_count;
64                 time(&now);
65                 now_tm = localtime(&now);
66                 if (!nooutput)
67                         printf("\033[34m--------------------- %04d.%02d.%02d %02d:%02d:%02d %06d\033[36m\n", now_tm->tm_year+1900, now_tm->tm_mon+1, now_tm->tm_mday, now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec, debug_count%1000000);
68                 if (debug_fp)
69                         fprintf(debug_fp, "--------------------- %04d.%02d.%02d %02d:%02d:%02d %06d\n", now_tm->tm_year+1900, now_tm->tm_mon+1, now_tm->tm_mday, now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec, debug_count%1000000);
70         }
71
72         if (!nooutput) {
73                 if (debug_newline)
74                         printf("\033[32m%06d %s\033[37m%s", debug_count%1000000, prefix?prefix:"", prefix?" ":"");
75                 if (function)
76                         printf("(in %s/%s() line %d): %s", file, function, line, buffer);
77                 else
78                         printf("%s", buffer);
79         }
80
81         if (debug_fp) {
82                 if (debug_newline) {
83                         if (function)
84                                 fprintf(debug_fp, "%s%s(in %s() line %d): %s", prefix?prefix:"", prefix?" ":"", function, line, buffer);
85                         else
86                                 fprintf(debug_fp, "%s%s: %s", prefix?prefix:"", prefix?" ":"", buffer);
87                         fflush(debug_fp);
88                 }
89         }
90
91         debug_newline = 0;
92         if (buffer[0])
93                 if (buffer[strlen(buffer)-1] == '\n')
94                         debug_newline = 1;
95 }
96
97
98 void _printdebug(const char *file, const char *function, int line, unsigned int mask, const char *fmt, ...)
99 {
100         char buffer[4096];
101         va_list args;
102
103         if (!(options.deb & mask))
104                 return;
105         pthread_mutex_lock(&mutexd);
106
107         va_start(args,fmt);
108         VUNPRINT(buffer,sizeof(buffer)-1,fmt,args);
109         buffer[sizeof(buffer)-1]=0;
110         va_end(args);
111
112         debug(file, function, line, "DEBUG", buffer);
113
114         pthread_mutex_unlock(&mutexd);
115 }
116
117 void _printerror(const char *file, const char *function, int line, const char *fmt, ...)
118 {
119         char buffer[4096];
120         va_list args;
121
122         pthread_mutex_lock(&mutexe);
123
124         va_start(args,fmt);
125         VUNPRINT(buffer,sizeof(buffer)-1,fmt,args);
126         buffer[sizeof(buffer)-1]=0;
127         va_end(args);
128
129         if (options.deb)
130                 debug(file, function, line, "ERROR", buffer);
131         else { /* only if we do not debug */
132                 if (function)
133                         fprintf(stderr, "ERROR (in %s() line %d) %s", function, line, buffer);
134                 else
135                         fprintf(stderr, "ERROR %s", buffer);
136         }
137
138         pthread_mutex_unlock(&mutexe);
139 }
140
141
142 void sighandler(int sigset)
143 {
144         struct sched_param schedp;
145
146         if (sigset == SIGHUP)
147                 return;
148         if (sigset == SIGPIPE)
149                 return;
150         fprintf(stderr, "LCR: Signal received: %d\n", sigset);
151         PDEBUG(DEBUG_LOG, "Signal received: %d\n", sigset);
152         /* reset signals */
153         signal(SIGINT,SIG_DFL);
154         signal(SIGHUP,SIG_DFL);
155         signal(SIGTERM,SIG_DFL);
156         signal(SIGPIPE,SIG_DFL);
157         if (!quit) {
158                 quit = sigset;
159                 /* set scheduler & priority */
160                 if (options.schedule > 1) {
161                         memset(&schedp, 0, sizeof(schedp));
162                         schedp.sched_priority = 0;
163                         sched_setscheduler(0, SCHED_OTHER, &schedp);
164                 }
165         }
166 }
167
168
169 /*
170  * the main
171  */
172 int main(int argc, char *argv[])
173 {
174 #if 0
175         double                  now_d, last_d;
176         int                     all_idle;
177 #endif
178         int                     ret = -1;
179         int                     lockfd = -1; /* file lock */
180         struct lcr_msg          *message;
181         int                     i;
182         struct sched_param      schedp;
183         int                     created_mutexd = 0,/* created_mutext = 0,*/ created_mutexe = 0,
184                                 created_lock = 0, created_signal = 0, created_message = 0;
185 #ifdef WITH_MISDN
186         int                     created_misdn = 0;
187 #endif
188         char                    tracetext[256], lock[128];
189         char                    options_error[256];
190
191 #if 0
192         /* init fdset */
193         memset(lcr_fdset, 0, sizeof(lcr_fdset));
194 #endif
195
196         /* lock LCR process */
197 //      pthread_mutex_lock(&mutex_lcr);
198
199         /* show version */
200         printf("\n** %s  Version %s\n\n", NAME, VERSION_STRING);
201
202         /* show options */
203         if (argc <= 1) {
204                 usage:
205                 printf("\n");
206                 printf("Usage: lcr (query | start | fork | rules | route)\n");
207                 printf("query     = Show available isdn ports.\n");
208                 printf("start     = Run lcr normally, abort with CTRL+C.\n");
209                 printf("fork      = Do daemon fork and run as background process.\n");
210                 printf("interface = Get help of available interface syntax.\n");
211                 printf("rules     = Get help of available routing rule syntax.\n");
212                 printf("rules [action] = Get individual help for given action.\n");
213 //              printf("route = Show current routing as it is parsed.\n");
214                 printf("\n");
215                 ret = 999;
216                 goto free;
217         }
218
219 #ifdef WITH_CRYPT
220         /* init crc */
221         crc_init();
222 #endif
223
224 #ifdef WITH_VOOTP
225         /* init VoOTP */
226         vootp_init(stderr);
227         vootp_loglevel(VOOTP_LOGL_INFO);
228 #endif
229
230         /* the mutex init */
231         if (pthread_mutex_init(&mutexd, NULL)) {
232                 fprintf(stderr, "cannot create 'PDEBUG' mutex\n");
233                 goto free;
234         }
235         created_mutexd = 1;
236 //      if (pthread_mutex_init(&mutext, NULL)) {
237 //              fprintf(stderr, "cannot create 'trace' mutex\n");
238 //              goto free;
239 //      }
240 //      created_mutext = 1;
241         if (pthread_mutex_init(&mutexe, NULL)) {
242                 fprintf(stderr, "cannot create 'PERROR' mutex\n");
243                 goto free;
244         }
245         created_mutexe = 1;
246
247         /* show interface */
248         if (!(strcasecmp(argv[1],"interface"))) {
249                 doc_interface();
250                 ret = 0;
251                 goto free;
252         }
253
254         /* show rules */
255         if (!(strcasecmp(argv[1],"rules"))) {
256                 if (argc <= 2)
257                         doc_rules(NULL);
258                 else
259                         doc_rules(argv[2]);
260                 ret = 0;
261                 goto free;
262         }
263
264         /* query available isdn ports */
265         if (!(strcasecmp(argv[1],"query"))) {
266                 int __attribute__((__unused__)) rc;
267                 fprintf(stderr, "-> Using 'misdn_info'\n");
268                 rc = system("misdn_info");
269                 ret = 0;
270                 goto free;
271         }
272
273         /* read options */
274         if (read_options(options_error) == 0) {
275                 PERROR("%s", options_error);
276                 goto free;
277         }
278
279 #ifdef WITH_MISDN
280         /* init mISDN */
281         if (mISDN_initialize() < 0)
282                 goto free;
283         created_misdn = 1;
284 #endif
285
286         /* read ruleset(s) */
287         if (!(ruleset_first = ruleset_parse()))
288                 goto free;
289
290         /* set pointer to main ruleset */
291         ruleset_main = getrulesetbyname("main");
292         if (!ruleset_main) {
293                 fprintf(stderr, "\n***\n -> Missing 'main' ruleset, causing ALL calls to be disconnected.\n***\n\n");
294                 PDEBUG(DEBUG_LOG, "Missing 'main' ruleset, causing ALL calls to be disconnected.\n");
295                 sleep(2);
296         }
297
298 #if 0
299         /* query available isdn ports */
300         if (!(strcasecmp(argv[1],"route"))) {
301                 ruleset_debug(ruleset_first);
302                 ret = 0;
303                 goto free;
304         }
305 #endif
306
307         /* do fork in special cases */
308         if (!(strcasecmp(argv[1],"fork"))) {
309                 pid_t pid;
310                 FILE *pidfile;
311
312                 /* do daemon fork */
313                 pid = fork();
314
315                 if (pid < 0) {
316                         fprintf(stderr, "Cannot fork!\n");
317                         goto free;
318                 }
319                 if (pid != 0) {
320                         exit(0);
321                 }
322                 usleep(200000);
323                 printf("\n");
324                 
325                 /* do second fork */
326                 pid = fork();
327
328                 if (pid < 0) {
329                         fprintf(stderr, "Cannot fork!\n");
330                         goto free;
331                 }
332                 if (pid != 0) {
333                         printf("LCR: Starting daemon.\n");
334                         exit(0);
335                 }
336                 nooutput = 1;
337
338                 /* write pid file */
339                 SPRINT(lock, "%s/lcr.pid", options.lock);
340                 pidfile = fopen(lock,"w");
341                 if (pidfile) {
342                         fprintf(pidfile, "%d\n", getpid());
343                         fclose(pidfile);
344                 } else
345                         fprintf(stderr, "Failed to create PID file: %s\n", lock);
346         } else
347         /* if not start */
348         if (!!strcasecmp(argv[1],"start")) {
349                 goto usage;
350         }
351
352         /* create lock and lock! */
353         SPRINT(lock, "%s/lcr.lock", options.lock);
354         if ((lockfd = open(lock, O_CREAT | O_WRONLY, S_IWUSR)) < 0) {
355                 fprintf(stderr, "Cannot create lock file: %s\n", lock);
356                 fprintf(stderr, "Check options.conf to change to path with permissions for you.\n");
357                 goto free;
358         }
359         if (flock(lockfd, LOCK_EX|LOCK_NB) < 0) {
360                 if (errno == EWOULDBLOCK)
361                         fprintf(stderr, "LCR: Another LCR process is running. Please kill the other one.\n");
362                 else    fprintf(stderr, "Locking process failed: errno=%d\n", errno);
363                 goto free;
364         }
365         created_lock = 1;
366
367         /* initialize admin socket */
368         if (admin_init()) {
369                 fprintf(stderr, "Unable to initialize admin socket.\n");
370                 goto free;
371         }
372
373         /* generate alaw / ulaw tables */
374         generate_tables(options.law);
375
376 #ifdef WITH_SIP
377         /* init SIP globals */
378         sip_init();
379 #endif
380
381 #ifdef WITH_SS5
382         /* init ss5 sine tables */
383         ss5_sine_generate();
384         ss5_test_decode();
385 #endif
386
387         /* load tones (if requested) */
388         if (fetch_tones() == 0) {
389                 fprintf(stderr, "Unable to fetch tones into memory.\n");
390                 goto free;
391         }
392
393 #if defined WITH_GSM_BS || defined WITH_GSM_MS
394         /* init gsm */
395         if (gsm_init()) {
396                 fprintf(stderr, "GSM initialization failed.\n");
397                 goto free;
398         }
399 #endif
400 #ifdef WITH_GSM_BS
401         if (gsm_bs_init()) {
402                 fprintf(stderr, "GSM BS initialization failed.\n");
403                 goto free;
404         }
405 #endif
406 #ifdef WITH_GSM_MS
407         if (gsm_ms_init()) {
408                 fprintf(stderr, "GSM MS initialization failed.\n");
409                 goto free;
410         }
411 #endif
412
413         /* read interfaces and open ports */
414         if (!read_interfaces()) {
415                 PERROR_RUNTIME("No interfaces specified or failed to parse interface.conf.\n");
416                 fprintf(stderr, "No interfaces specified or failed to parse interface.conf.\n");
417                 goto free;
418         }
419         relink_interfaces();
420         interface_first = interface_newlist;
421         interface_newlist = NULL;
422         
423         /* locking memory paging */
424         i = 0;
425         while(i < 10) {
426                 if (mlockall(MCL_CURRENT | MCL_FUTURE) >= 0)
427                         break;
428                 usleep(200000);
429                 i++;
430         }
431         if (i == 10) {
432                 switch(errno) {
433                         case ENOMEM:
434                         fprintf(stderr, "Warning: Not enough memory to lock paging.\n");
435                         break;
436                         case EPERM:
437                         fprintf(stderr, "Warning: No permission to lock paging.\n");
438                         break;
439                         case EFAULT:
440                         fprintf(stderr, "Warning: 'Bad address' while locking paging.\n");
441                         break;
442                         default:
443                         fprintf(stderr, "Warning: Unknown error %d while locking paging.\n", errno);
444                 }
445         }
446
447         /* set real time scheduler & priority */
448         if (options.schedule > 1) {
449                 memset(&schedp, 0, sizeof(schedp));
450                 schedp.sched_priority = options.schedule;
451                 ret = sched_setscheduler(0, SCHED_RR, &schedp);
452                 if (ret < 0) {
453                         PERROR("Scheduling failed with given priority %d (errno = %d).\nCheck options.conf 'schedule', exitting...\n", options.schedule, errno);
454                         goto free;
455                 }
456         }
457
458         /* signal handlers */   
459         signal(SIGINT,sighandler);
460         signal(SIGHUP,sighandler);
461         signal(SIGTERM,sighandler);
462         signal(SIGPIPE,sighandler);
463         created_signal = 1;
464
465         /* init message */
466         init_message();
467         created_message = 1;
468
469         /*** main loop ***/
470         SPRINT(tracetext, "%s %s started, waiting for calls...", NAME, VERSION_STRING);
471         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
472         printf("%s\n", tracetext);
473         end_trace();
474         quit = 0;
475 #if 0
476         GET_NOW();
477 #endif
478         while(!quit) {
479 #if 0
480                 last_d = now_d;
481                 GET_NOW();
482                 if (now_d-last_d > 1.0) {
483                         PERROR("LCR was stalling %d.%d seconds\n", ((int)((now_d-last_d)*10.0))/10, (int)((now_d-last_d)*10.0));
484                 }
485                 /* all loops must be counted from the beginning since nodes might get freed during handler */
486                 all_idle = 1;
487
488                 /* must be processed after all queues, so they are empty */
489                 if (select_main(1, NULL, NULL, NULL))
490                         all_idle = 0;
491                 if (all_idle) {
492                         usleep(10000);
493                 }
494 #else
495 #ifdef WITH_SIP
496                 if (options.polling || any_sip_interface) {
497 #else
498                 if (options.polling) {
499 #endif
500                         if (!select_main(1, NULL, NULL, NULL)) {
501 #ifdef WITH_SIP
502                                 /* FIXME: check if work was done */
503                                 sip_handle();
504 #endif
505                                 usleep(10000);
506                         }
507                 } else
508                         select_main(0, NULL, NULL, NULL);
509 #endif
510         }
511         SPRINT(tracetext, "%s terminated", NAME);
512         printf("%s\n", tracetext);
513         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
514         if (quit > 0)
515                 add_trace((char *)"signal", NULL, "%d", quit);
516         if (quit < 0)
517                 add_trace((char *)"errno", NULL, "%d", quit);
518         end_trace();
519         ret=0;
520
521         /* free all */
522 free:
523
524         /* set scheduler & priority
525          */
526         if (options.schedule > 1) {
527                 memset(&schedp, 0, sizeof(schedp));
528                 schedp.sched_priority = options.schedule;
529                 sched_setscheduler(0, SCHED_OTHER, &schedp);
530         }
531         /* reset signals */
532         if (created_signal) {
533                 signal(SIGINT,SIG_DFL);
534                 signal(SIGHUP,SIG_DFL);
535                 signal(SIGTERM,SIG_DFL);
536                 signal(SIGPIPE,SIG_DFL);
537         }
538
539         /* destroy objects */
540         while(port_first) {
541                 debug_count++;
542                 delete port_first;
543         }
544         while(epoint_first) {
545                 debug_count++;
546                 delete epoint_first;
547         }
548         epoint_first = NULL;
549         debug_count++;
550         join_free();
551
552 #ifdef WITH_MISDN
553         /* close isdn ports */
554         mISDNport_close_all();
555 #endif
556
557         /* free interfaces */
558         if (interface_first)
559                 free_interfaces(interface_first);
560         interface_first = NULL;
561
562         /* flush messages */
563         debug_count++;
564         i = 0;
565         while ((message = message_get())) {
566                 i++;
567                 message_free(message);
568         }
569         if (i) {
570                 PDEBUG(DEBUG_MSG, "freed %d pending messages\n", i);
571         }
572
573         /* clean messages */
574         if (created_message)
575                 cleanup_message();
576
577         /* free tones */
578         if (toneset_first)
579                 free_tones();
580
581         /* free admin socket */
582         admin_cleanup();
583
584         /* close lock */
585         if (created_lock)
586                 flock(lockfd, LOCK_UN);
587         if (lockfd >= 0) {
588                 if (created_lock) {
589                         chmod(lock, 0700);
590                         unlink(lock);
591                 }
592                 close(lockfd);
593         }
594
595         /* free rulesets */
596         if (ruleset_first)
597                 ruleset_free(ruleset_first);
598         ruleset_first = NULL;
599
600         /* free mutex */
601         if (created_mutexe)
602                 if (pthread_mutex_destroy(&mutexe))
603                         fprintf(stderr, "cannot destroy 'PERROR' mutex\n");
604 //      if (created_mutext)
605 //              if (pthread_mutex_destroy(&mutext))
606 //                      fprintf(stderr, "cannot destroy 'trace' mutex\n");
607         if (created_mutexd)
608                 if (pthread_mutex_destroy(&mutexd))
609                         fprintf(stderr, "cannot destroy 'PDEBUG' mutex\n");
610
611 #ifdef WITH_MISDN
612         /* deinitialize mISDN */
613         if (created_misdn)
614                 mISDN_deinitialize();
615 #endif
616
617         /* free gsm */
618 #ifdef WITH_GSM_BS
619         gsm_bs_exit(0);
620 #endif
621 #ifdef WITH_GSM_MS
622         gsm_ms_exit(0);
623 #endif
624 #if defined WITH_GSM_BS || defined WITH_GSM_MS
625         gsm_exit(0);
626 #endif
627
628 #ifdef WITH_SIP
629         /* cleanup SIP globals */
630         sip_exit();
631 #endif
632
633         /* display memory leak */
634 #define MEMCHECK(a, b) \
635         if (b) { \
636                 SPRINT(tracetext, a, NAME); \
637                 start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext); \
638                 if (ret) add_trace("blocks", NULL, "%d", b); \
639                 end_trace(); \
640                 printf("\n******************************\n\007"); \
641                 printf("\nERROR: %d %s\n", b, a); \
642                 printf("\n******************************\n"); \
643                 ret = -1; \
644         }
645         MEMCHECK("",memuse)
646         MEMCHECK("memory block(s) left (port.cpp ...)",pmemuse)
647         MEMCHECK("memory block(s) left (epoint*.cpp ...)",ememuse)
648         MEMCHECK("memory block(s) left (join*.cpp)",cmemuse)
649         MEMCHECK("memory block(s) left (message.c)",mmemuse)
650         MEMCHECK("memory block(s) left (route.c)",rmemuse)
651         MEMCHECK("memory block(s) left (args)",amemuse)
652         MEMCHECK("class(es) left",classuse)
653         MEMCHECK("file descriptor(s) left",fduse)
654         MEMCHECK("file handler(s) left",fhuse)
655
656         /* unlock LCR process */
657 //      pthread_mutex_unlock(&mutex_lcr);
658
659         /* take me out */
660         return(ret);
661 }
662
663
664