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