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