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