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