84f357f492664f1081829b4e5a61d682707bb506
[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 *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() line %d): %s", 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 *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(function, line, "DEBUG", buffer);
113
114         pthread_mutex_unlock(&mutexd);
115 }
116
117 void _printerror(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(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;
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_SS5
366         /* init ss5 sine tables */
367         ss5_sine_generate();
368         ss5_test_decode();
369 #endif
370
371         /* load tones (if requested) */
372         if (fetch_tones() == 0) {
373                 fprintf(stderr, "Unable to fetch tones into memory.\n");
374                 goto free;
375         }
376
377 #if defined WITH_GSM_BS || defined WITH_GSM_MS
378         /* init gsm */
379         if (gsm_init()) {
380                 fprintf(stderr, "GSM initialization failed.\n");
381                 goto free;
382         }
383 #endif
384 #if 0
385 init is done when interface is up
386 #ifdef WITH_GSM_BS
387         if (gsm_bs_init()) {
388                 fprintf(stderr, "GSM BS initialization failed.\n");
389                 goto free;
390         }
391 #endif
392 #endif
393 #ifdef WITH_GSM_MS
394         if (gsm_ms_init()) {
395                 fprintf(stderr, "GSM MS initialization failed.\n");
396                 goto free;
397         }
398 #endif
399
400         /* read interfaces and open ports */
401         if (!read_interfaces()) {
402                 PERROR_RUNTIME("No interfaces specified or failed to parse interface.conf.\n");
403                 fprintf(stderr, "No interfaces specified or failed to parse interface.conf.\n");
404                 goto free;
405         }
406         relink_interfaces();
407         interface_first = interface_newlist;
408         interface_newlist = NULL;
409         
410         /* locking memory paging */
411         i = 0;
412         while(i < 10) {
413                 if (mlockall(MCL_CURRENT | MCL_FUTURE) >= 0)
414                         break;
415                 usleep(200000);
416                 i++;
417         }
418         if (i == 10) {
419                 switch(errno) {
420                         case ENOMEM:
421                         fprintf(stderr, "Warning: Not enough memory to lock paging.\n");
422                         break;
423                         case EPERM:
424                         fprintf(stderr, "Warning: No permission to lock paging.\n");
425                         break;
426                         case EFAULT:
427                         fprintf(stderr, "Warning: 'Bad address' while locking paging.\n");
428                         break;
429                         default:
430                         fprintf(stderr, "Warning: Unknown error %d while locking paging.\n", errno);
431                 }
432         }
433
434         /* set real time scheduler & priority */
435         if (options.schedule > 1) {
436                 memset(&schedp, 0, sizeof(schedp));
437                 schedp.sched_priority = options.schedule;
438                 ret = sched_setscheduler(0, SCHED_RR, &schedp);
439                 if (ret < 0) {
440                         PERROR("Scheduling failed with given priority %d (errno = %d).\nCheck options.conf 'schedule', exitting...\n", options.schedule, errno);
441                         goto free;
442                 }
443         }
444
445         /* signal handlers */   
446         signal(SIGINT,sighandler);
447         signal(SIGHUP,sighandler);
448         signal(SIGTERM,sighandler);
449         signal(SIGPIPE,sighandler);
450         created_signal = 1;
451
452         /* init message */
453         init_message();
454
455         /*** main loop ***/
456         SPRINT(tracetext, "%s %s started, waiting for calls...", NAME, VERSION_STRING);
457         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
458         printf("%s\n", tracetext);
459         end_trace();
460         quit = 0;
461 #if 0
462         GET_NOW();
463 #endif
464         while(!quit) {
465 #if 0
466                 last_d = now_d;
467                 GET_NOW();
468                 if (now_d-last_d > 1.0) {
469                         PERROR("LCR was stalling %d.%d seconds\n", ((int)((now_d-last_d)*10.0))/10, (int)((now_d-last_d)*10.0));
470                 }
471                 /* all loops must be counted from the beginning since nodes might get freed during handler */
472                 all_idle = 1;
473
474                 /* must be processed after all queues, so they are empty */
475                 if (select_main(1, NULL, NULL, NULL))
476                         all_idle = 0;
477                 if (all_idle) {
478                         usleep(10000);
479                 }
480 #else
481                 if (options.polling) {
482                         if (!select_main(1, NULL, NULL, NULL)) {
483                                 usleep(10000);
484                         }
485                 } else
486                         select_main(0, NULL, NULL, NULL);
487 #endif
488         }
489         SPRINT(tracetext, "%s terminated", NAME);
490         printf("%s\n", tracetext);
491         start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext);
492         if (quit > 0)
493                 add_trace((char *)"signal", NULL, "%d", quit);
494         if (quit < 0)
495                 add_trace((char *)"errno", NULL, "%d", quit);
496         end_trace();
497         ret=0;
498
499         /* clean messacleane */
500         cleanup_message();
501
502         /* free all */
503 free:
504
505         /* set scheduler & priority
506          */
507         if (options.schedule > 1) {
508                 memset(&schedp, 0, sizeof(schedp));
509                 schedp.sched_priority = options.schedule;
510                 sched_setscheduler(0, SCHED_OTHER, &schedp);
511         }
512         /* reset signals */
513         if (created_signal) {
514                 signal(SIGINT,SIG_DFL);
515                 signal(SIGHUP,SIG_DFL);
516                 signal(SIGTERM,SIG_DFL);
517                 signal(SIGPIPE,SIG_DFL);
518         }
519
520         /* destroy objects */
521
522         while(port_first) {
523                 debug_count++;
524                 delete port_first;
525         }
526         while(epoint_first) {
527                 debug_count++;
528                 delete epoint_first;
529         }
530         epoint_first = NULL;
531         debug_count++;
532         join_free();
533
534         /* free interfaces */
535         if (interface_first)
536                 free_interfaces(interface_first);
537         interface_first = NULL;
538
539         /* close isdn ports */
540         mISDNport_close_all();
541
542         /* flush messages */
543         debug_count++;
544         i = 0;
545         while ((message = message_get())) {
546                 i++;
547                 message_free(message);
548         }
549         if (i) {
550                 PDEBUG(DEBUG_MSG, "freed %d pending messages\n", i);
551         }
552
553         /* free tones */
554         if (toneset_first)
555                 free_tones();
556
557         /* free admin socket */
558         admin_cleanup();
559
560         /* close lock */
561         if (created_lock)
562                 flock(lockfd, LOCK_UN);
563         if (lockfd >= 0) {
564                 chmod(lock, 0700);
565                 unlink(lock);
566                 close(lockfd);
567         }
568
569         /* free rulesets */
570         if (ruleset_first)
571                 ruleset_free(ruleset_first);
572         ruleset_first = NULL;
573
574         /* free mutex */
575         if (created_mutexe)
576                 if (pthread_mutex_destroy(&mutexe))
577                         fprintf(stderr, "cannot destroy 'PERROR' mutex\n");
578 //      if (created_mutext)
579 //              if (pthread_mutex_destroy(&mutext))
580 //                      fprintf(stderr, "cannot destroy 'trace' mutex\n");
581         if (created_mutexd)
582                 if (pthread_mutex_destroy(&mutexd))
583                         fprintf(stderr, "cannot destroy 'PDEBUG' mutex\n");
584
585         /* deinitialize mISDN */
586         if (created_misdn)
587                 mISDN_deinitialize();
588
589         /* free gsm */
590 #if 0
591 exit is done when interface is down
592 #ifdef WITH_GSM_BS
593         gsm_bs_exit(0);
594 #endif
595 #endif
596 #ifdef WITH_GSM_MS
597         gsm_ms_exit(0);
598 #endif
599 #if defined WITH_GSM_BS || defined WITH_GSM_MS
600         gsm_exit(0);
601 #endif
602
603         /* close loopback, if used by GSM or remote */
604         if (mISDNloop.sock > -1)
605                 mISDNloop_close();
606
607         /* display memory leak */
608 #define MEMCHECK(a, b) \
609         if (b) { \
610                 SPRINT(tracetext, a, NAME); \
611                 start_trace(-1, NULL, NULL, NULL, 0, 0, 0, tracetext); \
612                 if (ret) add_trace("blocks", NULL, "%d", b); \
613                 end_trace(); \
614                 printf("\n******************************\n\007"); \
615                 printf("\nERROR: %d %s\n", b, a); \
616                 printf("\n******************************\n"); \
617                 ret = -1; \
618         }
619         MEMCHECK("",memuse)
620         MEMCHECK("memory block(s) left (port.cpp ...)",pmemuse)
621         MEMCHECK("memory block(s) left (epoint*.cpp ...)",ememuse)
622         MEMCHECK("memory block(s) left (join*.cpp)",cmemuse)
623         MEMCHECK("memory block(s) left (message.c)",mmemuse)
624         MEMCHECK("memory block(s) left (route.c)",rmemuse)
625         MEMCHECK("memory block(s) left (args)",amemuse)
626         MEMCHECK("class(es) left",classuse)
627         MEMCHECK("file descriptor(s) left",fduse)
628         MEMCHECK("file handler(s) left",fhuse)
629
630         /* unlock LCR process */
631 //      pthread_mutex_unlock(&mutex_lcr);
632
633         /* take me out */
634         return(ret);
635 }
636
637
638