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