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