69d6ab7dfdafd0b5f49e658bcd852d4952dc520d
[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 <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/types.h>
16 #include <sys/wait.h>
17 #include <sys/stat.h>
18 #include <unistd.h>
19 #include <signal.h>
20 #include <stdarg.h>
21 #include <fcntl.h>
22 #include <sys/ioctl.h>
23 #include <sys/file.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #include <sys/resource.h>
27 #include "main.h"
28
29 MESSAGES
30
31 double now_d;
32 time_t now;
33 struct tm *now_tm;
34 struct timeval now_tv;
35 struct timezone now_tz;
36 #define GET_NOW() \
37         { \
38                 gettimeofday(&now_tv, &now_tz); \
39                 now_d = ((double)(now_tv.tv_usec))/1000000 + now_tv.tv_sec; \
40                 now = now_tv.tv_sec; \
41                 now_tm = localtime(&now); \
42         }
43 //#define DEBUG_DURATION
44
45 int global_debug = 0;
46 int quit=0;
47
48 pthread_mutex_t mutexd; // debug output mutex
49 //pthread_mutex_t mutext; // trace output mutex
50 pthread_mutex_t mutexe; // error output mutex
51
52 int memuse = 0;
53 int mmemuse = 0;
54 int cmemuse = 0;
55 int ememuse = 0;
56 int pmemuse = 0;
57 int amemuse = 0;
58 int rmemuse = 0;
59 int classuse = 0;
60 int fduse = 0;
61 int fhuse = 0;
62
63 char *debug_prefix = 0;
64 int debug_count = 0;
65 int last_debug = 0;
66 int debug_newline = 1;
67 int nooutput = 0;
68
69 void debug_usleep(int msec, char *file, int line, int hour, int min, int sec)
70 {
71         usleep(msec);
72 }
73
74 void debug(const char *function, int line, char *prefix, char *buffer)
75 {
76         /* if we have a new debug count, we add a mark */
77         if (last_debug != debug_count)
78         {
79                 last_debug = debug_count;
80                 if (!nooutput)
81                         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);
82                 if (options.deb&DEBUG_LOG && global_debug)
83                         dprint(DBGM_MAN, 0, "--------------------- %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);
84         }
85
86         if (!nooutput)
87         {
88                 if (debug_newline)
89                         printf("\033[32m%06d %s\033[37m%s", debug_count%1000000, prefix?prefix:"", prefix?" ":"");
90                 if (function)
91                         printf("(in %s() line %d): %s", function, line, buffer);
92                 else
93                         printf("%s", buffer);
94         }
95
96         if (options.deb&DEBUG_LOG && global_debug)
97         {
98                 if (debug_newline)
99                 {
100                         if (function)
101                                 dprint(DBGM_MAN, 0, "%s%s(in %s() line %d): %s", prefix?prefix:"", prefix?" ":"", function, line, buffer);
102                         else
103                                 dprint(DBGM_MAN, 0, "%s%s: %s", prefix?prefix:"", prefix?" ":"", buffer);
104                 }
105         }
106
107         debug_newline = 0;
108         if (buffer[0])
109                 if (buffer[strlen(buffer)-1] == '\n')
110                         debug_newline = 1;
111 }
112
113
114 void _printdebug(const char *function, int line, unsigned long mask, const char *fmt, ...)
115 {
116         char buffer[4096];
117         va_list args;
118
119         if (!(options.deb & mask))
120                 return;
121         pthread_mutex_lock(&mutexd);
122
123         va_start(args,fmt);
124         VUNPRINT(buffer,sizeof(buffer)-1,fmt,args);
125         buffer[sizeof(buffer)-1]=0;
126         va_end(args);
127
128         debug(function, line, debug_prefix, buffer);
129
130         pthread_mutex_unlock(&mutexd);
131 }
132
133 void _printerror(const char *function, int line, const char *fmt, ...)
134 {
135         char buffer[4096];
136         va_list args;
137
138         pthread_mutex_lock(&mutexe);
139
140         va_start(args,fmt);
141         VUNPRINT(buffer,sizeof(buffer)-1,fmt,args);
142         buffer[sizeof(buffer)-1]=0;
143         va_end(args);
144
145         if (options.deb)
146                 debug(function, line, "ERROR", buffer);
147         else /* only if we do not debug */
148         {
149                 if (function)
150                         fprintf(stderr, "ERROR (in %s() line %d) %s", function, line, buffer);
151                 else
152                         fprintf(stderr, "ERROR %s", buffer);
153         }
154
155         pthread_mutex_unlock(&mutexe);
156 }
157
158
159 void sighandler(int sigset)
160 {
161         struct sched_param schedp;
162
163         if (sigset == SIGHUP)
164                 return;
165         if (sigset == SIGPIPE)
166                 return;
167         if (!quit)
168         {
169                 quit=1;
170                 /* set scheduler & priority */
171                 if (options.schedule > 1)
172                 {
173                         memset(&schedp, 0, sizeof(schedp));
174                         schedp.sched_priority = 0;
175                         sched_setscheduler(0, SCHED_OTHER, &schedp);
176                 }
177                 fprintf(stderr, "LCR: Signal received: %d\n", sigset);
178                 PERROR("Signal received: %d\n", sigset);
179         }
180 }
181
182
183 /*
184  * the main
185  */
186 int main(int argc, char *argv[])
187 {
188         int                     ret = -1;
189         int                     lockfd = -1; /* file lock */
190         struct message          *message;
191         class Port              *port;
192         class Endpoint          *epoint;
193         class Join              *join;
194         int                     i;
195         int                     all_idle;
196         char                    prefix_string[64];
197         struct sched_param      schedp;
198         char                    *debug_prefix = "alloc";
199         int                     created_mutexd = 0,/* created_mutext = 0,*/ created_mutexe = 0,
200                                 created_lock = 0, created_signal = 0, created_debug = 0;
201 #ifdef DEBUG_DURATION
202         time_t                  durationupdate;
203         double                  idle_duration, isdn_duration, port_duration, epoint_duration, join_duration, message_duration, admin_duration;
204         double                  start_d;
205 #endif
206         int                     idletime = 0, idlecheck = 0;
207         char                    tracetext[256];
208
209         /* current time */
210         GET_NOW();
211
212         /* show version */
213         printf("\n** %s  Version %s\n\n", NAME, VERSION_STRING);
214
215         /* show options */
216         if (argc <= 1)
217         {
218                 usage:
219                 printf("\n");
220                 printf("Usage: lcr (query | start | fork | rules | route)\n");
221                 printf("query     = Show available isdn ports.\n");
222                 printf("start     = Run lcr normally, abort with CTRL+C.\n");
223                 printf("fork      = Do daemon fork and run as background process.\n");
224                 printf("interface = Get help of available interface syntax.\n");
225                 printf("rules     = Get help of available routing rule syntax.\n");
226                 printf("rules [action] = Get individual help for given action.\n");
227 //              printf("route = Show current routing as it is parsed.\n");
228                 printf("\n");
229                 ret = 999;
230                 goto free;
231         }
232
233         /* init crc */
234         crc_init();
235
236         /* check for root (real or effective) */
237         if (getuid() && geteuid())
238         {
239                 fprintf(stderr, "Please run %s as super-user.\n", NAME);
240                 goto free;
241         }
242
243         /* the mutex init */
244         if (pthread_mutex_init(&mutexd, NULL))
245         {
246                 fprintf(stderr, "cannot create 'PDEBUG' mutex\n");
247                 goto free;
248         }
249         created_mutexd = 1;
250 //      if (pthread_mutex_init(&mutext, NULL))
251 //      {
252 //              fprintf(stderr, "cannot create 'trace' mutex\n");
253 //              goto free;
254 //      }
255 //      created_mutext = 1;
256         if (pthread_mutex_init(&mutexe, NULL))
257         {
258                 fprintf(stderr, "cannot create 'PERROR' mutex\n");
259                 goto free;
260         }
261         created_mutexe = 1;
262
263         /* show interface */
264         if (!(strcasecmp(argv[1],"interface")))
265         {
266                 doc_interface();
267                 ret = 0;
268                 goto free;
269         }
270
271         /* show rules */
272         if (!(strcasecmp(argv[1],"rules")))
273         {
274                 if (argc <= 2)
275                         doc_rules(NULL);
276                 else
277                         doc_rules(argv[2]);
278                 ret = 0;
279                 goto free;
280         }
281
282         /* query available isdn ports */
283         if (!(strcasecmp(argv[1],"query")))
284         {
285                 mISDN_port_info();
286                 ret = 0;
287                 goto free;
288         }
289
290         /* read options */
291         if (read_options() == 0)
292                 goto free;
293
294         /* init mISDN */
295         if (mISDN_initialize() < 0)
296                 goto free;
297         created_debug = 1;
298
299         /* read ruleset(s) */
300         if (!(ruleset_first = ruleset_parse()))
301                 goto free;
302
303         /* set pointer to main ruleset */
304         ruleset_main = getrulesetbyname("main");
305         if (!ruleset_main)
306         {
307                 fprintf(stderr, "\n***\n -> Missing 'main' ruleset, causing ALL calls to be disconnected.\n***\n\n");
308                 PDEBUG(DEBUG_LOG, "Missing 'main' ruleset, causing ALL calls to be disconnected.\n");
309                 sleep(2);
310         }
311
312 #if 0
313         /* query available isdn ports */
314         if (!(strcasecmp(argv[1],"route")))
315         {
316                 ruleset_debug(ruleset_first);
317                 ret = 0;
318                 goto free;
319         }
320 #endif
321
322         /* do fork in special cases */
323         if (!(strcasecmp(argv[1],"fork")))
324         {
325                 pid_t pid;
326
327                 /* do daemon fork */
328                 pid = fork();
329
330                 if (pid < 0)
331                 {
332                         fprintf(stderr, "Cannot fork!\n");
333                         goto free;
334                 }
335                 if (pid != 0)
336                 {
337                         exit(0);
338                 }
339                 usleep(200000);
340                 printf("\n");
341                 
342                 /* do second fork */
343                 pid = fork();
344
345                 if (pid < 0)
346                 {
347                         fprintf(stderr, "Cannot fork!\n");
348                         goto free;
349                 }
350                 if (pid != 0)
351                 {
352                         printf("LCR: Starting daemon.\n");
353                         exit(0);
354                 }
355                 nooutput = 1;
356         } else
357         /* if not start */
358         if (!!strcasecmp(argv[1],"start"))
359         {
360                 goto usage;
361         }
362
363         /* create lock and lock! */
364         if ((lockfd = open("/var/run/lcr.lock", O_CREAT, 0)) < 0)
365         {
366                 fprintf(stderr, "Cannot create lock file: /var/run/lcr.lock\n");
367                 goto free;
368         }
369         if (flock(lockfd, LOCK_EX|LOCK_NB) < 0)
370         {
371                 if (errno == EWOULDBLOCK)
372                         fprintf(stderr, "LCR: Another LCR process is running. Please kill the other one.\n");
373                 else    fprintf(stderr, "Locking process failed: errno=%d\n", errno);
374                 goto free;
375         }
376         created_lock = 1;
377
378         /* initialize admin socket */
379         if (admin_init())
380         {
381                 fprintf(stderr, "Unable to initialize admin socket.\n");
382                 goto free;
383         }
384
385         /* generate alaw / ulaw tables */
386         generate_tables(options.law);
387
388         /* load tones (if requested) */
389         if (fetch_tones() == 0)
390         {
391                 fprintf(stderr, "Unable to fetch tones into memory.\n");
392                 goto free;
393         }
394
395         /* read interfaces and open ports */
396         if (!read_interfaces())
397         {
398                 PERROR_RUNTIME("No interfaces specified or failed to parse interface.conf.\n");
399                 fprintf(stderr, "No interfaces specified or failed to parse interface.conf.\n");
400                 goto free;
401         }
402         relink_interfaces();
403         interface_first = interface_newlist;
404         interface_newlist = NULL;
405         
406         /* locking memory paging */
407         i = 0;
408         while(i < 10)
409         {
410                 if (mlockall(MCL_CURRENT | MCL_FUTURE) >= 0)
411                         break;
412                 usleep(200000);
413                 i++;
414         }
415         if (i == 10)
416         {
417                 switch(errno)
418                 {
419                         case ENOMEM:
420                         fprintf(stderr, "Not enough memory to lock paging, exitting...\n");
421                         break;
422                         case EPERM:
423                         fprintf(stderr, "No permission to lock paging, exitting...\n");
424                         break;
425                         case EFAULT:
426                         fprintf(stderr, "'Bad address' while locking paging, exitting...\n");
427                         break;
428                         default:
429                         fprintf(stderr, "Unknown error %d while locking paging, exitting...\n", errno);
430                 }
431                 goto free;
432         }
433
434         /* set real time scheduler & priority */
435         if (options.schedule > 1)
436         {
437                 memset(&schedp, 0, sizeof(schedp));
438                 schedp.sched_priority = options.schedule;
439                 ret = sched_setscheduler(0, SCHED_RR, &schedp);
440                 if (ret < 0)
441                 {
442                         PERROR("Scheduling failed with given priority %d (errno = %d).\nCheck options.conf 'schedule', exitting...\n", options.schedule, errno);
443                         goto free;
444                 }
445         }
446
447         /* signal handlers */   
448         signal(SIGINT,sighandler);
449         signal(SIGHUP,sighandler);
450         signal(SIGTERM,sighandler);
451         signal(SIGPIPE,sighandler);
452         created_signal = 1;
453
454         /*** main loop ***/
455         SPRINT(tracetext, "%s %s started, waiting for calls...", NAME, VERSION_STRING);
456         start_trace(0, NULL, NULL, NULL, 0, 0, 0, tracetext);
457         printf("%s\n", tracetext);
458         end_trace();
459         GET_NOW();
460 #ifdef DEBUG_DURATION
461         start_d = now_d;
462         durationupdate = now;
463         idle_duration = isdn_duration = port_duration = epoint_duration = call_duration = message_duration = admin_duration = 0;
464 #endif
465         quit = 0;
466         while(!quit)
467         {
468                 /* all loops must be counted from the beginning since nodes might get freed during handler */
469                 all_idle = 1;
470
471 #warning debugging usleep crash
472                 debug_usleep(1, __FILE__, __LINE__, now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec);
473
474                 /* handle mISDN messages from kernel */
475                 debug_prefix = "ISDN";
476                 if (mISDN_handler())
477                         all_idle = 0;
478 #warning debugging usleep crash
479                 debug_usleep(1, __FILE__, __LINE__, now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec);
480
481 #ifdef DEBUG_DURATION
482                 GET_NOW();
483                 isdn_duration += (now_d - start_d);
484                 start_d = now_d;
485 #endif
486 BUDETECT
487
488                 /* loop through all port ports and call their handler */
489                 port_again:
490                 port = port_first;
491                 while(port)
492                 {
493                         debug_prefix = port->p_name;
494                         debug_count++;
495                         ret = port->handler();
496                         if (ret)
497                                 all_idle = 0;
498                         if (ret < 0) /* port has been destroyed */
499                                 goto port_again;
500                         port = port->next;
501                 }
502 #ifdef DEBUG_DURATION
503                 GET_NOW();
504                 port_duration += (now_d - start_d);
505                 start_d = now_d;
506 #endif
507
508                 /* loop through all epoint and call their handler */
509                 epoint_again:
510                 epoint = epoint_first;
511                 while(epoint)
512                 {
513                         debug_prefix = prefix_string;
514                         SPRINT(prefix_string, "ep%ld", epoint->ep_serial);
515                         debug_count++;
516                         ret = epoint->handler();
517                         if (ret)
518                                 all_idle = 0;
519                         if (ret < 0) /* epoint has been destroyed */
520                                 goto epoint_again;
521                         epoint = epoint->next;
522                 }
523 #ifdef DEBUG_DURATION
524                 GET_NOW();
525                 epoint_duration += (now_d - start_d);
526                 start_d = now_d;
527 #endif
528
529                 /* loop through all joins and call their handler */
530                 join_again:
531                 join = join_first;
532                 while(join)
533                 {
534                         debug_prefix = "join";
535                         debug_count++;
536                         ret = join->handler();
537                         if (ret)
538                                 all_idle = 0;
539                         if (ret < 0) /* join has been destroyed */
540                                 goto join_again;
541                         join = join->next;
542                 }
543 #ifdef DEBUG_DURATION
544                 GET_NOW();
545                 join_duration += (now_d - start_d);
546                 start_d = now_d;
547 #endif
548
549                 debug_prefix = 0;
550
551                 /* process any message */
552                 debug_count++;
553                 debug_prefix = "message";
554                 while ((message = message_get()))
555                 {
556                         all_idle = 0;
557                         switch(message->flow)
558                         {
559                                 case PORT_TO_EPOINT:
560                                 debug_prefix = "msg port->epoint";
561                                 epoint = find_epoint_id(message->id_to);
562                                 if (epoint)
563                                 {
564                                         if (epoint->ep_app)
565                                         {
566                                                 epoint->ep_app->ea_message_port(message->id_from, message->type, &message->param);
567                                         } else
568                                         {
569                                                 PDEBUG(DEBUG_MSG, "Warning: message %s from port %d to endpoint %d. endpoint doesn't have an application.\n", messages_txt[message->type], message->id_from, message->id_to);
570                                         }
571                                 } else
572                                 {
573                                         PDEBUG(DEBUG_MSG, "Warning: message %s from port %d to endpoint %d. endpoint doesn't exist anymore.\n", messages_txt[message->type], message->id_from, message->id_to);
574                                 }
575                                 break;
576
577                                 case EPOINT_TO_JOIN:
578                                 debug_prefix = "msg epoint->join";
579                                 join = find_join_id(message->id_to);
580                                 if (join)
581                                 {
582                                         join->message_epoint(message->id_from, message->type, &message->param);
583                                 } else
584                                 {
585                                         PDEBUG(DEBUG_MSG, "Warning: message %s from endpoint %d to join %d. join doesn't exist anymore\n", messages_txt[message->type], message->id_from, message->id_to);
586                                 }
587                                 break;
588
589                                 case JOIN_TO_EPOINT:
590                                 debug_prefix = "msg join->epoint";
591                                 epoint = find_epoint_id(message->id_to);
592                                 if (epoint)
593                                 {
594                                         if (epoint->ep_app)
595                                         {
596                                                 epoint->ep_app->ea_message_join(message->id_from, message->type, &message->param);
597                                         } else
598                                         {
599                                                 PDEBUG(DEBUG_MSG, "Warning: message %s from join %d to endpoint %d. endpoint doesn't have an application.\n", messages_txt[message->type], message->id_from, message->id_to);
600                                         }
601                                 } else
602                                 {
603                                         PDEBUG(DEBUG_MSG, "Warning: message %s from join %d to endpoint %d. endpoint doesn't exist anymore.\n", messages_txt[message->type], message->id_from, message->id_to);
604                                 }
605                                 break;
606
607                                 case EPOINT_TO_PORT:
608                                 debug_prefix = "msg epoint->port";
609                                 port = find_port_id(message->id_to);
610                                 if (port)
611                                 {
612                                         port->message_epoint(message->id_from, message->type, &message->param);
613 BUDETECT
614                                 } else
615                                 {
616                                         PDEBUG(DEBUG_MSG, "Warning: message %s from endpoint %d to port %d. port doesn't exist anymore\n", messages_txt[message->type], message->id_from, message->id_to);
617                                 }
618                                 break;
619
620                                 default:
621                                 PERROR("Message flow %d unknown.\n", message->flow);
622                         }
623                         message_free(message);
624                         debug_count++;
625                         debug_prefix = "message";
626                 }
627 #ifdef DEBUG_DURATION
628                 GET_NOW();
629                 message_duration += (now_d - start_d);
630                 start_d = now_d;
631 #endif
632 BUDETECT
633
634                 /* handle socket */
635                 if (admin_handle())
636                         all_idle = 0;
637 #ifdef DEBUG_DURATION
638                 GET_NOW();
639                 admin_duration += (now_d - start_d);
640                 start_d = now_d;
641 #endif
642 BUDETECT
643
644 #if 0
645                 /* check for child to exit (eliminate zombies) */
646                 if (waitpid(-1, NULL, WNOHANG) > 0)
647                 {
648                         PDEBUG(DEBUG_EPOINT, "a child process (created by endpoint) has exitted.\n");
649                         all_idle = 0;
650                 }
651 #endif
652 #warning debugging usleep crash
653                 debug_usleep(1, __FILE__, __LINE__, now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec);
654
655                 /* do idle checking */
656                 if (idlecheck != now)
657                 {
658                         PDEBUG(DEBUG_IDLETIME, "Idle time : %d%%\n", idletime/10000);
659                         idletime = 0;
660                         idlecheck = now;
661                 }
662 #ifdef DEBUG_DURATION
663                 GET_NOW();
664                 idle_duration += (now_d - start_d);
665                 start_d = now_d;
666                 if (durationupdate != now)
667                 {
668                         durationupdate = now;
669                         printf("Idle:%3d ISDN:%3d Port:%3d Epoint:%3d Join:%3d Message:%3d Admin:%3d\n",
670                                 (int)(idle_duration*100),
671                                 (int)(isdn_duration*100),
672                                 (int)(port_duration*100),
673                                 (int)(epoint_duration*100),
674                                 (int)(join_duration*100),
675                                 (int)(message_duration*100),
676                                 (int)(admin_duration*100));
677                         idle_duration = isdn_duration = port_duration = epoint_duration = join_duration = message_duration = admin_duration = 0;
678                 }
679 #else
680                 GET_NOW();
681 #endif
682
683                 /* did we do nothing? so we wait to give time to other processes */
684                 if (all_idle)
685                 {
686                         debug_usleep(4000, __FILE__, __LINE__, now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec);
687                         idletime += 4000;
688                 }
689         }
690         SPRINT(tracetext, "%s terminated", NAME);
691         printf("%s\n", tracetext);
692         start_trace(0, NULL, NULL, NULL, 0, 0, 0, tracetext);
693         if (ret)
694                 add_trace("error", NULL, "%d", ret);
695         end_trace();
696         ret=0;
697
698         /* free all */
699 free:
700
701
702         /* set scheduler & priority
703          */
704         if (options.schedule > 1)
705         {
706                 memset(&schedp, 0, sizeof(schedp));
707                 schedp.sched_priority = 0;
708                 sched_setscheduler(0, SCHED_OTHER, &schedp);
709         }
710         /* reset signals */
711         if (created_signal)
712         {
713                 signal(SIGINT,SIG_DFL);
714                 signal(SIGHUP,SIG_DFL);
715                 signal(SIGTERM,SIG_DFL);
716                 signal(SIGPIPE,SIG_DFL);
717         }
718
719         /* destroy objects */
720         debug_prefix = "free";
721
722         while(port_first)
723         {
724                 debug_count++;
725                 delete port_first;
726         }
727         while(epoint_first)
728         {
729                 debug_count++;
730                 delete epoint_first;
731         }
732         epoint_first = NULL;
733         debug_count++;
734         join_free();
735
736         /* free interfaces */
737         if (interface_first)
738                 free_interfaces(interface_first);
739         interface_first = NULL;
740
741         /* close isdn ports */
742         mISDNport_close_all();
743
744         /* flush messages */
745         debug_count++;
746         i = 0;
747         while ((message = message_get()))
748         {
749                 i++;
750                 message_free(message);
751         }
752         if (i)
753         {
754                 PDEBUG(DEBUG_MSG, "freed %d pending messages\n", i);
755         }
756
757         /* free tones */
758         if (toneset_first)
759                 free_tones();
760
761         /* free admin socket */
762         admin_cleanup();
763
764         /* close lock */
765         if (created_lock)
766                 flock(lockfd, LOCK_UN);
767         if (lockfd >= 0)
768                 close(lockfd);
769
770         /* free rulesets */
771         if (ruleset_first)
772                 ruleset_free(ruleset_first);
773         ruleset_first = NULL;
774
775         /* free mutex */
776         if (created_mutexe)
777                 if (pthread_mutex_destroy(&mutexe))
778                         fprintf(stderr, "cannot destroy 'PERROR' mutex\n");
779 //      if (created_mutext)
780 //              if (pthread_mutex_destroy(&mutext))
781 //                      fprintf(stderr, "cannot destroy 'trace' mutex\n");
782         if (created_mutexd)
783                 if (pthread_mutex_destroy(&mutexd))
784                         fprintf(stderr, "cannot destroy 'PDEBUG' mutex\n");
785
786         /* deinitialize mISDN */
787         mISDN_deinitialize();
788         global_debug = 0;
789
790         /* display memory leak */
791 #define MEMCHECK(a, b) \
792         if (b) \
793         { \
794                 SPRINT(tracetext, a, NAME); \
795                 start_trace(0, NULL, NULL, NULL, 0, 0, 0, tracetext); \
796                 if (ret) add_trace("blocks", NULL, "%d", b); \
797                 end_trace(); \
798                 printf("\n******************************\n\007"); \
799                 printf("\nERROR: %d %s\n", b, a); \
800                 printf("\n******************************\n"); \
801                 ret = -1; \
802         }
803         MEMCHECK("",memuse)
804         MEMCHECK("memory block(s) left (port.cpp ...)",pmemuse)
805         MEMCHECK("memory block(s) left (epoint*.cpp ...)",ememuse)
806         MEMCHECK("memory block(s) left (join*.cpp)",cmemuse)
807         MEMCHECK("memory block(s) left (message.c)",mmemuse)
808         MEMCHECK("memory block(s) left (route.c)",rmemuse)
809         MEMCHECK("memory block(s) left (args)",amemuse)
810         MEMCHECK("class(es) left",classuse)
811         MEMCHECK("file descriptor(s) left",fduse)
812         MEMCHECK("file handler(s) left",fhuse)
813
814         /* take me out */
815         return(ret);
816 }
817
818
819 #ifdef BUDETECT_DEF
820 /* special debug function to detect buffer overflow
821  */
822 int budetect_stop = 0;
823 void budetect(const char *file, int line, char *function)
824 {
825         if (budetect_stop)
826                 return;
827         /* modify this function to detect race-bugs */
828 #warning DID YOU MODIFY THIS FUNCTION TO DETECT THE BUFFER OVERFLOW BUG?
829         class Port *port;
830         class PmISDN *pmisdn;
831         struct mISDNport *mISDNport = mISDNport_first;
832         int i, ii;
833
834         while(mISDNport)
835         {
836                 i = 0;
837                 ii = mISDNport->b_num;
838                 while(i < ii)
839                 {
840                         if (mISDNport->b_port[i])
841                         {
842                                 port = port_first;
843                                 while(port)
844                                 {
845                                         if ((port->p_type&PORT_CLASS_MASK) == PORT_CLASS_ISDN)
846                                         {
847                                                 pmisdn = (class PmISDN *)port;
848                                                 if (pmisdn->p_isdn_crypt_listen)
849                                                 {
850                                                         PERROR_RUNTIME("************************************************\n");
851                                                         PERROR_RUNTIME("** BUG detected in %s, line %d, function %s\n", file, line, function);
852                                                         PERROR_RUNTIME("** p_isdn_crypt_listen = %d\n", pmisdn->p_isdn_crypt_listen);
853                                                         PERROR_RUNTIME("************************************************\n");
854                                                         budetect_stop = 1;
855                                                 }
856                                         }
857                                         if (port == mISDNport->b_port[i])
858                                                 break;
859                                         port = port->next;
860                                         if (!port)
861                                         {
862                                                 PERROR_RUNTIME("************************************************\n");
863                                                 PERROR_RUNTIME("** BUG detected in %s, line %d, function %s\n", file, line, function);
864                                                 PERROR_RUNTIME("** b_port not in list.\n");
865                                                 PERROR_RUNTIME("************************************************\n");
866                                                 budetect_stop = 1;
867                                         }
868                                 }
869                         }
870                         i++;
871                 }
872                 mISDNport = mISDNport->next;
873         }
874
875 }
876 #endif
877