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