- Add support of ORF P4 Irdeto mode
[oscam.git] / oscam.c
blob20075088041a605363d4906a3770c6416905d262
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-ird-guess.h"
20 #include "module-lcd.h"
21 #include "module-led.h"
22 #include "module-stat.h"
23 #include "module-webif.h"
24 #include "module-webif-tpl.h"
25 #include "module-cw-cycle-check.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 ERR_remove_state(0);
60 ERR_free_strings();
61 EVP_cleanup();
62 CRYPTO_cleanup_all_ex_data();
65 #else
66 static void ssl_init(void) { }
67 static void ssl_done(void) { }
68 #endif
70 extern char *config_mak;
72 /*****************************************************************************
73 Globals
74 *****************************************************************************/
75 const char *syslog_ident = "oscam";
76 static char *oscam_pidfile;
77 static char default_pidfile[64];
79 int32_t exit_oscam = 0;
80 static struct s_module modules[CS_MAX_MOD];
82 struct s_client *first_client = NULL; //Pointer to clients list, first client is master
83 struct s_reader *first_active_reader = NULL; //list of active readers (enable=1 deleted = 0)
84 LLIST *configured_readers = NULL; //list of all (configured) readers
86 uint16_t len4caid[256]; // table for guessing caid (by len)
87 char cs_confdir[128] = CS_CONFDIR;
88 uint16_t cs_dblevel = 0; // Debug Level
89 int32_t thread_pipe[2] = {0, 0};
90 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
91 #ifdef WITH_UTF8
92 uint8_t cs_http_use_utf8 = 1;
93 #else
94 uint8_t cs_http_use_utf8 = 0;
95 #endif
96 static int8_t cs_capture_SEGV;
97 static int8_t cs_dump_stack;
98 static uint16_t cs_waittime = 60;
99 char cs_tmpdir[200] = {0x00};
100 CS_MUTEX_LOCK system_lock;
101 CS_MUTEX_LOCK config_lock;
102 CS_MUTEX_LOCK gethostbyname_lock;
103 CS_MUTEX_LOCK clientlist_lock;
104 CS_MUTEX_LOCK readerlist_lock;
105 CS_MUTEX_LOCK fakeuser_lock;
106 CS_MUTEX_LOCK readdir_lock;
107 CS_MUTEX_LOCK cwcycle_lock;
108 pthread_key_t getclient;
109 static int32_t bg;
110 static int32_t gbdb;
111 static int32_t max_pending = 32;
113 //ecms list
114 CS_MUTEX_LOCK ecmcache_lock;
115 struct ecm_request_t *ecmcwcache = NULL;
116 uint32_t ecmcwcache_size = 0;
118 //pushout deleted list
119 CS_MUTEX_LOCK ecm_pushed_deleted_lock;
120 struct ecm_request_t *ecm_pushed_deleted = NULL;
123 struct s_config cfg;
125 int log_remove_sensitive = 1;
127 static char *prog_name;
128 static char *stb_boxtype;
129 static char *stb_boxname;
131 static uint32_t oscam_stacksize = 0;
133 /*****************************************************************************
134 Statics
135 *****************************************************************************/
136 /* Prints usage information and information about the built-in modules. */
137 static void show_usage(void)
139 printf("%s",
140 " ___ ____ ___\n"
141 " / _ \\/ ___| / __|__ _ _ __ ___\n"
142 "| | | \\___ \\| | / _` | '_ ` _ \\\n"
143 "| |_| |___) | |_| (_| | | | | | |\n"
144 " \\___/|____/ \\___\\__,_|_| |_| |_|\n\n");
145 printf("OSCam cardserver v%s, build r%s (%s)\n", CS_VERSION, CS_SVN_VERSION, CS_TARGET);
146 printf("Copyright (C) 2009-2015 OSCam developers.\n");
147 printf("This program is distributed under GPLv3.\n");
148 printf("OSCam is based on Streamboard mp-cardserver v0.9d written by dukat\n");
149 printf("Visit http://www.streamboard.tv/oscam/ for more details.\n\n");
151 printf(" ConfigDir : %s\n", CS_CONFDIR);
152 printf("\n");
153 printf(" Usage: oscam [parameters]\n");
154 printf("\n Directories:\n");
155 printf(" -c, --config-dir <dir> | Read configuration files from <dir>.\n");
156 printf(" . Default: %s\n", CS_CONFDIR);
157 printf(" -t, --temp-dir <dir> | Set temporary directory to <dir>.\n");
158 #if defined(__CYGWIN__)
159 printf(" . Default: (OS-TMP)\n");
160 #else
161 printf(" . Default: /tmp/.oscam\n");
162 #endif
163 printf("\n Startup:\n");
164 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
165 printf(" -f, --foreground | Start in the foreground mode.\n");
166 #else
167 printf(" -b, --daemon | Start in the background as daemon.\n");
168 #endif
169 printf(" -B, --pidfile <pidfile> | Create pidfile when starting.\n");
170 if(config_enabled(WEBIF))
172 printf(" -r, --restart <level> | Set restart level:\n");
173 printf(" . 0 - Restart disabled (exit on restart request).\n");
174 printf(" . 1 - WebIf restart is active (default).\n");
175 printf(" . 2 - Like 1, but also restart on segfaults.\n");
177 printf(" -w, --wait <secs> | Set how much seconds to wait at startup for the\n");
178 printf(" . system clock to be set correctly. Default: 60\n");
179 printf("\n Logging:\n");
180 printf(" -I, --syslog-ident <ident> | Set syslog ident. Default: oscam\n");
181 printf(" -S, --show-sensitive | Do not filter sensitive info (card serials, boxids)\n");
182 printf(" . from the logs.\n");
183 printf(" -d, --debug <level> | Set debug level mask used for logging:\n");
184 printf(" . 0 - No extra debugging (default).\n");
185 printf(" . 1 - Detailed error messages.\n");
186 printf(" . 2 - ATR parsing info, ECM, EMM and CW dumps.\n");
187 printf(" . 4 - Traffic from/to the reader.\n");
188 printf(" . 8 - Traffic from/to the clients.\n");
189 printf(" . 16 - Traffic to the reader-device on IFD layer.\n");
190 printf(" . 32 - Traffic to the reader-device on I/O layer.\n");
191 printf(" . 64 - EMM logging.\n");
192 printf(" . 128 - DVBAPI logging.\n");
193 printf(" . 256 - Loadbalancer logging.\n");
194 printf(" . 512 - CACHEEX logging.\n");
195 printf(" . 1024 - Client ECM logging.\n");
196 printf(" . 2048 - CSP logging.\n");
197 printf(" . 4096 - CWC logging.\n");
198 printf(" . 65535 - Debug all.\n");
199 printf("\n Settings:\n");
200 printf(" -p, --pending-ecm <num> | Set the maximum number of pending ECM packets.\n");
201 printf(" . Default: 32 Max: 4096\n");
202 if(config_enabled(WEBIF))
204 printf(" -u, --utf8 | Enable WebIf support for UTF-8 charset.\n");
206 printf("\n Debug parameters:\n");
207 printf(" -a, --crash-dump | Write oscam.crash file on segfault. This option\n");
208 printf(" . needs GDB to be installed and OSCam executable to\n");
209 printf(" . contain the debug information (run oscam-XXXX.debug)\n");
210 printf(" -s, --capture-segfaults | Capture segmentation faults.\n");
211 printf(" -g, --gcollect <mode> | Garbage collector debug mode:\n");
212 printf(" . 1 - Immediate free.\n");
213 printf(" . 2 - Check for double frees.\n");
214 printf("\n Information:\n");
215 printf(" -h, --help | Show command line help text.\n");
216 printf(" -V, --build-info | Show OSCam binary configuration and version.\n");
219 /* Keep the options sorted */
220 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
221 static const char short_options[] = "aB:fc:d:g:hI:p:r:Sst:uVw:";
222 #else
223 static const char short_options[] = "aB:bc:d:g:hI:p:r:Sst:uVw:";
224 #endif
226 /* Keep the options sorted by short option */
227 static const struct option long_options[] =
229 { "crash-dump", no_argument, NULL, 'a' },
230 { "pidfile", required_argument, NULL, 'B' },
231 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
232 { "foreground", no_argument, NULL, 'f' },
233 #else
234 { "daemon", no_argument, NULL, 'b' },
235 #endif
236 { "config-dir", required_argument, NULL, 'c' },
237 { "debug", required_argument, NULL, 'd' },
238 { "gcollect", required_argument, NULL, 'g' },
239 { "help", no_argument, NULL, 'h' },
240 { "syslog-ident", required_argument, NULL, 'I' },
241 { "pending-ecm", required_argument, NULL, 'p' },
242 { "restart", required_argument, NULL, 'r' },
243 { "show-sensitive", no_argument, NULL, 'S' },
244 { "capture-segfaults", no_argument, NULL, 's' },
245 { "temp-dir", required_argument, NULL, 't' },
246 { "utf8", no_argument, NULL, 'u' },
247 { "build-info", no_argument, NULL, 'V' },
248 { "wait", required_argument, NULL, 'w' },
249 { 0, 0, 0, 0 }
252 static void write_versionfile(bool use_stdout);
254 static void parse_cmdline_params(int argc, char **argv)
256 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
257 bg = 1;
258 #endif
260 int i;
261 while((i = getopt_long(argc, argv, short_options, long_options, NULL)) != EOF)
263 if(i == '?')
264 { fprintf(stderr, "ERROR: Unknown command line parameter: %s\n", argv[optind - 1]); }
265 switch(i)
267 case 'a': // --crash-dump
268 cs_dump_stack = 1;
269 break;
270 case 'B': // --pidfile
271 oscam_pidfile = optarg;
272 break;
273 #if defined(WITH_STAPI) || defined(WITH_STAPI5)
274 case 'f': // --foreground
275 bg = 0;
276 break;
277 #else
278 case 'b': // --daemon
279 bg = 1;
280 break;
281 #endif
282 case 'c': // --config-dir
283 cs_strncpy(cs_confdir, optarg, sizeof(cs_confdir));
284 break;
285 case 'd': // --debug
286 cs_dblevel = atoi(optarg);
287 break;
288 case 'g': // --gcollect
289 gbdb = atoi(optarg);
290 break;
291 case 'h': // --help
292 show_usage();
293 exit(EXIT_SUCCESS);
294 break;
295 case 'I': // --syslog-ident
296 syslog_ident = optarg;
297 break;
298 case 'p': // --pending-ecm
299 max_pending = atoi(optarg) <= 0 ? 32 : MIN(atoi(optarg), 4096);
300 break;
301 case 'r': // --restart
302 if(config_enabled(WEBIF))
304 cs_restart_mode = atoi(optarg);
306 break;
307 case 'S': // --show-sensitive
308 log_remove_sensitive = !log_remove_sensitive;
309 break;
310 case 's': // --capture-segfaults
311 cs_capture_SEGV = 1;
312 break;
313 case 't': // --temp-dir
315 mkdir(optarg, S_IRWXU);
316 int j = open(optarg, O_RDONLY);
317 if(j >= 0)
319 close(j);
320 cs_strncpy(cs_tmpdir, optarg, sizeof(cs_tmpdir));
322 else
324 printf("WARNING: Temp dir does not exist. Using default value.\n");
326 break;
328 case 'u': // --utf8
329 if(config_enabled(WEBIF))
331 cs_http_use_utf8 = 1;
332 printf("WARNING: Web interface UTF-8 mode enabled. Carefully read documentation as bugs may arise.\n");
334 break;
335 case 'V': // --build-info
336 write_versionfile(true);
337 exit(EXIT_SUCCESS);
338 break;
339 case 'w': // --wait
340 cs_waittime = strtoul(optarg, NULL, 10);
341 break;
346 #define write_conf(CONFIG_VAR, text) \
347 fprintf(fp, "%-40s %s\n", text ":", config_enabled(CONFIG_VAR) ? "yes" : "no")
349 #define write_readerconf(CONFIG_VAR, text) \
350 fprintf(fp, "%-40s %s\n", text ":", config_enabled(CONFIG_VAR) ? "yes" : "no - no EMM support!")
352 #define write_cardreaderconf(CONFIG_VAR, text) \
353 fprintf(fp, "%s%-29s %s\n", "cardreader_", text ":", config_enabled(CONFIG_VAR) ? "yes" : "no")
355 static void write_versionfile(bool use_stdout)
357 FILE *fp = stdout;
358 if(!use_stdout)
360 char targetfile[256];
361 fp = fopen(get_tmp_dir_filename(targetfile, sizeof(targetfile), "oscam.version"), "w");
362 if(!fp)
364 cs_log("Cannot open %s (errno=%d %s)", targetfile, errno, strerror(errno));
365 return;
367 struct tm st;
368 time_t walltime = cs_time();
369 localtime_r(&walltime, &st);
370 fprintf(fp, "Unix starttime: %ld\n", walltime);
371 fprintf(fp, "Starttime: %02d.%02d.%04d %02d:%02d:%02d\n",
372 st.tm_mday, st.tm_mon + 1, st.tm_year + 1900,
373 st.tm_hour, st.tm_min, st.tm_sec);
376 fprintf(fp, "Version: oscam-%s-r%s\n", CS_VERSION, CS_SVN_VERSION);
377 fprintf(fp, "Compiler: %s\n", CS_TARGET);
378 fprintf(fp, "Box type: %s (%s)\n", boxtype_get(), boxname_get());
379 fprintf(fp, "PID: %d\n", getppid());
380 fprintf(fp, "TempDir: %s\n", cs_tmpdir);
381 fprintf(fp, "ConfigDir: %s\n", cs_confdir);
382 #ifdef WEBIF
383 fprintf(fp, "WebifPort: %d\n", cfg.http_port);
384 #endif
385 fprintf(fp, "\n");
386 write_conf(WEBIF, "Web interface support");
387 write_conf(WEBIF_LIVELOG, "LiveLog support");
388 write_conf(WEBIF_JQUERY, "jQuery support intern");
389 write_conf(TOUCH, "Touch interface support");
390 write_conf(WITH_SSL, "SSL support");
391 write_conf(HAVE_DVBAPI, "DVB API support");
392 if(config_enabled(HAVE_DVBAPI))
394 write_conf(WITH_AZBOX, "DVB API with AZBOX support");
395 write_conf(WITH_MCA, "DVB API with MCA support");
396 write_conf(WITH_COOLAPI, "DVB API with COOLAPI support");
397 write_conf(WITH_COOLAPI2, "DVB API with COOLAPI2 support");
398 write_conf(WITH_STAPI, "DVB API with STAPI support");
399 write_conf(WITH_STAPI5, "DVB API with STAPI5 support");
400 write_conf(READ_SDT_CHARSETS, "DVB API read-sdt charsets");
402 write_conf(IRDETO_GUESSING, "Irdeto guessing");
403 write_conf(CS_ANTICASC, "Anti-cascading support");
404 write_conf(WITH_DEBUG, "Debug mode");
405 write_conf(MODULE_MONITOR, "Monitor");
406 write_conf(WITH_LB, "Loadbalancing support");
407 write_conf(CS_CACHEEX, "Cache exchange support");
408 write_conf(CW_CYCLE_CHECK, "CW Cycle Check support");
409 write_conf(LCDSUPPORT, "LCD support");
410 write_conf(LEDSUPPORT, "LED support");
411 switch (cs_getclocktype()) {
412 case CLOCK_TYPE_UNKNOWN : write_conf(CLOCKFIX, "Clockfix with UNKNOWN clock"); break;
413 case CLOCK_TYPE_REALTIME : write_conf(CLOCKFIX, "Clockfix with realtime clock"); break;
414 case CLOCK_TYPE_MONOTONIC: write_conf(CLOCKFIX, "Clockfix with monotonic clock"); break;
416 write_conf(IPV6SUPPORT, "IPv6 support");
418 fprintf(fp, "\n");
419 write_conf(MODULE_CAMD33, "camd 3.3x");
420 write_conf(MODULE_CAMD35, "camd 3.5 UDP");
421 write_conf(MODULE_CAMD35_TCP, "camd 3.5 TCP");
422 write_conf(MODULE_NEWCAMD, "newcamd");
423 write_conf(MODULE_CCCAM, "CCcam");
424 write_conf(MODULE_CCCSHARE, "CCcam share");
425 write_conf(MODULE_GBOX, "gbox");
426 write_conf(MODULE_RADEGAST, "radegast");
427 write_conf(MODULE_SCAM, "scam");
428 write_conf(MODULE_SERIAL, "serial");
429 write_conf(MODULE_CONSTCW, "constant CW");
430 write_conf(MODULE_PANDORA, "Pandora");
431 write_conf(MODULE_GHTTP, "ghttp");
433 fprintf(fp, "\n");
434 write_conf(WITH_CARDREADER, "Reader support");
435 if(config_enabled(WITH_CARDREADER))
437 fprintf(fp, "\n");
438 write_readerconf(READER_NAGRA, "Nagra");
439 write_readerconf(READER_IRDETO, "Irdeto");
440 write_readerconf(READER_CONAX, "Conax");
441 write_readerconf(READER_CRYPTOWORKS, "Cryptoworks");
442 write_readerconf(READER_SECA, "Seca");
443 write_readerconf(READER_VIACCESS, "Viaccess");
444 write_readerconf(READER_VIDEOGUARD, "NDS Videoguard");
445 write_readerconf(READER_DRE, "DRE Crypt");
446 write_readerconf(READER_TONGFANG, "TONGFANG");
447 write_readerconf(READER_BULCRYPT, "Bulcrypt");
448 write_readerconf(READER_GRIFFIN, "Griffin");
449 write_readerconf(READER_DGCRYPT, "DGCrypt");
450 fprintf(fp, "\n");
451 write_cardreaderconf(CARDREADER_PHOENIX, "phoenix");
452 write_cardreaderconf(CARDREADER_DRECAS, "drecas");
453 write_cardreaderconf(CARDREADER_INTERNAL_AZBOX, "internal_azbox");
454 write_cardreaderconf(CARDREADER_INTERNAL_COOLAPI, "internal_coolapi");
455 write_cardreaderconf(CARDREADER_INTERNAL_COOLAPI2, "internal_coolapi2");
456 write_cardreaderconf(CARDREADER_INTERNAL_SCI, "internal_sci");
457 write_cardreaderconf(CARDREADER_SC8IN1, "sc8in1");
458 write_cardreaderconf(CARDREADER_MP35, "mp35");
459 write_cardreaderconf(CARDREADER_SMARGO, "smargo");
460 write_cardreaderconf(CARDREADER_PCSC, "pcsc");
461 write_cardreaderconf(CARDREADER_SMART, "smartreader");
462 write_cardreaderconf(CARDREADER_DB2COM, "db2com");
463 write_cardreaderconf(CARDREADER_STAPI, "stapi");
464 write_cardreaderconf(CARDREADER_STAPI5, "stapi5");
465 write_cardreaderconf(CARDREADER_STINGER, "stinger");
467 else
469 write_readerconf(WITH_CARDREADER, "Reader Support");
471 if(!use_stdout)
472 { fclose(fp); }
474 #undef write_conf
475 #undef write_readerconf
476 #undef write_cardreaderconf
478 static void remove_versionfile(void)
480 char targetfile[256];
481 unlink(get_tmp_dir_filename(targetfile, sizeof(targetfile), "oscam.version"));
484 #define report_emm_support(CONFIG_VAR, text) \
485 do { \
486 if (!config_enabled(CONFIG_VAR)) \
487 cs_log("Binary without %s module - no EMM processing for %s possible!", text, text); \
488 } while(0)
490 static void do_report_emm_support(void)
492 if(!config_enabled(WITH_CARDREADER))
494 cs_log("Binary without Cardreader Support! No EMM processing possible!");
496 else
498 report_emm_support(READER_NAGRA, "Nagra");
499 report_emm_support(READER_IRDETO, "Irdeto");
500 report_emm_support(READER_CONAX, "Conax");
501 report_emm_support(READER_CRYPTOWORKS, "Cryptoworks");
502 report_emm_support(READER_SECA, "Seca");
503 report_emm_support(READER_VIACCESS, "Viaccess");
504 report_emm_support(READER_VIDEOGUARD, "NDS Videoguard");
505 report_emm_support(READER_DRE, "DRE Crypt");
506 report_emm_support(READER_TONGFANG, "TONGFANG");
507 report_emm_support(READER_BULCRYPT, "Bulcrypt");
508 report_emm_support(READER_GRIFFIN, "Griffin");
509 report_emm_support(READER_DGCRYPT, "DGCrypt");
512 #undef report_emm_support
514 #ifdef NEED_DAEMON
515 // The compat function is not called daemon() because this may cause problems.
516 static int32_t do_daemon(int32_t nochdir, int32_t noclose)
518 int32_t fd;
520 switch(fork())
522 case -1:
523 return (-1);
524 case 0:
525 break;
526 default:
527 _exit(0);
530 if(setsid() == (-1))
531 { return (-1); }
533 if(!nochdir)
534 { (void)chdir("/"); }
536 if(!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1)
538 (void)dup2(fd, STDIN_FILENO);
539 (void)dup2(fd, STDOUT_FILENO);
540 (void)dup2(fd, STDERR_FILENO);
541 if(fd > 2)
542 { (void)close(fd); }
544 return (0);
546 #else
547 #define do_daemon daemon
548 #endif
551 * flags: 1 = restart, 2 = don't modify if SIG_IGN, may be combined
553 static void set_signal_handler(int32_t sig, int32_t flags, void (*sighandler))
555 struct sigaction sa;
556 sigaction(sig, (struct sigaction *) 0, &sa);
557 if(!((flags & 2) && (sa.sa_handler == SIG_IGN)))
559 sigemptyset(&sa.sa_mask);
560 sa.sa_flags = (flags & 1) ? SA_RESTART : 0;
561 sa.sa_handler = sighandler;
562 sigaction(sig, &sa, (struct sigaction *) 0);
566 static void cs_master_alarm(void)
568 cs_log("PANIC: master deadlock!");
569 fprintf(stderr, "PANIC: master deadlock!");
570 fflush(stderr);
573 static void cs_sigpipe(void)
575 if(cs_dblevel & D_ALL_DUMP)
576 { cs_log("Got sigpipe signal -> captured"); }
579 static void cs_dummy(void)
581 return;
584 /* Switch debuglevel forward one step (called when receiving SIGUSR1). */
585 static void cs_debug_level(void)
587 switch(cs_dblevel)
589 case 0:
590 cs_dblevel = 1;
591 break;
592 case 128:
593 cs_dblevel = 255;
594 break;
595 case 255:
596 cs_dblevel = 0;
597 break;
598 default:
599 cs_dblevel <<= 1;
602 cs_log("debug_level=%d", cs_dblevel);
606 * write stacktrace to oscam.crash. file is always appended
607 * Usage:
608 * 1. compile oscam with debug parameters (Makefile: DS_OPTS="-ggdb")
609 * 2. you need gdb installed and working on the local machine
610 * 3. start oscam with parameter: -a
612 static void cs_dumpstack(int32_t sig)
614 FILE *fp = fopen("oscam.crash", "a+");
616 time_t timep;
617 char buf[200];
619 time(&timep);
620 cs_ctime_r(&timep, buf);
622 fprintf(stderr, "crashed with signal %d on %swriting oscam.crash\n", sig, buf);
624 fprintf(fp, "%sOSCam cardserver v%s, build r%s (%s)\n", buf, CS_VERSION, CS_SVN_VERSION, CS_TARGET);
625 fprintf(fp, "FATAL: Signal %d: %s Fault. Logged StackTrace:\n\n", sig, (sig == SIGSEGV) ? "Segmentation" : ((sig == SIGBUS) ? "Bus" : "Unknown"));
626 fclose(fp);
628 FILE *cmd = fopen("/tmp/gdbcmd", "w");
629 fputs("bt\n", cmd);
630 fputs("thread apply all bt\n", cmd);
631 fclose(cmd);
633 snprintf(buf, sizeof(buf) - 1, "gdb %s %d -batch -x /tmp/gdbcmd >> oscam.crash", prog_name, getpid());
634 if(system(buf) == -1)
635 { fprintf(stderr, "Fatal error on trying to start gdb process."); }
637 exit(-1);
642 * called by signal SIGHUP
644 * reloads configs:
645 * - useraccounts (oscam.user)
646 * - readers (oscam.server)
647 * - services ids (oscam.srvid)
648 * - tier ids (oscam.tiers)
649 * Also clears anticascading stats.
651 static void cs_reload_config(void)
653 static pthread_mutex_t mutex;
654 static int8_t mutex_init = 0;
656 if(!mutex_init)
658 SAFE_MUTEX_INIT(&mutex, NULL);
659 mutex_init = 1;
662 if(pthread_mutex_trylock(&mutex))
664 return;
667 if(cfg.reload_useraccounts)
669 cs_accounts_chk();
672 if(cfg.reload_readers)
674 reload_readerdb();
677 if(cfg.reload_provid)
679 init_provid();
682 if(cfg.reload_services_ids)
684 init_srvid();
687 if(cfg.reload_tier_ids)
689 init_tierid();
692 if(cfg.reload_fakecws)
694 init_fakecws();
697 if(cfg.reload_ac_stat)
699 ac_init_stat();
702 if(cfg.reload_log)
704 cs_reopen_log(); // FIXME: aclog.log, emm logs, cw logs (?)
707 SAFE_MUTEX_UNLOCK(&mutex);
710 /* Sets signal handlers to ignore for early startup of OSCam because for example log
711 could cause SIGPIPE errors and the normal signal handlers can't be used at this point. */
712 static void init_signal_pre(void)
714 set_signal_handler(SIGPIPE , 1, SIG_IGN);
715 set_signal_handler(SIGWINCH, 1, SIG_IGN);
716 set_signal_handler(SIGALRM , 1, SIG_IGN);
717 set_signal_handler(SIGHUP , 1, SIG_IGN);
720 /* Sets the signal handlers.*/
721 static void init_signal(void)
723 set_signal_handler(SIGINT, 3, cs_exit);
724 #if defined(__APPLE__)
725 set_signal_handler(SIGEMT, 3, cs_exit);
726 #endif
727 set_signal_handler(SIGTERM, 3, cs_exit);
729 set_signal_handler(SIGWINCH, 1, SIG_IGN);
730 set_signal_handler(SIGPIPE , 0, cs_sigpipe);
731 set_signal_handler(SIGALRM , 0, cs_master_alarm);
732 set_signal_handler(SIGHUP , 1, cs_reload_config);
733 set_signal_handler(SIGUSR1, 1, cs_debug_level);
734 set_signal_handler(SIGUSR2, 1, cs_card_info);
735 set_signal_handler(OSCAM_SIGNAL_WAKEUP, 0, cs_dummy);
737 if(cs_capture_SEGV)
739 set_signal_handler(SIGSEGV, 1, cs_exit);
740 set_signal_handler(SIGBUS, 1, cs_exit);
742 else if(cs_dump_stack)
744 set_signal_handler(SIGSEGV, 1, cs_dumpstack);
745 set_signal_handler(SIGBUS, 1, cs_dumpstack);
748 cs_log("signal handling initialized");
749 return;
752 void cs_exit(int32_t sig)
754 if(cs_dump_stack && (sig == SIGSEGV || sig == SIGBUS || sig == SIGQUIT))
755 { cs_dumpstack(sig); }
757 set_signal_handler(SIGHUP , 1, SIG_IGN);
758 set_signal_handler(SIGPIPE, 1, SIG_IGN);
760 struct s_client *cl = cur_client();
761 if(!cl)
762 { return; }
764 // this is very important - do not remove
765 if(cl->typ != 's')
767 cs_log_dbg(D_TRACE, "thread %8lX ended!", (unsigned long)pthread_self());
769 free_client(cl);
771 //Restore signals before exiting thread
772 set_signal_handler(SIGPIPE , 0, cs_sigpipe);
773 set_signal_handler(SIGHUP , 1, cs_reload_config);
775 pthread_exit(NULL);
776 return;
779 if(!exit_oscam)
780 { exit_oscam = sig ? sig : 1; }
783 static char *read_line_from_file(char *fname, char *buf, int bufsz)
785 memset(buf, 0, bufsz);
786 FILE *f = fopen(fname, "r");
787 if (!f)
788 return NULL;
789 while (fgets(buf, bufsz, f))
791 if (strstr(buf,"\n")) //we need only the first line
793 buf[strlen(buf)-1] = '\0';
794 break;
797 fclose(f);
798 if (buf[0])
799 return buf;
800 return NULL;
803 static void init_machine_info(void)
805 struct utsname buffer;
806 if (uname(&buffer) == 0)
808 cs_log("System name = %s", buffer.sysname);
809 cs_log("Host name = %s", buffer.nodename);
810 cs_log("Release = %s", buffer.release);
811 cs_log("Version = %s", buffer.version);
812 cs_log("Machine = %s", buffer.machine);
813 } else {
814 cs_log("ERROR: uname call failed: %s", strerror(errno));
817 #if !defined(__linux__)
818 return;
819 #endif
821 // Linux only functionality
822 char boxtype[128];
823 boxtype[0] = 0;
824 char model[128];
825 model[0] = 0;
826 char vumodel[128];
827 vumodel[0] = 0;
828 int8_t azmodel = 0;
829 FILE *f;
831 if ((f = fopen("/proc/stb/info/azmodel", "r"))){ azmodel = 1; fclose(f);}
832 read_line_from_file("/proc/stb/info/model", model, sizeof(model));
833 read_line_from_file("/proc/stb/info/boxtype", boxtype, sizeof(boxtype));
834 read_line_from_file("/proc/stb/info/vumodel", vumodel, sizeof(vumodel));
835 if (vumodel[0] && !boxtype[0] && !azmodel)
836 snprintf(boxtype, sizeof(boxtype), "vu%s", vumodel);
837 if (!boxtype[0] && azmodel)
838 snprintf(boxtype, sizeof(boxtype), "Azbox-%s", model);
840 // Detect dreambox type
841 if (strcasecmp(buffer.machine, "ppc") == 0 && !model[0] && !boxtype[0])
843 char line[128], *p;
844 int have_dreambox = 0;
845 if ((f = fopen("/proc/cpuinfo", "r")))
847 while (fgets(line, sizeof(line), f))
849 if (strstr(line, "STBx25xx")) have_dreambox++;
850 if (strstr(line, "pvr" )) have_dreambox++;
851 if (strstr(line, "Dreambox")) have_dreambox++;
852 if (strstr(line, "9.80" )) have_dreambox++;
853 if (strstr(line, "63MHz" )) have_dreambox++;
855 fclose(f);
856 have_dreambox = have_dreambox == 5 ? 1 : 0; // Need to find all 5 strings
858 if (have_dreambox)
860 if (read_line_from_file("/proc/meminfo", line, sizeof(line)) && (p = strchr(line, ' ')))
862 unsigned long memtotal = strtoul(p, NULL, 10);
863 if (memtotal > 40000)
864 snprintf(boxtype, sizeof(boxtype), "%s", "dm600pvr");
865 else
866 snprintf(boxtype, sizeof(boxtype), "%s", "dm500");
871 if (!boxtype[0] && !strcasecmp(model, "dm800") && !strcasecmp(buffer.machine, "armv7l"))
872 snprintf(boxtype, sizeof(boxtype), "%s", "su980");
874 if (!boxtype[0])
876 uchar *pos;
877 pos = (uchar*) memchr(buffer.release, 'd', sizeof(buffer.release));
878 if(pos)
880 if((!memcmp(pos, "dbox2", sizeof("dbox2"))) && !strcasecmp(buffer.machine, "ppc"))
882 snprintf(boxtype, sizeof(boxtype), "%s", "dbox2");
887 if (model[0])
888 cs_log("Stb model = %s", model);
890 if (vumodel[0])
891 cs_log("Stb vumodel = vu%s", vumodel);
893 if (boxtype[0])
895 char boxname[128];
896 if(!strcasecmp(boxtype,"ini-8000am")){snprintf(boxname, sizeof(boxname), "%s", "Atemio Nemesis");}
897 else if(!strcasecmp(boxtype,"ini-9000ru")){snprintf(boxname, sizeof(boxname), "%s", "Sezam Marvel");}
898 else if(!strcasecmp(boxtype,"ini-8000sv")){snprintf(boxname, sizeof(boxname), "%s", "Miraclebox Ultra");}
899 else if(!strcasecmp(boxtype,"ini-9000de")){snprintf(boxname, sizeof(boxname), "%s", "Xpeed LX3");}
900 else boxname[0] = 0;
901 if(boxname[0]){cs_log("Stb boxname = %s", boxname); stb_boxname = cs_strdup(boxname);}
902 cs_log("Stb boxtype = %s", boxtype);
905 if (boxtype[0])
906 stb_boxtype = cs_strdup(boxtype);
907 else if (model[0])
908 stb_boxtype = cs_strdup(model);
911 const char *boxtype_get(void)
913 return stb_boxtype ? stb_boxtype : "generic";
916 const char *boxname_get(void)
918 return stb_boxname ? stb_boxname : "generic";
921 bool boxtype_is(const char *boxtype)
923 return strcasecmp(boxtype_get(), boxtype) == 0;
926 bool boxname_is(const char *boxname)
928 return strcasecmp(boxname_get(), boxname) == 0;
931 /* Checks if the date of the system is correct and waits if necessary. */
932 static void init_check(void)
934 char *ptr = __DATE__;
935 int32_t month, year = atoi(ptr + strlen(ptr) - 4), day = atoi(ptr + 4);
936 if(day > 0 && day < 32 && year > 2010 && year < 9999)
938 struct tm timeinfo;
939 char months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
940 for(month = 0; month < 12; ++month)
942 if(!strncmp(ptr, months[month], 3)) { break; }
944 if(month > 11) { month = 0; }
945 memset(&timeinfo, 0, sizeof(timeinfo));
946 timeinfo.tm_mday = day;
947 timeinfo.tm_mon = month;
948 timeinfo.tm_year = year - 1900;
949 time_t builddate = mktime(&timeinfo) - 86400;
950 int32_t i = 0;
951 while(time((time_t *)0) < builddate)
953 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); }
954 cs_sleepms(1000);
955 ++i;
956 if(i > cs_waittime)
958 cs_log("Waiting was not successful. OSCam will be started but is UNSUPPORTED this way. Do not report any errors with this version.");
959 break;
962 // adjust login time of first client
963 if(i > 0) { first_client->login = time((time_t *)0); }
967 #ifdef __linux__
968 #include <sys/prctl.h>
969 // PR_SET_NAME is introduced in 2.6.9 (which is ancient, released 18 Oct 2004)
970 // but apparantly we can't count on having at least that version :(
971 #ifndef PR_SET_NAME
972 #define PR_SET_NAME 15
973 #endif
974 // Set the thread name (comm) under linux (the limit is 16 chars)
975 void set_thread_name(const char *thread_name)
977 prctl(PR_SET_NAME, thread_name, NULL, NULL, NULL);
979 #else
980 void set_thread_name(const char *UNUSED(thread_name)) { }
981 #endif
984 static void fix_stacksize(void)
986 // Changing the default stack size is generally a bad idea.
987 // We are doing it anyway at the moment, because we are using several threads,
988 // and are running on machnies with little RAM.
989 // HOWEVER, as we do not know which minimal stack size is needed to run
990 // oscam without SEQFAULT (stack overflow), this is risky business.
991 // If after a code change SEQFAULTs related to stack overflow appear,
992 // increase OSCAM_STACK_MIN or remove the calls to SAFE_ATTR_SETSTACKSIZE.
994 #ifndef PTHREAD_STACK_MIN
995 #define PTHREAD_STACK_MIN 64000
996 #endif
997 #define OSCAM_STACK_MIN PTHREAD_STACK_MIN+32768
999 if(oscam_stacksize < OSCAM_STACK_MIN)
1001 long pagesize = sysconf(_SC_PAGESIZE);
1002 if(pagesize < 1)
1004 oscam_stacksize = OSCAM_STACK_MIN;
1005 return;
1008 oscam_stacksize = (((OSCAM_STACK_MIN) / pagesize) + 1) * pagesize;
1012 /* Starts a thread named nameroutine with the start function startroutine. */
1013 int32_t start_thread(char *nameroutine, void *startroutine, void *arg, pthread_t *pthread, int8_t detach, int8_t modify_stacksize)
1015 pthread_t temp;
1016 pthread_attr_t attr;
1018 cs_log_dbg(D_TRACE, "starting thread %s", nameroutine);
1020 SAFE_ATTR_INIT(&attr);
1022 if(modify_stacksize)
1023 { SAFE_ATTR_SETSTACKSIZE(&attr, oscam_stacksize); }
1025 int32_t ret = pthread_create(pthread == NULL ? &temp : pthread, &attr, startroutine, arg);
1026 if(ret)
1027 { cs_log("ERROR: can't create %s thread (errno=%d %s)", nameroutine, ret, strerror(ret)); }
1028 else
1030 cs_log_dbg(D_TRACE, "%s thread started", nameroutine);
1032 if(detach)
1033 { pthread_detach(pthread == NULL ? temp : *pthread); }
1036 pthread_attr_destroy(&attr);
1038 return ret;
1041 int32_t start_thread_nolog(char *nameroutine, void *startroutine, void *arg, pthread_t *pthread, int8_t detach, int8_t modify_stacksize)
1043 pthread_t temp;
1044 pthread_attr_t attr;
1046 SAFE_ATTR_INIT(&attr);
1048 if(modify_stacksize)
1049 { SAFE_ATTR_SETSTACKSIZE(&attr, oscam_stacksize); }
1051 int32_t ret = pthread_create(pthread == NULL ? &temp : pthread, &attr, startroutine, arg);
1052 if(ret)
1053 { fprintf(stderr, "ERROR: can't create %s thread (errno=%d %s)", nameroutine, ret, strerror(ret)); }
1054 else
1056 if(detach)
1057 { pthread_detach(pthread == NULL ? temp : *pthread); }
1060 pthread_attr_destroy(&attr);
1062 return ret;
1065 /* Allows to kill another thread specified through the client cl with locking.
1066 If the own thread has to be cancelled, cs_exit or cs_disconnect_client has to be used. */
1067 void kill_thread(struct s_client *cl)
1069 if(!cl || cl->kill) { return; }
1070 if(cl == cur_client())
1072 cs_log("Trying to kill myself, exiting.");
1073 cs_exit(0);
1075 add_job(cl, ACTION_CLIENT_KILL, NULL, 0); //add kill job, ...
1076 cl->kill = 1; //then set kill flag!
1079 struct s_module *get_module(struct s_client *cl)
1081 return &modules[cl->module_idx];
1084 void module_reader_set(struct s_reader *rdr)
1086 int i;
1087 if(!is_cascading_reader(rdr))
1088 { return; }
1089 for(i = 0; i < CS_MAX_MOD; i++)
1091 struct s_module *module = &modules[i];
1092 if(module->num && module->num == rdr->typ)
1093 rdr->ph = *module;
1097 static void cs_waitforcardinit(void)
1099 if(cfg.waitforcards)
1101 cs_log("waiting for local card init");
1102 int32_t card_init_done;
1105 card_init_done = 1;
1106 struct s_reader *rdr;
1107 LL_ITER itr = ll_iter_create(configured_readers);
1108 while((rdr = ll_iter_next(&itr)))
1110 if(rdr->enable && !is_cascading_reader(rdr) && (rdr->card_status == CARD_NEED_INIT || rdr->card_status == UNKNOWN))
1112 card_init_done = 0;
1113 break;
1117 if(!card_init_done)
1118 { cs_sleepms(300); } // wait a little bit
1119 //alarm(cfg.cmaxidle + cfg.ctimeout / 1000 + 1);
1121 while(!card_init_done && !exit_oscam);
1123 if(cfg.waitforcards_extra_delay > 0 && !exit_oscam)
1124 { cs_sleepms(cfg.waitforcards_extra_delay); }
1125 cs_log("init for all local cards done");
1129 static uint32_t resize_pfd_cllist(struct pollfd **pfd, struct s_client ***cl_list, uint32_t old_size, uint32_t new_size)
1131 if(old_size != new_size)
1133 struct pollfd *pfd_new;
1134 if(!cs_malloc(&pfd_new, new_size * sizeof(struct pollfd)))
1136 return old_size;
1138 struct s_client **cl_list_new;
1139 if(!cs_malloc(&cl_list_new, new_size * sizeof(cl_list)))
1141 NULLFREE(pfd_new);
1142 return old_size;
1144 if(old_size > 0)
1146 memcpy(pfd_new, *pfd, old_size * sizeof(struct pollfd));
1147 memcpy(cl_list_new, *cl_list, old_size * sizeof(cl_list));
1148 NULLFREE(*pfd);
1149 NULLFREE(*cl_list);
1151 *pfd = pfd_new;
1152 *cl_list = cl_list_new;
1154 return new_size;
1157 static uint32_t chk_resize_cllist(struct pollfd **pfd, struct s_client ***cl_list, uint32_t cur_size, uint32_t chk_size)
1159 chk_size++;
1160 if(chk_size > cur_size)
1162 uint32_t new_size = ((chk_size % 100) + 1) * 100; //increase 100 step
1163 cur_size = resize_pfd_cllist(pfd, cl_list, cur_size, new_size);
1165 return cur_size;
1168 static void process_clients(void)
1170 int32_t i, k, j, rc, pfdcount = 0;
1171 struct s_client *cl;
1172 struct s_reader *rdr;
1173 struct pollfd *pfd;
1174 struct s_client **cl_list;
1175 struct timeb start, end; // start time poll, end time poll
1176 uint32_t cl_size = 0;
1178 uchar buf[10];
1180 if(pipe(thread_pipe) == -1)
1182 printf("cannot create pipe, errno=%d\n", errno);
1183 exit(1);
1186 cl_size = chk_resize_cllist(&pfd, &cl_list, 0, 100);
1188 pfd[pfdcount].fd = thread_pipe[0];
1189 pfd[pfdcount].events = POLLIN | POLLPRI;
1190 cl_list[pfdcount] = NULL;
1192 while(!exit_oscam)
1194 pfdcount = 1;
1196 //connected tcp clients
1197 for(cl = first_client->next; cl; cl = cl->next)
1199 if(cl->init_done && !cl->kill && cl->pfd && cl->typ == 'c' && !cl->is_udp)
1201 if(cl->pfd && !cl->thread_active)
1203 cl_size = chk_resize_cllist(&pfd, &cl_list, cl_size, pfdcount);
1204 cl_list[pfdcount] = cl;
1205 pfd[pfdcount].fd = cl->pfd;
1206 pfd[pfdcount++].events = POLLIN | POLLPRI;
1209 //reader:
1210 //TCP:
1211 // - TCP socket must be connected
1212 // - no active init thread
1213 //UDP:
1214 // - connection status ignored
1215 // - no active init thread
1216 rdr = cl->reader;
1217 if(rdr && cl->typ == 'p' && cl->init_done)
1219 if(cl->pfd && !cl->thread_active && ((rdr->tcp_connected && rdr->ph.type == MOD_CONN_TCP) || (rdr->ph.type == MOD_CONN_UDP)))
1221 cl_size = chk_resize_cllist(&pfd, &cl_list, cl_size, pfdcount);
1222 cl_list[pfdcount] = cl;
1223 pfd[pfdcount].fd = cl->pfd;
1224 pfd[pfdcount++].events = (POLLIN | POLLPRI);
1229 //server (new tcp connections or udp messages)
1230 for(k = 0; k < CS_MAX_MOD; k++)
1232 struct s_module *module = &modules[k];
1233 if((module->type & MOD_CONN_NET))
1235 for(j = 0; j < module->ptab.nports; j++)
1237 if(module->ptab.ports[j].fd)
1239 cl_size = chk_resize_cllist(&pfd, &cl_list, cl_size, pfdcount);
1240 cl_list[pfdcount] = NULL;
1241 pfd[pfdcount].fd = module->ptab.ports[j].fd;
1242 pfd[pfdcount++].events = (POLLIN | POLLPRI);
1248 if(pfdcount >= 1024)
1249 { cs_log("WARNING: too many users!"); }
1250 cs_ftime(&start); // register start time
1251 rc = poll(pfd, pfdcount, 5000);
1252 if(rc < 1) { continue; }
1253 cs_ftime(&end); // register end time
1255 for(i = 0; i < pfdcount && rc > 0; i++)
1257 if(pfd[i].revents == 0) { continue; } // skip sockets with no changes
1258 rc--; //event handled!
1259 cs_log_dbg(D_TRACE, "[OSCAM] new event %d occurred on fd %d after %"PRId64" ms inactivity", pfd[i].revents,
1260 pfd[i].fd, comp_timeb(&end, &start));
1261 //clients
1262 cl = cl_list[i];
1263 if(cl && !is_valid_client(cl))
1264 { continue; }
1266 if(pfd[i].fd == thread_pipe[0] && (pfd[i].revents & (POLLIN | POLLPRI)))
1268 // a thread ended and cl->pfd should be added to pollfd list again (thread_active==0)
1269 int32_t len = read(thread_pipe[0], buf, sizeof(buf));
1270 if(len == -1)
1272 cs_log_dbg(D_TRACE, "[OSCAM] Reading from pipe failed (errno=%d %s)", errno, strerror(errno));
1274 cs_log_dump_dbg(D_TRACE, buf, len, "[OSCAM] Readed:");
1275 continue;
1278 //clients
1279 // message on an open tcp connection
1280 if(cl && cl->init_done && cl->pfd && (cl->typ == 'c' || cl->typ == 'm'))
1282 if(pfd[i].fd == cl->pfd && (pfd[i].revents & (POLLHUP | POLLNVAL | POLLERR)))
1284 //client disconnects
1285 kill_thread(cl);
1286 continue;
1288 if(pfd[i].fd == cl->pfd && (pfd[i].revents & (POLLIN | POLLPRI)))
1290 add_job(cl, ACTION_CLIENT_TCP, NULL, 0);
1295 //reader
1296 // either an ecm answer, a keepalive or connection closed from a proxy
1297 // physical reader ('r') should never send data without request
1298 rdr = NULL;
1299 struct s_client *cl2 = NULL;
1300 if(cl && cl->typ == 'p')
1302 rdr = cl->reader;
1303 if(rdr)
1304 { cl2 = rdr->client; }
1307 if(rdr && cl2 && cl2->init_done)
1309 if(cl2->pfd && pfd[i].fd == cl2->pfd && (pfd[i].revents & (POLLHUP | POLLNVAL | POLLERR)))
1311 //connection to remote proxy was closed
1312 //oscam should check for rdr->tcp_connected and reconnect on next ecm request sent to the proxy
1313 network_tcp_connection_close(rdr, "closed");
1314 rdr_log_dbg(rdr, D_READER, "connection closed");
1316 if(cl2->pfd && pfd[i].fd == cl2->pfd && (pfd[i].revents & (POLLIN | POLLPRI)))
1318 add_job(cl2, ACTION_READER_REMOTE, NULL, 0);
1323 //server sockets
1324 // new connection on a tcp listen socket or new message on udp listen socket
1325 if(!cl && (pfd[i].revents & (POLLIN | POLLPRI)))
1327 for(k = 0; k < CS_MAX_MOD; k++)
1329 struct s_module *module = &modules[k];
1330 if((module->type & MOD_CONN_NET))
1332 for(j = 0; j < module->ptab.nports; j++)
1334 if(module->ptab.ports[j].fd && module->ptab.ports[j].fd == pfd[i].fd)
1336 accept_connection(module, k, j);
1343 cs_ftime(&start); // register start time for new poll next run
1344 first_client->last = time((time_t *)0);
1346 NULLFREE(pfd);
1347 NULLFREE(cl_list);
1348 return;
1351 static pthread_cond_t reader_check_sleep_cond;
1352 static pthread_mutex_t reader_check_sleep_cond_mutex;
1354 static void *reader_check(void)
1356 struct s_client *cl;
1357 struct s_reader *rdr;
1358 set_thread_name(__func__);
1359 cs_pthread_cond_init(__func__, &reader_check_sleep_cond_mutex, &reader_check_sleep_cond);
1360 while(!exit_oscam)
1362 for(cl = first_client->next; cl ; cl = cl->next)
1364 if(!cl->thread_active)
1365 { client_check_status(cl); }
1367 cs_readlock(__func__, &readerlist_lock);
1368 for(rdr = first_active_reader; rdr; rdr = rdr->next)
1370 if(rdr->enable)
1372 cl = rdr->client;
1373 if(!cl || cl->kill)
1374 { restart_cardreader(rdr, 0); }
1375 else if(!cl->thread_active)
1376 { client_check_status(cl); }
1379 cs_readunlock(__func__, &readerlist_lock);
1380 sleepms_on_cond(__func__, &reader_check_sleep_cond_mutex, &reader_check_sleep_cond, 1000);
1382 return NULL;
1385 static pthread_cond_t card_poll_sleep_cond;
1387 static void * card_poll(void) {
1388 struct s_client *cl;
1389 struct s_reader *rdr;
1390 pthread_mutex_t card_poll_sleep_cond_mutex;
1391 SAFE_MUTEX_INIT(&card_poll_sleep_cond_mutex, NULL);
1392 SAFE_COND_INIT(&card_poll_sleep_cond, NULL);
1393 set_thread_name(__func__);
1394 while (!exit_oscam) {
1395 cs_readlock(__func__, &readerlist_lock);
1396 for (rdr=first_active_reader; rdr; rdr=rdr->next) {
1397 if (rdr->enable && rdr->card_status == CARD_INSERTED) {
1398 cl = rdr->client;
1399 if (cl && !cl->kill)
1400 { add_job(cl, ACTION_READER_POLL_STATUS, 0, 0); }
1403 cs_readunlock(__func__, &readerlist_lock);
1404 struct timespec ts;
1405 struct timeval tv;
1406 gettimeofday(&tv, NULL);
1407 ts.tv_sec = tv.tv_sec;
1408 ts.tv_nsec = tv.tv_usec * 1000;
1409 ts.tv_sec += 1;
1410 SAFE_MUTEX_LOCK(&card_poll_sleep_cond_mutex);
1411 SAFE_COND_TIMEDWAIT(&card_poll_sleep_cond, &card_poll_sleep_cond_mutex, &ts); // sleep on card_poll_sleep_cond
1412 SAFE_MUTEX_UNLOCK(&card_poll_sleep_cond_mutex);
1414 return NULL;
1417 #ifdef WEBIF
1418 static pid_t pid;
1421 static void fwd_sig(int32_t sig)
1423 kill(pid, sig);
1426 static void restart_daemon(void)
1428 while(1)
1431 //start client process:
1432 pid = fork();
1433 if(!pid)
1434 { return; } //client process=oscam process
1435 if(pid < 0)
1436 { exit(1); }
1438 //set signal handler for the restart daemon:
1439 set_signal_handler(SIGINT, 3, fwd_sig);
1440 #if defined(__APPLE__)
1441 set_signal_handler(SIGEMT, 3, fwd_sig);
1442 #endif
1443 set_signal_handler(SIGTERM, 3, fwd_sig);
1444 set_signal_handler(SIGQUIT, 0, fwd_sig);
1445 set_signal_handler(SIGHUP , 0, fwd_sig);
1446 set_signal_handler(SIGUSR1, 0, fwd_sig);
1447 set_signal_handler(SIGUSR2, 0, fwd_sig);
1448 set_signal_handler(SIGALRM , 0, fwd_sig);
1449 set_signal_handler(SIGWINCH, 1, SIG_IGN);
1450 set_signal_handler(SIGPIPE , 0, SIG_IGN);
1451 set_signal_handler(OSCAM_SIGNAL_WAKEUP, 0, SIG_IGN);
1453 //restart control process:
1454 int32_t res = 0;
1455 int32_t status = 0;
1458 res = waitpid(pid, &status, 0);
1459 if(res == -1)
1461 if(errno != EINTR)
1462 { exit(1); }
1465 while(res != pid);
1467 if(cs_restart_mode == 2 && WIFSIGNALED(status) && WTERMSIG(status) == SIGSEGV)
1468 { status = 99; } //restart on segfault!
1469 else
1470 { status = WEXITSTATUS(status); }
1472 //status=99 restart oscam, all other->terminate
1473 if(status != 99)
1475 exit(status);
1480 void cs_restart_oscam(void)
1482 exit_oscam = 99;
1483 cs_log("restart oscam requested");
1486 int32_t cs_get_restartmode(void)
1488 return cs_restart_mode;
1490 #endif
1492 void cs_exit_oscam(void)
1494 exit_oscam = 1;
1495 cs_log("exit oscam requested");
1498 static void pidfile_create(char *pidfile)
1500 FILE *f = fopen(pidfile, "w");
1501 if(f)
1503 pid_t my_pid = getpid();
1504 cs_log("creating pidfile %s with pid %d", pidfile, my_pid);
1505 fprintf(f, "%d\n", my_pid);
1506 fclose(f);
1510 static bool running_under_valgrind;
1512 static void detect_valgrind(void)
1514 #ifdef __linux__
1515 char fname[32];
1516 snprintf(fname, sizeof(fname), "/proc/%d/maps", getpid());
1517 FILE *f = fopen(fname, "r");
1518 if (f) {
1519 char line[256];
1520 while (fgets(line, sizeof(line), f)) {
1521 if (strstr(line, "/valgrind/")) {
1522 running_under_valgrind = true;
1523 break;
1527 fclose(f);
1528 #endif
1531 #ifdef BUILD_TESTS
1532 extern void run_all_tests(void);
1533 __attribute__ ((noreturn)) static void run_tests(void)
1535 run_all_tests();
1536 exit(0);
1538 #else
1539 static void run_tests(void) { }
1540 #endif
1542 const struct s_cardsystem *cardsystems[] =
1544 #ifdef READER_NAGRA
1545 &reader_nagra,
1546 #endif
1547 #ifdef READER_IRDETO
1548 &reader_irdeto,
1549 #endif
1550 #ifdef READER_CONAX
1551 &reader_conax,
1552 #endif
1553 #ifdef READER_CRYPTOWORKS
1554 &reader_cryptoworks,
1555 #endif
1556 #ifdef READER_SECA
1557 &reader_seca,
1558 #endif
1559 #ifdef READER_VIACCESS
1560 &reader_viaccess,
1561 #endif
1562 #ifdef READER_VIDEOGUARD
1563 &reader_videoguard1,
1564 &reader_videoguard2,
1565 &reader_videoguard12,
1566 #endif
1567 #ifdef READER_DRE
1568 &reader_dre,
1569 #endif
1570 #ifdef READER_DRECAS
1571 &reader_drecas,
1572 #endif
1573 #ifdef READER_TONGFANG
1574 &reader_tongfang,
1575 #endif
1576 #ifdef READER_BULCRYPT
1577 &reader_bulcrypt,
1578 #endif
1579 #ifdef READER_GRIFFIN
1580 &reader_griffin,
1581 #endif
1582 #ifdef READER_DGCRYPT
1583 &reader_dgcrypt,
1584 #endif
1585 NULL
1588 const struct s_cardreader *cardreaders[] =
1590 #ifdef CARDREADER_DB2COM
1591 &cardreader_db2com,
1592 #endif
1593 #if defined(CARDREADER_INTERNAL_AZBOX)
1594 &cardreader_internal_azbox,
1595 #elif defined(CARDREADER_INTERNAL_COOLAPI)
1596 &cardreader_internal_cool,
1597 #elif defined(CARDREADER_INTERNAL_COOLAPI2)
1598 &cardreader_internal_cool,
1599 #elif defined(CARDREADER_INTERNAL_SCI)
1600 &cardreader_internal_sci,
1601 #endif
1602 #ifdef CARDREADER_PHOENIX
1603 &cardreader_mouse,
1604 #endif
1605 #ifdef CARDREADER_DRECAS
1606 &cardreader_drecas,
1607 #endif
1608 #ifdef CARDREADER_MP35
1609 &cardreader_mp35,
1610 #endif
1611 #ifdef CARDREADER_PCSC
1612 &cardreader_pcsc,
1613 #endif
1614 #ifdef CARDREADER_SC8IN1
1615 &cardreader_sc8in1,
1616 #endif
1617 #ifdef CARDREADER_SMARGO
1618 &cardreader_smargo,
1619 #endif
1620 #ifdef CARDREADER_SMART
1621 &cardreader_smartreader,
1622 #endif
1623 #if defined(CARDREADER_STAPI) || defined(CARDREADER_STAPI5)
1624 &cardreader_stapi,
1625 #endif
1626 #ifdef CARDREADER_STINGER
1627 &cardreader_stinger,
1628 #endif
1629 NULL
1632 static void find_conf_dir(void)
1634 static const char* confdirs[] =
1635 { "/etc/tuxbox/config/",
1636 "/etc/tuxbox/config/oscam/",
1637 "/var/tuxbox/config/",
1638 "/usr/keys/",
1639 "/var/keys/",
1640 "/var/etc/oscam/",
1641 "/var/etc/",
1642 "/var/oscam/",
1643 "/config/oscam/",
1644 NULL
1647 char conf_file[128+16];
1648 int32_t i;
1650 if(cs_confdir[strlen(cs_confdir) - 1] != '/')
1651 { strcat(cs_confdir, "/"); }
1653 if(snprintf(conf_file, sizeof(conf_file), "%soscam.conf", cs_confdir) < 0)
1654 { return; }
1656 if(!access(conf_file, F_OK))
1657 { return; }
1659 for(i=0; confdirs[i] != NULL; i++)
1661 if(snprintf(conf_file, sizeof(conf_file), "%soscam.conf", confdirs[i]) < 0)
1662 { return; }
1664 if (!access(conf_file, F_OK))
1666 cs_strncpy(cs_confdir, confdirs[i], sizeof(cs_confdir));
1667 return;
1672 int32_t main(int32_t argc, char *argv[])
1674 fix_stacksize();
1676 run_tests();
1677 int32_t i, j;
1678 prog_name = argv[0];
1679 struct timespec start_ts;
1680 cs_gettime(&start_ts); // Initialize clock_type
1682 if(pthread_key_create(&getclient, NULL))
1684 fprintf(stderr, "Could not create getclient, exiting...");
1685 exit(1);
1688 void (*mod_def[])(struct s_module *) =
1690 #ifdef MODULE_MONITOR
1691 module_monitor,
1692 #endif
1693 #ifdef MODULE_CAMD33
1694 module_camd33,
1695 #endif
1696 #ifdef MODULE_CAMD35
1697 module_camd35,
1698 #endif
1699 #ifdef MODULE_CAMD35_TCP
1700 module_camd35_tcp,
1701 #endif
1702 #ifdef MODULE_NEWCAMD
1703 module_newcamd,
1704 #endif
1705 #ifdef MODULE_CCCAM
1706 module_cccam,
1707 #endif
1708 #ifdef MODULE_PANDORA
1709 module_pandora,
1710 #endif
1711 #ifdef MODULE_GHTTP
1712 module_ghttp,
1713 #endif
1714 #ifdef CS_CACHEEX
1715 module_csp,
1716 #endif
1717 #ifdef MODULE_GBOX
1718 module_gbox,
1719 #endif
1720 #ifdef MODULE_CONSTCW
1721 module_constcw,
1722 #endif
1723 #ifdef MODULE_RADEGAST
1724 module_radegast,
1725 #endif
1726 #ifdef MODULE_SCAM
1727 module_scam,
1728 #endif
1729 #ifdef MODULE_SERIAL
1730 module_serial,
1731 #endif
1732 #ifdef HAVE_DVBAPI
1733 module_dvbapi,
1734 #endif
1738 find_conf_dir();
1740 parse_cmdline_params(argc, argv);
1742 if(bg && do_daemon(1, 0))
1744 printf("Error starting in background (errno=%d: %s)", errno, strerror(errno));
1745 cs_exit(1);
1748 get_random_bytes_init();
1750 #ifdef WEBIF
1751 if(cs_restart_mode)
1752 { restart_daemon(); }
1753 #endif
1755 memset(&cfg, 0, sizeof(struct s_config));
1756 cfg.max_pending = max_pending;
1758 if(cs_confdir[strlen(cs_confdir) - 1] != '/') { strcat(cs_confdir, "/"); }
1759 init_signal_pre(); // because log could cause SIGPIPE errors, init a signal handler first
1760 init_first_client();
1761 cs_lock_create(__func__, &system_lock, "system_lock", 5000);
1762 cs_lock_create(__func__, &config_lock, "config_lock", 10000);
1763 cs_lock_create(__func__, &gethostbyname_lock, "gethostbyname_lock", 10000);
1764 cs_lock_create(__func__, &clientlist_lock, "clientlist_lock", 5000);
1765 cs_lock_create(__func__, &readerlist_lock, "readerlist_lock", 5000);
1766 cs_lock_create(__func__, &fakeuser_lock, "fakeuser_lock", 5000);
1767 cs_lock_create(__func__, &ecmcache_lock, "ecmcache_lock", 5000);
1768 cs_lock_create(__func__, &ecm_pushed_deleted_lock, "ecm_pushed_deleted_lock", 5000);
1769 cs_lock_create(__func__, &readdir_lock, "readdir_lock", 5000);
1770 cs_lock_create(__func__, &cwcycle_lock, "cwcycle_lock", 5000);
1771 init_cache();
1772 cacheex_init_hitcache();
1773 init_config();
1774 cs_init_log();
1775 init_machine_info();
1776 init_check();
1777 if(!oscam_pidfile && cfg.pidfile)
1778 { oscam_pidfile = cfg.pidfile; }
1779 if(!oscam_pidfile)
1781 oscam_pidfile = get_tmp_dir_filename(default_pidfile, sizeof(default_pidfile), "oscam.pid");
1783 if(oscam_pidfile)
1784 { pidfile_create(oscam_pidfile); }
1785 cs_init_statistics();
1786 coolapi_open_all();
1787 init_stat();
1788 ssl_init();
1790 // These initializations *MUST* be called after init_config()
1791 // because modules depend on config values.
1792 for(i = 0; mod_def[i]; i++)
1794 struct s_module *module = &modules[i];
1795 mod_def[i](module);
1798 init_sidtab();
1799 init_readerdb();
1800 cfg.account = init_userdb();
1801 init_signal();
1802 init_provid();
1803 init_srvid();
1804 init_tierid();
1805 init_fakecws();
1807 start_garbage_collector(gbdb);
1809 cacheex_init();
1811 init_len4caid();
1812 init_irdeto_guess_tab();
1814 write_versionfile(false);
1816 led_init();
1817 led_status_default();
1819 azbox_init();
1821 mca_init();
1823 global_whitelist_read();
1824 ratelimit_read();
1826 #ifdef MODULE_SERIAL
1827 twin_read();
1828 #endif
1830 for(i = 0; i < CS_MAX_MOD; i++)
1832 struct s_module *module = &modules[i];
1833 if((module->type & MOD_CONN_NET))
1835 for(j = 0; j < module->ptab.nports; j++)
1837 start_listener(module, &module->ptab.ports[j]);
1842 //set time for server to now to avoid 0 in monitor/webif
1843 first_client->last = time((time_t *)0);
1845 webif_init();
1847 start_thread("reader check", (void *) &reader_check, NULL, NULL, 1, 1);
1848 cw_process_thread_start();
1849 checkcache_process_thread_start();
1851 lcd_thread_start();
1853 do_report_emm_support();
1855 init_cardreader();
1857 cs_waitforcardinit();
1859 emm_load_cache();
1860 load_emmstat_from_file();
1862 led_status_starting();
1864 ac_init();
1866 start_thread("card poll", (void *) &card_poll, NULL, NULL, 1, 1);
1868 for(i = 0; i < CS_MAX_MOD; i++)
1870 struct s_module *module = &modules[i];
1871 if((module->type & MOD_CONN_SERIAL) && module->s_handler)
1872 { module->s_handler(NULL, NULL, i); }
1875 // main loop function
1876 process_clients();
1878 SAFE_COND_SIGNAL(&card_poll_sleep_cond); // Stop card_poll thread
1879 cw_process_thread_wakeup(); // Stop cw_process thread
1880 SAFE_COND_SIGNAL(&reader_check_sleep_cond); // Stop reader_check thread
1882 // Cleanup
1883 #ifdef MODULE_GBOX
1884 stop_sms_sender();
1885 #endif
1886 webif_close();
1887 azbox_close();
1888 coolapi_close_all();
1889 mca_close();
1891 led_status_stopping();
1892 led_stop();
1893 lcd_thread_stop();
1895 remove_versionfile();
1897 stat_finish();
1898 dvbapi_stop_all_descrambling();
1899 dvbapi_save_channel_cache();
1900 emm_save_cache();
1901 save_emmstat_to_file();
1903 cccam_done_share();
1904 gbox_send_good_night();
1906 kill_all_clients();
1907 kill_all_readers();
1908 for(i = 0; i < CS_MAX_MOD; i++)
1910 struct s_module *module = &modules[i];
1911 if((module->type & MOD_CONN_NET))
1913 for(j = 0; j < module->ptab.nports; j++)
1915 struct s_port *port = &module->ptab.ports[j];
1916 if(port->fd)
1918 shutdown(port->fd, SHUT_RDWR);
1919 close(port->fd);
1920 port->fd = 0;
1926 if(oscam_pidfile)
1927 { unlink(oscam_pidfile); }
1929 // sleep a bit, so hopefully all threads are stopped when we continue
1930 cs_sleepms(200);
1932 free_cache();
1933 cacheex_free_hitcache();
1934 webif_tpls_free();
1935 init_free_userdb(cfg.account);
1936 cfg.account = NULL;
1937 init_free_sidtab();
1938 free_readerdb();
1939 free_irdeto_guess_tab();
1940 config_free();
1941 ssl_done();
1943 detect_valgrind();
1944 if (!running_under_valgrind)
1945 cs_log("cardserver down");
1946 else
1947 cs_log("running under valgrind, waiting 5 seconds before stopping cardserver");
1948 log_free();
1950 if (running_under_valgrind) sleep(5); // HACK: Wait a bit for things to settle
1952 stop_garbage_collector();
1954 NULLFREE(first_client->account);
1955 NULLFREE(first_client);
1956 free(stb_boxtype);
1957 free(stb_boxname);
1959 // This prevents the compiler from removing config_mak from the final binary
1960 syslog_ident = config_mak;
1962 return exit_oscam;