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