GSM: Add audio frame type for uncompressed 16 bit frame
[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 #if 0
401 init is done when interface is up
402 #ifdef WITH_GSM_BS
403         if (gsm_bs_init()) {
404                 fprintf(stderr, "GSM BS initialization failed.\n");
405                 goto free;
406         }
407 #endif
408 #endif
409 #ifdef WITH_GSM_MS
410         if (gsm_ms_init()) {
411                 fprintf(stderr, "GSM MS initialization failed.\n");
412                 goto free;
413         }
414 #endif
415
416         /* read interfaces and open ports */
417         if (!read_interfaces()) {
418                 PERROR_RUNTIME("No interfaces specified or failed to parse interface.conf.\n");
419                 fprintf(stderr, "No interfaces specified or failed to parse interface.conf.\n");
420                 goto free;
421         }
422         relink_interfaces();
423         interface_first = interface_newlist;
424         interface_newlist = NULL;
425         
426         /* locking memory paging */
427         i = 0;
428         while(i < 10) {
429                 if (mlockall(MCL_CURRENT | MCL_FUTURE) >= 0)
430                         break;
431                 usleep(200000);
432                 i++;
433         }
434         if (i == 10) {
435                 switch(errno) {
436                         case ENOMEM:
437                         fprintf(stderr, "Warning: Not enough memory to lock paging.\n");
438                         break;
439                         case EPERM:
440                         fprintf(stderr, "Warning: No permission to lock paging.\n");
441                         break;
442                         case EFAULT:
443                         fprintf(stderr, "Warning: 'Bad address' while locking paging.\n");
444                         break;
445                         default:
446                         fprintf(stderr, "Warning: Unknown error %d while locking paging.\n", errno);
447                 }
448         }
449
450         /* set real time scheduler & priority */
451         if (options.schedule > 1) {
452                 memset(&schedp, 0, sizeof(schedp));
453                 schedp.sched_priority = options.schedule;
454                 ret = sched_setscheduler(0, SCHED_RR, &schedp);
455                 if (ret < 0) {
456                         PERROR("Scheduling failed with given priority %d (errno = %d).\nCheck options.conf 'schedule', exitting...\n", options.schedule, errno);
457                         goto free;
458                 }
459         }
460
461         /* signal handlers */   
462         signal(SIGINT,sighandler);
463         signal(SIGHUP,sighandler);
464         signal(SIGTERM,sighandler);
465         signal(SIGPIPE,sighandler);
466         created_signal = 1;
467
468         /* init message */
469         init_message();
470         created_message = 1;
471
472         /*** main loop ***/
473         SPRINT(tracetext, "%s %s started, waiting for calls...", NAME, VERSION_STRING);
474         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
475         printf("%s\n", tracetext);
476         end_trace();
477         quit = 0;
478 #if 0
479         GET_NOW();
480 #endif
481         while(!quit) {
482 #if 0
483                 last_d = now_d;
484                 GET_NOW();
485                 if (now_d-last_d > 1.0) {
486                         PERROR("LCR was stalling %d.%d seconds\n", ((int)((now_d-last_d)*10.0))/10, (int)((now_d-last_d)*10.0));
487                 }
488                 /* all loops must be counted from the beginning since nodes might get freed during handler */
489                 all_idle = 1;
490
491                 /* must be processed after all queues, so they are empty */
492                 if (select_main(1, NULL, NULL, NULL))
493                         all_idle = 0;
494                 if (all_idle) {
495                         usleep(10000);
496                 }
497 #else
498 #ifdef WITH_SIP
499                 if (options.polling || any_sip_interface) {
500 #else
501                 if (options.polling) {
502 #endif
503                         if (!select_main(1, NULL, NULL, NULL)) {
504 #ifdef WITH_SIP
505                                 /* FIXME: check if work was done */
506                                 sip_handle();
507 #endif
508                                 usleep(10000);
509                         }
510                 } else
511                         select_main(0, NULL, NULL, NULL);
512 #endif
513         }
514         SPRINT(tracetext, "%s terminated", NAME);
515         printf("%s\n", tracetext);
516         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
517         if (quit > 0)
518                 add_trace((char *)"signal", NULL, "%d", quit);
519         if (quit < 0)
520                 add_trace((char *)"errno", NULL, "%d", quit);
521         end_trace();
522         ret=0;
523
524         /* free all */
525 free:
526
527         /* set scheduler & priority
528          */
529         if (options.schedule > 1) {
530                 memset(&schedp, 0, sizeof(schedp));
531                 schedp.sched_priority = options.schedule;
532                 sched_setscheduler(0, SCHED_OTHER, &schedp);
533         }
534         /* reset signals */
535         if (created_signal) {
536                 signal(SIGINT,SIG_DFL);
537                 signal(SIGHUP,SIG_DFL);
538                 signal(SIGTERM,SIG_DFL);
539                 signal(SIGPIPE,SIG_DFL);
540         }
541
542         /* destroy objects */
543         while(port_first) {
544                 debug_count++;
545                 delete port_first;
546         }
547         while(epoint_first) {
548                 debug_count++;
549                 delete epoint_first;
550         }
551         epoint_first = NULL;
552         debug_count++;
553         join_free();
554
555         /* free interfaces */
556         if (interface_first)
557                 free_interfaces(interface_first);
558         interface_first = NULL;
559
560 #ifdef WITH_MISDN
561         /* close isdn ports */
562         mISDNport_close_all();
563 #endif
564
565         /* flush messages */
566         debug_count++;
567         i = 0;
568         while ((message = message_get())) {
569                 i++;
570                 message_free(message);
571         }
572         if (i) {
573                 PDEBUG(DEBUG_MSG, "freed %d pending messages\n", i);
574         }
575
576         /* clean messages */
577         if (created_message)
578                 cleanup_message();
579
580         /* free tones */
581         if (toneset_first)
582                 free_tones();
583
584         /* free admin socket */
585         admin_cleanup();
586
587         /* close lock */
588         if (created_lock)
589                 flock(lockfd, LOCK_UN);
590         if (lockfd >= 0) {
591                 if (created_lock) {
592                         chmod(lock, 0700);
593                         unlink(lock);
594                 }
595                 close(lockfd);
596         }
597
598         /* free rulesets */
599         if (ruleset_first)
600                 ruleset_free(ruleset_first);
601         ruleset_first = NULL;
602
603         /* free mutex */
604         if (created_mutexe)
605                 if (pthread_mutex_destroy(&mutexe))
606                         fprintf(stderr, "cannot destroy 'PERROR' mutex\n");
607 //      if (created_mutext)
608 //              if (pthread_mutex_destroy(&mutext))
609 //                      fprintf(stderr, "cannot destroy 'trace' mutex\n");
610         if (created_mutexd)
611                 if (pthread_mutex_destroy(&mutexd))
612                         fprintf(stderr, "cannot destroy 'PDEBUG' mutex\n");
613
614 #ifdef WITH_MISDN
615         /* deinitialize mISDN */
616         if (created_misdn)
617                 mISDN_deinitialize();
618 #endif
619
620         /* free gsm */
621 #if 0
622 exit is done when interface is down
623 #ifdef WITH_GSM_BS
624         gsm_bs_exit(0);
625 #endif
626 #endif
627 #ifdef WITH_GSM_MS
628         gsm_ms_exit(0);
629 #endif
630 #if defined WITH_GSM_BS || defined WITH_GSM_MS
631         gsm_exit(0);
632 #endif
633
634 #ifdef WITH_SIP
635         /* cleanup SIP globals */
636         sip_exit();
637 #endif
638
639         /* display memory leak */
640 #define MEMCHECK(a, b) \
641         if (b) { \
642                 SPRINT(tracetext, a, NAME); \
643                 start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext); \
644                 if (ret) add_trace("blocks", NULL, "%d", b); \
645                 end_trace(); \
646                 printf("\n******************************\n\007"); \
647                 printf("\nERROR: %d %s\n", b, a); \
648                 printf("\n******************************\n"); \
649                 ret = -1; \
650         }
651         MEMCHECK("",memuse)
652         MEMCHECK("memory block(s) left (port.cpp ...)",pmemuse)
653         MEMCHECK("memory block(s) left (epoint*.cpp ...)",ememuse)
654         MEMCHECK("memory block(s) left (join*.cpp)",cmemuse)
655         MEMCHECK("memory block(s) left (message.c)",mmemuse)
656         MEMCHECK("memory block(s) left (route.c)",rmemuse)
657         MEMCHECK("memory block(s) left (args)",amemuse)
658         MEMCHECK("class(es) left",classuse)
659         MEMCHECK("file descriptor(s) left",fduse)
660         MEMCHECK("file handler(s) left",fhuse)
661
662         /* unlock LCR process */
663 //      pthread_mutex_unlock(&mutex_lcr);
664
665         /* take me out */
666         return(ret);
667 }
668
669
670