Fix: Allow recording of audio for SIP/remote/GSM interfaces too
[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         /* the mutex init */
225         if (pthread_mutex_init(&mutexd, NULL)) {
226                 fprintf(stderr, "cannot create 'PDEBUG' mutex\n");
227                 goto free;
228         }
229         created_mutexd = 1;
230 //      if (pthread_mutex_init(&mutext, NULL)) {
231 //              fprintf(stderr, "cannot create 'trace' mutex\n");
232 //              goto free;
233 //      }
234 //      created_mutext = 1;
235         if (pthread_mutex_init(&mutexe, NULL)) {
236                 fprintf(stderr, "cannot create 'PERROR' mutex\n");
237                 goto free;
238         }
239         created_mutexe = 1;
240
241         /* show interface */
242         if (!(strcasecmp(argv[1],"interface"))) {
243                 doc_interface();
244                 ret = 0;
245                 goto free;
246         }
247
248         /* show rules */
249         if (!(strcasecmp(argv[1],"rules"))) {
250                 if (argc <= 2)
251                         doc_rules(NULL);
252                 else
253                         doc_rules(argv[2]);
254                 ret = 0;
255                 goto free;
256         }
257
258         /* query available isdn ports */
259         if (!(strcasecmp(argv[1],"query"))) {
260                 int rc;
261                 fprintf(stderr, "-> Using 'misdn_info'\n");
262                 rc = system("misdn_info");
263                 ret = 0;
264                 goto free;
265         }
266
267         /* read options */
268         if (read_options(options_error) == 0) {
269                 PERROR("%s", options_error);
270                 goto free;
271         }
272
273 #ifdef WITH_MISDN
274         /* init mISDN */
275         if (mISDN_initialize() < 0)
276                 goto free;
277         created_misdn = 1;
278 #endif
279
280         /* read ruleset(s) */
281         if (!(ruleset_first = ruleset_parse()))
282                 goto free;
283
284         /* set pointer to main ruleset */
285         ruleset_main = getrulesetbyname("main");
286         if (!ruleset_main) {
287                 fprintf(stderr, "\n***\n -> Missing 'main' ruleset, causing ALL calls to be disconnected.\n***\n\n");
288                 PDEBUG(DEBUG_LOG, "Missing 'main' ruleset, causing ALL calls to be disconnected.\n");
289                 sleep(2);
290         }
291
292 #if 0
293         /* query available isdn ports */
294         if (!(strcasecmp(argv[1],"route"))) {
295                 ruleset_debug(ruleset_first);
296                 ret = 0;
297                 goto free;
298         }
299 #endif
300
301         /* do fork in special cases */
302         if (!(strcasecmp(argv[1],"fork"))) {
303                 pid_t pid;
304                 FILE *pidfile;
305
306                 /* do daemon fork */
307                 pid = fork();
308
309                 if (pid < 0) {
310                         fprintf(stderr, "Cannot fork!\n");
311                         goto free;
312                 }
313                 if (pid != 0) {
314                         exit(0);
315                 }
316                 usleep(200000);
317                 printf("\n");
318                 
319                 /* do second fork */
320                 pid = fork();
321
322                 if (pid < 0) {
323                         fprintf(stderr, "Cannot fork!\n");
324                         goto free;
325                 }
326                 if (pid != 0) {
327                         printf("LCR: Starting daemon.\n");
328                         exit(0);
329                 }
330                 nooutput = 1;
331
332                 /* write pid file */
333                 SPRINT(lock, "%s/lcr.pid", options.lock);
334                 pidfile = fopen(lock,"w");
335                 if (pidfile) {
336                         fprintf(pidfile, "%d\n", getpid());
337                         fclose(pidfile);
338                 } else
339                         fprintf(stderr, "Failed to create PID file: %s\n", lock);
340         } else
341         /* if not start */
342         if (!!strcasecmp(argv[1],"start")) {
343                 goto usage;
344         }
345
346         /* create lock and lock! */
347         SPRINT(lock, "%s/lcr.lock", options.lock);
348         if ((lockfd = open(lock, O_CREAT | O_WRONLY, S_IWUSR)) < 0) {
349                 fprintf(stderr, "Cannot create lock file: %s\n", lock);
350                 fprintf(stderr, "Check options.conf to change to path with permissions for you.\n");
351                 goto free;
352         }
353         if (flock(lockfd, LOCK_EX|LOCK_NB) < 0) {
354                 if (errno == EWOULDBLOCK)
355                         fprintf(stderr, "LCR: Another LCR process is running. Please kill the other one.\n");
356                 else    fprintf(stderr, "Locking process failed: errno=%d\n", errno);
357                 goto free;
358         }
359         created_lock = 1;
360
361         /* initialize admin socket */
362         if (admin_init()) {
363                 fprintf(stderr, "Unable to initialize admin socket.\n");
364                 goto free;
365         }
366
367         /* generate alaw / ulaw tables */
368         generate_tables(options.law);
369
370 #ifdef WITH_SIP
371         /* init SIP globals */
372         sip_init();
373 #endif
374
375 #ifdef WITH_SS5
376         /* init ss5 sine tables */
377         ss5_sine_generate();
378         ss5_test_decode();
379 #endif
380
381         /* load tones (if requested) */
382         if (fetch_tones() == 0) {
383                 fprintf(stderr, "Unable to fetch tones into memory.\n");
384                 goto free;
385         }
386
387 #if defined WITH_GSM_BS || defined WITH_GSM_MS
388         /* init gsm */
389         if (gsm_init()) {
390                 fprintf(stderr, "GSM initialization failed.\n");
391                 goto free;
392         }
393 #endif
394 #if 0
395 init is done when interface is up
396 #ifdef WITH_GSM_BS
397         if (gsm_bs_init()) {
398                 fprintf(stderr, "GSM BS initialization failed.\n");
399                 goto free;
400         }
401 #endif
402 #endif
403 #ifdef WITH_GSM_MS
404         if (gsm_ms_init()) {
405                 fprintf(stderr, "GSM MS initialization failed.\n");
406                 goto free;
407         }
408 #endif
409
410         /* read interfaces and open ports */
411         if (!read_interfaces()) {
412                 PERROR_RUNTIME("No interfaces specified or failed to parse interface.conf.\n");
413                 fprintf(stderr, "No interfaces specified or failed to parse interface.conf.\n");
414                 goto free;
415         }
416         relink_interfaces();
417         interface_first = interface_newlist;
418         interface_newlist = NULL;
419         
420         /* locking memory paging */
421         i = 0;
422         while(i < 10) {
423                 if (mlockall(MCL_CURRENT | MCL_FUTURE) >= 0)
424                         break;
425                 usleep(200000);
426                 i++;
427         }
428         if (i == 10) {
429                 switch(errno) {
430                         case ENOMEM:
431                         fprintf(stderr, "Warning: Not enough memory to lock paging.\n");
432                         break;
433                         case EPERM:
434                         fprintf(stderr, "Warning: No permission to lock paging.\n");
435                         break;
436                         case EFAULT:
437                         fprintf(stderr, "Warning: 'Bad address' while locking paging.\n");
438                         break;
439                         default:
440                         fprintf(stderr, "Warning: Unknown error %d while locking paging.\n", errno);
441                 }
442         }
443
444         /* set real time scheduler & priority */
445         if (options.schedule > 1) {
446                 memset(&schedp, 0, sizeof(schedp));
447                 schedp.sched_priority = options.schedule;
448                 ret = sched_setscheduler(0, SCHED_RR, &schedp);
449                 if (ret < 0) {
450                         PERROR("Scheduling failed with given priority %d (errno = %d).\nCheck options.conf 'schedule', exitting...\n", options.schedule, errno);
451                         goto free;
452                 }
453         }
454
455         /* signal handlers */   
456         signal(SIGINT,sighandler);
457         signal(SIGHUP,sighandler);
458         signal(SIGTERM,sighandler);
459         signal(SIGPIPE,sighandler);
460         created_signal = 1;
461
462         /* init message */
463         init_message();
464         created_message = 1;
465
466         /*** main loop ***/
467         SPRINT(tracetext, "%s %s started, waiting for calls...", NAME, VERSION_STRING);
468         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
469         printf("%s\n", tracetext);
470         end_trace();
471         quit = 0;
472 #if 0
473         GET_NOW();
474 #endif
475         while(!quit) {
476 #if 0
477                 last_d = now_d;
478                 GET_NOW();
479                 if (now_d-last_d > 1.0) {
480                         PERROR("LCR was stalling %d.%d seconds\n", ((int)((now_d-last_d)*10.0))/10, (int)((now_d-last_d)*10.0));
481                 }
482                 /* all loops must be counted from the beginning since nodes might get freed during handler */
483                 all_idle = 1;
484
485                 /* must be processed after all queues, so they are empty */
486                 if (select_main(1, NULL, NULL, NULL))
487                         all_idle = 0;
488                 if (all_idle) {
489                         usleep(10000);
490                 }
491 #else
492 #ifdef WITH_SIP
493                 if (options.polling || any_sip_interface) {
494 #else
495                 if (options.polling) {
496 #endif
497                         if (!select_main(1, NULL, NULL, NULL)) {
498 #ifdef WITH_SIP
499                                 /* FIXME: check if work was done */
500                                 sip_handle();
501 #endif
502                                 usleep(10000);
503                         }
504                 } else
505                         select_main(0, NULL, NULL, NULL);
506 #endif
507         }
508         SPRINT(tracetext, "%s terminated", NAME);
509         printf("%s\n", tracetext);
510         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
511         if (quit > 0)
512                 add_trace((char *)"signal", NULL, "%d", quit);
513         if (quit < 0)
514                 add_trace((char *)"errno", NULL, "%d", quit);
515         end_trace();
516         ret=0;
517
518         /* free all */
519 free:
520
521         /* set scheduler & priority
522          */
523         if (options.schedule > 1) {
524                 memset(&schedp, 0, sizeof(schedp));
525                 schedp.sched_priority = options.schedule;
526                 sched_setscheduler(0, SCHED_OTHER, &schedp);
527         }
528         /* reset signals */
529         if (created_signal) {
530                 signal(SIGINT,SIG_DFL);
531                 signal(SIGHUP,SIG_DFL);
532                 signal(SIGTERM,SIG_DFL);
533                 signal(SIGPIPE,SIG_DFL);
534         }
535
536         /* destroy objects */
537         while(port_first) {
538                 debug_count++;
539                 delete port_first;
540         }
541         while(epoint_first) {
542                 debug_count++;
543                 delete epoint_first;
544         }
545         epoint_first = NULL;
546         debug_count++;
547         join_free();
548
549         /* free interfaces */
550         if (interface_first)
551                 free_interfaces(interface_first);
552         interface_first = NULL;
553
554 #ifdef WITH_MISDN
555         /* close isdn ports */
556         mISDNport_close_all();
557 #endif
558
559         /* flush messages */
560         debug_count++;
561         i = 0;
562         while ((message = message_get())) {
563                 i++;
564                 message_free(message);
565         }
566         if (i) {
567                 PDEBUG(DEBUG_MSG, "freed %d pending messages\n", i);
568         }
569
570         /* clean messages */
571         if (created_message)
572                 cleanup_message();
573
574         /* free tones */
575         if (toneset_first)
576                 free_tones();
577
578         /* free admin socket */
579         admin_cleanup();
580
581         /* close lock */
582         if (created_lock)
583                 flock(lockfd, LOCK_UN);
584         if (lockfd >= 0) {
585                 if (created_lock) {
586                         chmod(lock, 0700);
587                         unlink(lock);
588                 }
589                 close(lockfd);
590         }
591
592         /* free rulesets */
593         if (ruleset_first)
594                 ruleset_free(ruleset_first);
595         ruleset_first = NULL;
596
597         /* free mutex */
598         if (created_mutexe)
599                 if (pthread_mutex_destroy(&mutexe))
600                         fprintf(stderr, "cannot destroy 'PERROR' mutex\n");
601 //      if (created_mutext)
602 //              if (pthread_mutex_destroy(&mutext))
603 //                      fprintf(stderr, "cannot destroy 'trace' mutex\n");
604         if (created_mutexd)
605                 if (pthread_mutex_destroy(&mutexd))
606                         fprintf(stderr, "cannot destroy 'PDEBUG' mutex\n");
607
608 #ifdef WITH_MISDN
609         /* deinitialize mISDN */
610         if (created_misdn)
611                 mISDN_deinitialize();
612 #endif
613
614         /* free gsm */
615 #if 0
616 exit is done when interface is down
617 #ifdef WITH_GSM_BS
618         gsm_bs_exit(0);
619 #endif
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