Use variables set by configure script instead of installing files to a
[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         int                     polling = 0;
191
192 #if 0
193         /* init fdset */
194         memset(lcr_fdset, 0, sizeof(lcr_fdset));
195 #endif
196
197         /* lock LCR process */
198 //      pthread_mutex_lock(&mutex_lcr);
199
200         /* show version */
201         printf("\n** %s  Version %s\n\n", NAME, VERSION_STRING);
202
203         /* show options */
204         if (argc <= 1) {
205                 usage:
206                 printf("\n");
207                 printf("Usage: lcr (query | start | fork | rules | route)\n");
208                 printf("query     = Show available isdn ports.\n");
209                 printf("start     = Run lcr normally, abort with CTRL+C.\n");
210                 printf("fork      = Do daemon fork and run as background process.\n");
211                 printf("interface = Get help of available interface syntax.\n");
212                 printf("rules     = Get help of available routing rule syntax.\n");
213                 printf("rules [action] = Get individual help for given action.\n");
214 //              printf("route = Show current routing as it is parsed.\n");
215                 printf("\n");
216                 ret = 999;
217                 goto free;
218         }
219
220 #ifdef WITH_CRYPT
221         /* init crc */
222         crc_init();
223 #endif
224
225         /* the mutex init */
226         if (pthread_mutex_init(&mutexd, NULL)) {
227                 fprintf(stderr, "cannot create 'PDEBUG' mutex\n");
228                 goto free;
229         }
230         created_mutexd = 1;
231 //      if (pthread_mutex_init(&mutext, NULL)) {
232 //              fprintf(stderr, "cannot create 'trace' mutex\n");
233 //              goto free;
234 //      }
235 //      created_mutext = 1;
236         if (pthread_mutex_init(&mutexe, NULL)) {
237                 fprintf(stderr, "cannot create 'PERROR' mutex\n");
238                 goto free;
239         }
240         created_mutexe = 1;
241
242         /* show interface */
243         if (!(strcasecmp(argv[1],"interface"))) {
244                 doc_interface();
245                 ret = 0;
246                 goto free;
247         }
248
249         /* show rules */
250         if (!(strcasecmp(argv[1],"rules"))) {
251                 if (argc <= 2)
252                         doc_rules(NULL);
253                 else
254                         doc_rules(argv[2]);
255                 ret = 0;
256                 goto free;
257         }
258
259         /* query available isdn ports */
260         if (!(strcasecmp(argv[1],"query"))) {
261                 int rc;
262                 fprintf(stderr, "-> Using 'misdn_info'\n");
263                 rc = system("misdn_info");
264                 ret = 0;
265                 goto free;
266         }
267
268         /* read options */
269         if (read_options(options_error) == 0) {
270                 PERROR("%s", options_error);
271                 goto free;
272         }
273         polling = options.polling;
274
275 #ifdef WITH_MISDN
276         /* init mISDN */
277         if (mISDN_initialize() < 0)
278                 goto free;
279         created_misdn = 1;
280 #endif
281
282         /* read ruleset(s) */
283         if (!(ruleset_first = ruleset_parse()))
284                 goto free;
285
286         /* set pointer to main ruleset */
287         ruleset_main = getrulesetbyname("main");
288         if (!ruleset_main) {
289                 fprintf(stderr, "\n***\n -> Missing 'main' ruleset, causing ALL calls to be disconnected.\n***\n\n");
290                 PDEBUG(DEBUG_LOG, "Missing 'main' ruleset, causing ALL calls to be disconnected.\n");
291                 sleep(2);
292         }
293
294 #if 0
295         /* query available isdn ports */
296         if (!(strcasecmp(argv[1],"route"))) {
297                 ruleset_debug(ruleset_first);
298                 ret = 0;
299                 goto free;
300         }
301 #endif
302
303         /* do fork in special cases */
304         if (!(strcasecmp(argv[1],"fork"))) {
305                 pid_t pid;
306                 FILE *pidfile;
307
308                 /* do daemon fork */
309                 pid = fork();
310
311                 if (pid < 0) {
312                         fprintf(stderr, "Cannot fork!\n");
313                         goto free;
314                 }
315                 if (pid != 0) {
316                         exit(0);
317                 }
318                 usleep(200000);
319                 printf("\n");
320                 
321                 /* do second fork */
322                 pid = fork();
323
324                 if (pid < 0) {
325                         fprintf(stderr, "Cannot fork!\n");
326                         goto free;
327                 }
328                 if (pid != 0) {
329                         printf("LCR: Starting daemon.\n");
330                         exit(0);
331                 }
332                 nooutput = 1;
333
334                 /* write pid file */
335                 SPRINT(lock, "%s/lcr.pid", options.lock);
336                 pidfile = fopen(lock,"w");
337                 if (pidfile) {
338                         fprintf(pidfile, "%d\n", getpid());
339                         fclose(pidfile);
340                 } else
341                         fprintf(stderr, "Failed to create PID file: %s\n", lock);
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_SIP
373         /* init SIP globals */
374         sip_init();
375         polling = 1; /* must poll, because of SIP events */
376 #endif
377
378 #ifdef WITH_SS5
379         /* init ss5 sine tables */
380         ss5_sine_generate();
381         ss5_test_decode();
382 #endif
383
384         /* load tones (if requested) */
385         if (fetch_tones() == 0) {
386                 fprintf(stderr, "Unable to fetch tones into memory.\n");
387                 goto free;
388         }
389
390 #if defined WITH_GSM_BS || defined WITH_GSM_MS
391         /* init gsm */
392         if (gsm_init()) {
393                 fprintf(stderr, "GSM initialization failed.\n");
394                 goto free;
395         }
396 #endif
397 #if 0
398 init is done when interface is up
399 #ifdef WITH_GSM_BS
400         if (gsm_bs_init()) {
401                 fprintf(stderr, "GSM BS initialization failed.\n");
402                 goto free;
403         }
404 #endif
405 #endif
406 #ifdef WITH_GSM_MS
407         if (gsm_ms_init()) {
408                 fprintf(stderr, "GSM MS initialization failed.\n");
409                 goto free;
410         }
411 #endif
412
413         /* read interfaces and open ports */
414         if (!read_interfaces()) {
415                 PERROR_RUNTIME("No interfaces specified or failed to parse interface.conf.\n");
416                 fprintf(stderr, "No interfaces specified or failed to parse interface.conf.\n");
417                 goto free;
418         }
419         relink_interfaces();
420         interface_first = interface_newlist;
421         interface_newlist = NULL;
422         
423         /* locking memory paging */
424         i = 0;
425         while(i < 10) {
426                 if (mlockall(MCL_CURRENT | MCL_FUTURE) >= 0)
427                         break;
428                 usleep(200000);
429                 i++;
430         }
431         if (i == 10) {
432                 switch(errno) {
433                         case ENOMEM:
434                         fprintf(stderr, "Warning: Not enough memory to lock paging.\n");
435                         break;
436                         case EPERM:
437                         fprintf(stderr, "Warning: No permission to lock paging.\n");
438                         break;
439                         case EFAULT:
440                         fprintf(stderr, "Warning: 'Bad address' while locking paging.\n");
441                         break;
442                         default:
443                         fprintf(stderr, "Warning: Unknown error %d while locking paging.\n", errno);
444                 }
445         }
446
447         /* set real time scheduler & priority */
448         if (options.schedule > 1) {
449                 memset(&schedp, 0, sizeof(schedp));
450                 schedp.sched_priority = options.schedule;
451                 ret = sched_setscheduler(0, SCHED_RR, &schedp);
452                 if (ret < 0) {
453                         PERROR("Scheduling failed with given priority %d (errno = %d).\nCheck options.conf 'schedule', exitting...\n", options.schedule, errno);
454                         goto free;
455                 }
456         }
457
458         /* signal handlers */   
459         signal(SIGINT,sighandler);
460         signal(SIGHUP,sighandler);
461         signal(SIGTERM,sighandler);
462         signal(SIGPIPE,sighandler);
463         created_signal = 1;
464
465         /* init message */
466         init_message();
467         created_message = 1;
468
469         /*** main loop ***/
470         SPRINT(tracetext, "%s %s started, waiting for calls...", NAME, VERSION_STRING);
471         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
472         printf("%s\n", tracetext);
473         end_trace();
474         quit = 0;
475 #if 0
476         GET_NOW();
477 #endif
478         while(!quit) {
479 #if 0
480                 last_d = now_d;
481                 GET_NOW();
482                 if (now_d-last_d > 1.0) {
483                         PERROR("LCR was stalling %d.%d seconds\n", ((int)((now_d-last_d)*10.0))/10, (int)((now_d-last_d)*10.0));
484                 }
485                 /* all loops must be counted from the beginning since nodes might get freed during handler */
486                 all_idle = 1;
487
488                 /* must be processed after all queues, so they are empty */
489                 if (select_main(1, NULL, NULL, NULL))
490                         all_idle = 0;
491                 if (all_idle) {
492                         usleep(10000);
493                 }
494 #else
495                 if (options.polling) {
496                         if (!select_main(1, NULL, NULL, NULL)) {
497 #ifdef WITH_SIP
498                                 /* FIXME: check if work was done */
499                                 sip_handle();
500 #endif
501                                 usleep(10000);
502                         }
503                 } else
504                         select_main(0, NULL, NULL, NULL);
505 #endif
506         }
507         SPRINT(tracetext, "%s terminated", NAME);
508         printf("%s\n", tracetext);
509         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
510         if (quit > 0)
511                 add_trace((char *)"signal", NULL, "%d", quit);
512         if (quit < 0)
513                 add_trace((char *)"errno", NULL, "%d", quit);
514         end_trace();
515         ret=0;
516
517         /* free all */
518 free:
519
520         /* set scheduler & priority
521          */
522         if (options.schedule > 1) {
523                 memset(&schedp, 0, sizeof(schedp));
524                 schedp.sched_priority = options.schedule;
525                 sched_setscheduler(0, SCHED_OTHER, &schedp);
526         }
527         /* reset signals */
528         if (created_signal) {
529                 signal(SIGINT,SIG_DFL);
530                 signal(SIGHUP,SIG_DFL);
531                 signal(SIGTERM,SIG_DFL);
532                 signal(SIGPIPE,SIG_DFL);
533         }
534
535         /* destroy objects */
536         while(port_first) {
537                 debug_count++;
538                 delete port_first;
539         }
540         while(epoint_first) {
541                 debug_count++;
542                 delete epoint_first;
543         }
544         epoint_first = NULL;
545         debug_count++;
546         join_free();
547
548         /* free interfaces */
549         if (interface_first)
550                 free_interfaces(interface_first);
551         interface_first = NULL;
552
553 #ifdef WITH_MISDN
554         /* close isdn ports */
555         mISDNport_close_all();
556 #endif
557
558         /* flush messages */
559         debug_count++;
560         i = 0;
561         while ((message = message_get())) {
562                 i++;
563                 message_free(message);
564         }
565         if (i) {
566                 PDEBUG(DEBUG_MSG, "freed %d pending messages\n", i);
567         }
568
569         /* clean messages */
570         if (created_message)
571                 cleanup_message();
572
573         /* free tones */
574         if (toneset_first)
575                 free_tones();
576
577         /* free admin socket */
578         admin_cleanup();
579
580         /* close lock */
581         if (created_lock)
582                 flock(lockfd, LOCK_UN);
583         if (lockfd >= 0) {
584                 chmod(lock, 0700);
585                 unlink(lock);
586                 close(lockfd);
587         }
588
589         /* free rulesets */
590         if (ruleset_first)
591                 ruleset_free(ruleset_first);
592         ruleset_first = NULL;
593
594         /* free mutex */
595         if (created_mutexe)
596                 if (pthread_mutex_destroy(&mutexe))
597                         fprintf(stderr, "cannot destroy 'PERROR' mutex\n");
598 //      if (created_mutext)
599 //              if (pthread_mutex_destroy(&mutext))
600 //                      fprintf(stderr, "cannot destroy 'trace' mutex\n");
601         if (created_mutexd)
602                 if (pthread_mutex_destroy(&mutexd))
603                         fprintf(stderr, "cannot destroy 'PDEBUG' mutex\n");
604
605 #ifdef WITH_MISDN
606         /* deinitialize mISDN */
607         if (created_misdn)
608                 mISDN_deinitialize();
609 #endif
610
611         /* free gsm */
612 #if 0
613 exit is done when interface is down
614 #ifdef WITH_GSM_BS
615         gsm_bs_exit(0);
616 #endif
617 #endif
618 #ifdef WITH_GSM_MS
619         gsm_ms_exit(0);
620 #endif
621 #if defined WITH_GSM_BS || defined WITH_GSM_MS
622         gsm_exit(0);
623 #endif
624
625 #ifdef WITH_SIP
626         /* cleanup SIP globals */
627         sip_exit();
628 #endif
629
630 #ifdef WITH_MISDN
631         /* close loopback, if used by GSM or remote */
632         if (mISDNloop.sock > -1)
633                 mISDNloop_close();
634 #endif
635
636         /* display memory leak */
637 #define MEMCHECK(a, b) \
638         if (b) { \
639                 SPRINT(tracetext, a, NAME); \
640                 start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext); \
641                 if (ret) add_trace("blocks", NULL, "%d", b); \
642                 end_trace(); \
643                 printf("\n******************************\n\007"); \
644                 printf("\nERROR: %d %s\n", b, a); \
645                 printf("\n******************************\n"); \
646                 ret = -1; \
647         }
648         MEMCHECK("",memuse)
649         MEMCHECK("memory block(s) left (port.cpp ...)",pmemuse)
650         MEMCHECK("memory block(s) left (epoint*.cpp ...)",ememuse)
651         MEMCHECK("memory block(s) left (join*.cpp)",cmemuse)
652         MEMCHECK("memory block(s) left (message.c)",mmemuse)
653         MEMCHECK("memory block(s) left (route.c)",rmemuse)
654         MEMCHECK("memory block(s) left (args)",amemuse)
655         MEMCHECK("class(es) left",classuse)
656         MEMCHECK("file descriptor(s) left",fduse)
657         MEMCHECK("file handler(s) left",fhuse)
658
659         /* unlock LCR process */
660 //      pthread_mutex_unlock(&mutex_lcr);
661
662         /* take me out */
663         return(ret);
664 }
665
666
667