- fix Building without Nagra not possible at Nagra_Merlin https://trac.streamboard...
[oscam.git] / oscam.c
blob7a9220898f6571be8b2916bf29816d853e1d7afa
1 #define MODULE_LOG_PREFIX "main"
3 #include "globals.h"
4 #include <getopt.h>
6 #include "csctapi/cardreaders.h"
7 #include "modules.h"
8 #include "readers.h"
10 #include "extapi/coolapi.h"
11 #include "module-anticasc.h"
12 #include "module-cacheex.h"
13 #include "module-cccam.h"
14 #include "module-dvbapi.h"
15 #include "module-dvbapi-azbox.h"
16 #include "module-dvbapi-mca.h"
17 #include "module-dvbapi-chancache.h"
18 #include "module-gbox-sms.h"
19 #include "module-lcd.h"
20 #include "module-led.h"
21 #include "module-stat.h"
22 #include "module-webif.h"
23 #include "module-webif-tpl.h"
24 #include "module-cw-cycle-check.h"
25 #include "module-streamrelay.h"
26 #include "oscam-chk.h"
27 #include "oscam-cache.h"
28 #include "oscam-client.h"
29 #include "oscam-config.h"
30 #include "oscam-ecm.h"
31 #include "oscam-emm.h"
32 #include "oscam-emm-cache.h"
33 #include "oscam-files.h"
34 #include "oscam-garbage.h"
35 #include "oscam-lock.h"
36 #include "oscam-net.h"
37 #include "oscam-reader.h"
38 #include "oscam-string.h"
39 #include "oscam-time.h"
40 #include "oscam-work.h"
41 #include "reader-common.h"
42 #include "module-gbox.h"
44 #ifdef WITH_SSL
45 #include <openssl/crypto.h>
46 #include <openssl/ssl.h>
47 #include <openssl/err.h>
49 static void ssl_init(void)
51 SSL_load_error_strings();
52 ERR_load_BIO_strings();
53 ERR_load_SSL_strings();
54 SSL_library_init();
57 static void ssl_done(void)
59 #if OPENSSL_VERSION_NUMBER < 0x1010005fL
60 ERR_remove_state(0);
61 #endif
62 ERR_free_strings();
63 EVP_cleanup();
64 CRYPTO_cleanup_all_ex_data();
67 #else
68 static void ssl_init(void) { }
69 static void ssl_done(void) { }
70 #endif
72 extern char *config_mak;
74 /*****************************************************************************
75 Globals
76 *****************************************************************************/
77 const char *syslog_ident = "oscam";
78 static char *oscam_pidfile;
79 static char default_pidfile[64];
81 int32_t exit_oscam = 0;
82 static struct s_module modules[CS_MAX_MOD];
84 struct s_client *first_client = NULL; // Pointer to clients list, first client is master
85 struct s_reader *first_active_reader = NULL; // list of active readers (enable=1 deleted = 0)
86 LLIST *configured_readers = NULL; // list of all (configured) readers
88 char cs_confdir[128];
89 uint16_t cs_dblevel = 0; // Debug Level
90 int32_t thread_pipe[2] = {0, 0};
91 static int8_t cs_restart_mode = 1; // Restartmode: 0=off, no restart fork, 1=(default)restart fork, restart by webif, 2=like=1, but also restart on segfaults
92 static int8_t cs_capture_SEGV;
93 static int8_t cs_dump_stack;
94 static uint16_t cs_waittime = 60;
95 char cs_tmpdir[200];
96 CS_MUTEX_LOCK system_lock;
97 CS_MUTEX_LOCK config_lock;
98 CS_MUTEX_LOCK gethostbyname_lock;
99 CS_MUTEX_LOCK clientlist_lock;
100 CS_MUTEX_LOCK readerlist_lock;
101 CS_MUTEX_LOCK fakeuser_lock;
102 CS_MUTEX_LOCK readdir_lock;
103 CS_MUTEX_LOCK cwcycle_lock;
104 pthread_key_t getclient;
105 static int32_t bg;
106 static int32_t gbdb;
107 static int32_t max_pending = 32;
109 // ecms list
110 CS_MUTEX_LOCK ecmcache_lock;
111 struct ecm_request_t *ecmcwcache = NULL;
112 uint32_t ecmcwcache_size = 0;
114 // pushout deleted list
115 CS_MUTEX_LOCK ecm_pushed_deleted_lock;
116 struct ecm_request_t *ecm_pushed_deleted = NULL;
118 struct s_config cfg;
120 int log_remove_sensitive = 1;
122 static char *prog_name;
123 static char *stb_boxtype;
124 static char *stb_boxname;
126 static int32_t oscam_stacksize = 0;
128 /*****************************************************************************
129 Statics
130 *****************************************************************************/
131 /* Prints usage information and information about the built-in modules. */
132 static void show_usage(void)
134 printf("%s",
135 " ___ ____ ___\n"
136 " / _ \\/ ___| / __|__ _ _ __ ___\n"
137 "| | | \\___ \\| | / _` | '_ ` _ \\\n"
138 "| |_| |___) | |_| (_| | | | | | |\n"
139 " \\___/|____/ \\___\\__,_|_| |_| |_|\n\n");
140 printf("OSCam Cardserver v%s, build r%s (%s)\n", CS_VERSION, CS_SVN_VERSION, CS_TARGET);
141 printf("Copyright (C) 2009-2024 OSCam developers.\n");
142 printf("This program is distributed under GPLv3.\n");
143 printf("OSCam is based on Streamboard mp-cardserver v0.9d written by dukat\n");
144 printf("Visit https://board.streamboard.tv/ for more details.\n\n");
146 printf(" ConfigDir : %s\n", CS_CONFDIR);
147 printf("\n");
148 printf(" Usage: oscam [parameters]\n");
149 printf("\n Directories:\n");
150 printf(" -c, --config-dir <dir> | Read configuration files from <dir>.\n");
151 printf(" . Default: %s\n", CS_CONFDIR);
152 printf(" -t, --temp-dir <dir> | Set temporary directory to <dir>.\n");
153 #if defined(__CYGWIN__)
154 printf(" . Default: (OS-TMP)\n");
155 #else
156 printf(" . Default: /tmp/.oscam\n");
157 #endif
158 printf("\n Startup:\n");
159 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
160 printf(" -f, --foreground | Start in the foreground mode.\n");
161 #else
162 printf(" -b, --daemon | Start in the background as daemon.\n");
163 #endif
164 printf(" -B, --pidfile <pidfile> | Create pidfile when starting.\n");
165 if(config_enabled(WEBIF))
167 printf(" -r, --restart <level> | Set restart level:\n");
168 printf(" . 0 - Restart disabled (exit on restart request).\n");
169 printf(" . 1 - WebIf restart is active (default).\n");
170 printf(" . 2 - Like 1, but also restart on segfaults.\n");
172 printf(" -w, --wait <secs> | Set how much seconds to wait at startup for the\n");
173 printf(" . system clock to be set correctly. Default: 60\n");
174 printf("\n Logging:\n");
175 printf(" -I, --syslog-ident <ident> | Set syslog ident. Default: oscam\n");
176 printf(" -S, --show-sensitive | Do not filter sensitive info (card serials, boxids)\n");
177 printf(" . from the logs.\n");
178 printf(" -d, --debug <level> | Set debug level mask used for logging:\n");
179 printf(" . 0 - No extra debugging (default).\n");
180 printf(" . 1 - Detailed error messages.\n");
181 printf(" . 2 - ATR parsing info, ECM, EMM and CW dumps.\n");
182 printf(" . 4 - Traffic from/to the reader.\n");
183 printf(" . 8 - Traffic from/to the clients.\n");
184 printf(" . 16 - Traffic to the reader-device on IFD layer.\n");
185 printf(" . 32 - Traffic to the reader-device on I/O layer.\n");
186 printf(" . 64 - EMM logging.\n");
187 printf(" . 128 - DVBAPI logging.\n");
188 printf(" . 256 - Loadbalancer logging.\n");
189 printf(" . 512 - CACHEEX logging.\n");
190 printf(" . 1024 - Client ECM logging.\n");
191 printf(" . 2048 - CSP logging.\n");
192 printf(" . 4096 - CWC logging.\n");
193 #ifdef CS_CACHEEX_AIO
194 printf(" . 8192 - CW Cache logging.\n");
195 #endif
196 printf(" . 65535 - Debug all.\n");
197 printf("\n Settings:\n");
198 printf(" -p, --pending-ecm <num> | Set the maximum number of pending ECM packets.\n");
199 printf(" . Default: 32 Max: 4096\n");
200 printf("\n Debug parameters:\n");
201 printf(" -a, --crash-dump | Write oscam.crash file on segfault. This option\n");
202 printf(" . needs GDB to be installed and OSCam executable to\n");
203 printf(" . contain the debug information (run oscam-XXXX.debug)\n");
204 printf(" -s, --capture-segfaults | Capture segmentation faults.\n");
205 printf(" -g, --gcollect <mode> | Garbage collector debug mode:\n");
206 printf(" . 1 - Immediate free.\n");
207 printf(" . 2 - Check for double frees.\n");
208 printf("\n Information:\n");
209 printf(" -h, --help | Show command line help text.\n");
210 printf(" -V, --build-info | Show OSCam binary configuration and version.\n");
213 /* Keep the options sorted */
214 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
215 static const char short_options[] = "aB:fc:d:g:hI:p:r:Sst:uVw:";
216 #else
217 static const char short_options[] = "aB:bc:d:g:hI:p:r:Sst:uVw:";
218 #endif
220 /* Keep the options sorted by short option */
221 static const struct option long_options[] =
223 { "crash-dump", no_argument, NULL, 'a' },
224 { "pidfile", required_argument, NULL, 'B' },
225 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
226 { "foreground", no_argument, NULL, 'f' },
227 #else
228 { "daemon", no_argument, NULL, 'b' },
229 #endif
230 { "config-dir", required_argument, NULL, 'c' },
231 { "debug", required_argument, NULL, 'd' },
232 { "gcollect", required_argument, NULL, 'g' },
233 { "help", no_argument, NULL, 'h' },
234 { "syslog-ident", required_argument, NULL, 'I' },
235 { "pending-ecm", required_argument, NULL, 'p' },
236 { "restart", required_argument, NULL, 'r' },
237 { "show-sensitive", no_argument, NULL, 'S' },
238 { "capture-segfaults", no_argument, NULL, 's' },
239 { "temp-dir", required_argument, NULL, 't' },
240 { "build-info", no_argument, NULL, 'V' },
241 { "wait", required_argument, NULL, 'w' },
242 { 0, 0, 0, 0 }
245 static void set_default_dirs_first(void)
247 snprintf(cs_confdir, sizeof(cs_confdir), "%s", CS_CONFDIR);
248 memset(cs_tmpdir, 0, sizeof(cs_tmpdir)); // will get further procesed trought oscam_files.c !!
251 static void write_versionfile(bool use_stdout);
253 static void parse_cmdline_params(int argc, char **argv)
255 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
256 bg = 1;
257 #endif
259 int i;
260 while((i = getopt_long(argc, argv, short_options, long_options, NULL)) != EOF)
262 if(i == '?')
263 { fprintf(stderr, "ERROR: Unknown command line parameter: %s\n", argv[optind - 1]); }
264 switch(i)
266 case 'a': // --crash-dump
267 cs_dump_stack = 1;
268 break;
269 case 'B': // --pidfile
270 oscam_pidfile = optarg;
271 break;
272 case 'f': // --foreground
273 bg = 0;
274 break;
275 case 'b': // --daemon
276 bg = 1;
277 break;
278 case 'c': // --config-dir
279 cs_strncpy(cs_confdir, optarg, sizeof(cs_confdir));
280 break;
281 case 'd': // --debug
282 cs_dblevel = atoi(optarg);
283 break;
284 case 'g': // --gcollect
285 gbdb = atoi(optarg);
286 break;
287 case 'h': // --help
288 show_usage();
289 exit(EXIT_SUCCESS);
290 break;
291 case 'I': // --syslog-ident
292 syslog_ident = optarg;
293 break;
294 case 'p': // --pending-ecm
295 max_pending = atoi(optarg) <= 0 ? 32 : MIN(atoi(optarg), 4096);
296 break;
297 case 'r': // --restart
298 if(config_enabled(WEBIF))
300 cs_restart_mode = atoi(optarg);
302 break;
303 case 'S': // --show-sensitive
304 log_remove_sensitive = !log_remove_sensitive;
305 break;
306 case 's': // --capture-segfaults
307 cs_capture_SEGV = 1;
308 break;
309 case 't': // --temp-dir
311 mkdir(optarg, S_IRWXU);
312 int j = open(optarg, O_RDONLY);
313 if(j >= 0)
315 close(j);
316 cs_strncpy(cs_tmpdir, optarg, sizeof(cs_tmpdir));
318 else
320 printf("WARNING: Temp dir does not exist. Using default value.\n");
322 break;
324 case 'V': // --build-info
325 write_versionfile(true);
326 exit(EXIT_SUCCESS);
327 break;
328 case 'w': // --wait
329 cs_waittime = strtoul(optarg, NULL, 10);
330 break;
335 #define write_conf(CONFIG_VAR, text) \
336 fprintf(fp, "%-40s %s\n", text ":", config_enabled(CONFIG_VAR) ? "yes" : "no")
338 #define write_readerconf(CONFIG_VAR, text) \
339 fprintf(fp, "%-40s %s\n", text ":", config_enabled(CONFIG_VAR) ? "yes" : "no - no EMM support!")
341 #define write_cardreaderconf(CONFIG_VAR, text) \
342 fprintf(fp, "%s%-29s %s\n", "cardreader_", text ":", config_enabled(CONFIG_VAR) ? "yes" : "no")
344 static void write_versionfile(bool use_stdout)
346 FILE *fp = stdout;
347 if(!use_stdout)
349 char targetfile[256];
350 fp = fopen(get_tmp_dir_filename(targetfile, sizeof(targetfile), "oscam.version"), "w");
351 if(!fp)
353 cs_log("Cannot open %s (errno=%d %s)", targetfile, errno, strerror(errno));
354 return;
356 struct tm st;
357 time_t walltime = cs_time();
358 localtime_r(&walltime, &st);
359 fprintf(fp, "Unix starttime: %ld\n", walltime);
360 fprintf(fp, "Starttime: %02d.%02d.%04d %02d:%02d:%02d\n",
361 st.tm_mday, st.tm_mon + 1, st.tm_year + 1900,
362 st.tm_hour, st.tm_min, st.tm_sec);
365 fprintf(fp, "Version: oscam-%s-r%s\n", CS_VERSION, CS_SVN_VERSION);
366 fprintf(fp, "Compiler: %s\n", CS_TARGET);
367 fprintf(fp, "Box type: %s (%s)\n", boxtype_get(), boxname_get());
368 fprintf(fp, "PID: %d\n", getppid());
369 fprintf(fp, "TempDir: %s\n", cs_tmpdir);
370 #ifdef MODULE_GBOX
371 if(cfg.gbox_tmp_dir == NULL)
373 fprintf(fp, "GBox tmp_dir: not defined using: %s\n", cs_tmpdir);
375 else
377 fprintf(fp, "GBox tmp_dir: %s\n", cfg.gbox_tmp_dir);
379 #endif
381 fprintf(fp, "ConfigDir: %s\n", cs_confdir);
383 #ifdef WEBIF
384 fprintf(fp, "WebifPort: %d\n", cfg.http_port);
385 #endif
387 fprintf(fp, "\n");
388 write_conf(WEBIF, "Web interface support");
389 write_conf(WEBIF_LIVELOG, "LiveLog support");
390 write_conf(WEBIF_JQUERY, "jQuery support intern");
391 write_conf(WITH_SSL, "SSL support");
392 write_conf(HAVE_DVBAPI, "DVB API support");
393 if(config_enabled(HAVE_DVBAPI))
395 if(config_enabled(MODULE_STREAMRELAY))
397 write_conf(true, "DVB API with Stream Relay support");
399 write_conf(WITH_AZBOX, "DVB API with AZBOX support");
400 write_conf(WITH_MCA, "DVB API with MCA support");
401 write_conf(WITH_COOLAPI, "DVB API with COOLAPI support");
402 write_conf(WITH_COOLAPI2, "DVB API with COOLAPI2 support");
403 write_conf(WITH_STAPI, "DVB API with STAPI support");
404 write_conf(WITH_STAPI5, "DVB API with STAPI5 support");
405 write_conf(WITH_NEUTRINO, "DVB API with NEUTRINO support");
406 write_conf(READ_SDT_CHARSETS, "DVB API read-sdt charsets");
408 write_conf(CS_ANTICASC, "Anti-cascading support");
409 write_conf(WITH_DEBUG, "Debug mode");
410 write_conf(MODULE_MONITOR, "Monitor");
411 write_conf(WITH_LB, "Loadbalancing support");
412 write_conf(CS_CACHEEX, "Cache exchange support");
413 #ifdef CS_CACHEEX_AIO
414 write_conf(CS_CACHEEX_AIO, "Cache exchange AIO support");
415 #endif
416 write_conf(CW_CYCLE_CHECK, "CW Cycle Check support");
417 write_conf(LCDSUPPORT, "LCD support");
418 write_conf(LEDSUPPORT, "LED support");
419 switch (cs_getclocktype())
421 case CLOCK_TYPE_UNKNOWN : write_conf(CLOCKFIX, "Clockfix with UNKNOWN clock"); break;
422 case CLOCK_TYPE_REALTIME : write_conf(CLOCKFIX, "Clockfix with realtime clock"); break;
423 case CLOCK_TYPE_MONOTONIC: write_conf(CLOCKFIX, "Clockfix with monotonic clock"); break;
425 write_conf(IPV6SUPPORT, "IPv6 support");
426 #if defined(__arm__) || defined(__aarch64__)
427 write_conf(WITH_ARM_NEON, "ARM NEON (SIMD/MPE) support");
428 #endif
430 fprintf(fp, "\n");
431 write_conf(MODULE_CAMD33, "camd 3.3x");
432 write_conf(MODULE_CAMD35, "camd 3.5 UDP");
433 write_conf(MODULE_CAMD35_TCP, "camd 3.5 TCP");
434 write_conf(MODULE_NEWCAMD, "newcamd");
435 write_conf(MODULE_CCCAM, "CCcam");
436 write_conf(MODULE_CCCSHARE, "CCcam share");
437 write_conf(MODULE_GBOX, "gbox");
438 write_conf(MODULE_RADEGAST, "radegast");
439 write_conf(MODULE_SCAM, "scam");
440 write_conf(MODULE_SERIAL, "serial");
441 write_conf(MODULE_CONSTCW, "constant CW");
442 write_conf(MODULE_PANDORA, "Pandora");
443 write_conf(MODULE_GHTTP, "ghttp");
444 write_conf(MODULE_STREAMRELAY, "Streamrelay");
446 fprintf(fp, "\n");
447 write_conf(WITH_CARDREADER, "Reader support");
448 if(config_enabled(WITH_CARDREADER))
450 fprintf(fp, "\n");
451 write_readerconf(READER_NAGRA, "Nagra");
452 write_readerconf(READER_NAGRA_MERLIN, "Nagra Merlin");
453 write_readerconf(READER_IRDETO, "Irdeto");
454 write_readerconf(READER_CONAX, "Conax");
455 write_readerconf(READER_CRYPTOWORKS, "Cryptoworks");
456 write_readerconf(READER_SECA, "Seca");
457 write_readerconf(READER_VIACCESS, "Viaccess");
458 write_readerconf(READER_VIDEOGUARD, "NDS Videoguard");
459 write_readerconf(READER_DRE, "DRE Crypt");
460 write_readerconf(READER_TONGFANG, "TONGFANG");
461 write_readerconf(READER_BULCRYPT, "Bulcrypt");
462 write_readerconf(READER_GRIFFIN, "Griffin");
463 write_readerconf(READER_DGCRYPT, "DGCrypt");
464 fprintf(fp, "\n");
465 write_cardreaderconf(CARDREADER_PHOENIX, "phoenix");
466 write_cardreaderconf(CARDREADER_DRECAS, "drecas");
467 write_cardreaderconf(CARDREADER_INTERNAL_AZBOX, "internal_azbox");
468 write_cardreaderconf(CARDREADER_INTERNAL_COOLAPI, "internal_coolapi");
469 write_cardreaderconf(CARDREADER_INTERNAL_COOLAPI2, "internal_coolapi2");
470 write_cardreaderconf(CARDREADER_INTERNAL_SCI, "internal_sci");
471 write_cardreaderconf(CARDREADER_SC8IN1, "sc8in1");
472 write_cardreaderconf(CARDREADER_MP35, "mp35");
473 write_cardreaderconf(CARDREADER_SMARGO, "smargo");
474 write_cardreaderconf(CARDREADER_PCSC, "pcsc");
475 write_cardreaderconf(CARDREADER_SMART, "smartreader");
476 write_cardreaderconf(CARDREADER_DB2COM, "db2com");
477 write_cardreaderconf(CARDREADER_STAPI, "stapi");
478 write_cardreaderconf(CARDREADER_STAPI5, "stapi5");
479 write_cardreaderconf(CARDREADER_STINGER, "stinger");
481 else
483 write_readerconf(WITH_CARDREADER, "Reader Support");
485 if(!use_stdout)
486 { fclose(fp); }
488 #undef write_conf
489 #undef write_readerconf
490 #undef write_cardreaderconf
492 static void remove_versionfile(void)
494 char targetfile[256];
495 unlink(get_tmp_dir_filename(targetfile, sizeof(targetfile), "oscam.version"));
498 #define report_emm_support(CONFIG_VAR, text) \
499 do { \
500 if (!config_enabled(CONFIG_VAR)) \
501 cs_log_dbg(D_TRACE, "Binary without %s module - no EMM processing for %s possible!", text, text); \
502 } while(0)
504 static void do_report_emm_support(void)
506 if(!config_enabled(WITH_CARDREADER))
508 cs_log("Binary without Cardreader Support! No EMM processing possible!");
510 else
512 report_emm_support(READER_NAGRA, "Nagra");
513 report_emm_support(READER_NAGRA_MERLIN, "Nagra Merlin");
514 report_emm_support(READER_IRDETO, "Irdeto");
515 report_emm_support(READER_CONAX, "Conax");
516 report_emm_support(READER_CRYPTOWORKS, "Cryptoworks");
517 report_emm_support(READER_SECA, "Seca");
518 report_emm_support(READER_VIACCESS, "Viaccess");
519 report_emm_support(READER_VIDEOGUARD, "NDS Videoguard");
520 report_emm_support(READER_DRE, "DRE Crypt");
521 report_emm_support(READER_TONGFANG, "TONGFANG");
522 report_emm_support(READER_BULCRYPT, "Bulcrypt");
523 report_emm_support(READER_GRIFFIN, "Griffin");
524 report_emm_support(READER_DGCRYPT, "DGCrypt");
527 #undef report_emm_support
529 #ifdef NEED_DAEMON
530 // The compat function is not called daemon() because this may cause problems.
531 static int32_t do_daemon(int32_t nochdir, int32_t noclose)
533 int32_t fd;
535 switch(fork())
537 case -1:
538 return (-1);
539 case 0:
540 break;
541 default:
542 _exit(0);
545 if(setsid() == (-1))
546 { return (-1); }
548 if(!nochdir)
549 { (void)chdir("/"); }
551 if(!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1)
553 (void)dup2(fd, STDIN_FILENO);
554 (void)dup2(fd, STDOUT_FILENO);
555 (void)dup2(fd, STDERR_FILENO);
556 if(fd > 2)
557 { (void)close(fd); }
559 return (0);
561 #else
562 #define do_daemon daemon
563 #endif
566 * flags: 1 = restart, 2 = don't modify if SIG_IGN, may be combined
568 static void set_signal_handler(int32_t sig, int32_t flags, void (*sighandler))
570 struct sigaction sa;
571 sigaction(sig, (struct sigaction *) 0, &sa);
572 if(!((flags & 2) && (sa.sa_handler == SIG_IGN)))
574 sigemptyset(&sa.sa_mask);
575 sa.sa_flags = (flags & 1) ? SA_RESTART : 0;
576 sa.sa_handler = sighandler;
577 sigaction(sig, &sa, (struct sigaction *) 0);
581 static void cs_master_alarm(void)
583 cs_log("PANIC: master deadlock!");
584 fprintf(stderr, "PANIC: master deadlock!");
585 fflush(stderr);
588 static void cs_sigpipe(void)
590 if(cs_dblevel & D_ALL_DUMP)
591 { cs_log("Got sigpipe signal -> captured"); }
594 static void cs_dummy(void)
596 return;
599 /* Switch debuglevel forward one step (called when receiving SIGUSR1). */
600 static void cs_debug_level(void)
602 switch(cs_dblevel)
604 case 0:
605 cs_dblevel = 1;
606 break;
607 case 128:
608 cs_dblevel = 255;
609 break;
610 case 255:
611 cs_dblevel = 0;
612 break;
613 default:
614 cs_dblevel <<= 1;
617 cs_log("debug_level=%d", cs_dblevel);
621 * write stacktrace to oscam.crash. file is always appended
622 * Usage:
623 * 1. compile oscam with debug parameters (Makefile: DS_OPTS="-ggdb")
624 * 2. you need gdb installed and working on the local machine
625 * 3. start oscam with parameter: -a
627 static void cs_dumpstack(int32_t sig)
629 FILE *fp = fopen("oscam.crash", "a+");
631 time_t timep;
632 char buf[200];
634 time(&timep);
635 cs_ctime_r(&timep, buf);
637 fprintf(stderr, "crashed with signal %d on %swriting oscam.crash\n", sig, buf);
639 fprintf(fp, "%sOSCam cardserver v%s, build r%s (%s)\n", buf, CS_VERSION, CS_SVN_VERSION, CS_TARGET);
640 fprintf(fp, "FATAL: Signal %d: %s Fault. Logged StackTrace:\n\n", sig, (sig == SIGSEGV) ? "Segmentation" : ((sig == SIGBUS) ? "Bus" : "Unknown"));
641 fclose(fp);
643 FILE *cmd = fopen("/tmp/gdbcmd", "w");
644 fputs("bt\n", cmd);
645 fputs("thread apply all bt\n", cmd);
646 fclose(cmd);
648 snprintf(buf, sizeof(buf) - 1, "gdb %s %d -batch -x /tmp/gdbcmd >> oscam.crash", prog_name, getpid());
649 if(system(buf) == -1)
650 { fprintf(stderr, "Fatal error on trying to start gdb process."); }
652 exit(-1);
657 * called by signal SIGHUP
659 * reloads configs:
660 * - useraccounts (oscam.user)
661 * - readers (oscam.server)
662 * - services ids (oscam.srvid)
663 * - tier ids (oscam.tiers)
664 * Also clears anticascading stats.
666 static void cs_reload_config(void)
668 static pthread_mutex_t mutex;
669 static int8_t mutex_init = 0;
671 if(!mutex_init)
673 SAFE_MUTEX_INIT(&mutex, NULL);
674 mutex_init = 1;
677 if(pthread_mutex_trylock(&mutex))
679 return;
682 if(cfg.reload_useraccounts)
684 cs_accounts_chk();
687 if(cfg.reload_readers)
689 reload_readerdb();
692 if(cfg.reload_provid)
694 init_provid();
697 if(cfg.reload_services_ids)
699 init_srvid();
702 if(cfg.reload_tier_ids)
704 init_tierid();
707 if(cfg.reload_fakecws)
709 init_fakecws();
712 if(cfg.reload_ac_stat)
714 ac_init_stat();
717 if(cfg.reload_log)
719 cs_reopen_log(); // FIXME: aclog.log, emm logs, cw logs (?)
722 SAFE_MUTEX_UNLOCK(&mutex);
725 /* Sets signal handlers to ignore for early startup of OSCam because for example log
726 could cause SIGPIPE errors and the normal signal handlers can't be used at this point. */
727 static void init_signal_pre(void)
729 set_signal_handler(SIGPIPE , 1, SIG_IGN);
730 set_signal_handler(SIGWINCH, 1, SIG_IGN);
731 set_signal_handler(SIGALRM , 1, SIG_IGN);
732 set_signal_handler(SIGHUP , 1, SIG_IGN);
735 /* Sets the signal handlers.*/
736 static void init_signal(void)
738 set_signal_handler(SIGINT, 3, cs_exit);
739 #if defined(__APPLE__)
740 set_signal_handler(SIGEMT, 3, cs_exit);
741 #endif
742 set_signal_handler(SIGTERM, 3, cs_exit);
744 set_signal_handler(SIGWINCH, 1, SIG_IGN);
745 set_signal_handler(SIGPIPE, 0, cs_sigpipe);
746 set_signal_handler(SIGALRM, 0, cs_master_alarm);
747 set_signal_handler(SIGHUP, 1, cs_reload_config);
748 set_signal_handler(SIGUSR1, 1, cs_debug_level);
749 set_signal_handler(SIGUSR2, 1, cs_card_info);
750 set_signal_handler(OSCAM_SIGNAL_WAKEUP, 0, cs_dummy);
752 if(cs_capture_SEGV)
754 set_signal_handler(SIGSEGV, 1, cs_exit);
755 set_signal_handler(SIGBUS, 1, cs_exit);
757 else if(cs_dump_stack)
759 set_signal_handler(SIGSEGV, 1, cs_dumpstack);
760 set_signal_handler(SIGBUS, 1, cs_dumpstack);
763 cs_log("signal handling initialized");
764 return;
767 void cs_exit(int32_t sig)
769 if(cs_dump_stack && (sig == SIGSEGV || sig == SIGBUS || sig == SIGQUIT))
770 { cs_dumpstack(sig); }
772 set_signal_handler(SIGHUP , 1, SIG_IGN);
773 set_signal_handler(SIGPIPE, 1, SIG_IGN);
775 struct s_client *cl = cur_client();
776 if(!cl)
777 { return; }
779 // this is very important - do not remove
780 if(cl->typ != 's')
782 cs_log_dbg(D_TRACE, "thread %8lX ended!", (unsigned long)pthread_self());
784 free_client(cl);
786 // Restore signals before exiting thread
787 set_signal_handler(SIGPIPE, 0, cs_sigpipe);
788 set_signal_handler(SIGHUP, 1, cs_reload_config);
790 pthread_exit(NULL);
791 return;
794 if(!exit_oscam)
795 { exit_oscam = sig ? sig : 1; }
798 static char *read_line_from_file(char *fname, char *buf, int bufsz)
800 memset(buf, 0, bufsz);
801 FILE *f = fopen(fname, "r");
802 if (!f)
803 return NULL;
804 while (fgets(buf, bufsz, f))
806 if (strstr(buf,"\n")) // we need only the first line
808 buf[cs_strlen(buf)-1] = '\0';
809 break;
812 fclose(f);
813 if (buf[0])
814 return buf;
815 return NULL;
818 static void init_machine_info(void)
820 struct utsname buffer;
821 if (uname(&buffer) == 0)
823 cs_log("System name = %s", buffer.sysname);
824 cs_log("Host name = %s", buffer.nodename);
825 cs_log("Release = %s", buffer.release);
826 cs_log("Version = %s", buffer.version);
827 cs_log("Machine = %s", buffer.machine);
828 } else {
829 cs_log("ERROR: uname call failed: %s", strerror(errno));
832 #if !defined(__linux__)
833 return;
834 #endif
836 // Linux only functionality
837 char boxtype[128];
838 boxtype[0] = 0;
839 char model[64];
840 model[0] = 0;
841 char vumodel[64];
842 vumodel[0] = 0;
843 int8_t azmodel = 0;
844 FILE *f;
846 if ((f = fopen("/proc/stb/info/azmodel", "r"))){ azmodel = 1; fclose(f);}
847 read_line_from_file("/proc/stb/info/model", model, sizeof(model));
848 read_line_from_file("/proc/stb/info/boxtype", boxtype, sizeof(boxtype));
849 read_line_from_file("/proc/stb/info/vumodel", vumodel, sizeof(vumodel));
850 if (vumodel[0] && !boxtype[0] && !azmodel)
852 snprintf(boxtype, sizeof(boxtype), "vu%s", vumodel);
854 if (!boxtype[0] && azmodel)
855 snprintf(boxtype, sizeof(boxtype), "Azbox-%s", model);
857 // Detect dreambox type
858 if (strcasecmp(buffer.machine, "ppc") == 0 && !model[0] && !boxtype[0])
860 char line[128], *p;
861 int have_dreambox = 0;
862 if ((f = fopen("/proc/cpuinfo", "r")))
864 while (fgets(line, sizeof(line), f))
866 if (strstr(line, "STBx25xx")) have_dreambox++;
867 if (strstr(line, "pvr" )) have_dreambox++;
868 if (strstr(line, "Dreambox")) have_dreambox++;
869 if (strstr(line, "9.80" )) have_dreambox++;
870 if (strstr(line, "63MHz" )) have_dreambox++;
872 fclose(f);
873 have_dreambox = have_dreambox == 5 ? 1 : 0; // Need to find all 5 strings
875 if (have_dreambox)
877 if (read_line_from_file("/proc/meminfo", line, sizeof(line)) && (p = strchr(line, ' ')))
879 unsigned long memtotal = strtoul(p, NULL, 10);
880 if (memtotal > 40000)
881 snprintf(boxtype, sizeof(boxtype), "%s", "dm600pvr");
882 else
883 snprintf(boxtype, sizeof(boxtype), "%s", "dm500");
888 if (!boxtype[0] && !strcasecmp(model, "dm800") && !strcasecmp(buffer.machine, "armv7l"))
889 snprintf(boxtype, sizeof(boxtype), "%s", "su980");
891 if (!boxtype[0])
893 uint8_t *pos;
894 pos = (uint8_t *)memchr(buffer.release, 'd', sizeof(buffer.release));
895 if(pos)
897 if((!memcmp(pos, "dbox2", sizeof("dbox2"))) && !strcasecmp(buffer.machine, "ppc"))
899 snprintf(boxtype, sizeof(boxtype), "%s", "dbox2");
904 if (model[0])
905 cs_log("Stb model = %s", model);
907 if (vumodel[0])
908 cs_log("Stb vumodel = vu%s", vumodel);
910 if (boxtype[0])
912 char boxname[128];
913 if(!strcasecmp(boxtype,"ini-8000am")){snprintf(boxname, sizeof(boxname), "%s", "Atemio Nemesis");}
914 else if(!strcasecmp(boxtype,"ini-9000ru")){snprintf(boxname, sizeof(boxname), "%s", "Sezam Marvel");}
915 else if(!strcasecmp(boxtype,"ini-8000sv")){snprintf(boxname, sizeof(boxname), "%s", "Miraclebox Ultra");}
916 else if(!strcasecmp(boxtype,"ini-9000de")){snprintf(boxname, sizeof(boxname), "%s", "Xpeed LX3");}
917 else boxname[0] = 0;
918 if(boxname[0]){cs_log("Stb boxname = %s", boxname); stb_boxname = cs_strdup(boxname);}
919 cs_log("Stb boxtype = %s", boxtype);
922 if (boxtype[0])
923 stb_boxtype = cs_strdup(boxtype);
924 else if (model[0])
925 stb_boxtype = cs_strdup(model);
928 const char *boxtype_get(void)
930 return stb_boxtype ? stb_boxtype : "generic";
933 const char *boxname_get(void)
935 return stb_boxname ? stb_boxname : "generic";
938 bool boxtype_is(const char *boxtype)
940 return strcasecmp(boxtype_get(), boxtype) == 0;
943 bool boxname_is(const char *boxname)
945 return strcasecmp(boxname_get(), boxname) == 0;
948 /* Checks if the date of the system is correct and waits if necessary. */
949 static void init_check(void)
951 char *ptr = __DATE__;
952 int32_t month, year = atoi(ptr + cs_strlen(ptr) - 4), day = atoi(ptr + 4);
953 if(day > 0 && day < 32 && year > 2010 && year < 9999)
955 struct tm timeinfo;
956 char months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
957 for(month = 0; month < 12; ++month)
959 if(!strncmp(ptr, months[month], 3)) { break; }
961 if(month > 11) { month = 0; }
962 memset(&timeinfo, 0, sizeof(timeinfo));
963 timeinfo.tm_mday = day;
964 timeinfo.tm_mon = month;
965 timeinfo.tm_year = year - 1900;
966 time_t builddate = mktime(&timeinfo) - 86400;
967 int32_t i = 0;
968 while(time((time_t *)0) < builddate)
970 if(i == 0) { cs_log("The current system time is smaller than the build date (%s). Waiting up to %d seconds for time to correct", ptr, cs_waittime); }
971 cs_sleepms(1000);
972 ++i;
973 if(i > cs_waittime)
975 cs_log("Waiting was not successful. OSCam will be started but is UNSUPPORTED this way. Do not report any errors with this version.");
976 break;
979 // adjust login time of first client
980 if(i > 0) { first_client->login = time((time_t *)0); }
984 #ifdef __linux__
985 #include <sys/prctl.h>
986 // PR_SET_NAME is introduced in 2.6.9 (which is ancient, released 18 Oct 2004)
987 // but apparantly we can't count on having at least that version :(
988 #ifndef PR_SET_NAME
989 #define PR_SET_NAME 15
990 #endif
991 // Set the thread name (comm) under linux (the limit is 16 chars)
992 void set_thread_name(const char *thread_name)
994 prctl(PR_SET_NAME, thread_name, NULL, NULL, NULL);
996 #else
997 void set_thread_name(const char *UNUSED(thread_name)) { }
998 #endif
1001 static void fix_stacksize(void)
1003 // Changing the default stack size is generally a bad idea.
1004 // We are doing it anyway at the moment, because we are using several threads,
1005 // and are running on machnies with little RAM.
1006 // HOWEVER, as we do not know which minimal stack size is needed to run
1007 // oscam without SEQFAULT (stack overflow), this is risky business.
1008 // If after a code change SEQFAULTs related to stack overflow appear,
1009 // increase OSCAM_STACK_MIN or remove the calls to SAFE_ATTR_SETSTACKSIZE.
1011 #ifndef PTHREAD_STACK_MIN
1012 #define PTHREAD_STACK_MIN 64000
1013 #endif
1014 #define OSCAM_STACK_MIN PTHREAD_STACK_MIN + 32768
1016 if(oscam_stacksize < OSCAM_STACK_MIN)
1018 long pagesize = sysconf(_SC_PAGESIZE);
1019 if(pagesize < 1)
1021 oscam_stacksize = OSCAM_STACK_MIN;
1022 return;
1025 oscam_stacksize = ((OSCAM_STACK_MIN) / pagesize + 1) * pagesize;
1029 /* Starts a thread named nameroutine with the start function startroutine. */
1030 int32_t start_thread(char *nameroutine, void *startroutine, void *arg, pthread_t *pthread, int8_t detach, int8_t modify_stacksize)
1032 pthread_t temp;
1033 pthread_attr_t attr;
1035 cs_log_dbg(D_TRACE, "starting thread %s", nameroutine);
1037 SAFE_ATTR_INIT(&attr);
1039 if(modify_stacksize)
1040 { SAFE_ATTR_SETSTACKSIZE(&attr, oscam_stacksize); }
1042 int32_t ret = pthread_create(pthread == NULL ? &temp : pthread, &attr, startroutine, arg);
1043 if(ret)
1044 { cs_log("ERROR: can't create %s thread (errno=%d %s)", nameroutine, ret, strerror(ret)); }
1045 else
1047 cs_log_dbg(D_TRACE, "%s thread started", nameroutine);
1049 if(detach)
1050 { pthread_detach(pthread == NULL ? temp : *pthread); }
1053 pthread_attr_destroy(&attr);
1055 return ret;
1058 int32_t start_thread_nolog(char *nameroutine, void *startroutine, void *arg, pthread_t *pthread, int8_t detach, int8_t modify_stacksize)
1060 pthread_t temp;
1061 pthread_attr_t attr;
1063 SAFE_ATTR_INIT(&attr);
1065 if(modify_stacksize)
1066 { SAFE_ATTR_SETSTACKSIZE(&attr, oscam_stacksize); }
1068 int32_t ret = pthread_create(pthread == NULL ? &temp : pthread, &attr, startroutine, arg);
1069 if(ret)
1070 { fprintf(stderr, "ERROR: can't create %s thread (errno=%d %s)", nameroutine, ret, strerror(ret)); }
1071 else
1073 if(detach)
1074 { pthread_detach(pthread == NULL ? temp : *pthread); }
1077 pthread_attr_destroy(&attr);
1079 return ret;
1082 /* Allows to kill another thread specified through the client cl with locking.
1083 If the own thread has to be cancelled, cs_exit or cs_disconnect_client has to be used. */
1084 void kill_thread(struct s_client *cl)
1086 if(!cl || cl->kill) { return; }
1087 if(cl == cur_client())
1089 cs_log("Trying to kill myself, exiting.");
1090 cs_exit(0);
1092 add_job(cl, ACTION_CLIENT_KILL, NULL, 0); //add kill job, ...
1093 cl->kill = 1; //then set kill flag!
1096 struct s_module *get_module(struct s_client *cl)
1098 return &modules[cl->module_idx];
1101 void module_reader_set(struct s_reader *rdr)
1103 int i;
1104 if(!is_cascading_reader(rdr))
1105 { return; }
1106 for(i = 0; i < CS_MAX_MOD; i++)
1108 struct s_module *module = &modules[i];
1109 if(module->num && module->num == rdr->typ)
1110 rdr->ph = *module;
1114 static void cs_waitforcardinit(void)
1116 if(cfg.waitforcards)
1118 cs_log("waiting for local card init");
1119 int32_t card_init_done;
1122 card_init_done = 1;
1123 struct s_reader *rdr;
1124 LL_ITER itr = ll_iter_create(configured_readers);
1125 while((rdr = ll_iter_next(&itr)))
1127 if(rdr->enable && !is_cascading_reader(rdr) && (rdr->card_status == CARD_NEED_INIT || rdr->card_status == UNKNOWN))
1129 card_init_done = 0;
1130 break;
1134 if(!card_init_done)
1135 { cs_sleepms(300); } // wait a little bit
1136 //alarm(cfg.cmaxidle + cfg.ctimeout / 1000 + 1);
1138 while(!card_init_done && !exit_oscam);
1140 if(cfg.waitforcards_extra_delay > 0 && !exit_oscam)
1141 { cs_sleepms(cfg.waitforcards_extra_delay); }
1142 cs_log("init for all local cards done");
1146 static uint32_t resize_pfd_cllist(struct pollfd **pfd, struct s_client ***cl_list, uint32_t old_size, uint32_t new_size)
1148 if(old_size != new_size)
1150 struct pollfd *pfd_new;
1151 if(!cs_malloc(&pfd_new, new_size * sizeof(struct pollfd)))
1153 return old_size;
1155 struct s_client **cl_list_new;
1156 if(!cs_malloc(&cl_list_new, new_size * sizeof(cl_list)))
1158 NULLFREE(pfd_new);
1159 return old_size;
1161 if(old_size > 0)
1163 memcpy(pfd_new, *pfd, old_size * sizeof(struct pollfd));
1164 memcpy(cl_list_new, *cl_list, old_size * sizeof(cl_list));
1165 NULLFREE(*pfd);
1166 NULLFREE(*cl_list);
1168 *pfd = pfd_new;
1169 *cl_list = cl_list_new;
1171 return new_size;
1174 static uint32_t chk_resize_cllist(struct pollfd **pfd, struct s_client ***cl_list, uint32_t cur_size, uint32_t chk_size)
1176 chk_size++;
1177 if(chk_size > cur_size)
1179 uint32_t new_size = ((chk_size % 100) + 1) * 100; //increase 100 step
1180 cur_size = resize_pfd_cllist(pfd, cl_list, cur_size, new_size);
1182 return cur_size;
1185 static void process_clients(void)
1187 int32_t i, k, j, rc, pfdcount = 0;
1188 struct s_client *cl;
1189 struct s_reader *rdr;
1190 struct pollfd *pfd;
1191 struct s_client **cl_list;
1192 struct timeb start, end; // start time poll, end time poll
1193 uint32_t cl_size = 0;
1195 uint8_t buf[10];
1197 if(pipe(thread_pipe) == -1)
1199 printf("cannot create pipe, errno=%d\n", errno);
1200 exit(1);
1203 cl_size = chk_resize_cllist(&pfd, &cl_list, 0, 100);
1205 pfd[pfdcount].fd = thread_pipe[0];
1206 pfd[pfdcount].events = POLLIN | POLLPRI;
1207 cl_list[pfdcount] = NULL;
1209 while(!exit_oscam)
1211 pfdcount = 1;
1213 // connected tcp clients
1214 for(cl = first_client->next; cl; cl = cl->next)
1216 if(cl->init_done && !cl->kill && cl->pfd && cl->typ == 'c' && !cl->is_udp)
1218 if(cl->pfd && !cl->thread_active)
1220 cl_size = chk_resize_cllist(&pfd, &cl_list, cl_size, pfdcount);
1221 cl_list[pfdcount] = cl;
1222 pfd[pfdcount].fd = cl->pfd;
1223 pfd[pfdcount++].events = POLLIN | POLLPRI;
1226 //reader:
1227 //TCP:
1228 // - TCP socket must be connected
1229 // - no active init thread
1230 //UDP:
1231 // - connection status ignored
1232 // - no active init thread
1233 rdr = cl->reader;
1234 if(rdr && cl->typ == 'p' && cl->init_done)
1236 if(cl->pfd && !cl->thread_active && ((rdr->tcp_connected && rdr->ph.type == MOD_CONN_TCP) || (rdr->ph.type == MOD_CONN_UDP)))
1238 cl_size = chk_resize_cllist(&pfd, &cl_list, cl_size, pfdcount);
1239 cl_list[pfdcount] = cl;
1240 pfd[pfdcount].fd = cl->pfd;
1241 pfd[pfdcount++].events = (POLLIN | POLLPRI);
1246 //server (new tcp connections or udp messages)
1247 for(k = 0; k < CS_MAX_MOD; k++)
1249 struct s_module *module = &modules[k];
1250 if((module->type & MOD_CONN_NET))
1252 for(j = 0; j < module->ptab.nports; j++)
1254 if(module->ptab.ports[j].fd)
1256 cl_size = chk_resize_cllist(&pfd, &cl_list, cl_size, pfdcount);
1257 cl_list[pfdcount] = NULL;
1258 pfd[pfdcount].fd = module->ptab.ports[j].fd;
1259 pfd[pfdcount++].events = (POLLIN | POLLPRI);
1265 if(pfdcount >= 1024)
1266 { cs_log("WARNING: too many users!"); }
1267 cs_ftime(&start); // register start time
1268 rc = poll(pfd, pfdcount, 5000);
1269 if(rc < 1) { continue; }
1270 cs_ftime(&end); // register end time
1272 for(i = 0; i < pfdcount && rc > 0; i++)
1274 if(pfd[i].revents == 0) { continue; } // skip sockets with no changes
1275 rc--; //event handled!
1276 cs_log_dbg(D_TRACE, "[OSCAM] new event %d occurred on fd %d after %"PRId64" ms inactivity", pfd[i].revents,
1277 pfd[i].fd, comp_timeb(&end, &start));
1278 //clients
1279 cl = cl_list[i];
1280 if(cl && !is_valid_client(cl))
1281 { continue; }
1283 if(pfd[i].fd == thread_pipe[0] && (pfd[i].revents & (POLLIN | POLLPRI)))
1285 // a thread ended and cl->pfd should be added to pollfd list again (thread_active==0)
1286 int32_t len = read(thread_pipe[0], buf, sizeof(buf));
1287 if(len == -1)
1289 cs_log_dbg(D_TRACE, "[OSCAM] Reading from pipe failed (errno=%d %s)", errno, strerror(errno));
1291 cs_log_dump_dbg(D_TRACE, buf, len, "[OSCAM] Readed:");
1292 continue;
1295 //clients
1296 // message on an open tcp connection
1297 if(cl && cl->init_done && cl->pfd && (cl->typ == 'c' || cl->typ == 'm'))
1299 if(pfd[i].fd == cl->pfd && (pfd[i].revents & (POLLHUP | POLLNVAL | POLLERR)))
1301 //client disconnects
1302 kill_thread(cl);
1303 continue;
1305 if(pfd[i].fd == cl->pfd && (pfd[i].revents & (POLLIN | POLLPRI)))
1307 add_job(cl, ACTION_CLIENT_TCP, NULL, 0);
1311 //reader
1312 // either an ecm answer, a keepalive or connection closed from a proxy
1313 // physical reader ('r') should never send data without request
1314 rdr = NULL;
1315 struct s_client *cl2 = NULL;
1316 if(cl && cl->typ == 'p')
1318 rdr = cl->reader;
1319 if(rdr)
1320 { cl2 = rdr->client; }
1323 if(rdr && cl2 && cl2->init_done)
1325 if(cl2->pfd && pfd[i].fd == cl2->pfd && (pfd[i].revents & (POLLHUP | POLLNVAL | POLLERR)))
1327 //connection to remote proxy was closed
1328 //oscam should check for rdr->tcp_connected and reconnect on next ecm request sent to the proxy
1329 network_tcp_connection_close(rdr, "closed");
1330 rdr_log_dbg(rdr, D_READER, "connection closed");
1332 if(cl2->pfd && pfd[i].fd == cl2->pfd && (pfd[i].revents & (POLLIN | POLLPRI)))
1334 add_job(cl2, ACTION_READER_REMOTE, NULL, 0);
1338 //server sockets
1339 // new connection on a tcp listen socket or new message on udp listen socket
1340 if(!cl && (pfd[i].revents & (POLLIN | POLLPRI)))
1342 for(k = 0; k < CS_MAX_MOD; k++)
1344 struct s_module *module = &modules[k];
1345 if((module->type & MOD_CONN_NET))
1347 for(j = 0; j < module->ptab.nports; j++)
1349 if(module->ptab.ports[j].fd && module->ptab.ports[j].fd == pfd[i].fd)
1351 accept_connection(module, k, j);
1358 cs_ftime(&start); // register start time for new poll next run
1359 first_client->last = time((time_t *)0);
1361 NULLFREE(pfd);
1362 NULLFREE(cl_list);
1363 return;
1366 static pthread_cond_t reader_check_sleep_cond;
1367 static pthread_mutex_t reader_check_sleep_cond_mutex;
1369 static void *reader_check(void)
1371 struct s_client *cl;
1372 struct s_reader *rdr;
1373 set_thread_name(__func__);
1374 cs_pthread_cond_init(__func__, &reader_check_sleep_cond_mutex, &reader_check_sleep_cond);
1375 while(!exit_oscam)
1377 for(cl = first_client->next; cl ; cl = cl->next)
1379 if(!cl->thread_active)
1380 { client_check_status(cl); }
1382 cs_readlock(__func__, &readerlist_lock);
1383 for(rdr = first_active_reader; rdr; rdr = rdr->next)
1385 if(rdr->enable)
1387 cl = rdr->client;
1388 if(!cl || cl->kill)
1389 { restart_cardreader(rdr, 0); }
1390 else if(!cl->thread_active)
1391 { client_check_status(cl); }
1394 cs_readunlock(__func__, &readerlist_lock);
1395 sleepms_on_cond(__func__, &reader_check_sleep_cond_mutex, &reader_check_sleep_cond, 1000);
1397 return NULL;
1400 static pthread_cond_t card_poll_sleep_cond;
1402 static void * card_poll(void) {
1403 struct s_client *cl;
1404 struct s_reader *rdr;
1405 pthread_mutex_t card_poll_sleep_cond_mutex;
1406 SAFE_MUTEX_INIT(&card_poll_sleep_cond_mutex, NULL);
1407 SAFE_COND_INIT(&card_poll_sleep_cond, NULL);
1408 set_thread_name(__func__);
1409 while (!exit_oscam) {
1410 cs_readlock(__func__, &readerlist_lock);
1411 for (rdr=first_active_reader; rdr; rdr=rdr->next) {
1412 if (rdr->enable && rdr->card_status == CARD_INSERTED) {
1413 cl = rdr->client;
1414 if (cl && !cl->kill)
1415 { add_job(cl, ACTION_READER_POLL_STATUS, 0, 0); }
1418 cs_readunlock(__func__, &readerlist_lock);
1419 struct timespec ts;
1420 struct timeval tv;
1421 gettimeofday(&tv, NULL);
1422 ts.tv_sec = tv.tv_sec;
1423 ts.tv_nsec = tv.tv_usec * 1000;
1424 ts.tv_sec += 1;
1425 SAFE_MUTEX_LOCK(&card_poll_sleep_cond_mutex);
1426 SAFE_COND_TIMEDWAIT(&card_poll_sleep_cond, &card_poll_sleep_cond_mutex, &ts); // sleep on card_poll_sleep_cond
1427 SAFE_MUTEX_UNLOCK(&card_poll_sleep_cond_mutex);
1429 return NULL;
1432 #ifdef WEBIF
1433 static pid_t pid;
1435 static void fwd_sig(int32_t sig)
1437 kill(pid, sig);
1440 static void restart_daemon(void)
1442 while(1)
1444 // start client process:
1445 pid = fork();
1446 if(!pid)
1447 { return; } // client process=oscam process
1448 if(pid < 0)
1449 { exit(1); }
1451 // set signal handler for the restart daemon:
1452 set_signal_handler(SIGINT, 3, fwd_sig);
1453 #if defined(__APPLE__)
1454 set_signal_handler(SIGEMT, 3, fwd_sig);
1455 #endif
1456 set_signal_handler(SIGTERM, 3, fwd_sig);
1457 set_signal_handler(SIGQUIT, 0, fwd_sig);
1458 set_signal_handler(SIGHUP , 0, fwd_sig);
1459 set_signal_handler(SIGUSR1, 0, fwd_sig);
1460 set_signal_handler(SIGUSR2, 0, fwd_sig);
1461 set_signal_handler(SIGALRM , 0, fwd_sig);
1462 set_signal_handler(SIGWINCH, 1, SIG_IGN);
1463 set_signal_handler(SIGPIPE , 0, SIG_IGN);
1464 set_signal_handler(OSCAM_SIGNAL_WAKEUP, 0, SIG_IGN);
1466 // restart control process:
1467 int32_t res = 0;
1468 int32_t status = 0;
1471 res = waitpid(pid, &status, 0);
1472 if(res == -1)
1474 if(errno != EINTR)
1475 { exit(1); }
1478 while(res != pid);
1480 if(cs_restart_mode == 2 && WIFSIGNALED(status) && WTERMSIG(status) == SIGSEGV)
1481 { status = 99; } // restart on segfault!
1482 else
1483 { status = WEXITSTATUS(status); }
1485 // status=99 restart oscam, all other->terminate
1486 if(status != 99)
1488 exit(status);
1493 void cs_restart_oscam(void)
1495 exit_oscam = 99;
1496 cs_log("restart oscam requested");
1499 int32_t cs_get_restartmode(void)
1501 return cs_restart_mode;
1503 #endif
1505 void cs_exit_oscam(void)
1507 exit_oscam = 1;
1508 cs_log("exit oscam requested");
1511 static void pidfile_create(char *pidfile)
1513 FILE *f = fopen(pidfile, "w");
1514 if(f)
1516 pid_t my_pid = getpid();
1517 cs_log("creating pidfile %s with pid %d", pidfile, my_pid);
1518 fprintf(f, "%d\n", my_pid);
1519 fclose(f);
1523 static bool running_under_valgrind;
1525 static void detect_valgrind(void)
1527 #ifdef __linux__
1528 char fname[32];
1529 snprintf(fname, sizeof(fname), "/proc/%d/maps", getpid());
1530 FILE *f = fopen(fname, "r");
1531 if (f) {
1532 char line[256];
1533 while (fgets(line, sizeof(line), f)) {
1534 if (strstr(line, "/valgrind/")) {
1535 running_under_valgrind = true;
1536 break;
1540 fclose(f);
1541 #endif
1544 #ifdef BUILD_TESTS
1545 extern void run_all_tests(void);
1546 __attribute__ ((noreturn)) static void run_tests(void)
1548 run_all_tests();
1549 exit(0);
1551 #else
1552 static void run_tests(void) { }
1553 #endif
1555 const struct s_cardsystem *cardsystems[] =
1557 #ifdef READER_NAGRA
1558 &reader_nagra,
1559 #endif
1560 #ifdef READER_NAGRA_MERLIN
1561 &reader_nagracak7,
1562 #endif
1563 #ifdef READER_IRDETO
1564 &reader_irdeto,
1565 #endif
1566 #ifdef READER_CONAX
1567 &reader_conax,
1568 #endif
1569 #ifdef READER_CRYPTOWORKS
1570 &reader_cryptoworks,
1571 #endif
1572 #ifdef READER_SECA
1573 &reader_seca,
1574 #endif
1575 #ifdef READER_VIACCESS
1576 &reader_viaccess,
1577 #endif
1578 #ifdef READER_VIDEOGUARD
1579 &reader_videoguard1,
1580 &reader_videoguard2,
1581 &reader_videoguard12,
1582 #endif
1583 #ifdef READER_DRE
1584 &reader_dre,
1585 #endif
1586 #ifdef READER_DRECAS
1587 &reader_drecas,
1588 #endif
1589 #ifdef READER_TONGFANG
1590 &reader_tongfang,
1591 #endif
1592 #ifdef READER_BULCRYPT
1593 &reader_bulcrypt,
1594 #endif
1595 #ifdef READER_GRIFFIN
1596 &reader_griffin,
1597 #endif
1598 #ifdef READER_DGCRYPT
1599 &reader_dgcrypt,
1600 #endif
1601 NULL
1604 const struct s_cardreader *cardreaders[] =
1606 #ifdef CARDREADER_DB2COM
1607 &cardreader_db2com,
1608 #endif
1609 #if defined(CARDREADER_INTERNAL_AZBOX)
1610 &cardreader_internal_azbox,
1611 #elif defined(CARDREADER_INTERNAL_COOLAPI)
1612 &cardreader_internal_cool,
1613 #elif defined(CARDREADER_INTERNAL_COOLAPI2)
1614 &cardreader_internal_cool,
1615 #elif defined(CARDREADER_INTERNAL_SCI)
1616 &cardreader_internal_sci,
1617 #endif
1618 #ifdef CARDREADER_PHOENIX
1619 &cardreader_mouse,
1620 #endif
1621 #ifdef CARDREADER_DRECAS
1622 &cardreader_drecas,
1623 #endif
1624 #ifdef CARDREADER_MP35
1625 &cardreader_mp35,
1626 #endif
1627 #ifdef CARDREADER_PCSC
1628 &cardreader_pcsc,
1629 #endif
1630 #ifdef CARDREADER_SC8IN1
1631 &cardreader_sc8in1,
1632 #endif
1633 #ifdef CARDREADER_SMARGO
1634 &cardreader_smargo,
1635 #endif
1636 #ifdef CARDREADER_SMART
1637 &cardreader_smartreader,
1638 #endif
1639 #if defined(CARDREADER_STAPI) || defined(CARDREADER_STAPI5)
1640 &cardreader_stapi,
1641 #endif
1642 #ifdef CARDREADER_STINGER
1643 &cardreader_stinger,
1644 #endif
1645 #ifdef WITH_EMU
1646 &cardreader_emu,
1647 #endif
1649 NULL
1652 static void find_conf_dir(void)
1654 static const char* confdirs[] =
1656 "/etc/tuxbox/config/",
1657 "/etc/tuxbox/config/oscam/",
1658 "/var/tuxbox/config/",
1659 "/usr/keys/",
1660 "/var/keys/",
1661 "/var/etc/oscam/",
1662 "/var/etc/",
1663 "/var/oscam/",
1664 "/config/oscam/",
1665 NULL
1668 char conf_file[128+16];
1669 int32_t i;
1671 if(cs_confdir[cs_strlen(cs_confdir) - 1] != '/')
1672 { cs_strncat(cs_confdir, "/", sizeof(cs_confdir)); }
1674 if(snprintf(conf_file, sizeof(conf_file), "%soscam.conf", cs_confdir) < 0)
1675 { return; }
1677 if(!access(conf_file, F_OK))
1678 { return; }
1680 for(i=0; confdirs[i] != NULL; i++)
1682 if(snprintf(conf_file, sizeof(conf_file), "%soscam.conf", confdirs[i]) < 0)
1683 { return; }
1685 if (!access(conf_file, F_OK))
1687 cs_strncpy(cs_confdir, confdirs[i], sizeof(cs_confdir));
1688 return;
1693 int32_t main(int32_t argc, char *argv[])
1695 fix_stacksize();
1697 run_tests();
1698 int32_t i, j;
1699 prog_name = argv[0];
1700 struct timespec start_ts;
1701 cs_gettime(&start_ts); // Initialize clock_type
1703 if(pthread_key_create(&getclient, NULL))
1705 fprintf(stderr, "Could not create getclient, exiting...");
1706 exit(1);
1709 void (*mod_def[])(struct s_module *) =
1711 #ifdef MODULE_MONITOR
1712 module_monitor,
1713 #endif
1714 #ifdef MODULE_CAMD33
1715 module_camd33,
1716 #endif
1717 #ifdef MODULE_CAMD35
1718 module_camd35,
1719 #endif
1720 #ifdef MODULE_CAMD35_TCP
1721 module_camd35_tcp,
1722 #endif
1723 #ifdef MODULE_NEWCAMD
1724 module_newcamd,
1725 #endif
1726 #ifdef MODULE_CCCAM
1727 module_cccam,
1728 #endif
1729 #ifdef MODULE_PANDORA
1730 module_pandora,
1731 #endif
1732 #ifdef MODULE_GHTTP
1733 module_ghttp,
1734 #endif
1735 #ifdef CS_CACHEEX
1736 module_csp,
1737 #endif
1738 #ifdef MODULE_GBOX
1739 module_gbox,
1740 #endif
1741 #ifdef MODULE_CONSTCW
1742 module_constcw,
1743 #endif
1744 #ifdef MODULE_RADEGAST
1745 module_radegast,
1746 #endif
1747 #ifdef MODULE_SCAM
1748 module_scam,
1749 #endif
1750 #ifdef MODULE_SERIAL
1751 module_serial,
1752 #endif
1753 #ifdef HAVE_DVBAPI
1754 module_dvbapi,
1755 #endif
1759 set_default_dirs_first();
1761 find_conf_dir();
1763 parse_cmdline_params(argc, argv);
1765 if(bg && do_daemon(1, 0))
1767 printf("Error starting in background (errno=%d: %s)", errno, strerror(errno));
1768 cs_exit(1);
1771 get_random_bytes_init();
1773 #ifdef WEBIF
1774 if(cs_restart_mode)
1775 { restart_daemon(); }
1776 #endif
1778 memset(&cfg, 0, sizeof(struct s_config));
1779 cfg.max_pending = max_pending;
1781 if(cs_confdir[cs_strlen(cs_confdir) - 1] != '/') { cs_strncat(cs_confdir, "/", sizeof(cs_confdir)); }
1782 init_signal_pre(); // because log could cause SIGPIPE errors, init a signal handler first
1783 init_first_client();
1784 cs_lock_create(__func__, &system_lock, "system_lock", 5000);
1785 cs_lock_create(__func__, &config_lock, "config_lock", 10000);
1786 cs_lock_create(__func__, &gethostbyname_lock, "gethostbyname_lock", 10000);
1787 cs_lock_create(__func__, &clientlist_lock, "clientlist_lock", 5000);
1788 cs_lock_create(__func__, &readerlist_lock, "readerlist_lock", 5000);
1789 cs_lock_create(__func__, &fakeuser_lock, "fakeuser_lock", 5000);
1790 cs_lock_create(__func__, &ecmcache_lock, "ecmcache_lock", 5000);
1791 cs_lock_create(__func__, &ecm_pushed_deleted_lock, "ecm_pushed_deleted_lock", 5000);
1792 cs_lock_create(__func__, &readdir_lock, "readdir_lock", 5000);
1793 cs_lock_create(__func__, &cwcycle_lock, "cwcycle_lock", 5000);
1794 init_cache();
1795 cacheex_init_hitcache();
1796 init_config();
1797 #ifdef CS_CACHEEX_AIO
1798 init_cw_cache();
1799 init_ecm_cache();
1800 #endif
1801 cs_init_log();
1802 init_machine_info();
1803 init_check();
1804 if(!oscam_pidfile && cfg.pidfile)
1805 { oscam_pidfile = cfg.pidfile; }
1806 if(!oscam_pidfile)
1808 oscam_pidfile = get_tmp_dir_filename(default_pidfile, sizeof(default_pidfile), "oscam.pid");
1810 if(oscam_pidfile)
1811 { pidfile_create(oscam_pidfile); }
1812 cs_init_statistics();
1813 coolapi_open_all();
1814 init_stat();
1815 ssl_init();
1817 // These initializations *MUST* be called after init_config()
1818 // because modules depend on config values.
1819 for(i = 0; mod_def[i]; i++)
1821 struct s_module *module = &modules[i];
1822 mod_def[i](module);
1825 init_sidtab();
1826 init_readerdb();
1827 #ifdef MODULE_STREAMRELAY
1828 init_stream_server();
1829 #endif
1830 cfg.account = init_userdb();
1831 init_signal();
1832 init_provid();
1833 init_srvid();
1834 init_tierid();
1835 init_fakecws();
1837 start_garbage_collector(gbdb);
1839 cacheex_init();
1841 write_versionfile(false);
1843 led_init();
1844 led_status_default();
1846 azbox_init();
1848 mca_init();
1850 global_whitelist_read();
1851 ratelimit_read();
1853 #ifdef MODULE_SERIAL
1854 twin_read();
1855 #endif
1857 for(i = 0; i < CS_MAX_MOD; i++)
1859 struct s_module *module = &modules[i];
1860 if((module->type & MOD_CONN_NET))
1862 for(j = 0; j < module->ptab.nports; j++)
1864 start_listener(module, &module->ptab.ports[j]);
1869 // set time for server to now to avoid 0 in monitor/webif
1870 first_client->last = time((time_t *)0);
1872 webif_init();
1874 start_thread("reader check", (void *) &reader_check, NULL, NULL, 1, 1);
1875 cw_process_thread_start();
1876 checkcache_process_thread_start();
1878 lcd_thread_start();
1880 do_report_emm_support();
1882 init_cardreader();
1884 cs_waitforcardinit();
1886 emm_load_cache();
1887 load_emmstat_from_file();
1889 led_status_starting();
1891 ac_init();
1893 gbox_send_init_hello();
1895 start_thread("card poll", (void *) &card_poll, NULL, NULL, 1, 1);
1897 for(i = 0; i < CS_MAX_MOD; i++)
1899 struct s_module *module = &modules[i];
1900 if((module->type & MOD_CONN_SERIAL) && module->s_handler)
1901 { module->s_handler(NULL, NULL, i); }
1904 // main loop function
1905 process_clients();
1907 SAFE_COND_SIGNAL(&card_poll_sleep_cond); // Stop card_poll thread
1908 cw_process_thread_wakeup(); // Stop cw_process thread
1909 SAFE_COND_SIGNAL(&reader_check_sleep_cond); // Stop reader_check thread
1911 // Cleanup
1912 #ifdef MODULE_GBOX
1913 stop_gbx_ticker();
1914 #endif
1915 #ifdef MODULE_STREAMRELAY
1916 stop_stream_server();
1917 #endif
1918 webif_close();
1919 azbox_close();
1920 coolapi_close_all();
1921 mca_close();
1923 led_status_stopping();
1924 led_stop();
1925 lcd_thread_stop();
1927 remove_versionfile();
1929 stat_finish();
1930 dvbapi_stop_all_descrambling(0);
1931 dvbapi_save_channel_cache();
1932 emm_save_cache();
1933 save_emmstat_to_file();
1935 cccam_done_share();
1936 gbox_send_good_night();
1938 kill_all_clients();
1939 kill_all_readers();
1940 for(i = 0; i < CS_MAX_MOD; i++)
1942 struct s_module *module = &modules[i];
1943 if((module->type & MOD_CONN_NET))
1945 for(j = 0; j < module->ptab.nports; j++)
1947 struct s_port *port = &module->ptab.ports[j];
1948 if(port->fd)
1950 shutdown(port->fd, SHUT_RDWR);
1951 close(port->fd);
1952 port->fd = 0;
1958 if(oscam_pidfile)
1959 { unlink(oscam_pidfile); }
1961 // sleep a bit, so hopefully all threads are stopped when we continue
1962 cs_sleepms(200);
1964 free_cache();
1965 #ifdef CS_CACHEEX_AIO
1966 free_ecm_cache();
1967 #endif
1968 cacheex_free_hitcache();
1969 webif_tpls_free();
1970 init_free_userdb(cfg.account);
1971 cfg.account = NULL;
1972 init_free_sidtab();
1973 free_readerdb();
1974 config_free();
1975 ssl_done();
1977 detect_valgrind();
1978 if (!running_under_valgrind)
1979 cs_log("cardserver down");
1980 else
1981 cs_log("running under valgrind, waiting 5 seconds before stopping cardserver");
1982 log_free();
1984 if (running_under_valgrind) sleep(5); // HACK: Wait a bit for things to settle
1986 stop_garbage_collector();
1988 NULLFREE(first_client->account);
1989 NULLFREE(first_client);
1990 free(stb_boxtype);
1991 free(stb_boxname);
1993 // This prevents the compiler from removing config_mak from the final binary
1994 syslog_ident = config_mak;
1996 return exit_oscam;