b70ed0597da7475065f37c98dcfaef6fbcdb71d7
[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                 fprintf(stderr, "-> Using 'misdn_info'\n");
246                 system("misdn_info");
247                 ret = 0;
248                 goto free;
249         }
250
251         /* read options */
252         if (read_options() == 0) {
253                 PERROR("%s", options_error);
254                 goto free;
255         }
256
257         /* init mISDN */
258         if (mISDN_initialize() < 0)
259                 goto free;
260         created_misdn = 1;
261         created_debug = 1;
262
263         /* read ruleset(s) */
264         if (!(ruleset_first = ruleset_parse()))
265                 goto free;
266
267         /* set pointer to main ruleset */
268         ruleset_main = getrulesetbyname("main");
269         if (!ruleset_main) {
270                 fprintf(stderr, "\n***\n -> Missing 'main' ruleset, causing ALL calls to be disconnected.\n***\n\n");
271                 PDEBUG(DEBUG_LOG, "Missing 'main' ruleset, causing ALL calls to be disconnected.\n");
272                 sleep(2);
273         }
274
275 #if 0
276         /* query available isdn ports */
277         if (!(strcasecmp(argv[1],"route"))) {
278                 ruleset_debug(ruleset_first);
279                 ret = 0;
280                 goto free;
281         }
282 #endif
283
284         /* do fork in special cases */
285         if (!(strcasecmp(argv[1],"fork"))) {
286                 pid_t pid;
287                 FILE *pidfile;
288
289                 /* do daemon fork */
290                 pid = fork();
291
292                 if (pid < 0) {
293                         fprintf(stderr, "Cannot fork!\n");
294                         goto free;
295                 }
296                 if (pid != 0) {
297                         exit(0);
298                 }
299                 usleep(200000);
300                 printf("\n");
301                 
302                 /* do second fork */
303                 pid = fork();
304
305                 if (pid < 0) {
306                         fprintf(stderr, "Cannot fork!\n");
307                         goto free;
308                 }
309                 if (pid != 0) {
310                         printf("LCR: Starting daemon.\n");
311                         exit(0);
312                 }
313                 nooutput = 1;
314
315                 /* write pid file */
316                 pidfile = fopen("/var/run/lcr.pid","w");
317                 if (pidfile) {
318                         fprintf(pidfile, "%d\n", getpid());
319                         fclose(pidfile);
320                 }
321         } else
322         /* if not start */
323         if (!!strcasecmp(argv[1],"start")) {
324                 goto usage;
325         }
326
327         /* create lock and lock! */
328         SPRINT(lock, "%s/lcr.lock", options.lock);
329         if ((lockfd = open(lock, O_CREAT | O_WRONLY, S_IWUSR)) < 0) {
330                 fprintf(stderr, "Cannot create lock file: %s\n", lock);
331                 fprintf(stderr, "Check options.conf to change to path with permissions for you.\n");
332                 goto free;
333         }
334         if (flock(lockfd, LOCK_EX|LOCK_NB) < 0) {
335                 if (errno == EWOULDBLOCK)
336                         fprintf(stderr, "LCR: Another LCR process is running. Please kill the other one.\n");
337                 else    fprintf(stderr, "Locking process failed: errno=%d\n", errno);
338                 goto free;
339         }
340         created_lock = 1;
341
342         /* initialize admin socket */
343         if (admin_init()) {
344                 fprintf(stderr, "Unable to initialize admin socket.\n");
345                 goto free;
346         }
347
348         /* generate alaw / ulaw tables */
349         generate_tables(options.law);
350
351 #ifdef WITH_SS5
352         /* init ss5 sine tables */
353         ss5_sine_generate();
354         ss5_test_decode();
355 #endif
356
357         /* load tones (if requested) */
358         if (fetch_tones() == 0) {
359                 fprintf(stderr, "Unable to fetch tones into memory.\n");
360                 goto free;
361         }
362
363 #ifdef WITH_GSM
364         /* handle gsm */
365         if (options.gsm && gsm_init()) {
366                 fprintf(stderr, "GSM initialization failed.\n");
367                 goto free;
368         }
369 #else
370         if (options.gsm) {
371                 fprintf(stderr, "GSM is enabled, but not compiled. Use --with-gsm while configure!\n");
372                 goto free;
373         }
374 #endif
375
376         /* read interfaces and open ports */
377         if (!read_interfaces()) {
378                 PERROR_RUNTIME("No interfaces specified or failed to parse interface.conf.\n");
379                 fprintf(stderr, "No interfaces specified or failed to parse interface.conf.\n");
380                 goto free;
381         }
382         relink_interfaces();
383         interface_first = interface_newlist;
384         interface_newlist = NULL;
385         
386         /* locking memory paging */
387         i = 0;
388         while(i < 10) {
389                 if (mlockall(MCL_CURRENT | MCL_FUTURE) >= 0)
390                         break;
391                 usleep(200000);
392                 i++;
393         }
394         if (i == 10) {
395                 switch(errno) {
396                         case ENOMEM:
397                         fprintf(stderr, "Warning: Not enough memory to lock paging.\n");
398                         break;
399                         case EPERM:
400                         fprintf(stderr, "Warning: No permission to lock paging.\n");
401                         break;
402                         case EFAULT:
403                         fprintf(stderr, "Warning: 'Bad address' while locking paging.\n");
404                         break;
405                         default:
406                         fprintf(stderr, "Warning: Unknown error %d while locking paging.\n", errno);
407                 }
408         }
409
410         /* set real time scheduler & priority */
411         if (options.schedule > 1) {
412                 memset(&schedp, 0, sizeof(schedp));
413                 schedp.sched_priority = options.schedule;
414                 ret = sched_setscheduler(0, SCHED_RR, &schedp);
415                 if (ret < 0) {
416                         PERROR("Scheduling failed with given priority %d (errno = %d).\nCheck options.conf 'schedule', exitting...\n", options.schedule, errno);
417                         goto free;
418                 }
419         }
420
421         /* signal handlers */   
422         signal(SIGINT,sighandler);
423         signal(SIGHUP,sighandler);
424         signal(SIGTERM,sighandler);
425         signal(SIGPIPE,sighandler);
426         created_signal = 1;
427
428         /* init message */
429         init_message();
430
431         /*** main loop ***/
432         SPRINT(tracetext, "%s %s started, waiting for calls...", NAME, VERSION_STRING);
433         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
434         printf("%s\n", tracetext);
435         end_trace();
436         quit = 0;
437 #ifdef WITH_GSM
438         GET_NOW();
439 #endif
440         while(!quit) {
441 #ifdef WITH_GSM
442                 last_d = now_d;
443                 GET_NOW();
444                 if (now_d-last_d > 1.0) {
445                         PERROR("LCR was stalling %d.%d seconds\n", ((int)((now_d-last_d)*10.0))/10, (int)((now_d-last_d)*10.0));
446                 }
447                 /* all loops must be counted from the beginning since nodes might get freed during handler */
448                 all_idle = 1;
449
450                 /* must be processed after all queues, so they are empty */
451                 if (select_main(1, NULL, NULL, NULL))
452                         all_idle = 0;
453                 /* handle gsm */
454                 if (options.gsm)
455                         while(handle_gsm())
456                                 all_idle = 0;
457                 if (all_idle) {
458                         usleep(10000);
459                 }
460 #else
461                 select_main(0, NULL, NULL, NULL);
462 #endif
463         }
464         SPRINT(tracetext, "%s terminated", NAME);
465         printf("%s\n", tracetext);
466         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
467         if (quit)
468                 add_trace((char *)"signal", NULL, "%d", quit);
469         end_trace();
470         ret=0;
471
472         /* clean messacleane */
473         cleanup_message();
474
475         /* free all */
476 free:
477
478         /* set scheduler & priority
479          */
480         if (options.schedule > 1) {
481                 memset(&schedp, 0, sizeof(schedp));
482                 schedp.sched_priority = options.schedule;
483                 sched_setscheduler(0, SCHED_OTHER, &schedp);
484         }
485         /* reset signals */
486         if (created_signal) {
487                 signal(SIGINT,SIG_DFL);
488                 signal(SIGHUP,SIG_DFL);
489                 signal(SIGTERM,SIG_DFL);
490                 signal(SIGPIPE,SIG_DFL);
491         }
492
493         /* destroy objects */
494
495         while(port_first) {
496                 debug_count++;
497                 delete port_first;
498         }
499         while(epoint_first) {
500                 debug_count++;
501                 delete epoint_first;
502         }
503         epoint_first = NULL;
504         debug_count++;
505         join_free();
506
507         /* free interfaces */
508         if (interface_first)
509                 free_interfaces(interface_first);
510         interface_first = NULL;
511
512         /* close isdn ports */
513         mISDNport_close_all();
514
515         /* flush messages */
516         debug_count++;
517         i = 0;
518         while ((message = message_get())) {
519                 i++;
520                 message_free(message);
521         }
522         if (i) {
523                 PDEBUG(DEBUG_MSG, "freed %d pending messages\n", i);
524         }
525
526         /* free tones */
527         if (toneset_first)
528                 free_tones();
529
530         /* free admin socket */
531         admin_cleanup();
532
533         /* close lock */
534         if (created_lock)
535                 flock(lockfd, LOCK_UN);
536         if (lockfd >= 0) {
537                 chmod(lock, 0700);
538                 unlink(lock);
539                 close(lockfd);
540         }
541
542         /* free rulesets */
543         if (ruleset_first)
544                 ruleset_free(ruleset_first);
545         ruleset_first = NULL;
546
547         /* free mutex */
548         if (created_mutexe)
549                 if (pthread_mutex_destroy(&mutexe))
550                         fprintf(stderr, "cannot destroy 'PERROR' mutex\n");
551 //      if (created_mutext)
552 //              if (pthread_mutex_destroy(&mutext))
553 //                      fprintf(stderr, "cannot destroy 'trace' mutex\n");
554         if (created_mutexd)
555                 if (pthread_mutex_destroy(&mutexd))
556                         fprintf(stderr, "cannot destroy 'PDEBUG' mutex\n");
557
558         /* deinitialize mISDN */
559         if (created_misdn)
560                 mISDN_deinitialize();
561
562 #ifdef WITH_GSM
563         /* free gsm */
564         if (options.gsm)
565                 gsm_exit(0);
566 #endif
567
568         /* display memory leak */
569 #define MEMCHECK(a, b) \
570         if (b) { \
571                 SPRINT(tracetext, a, NAME); \
572                 start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext); \
573                 if (ret) add_trace("blocks", NULL, "%d", b); \
574                 end_trace(); \
575                 printf("\n******************************\n\007"); \
576                 printf("\nERROR: %d %s\n", b, a); \
577                 printf("\n******************************\n"); \
578                 ret = -1; \
579         }
580         MEMCHECK("",memuse)
581         MEMCHECK("memory block(s) left (port.cpp ...)",pmemuse)
582         MEMCHECK("memory block(s) left (epoint*.cpp ...)",ememuse)
583         MEMCHECK("memory block(s) left (join*.cpp)",cmemuse)
584         MEMCHECK("memory block(s) left (message.c)",mmemuse)
585         MEMCHECK("memory block(s) left (route.c)",rmemuse)
586         MEMCHECK("memory block(s) left (args)",amemuse)
587         MEMCHECK("class(es) left",classuse)
588         MEMCHECK("file descriptor(s) left",fduse)
589         MEMCHECK("file handler(s) left",fhuse)
590
591         /* unlock LCR process */
592 //      pthread_mutex_unlock(&mutex_lcr);
593
594         /* take me out */
595         return(ret);
596 }
597
598
599