tsdecrypt reads and decrypts CSA encrypted incoming mpeg transport stream over UDP/RTP using code words obtained from OSCAM or similar CAM server. tsdecrypt communicates with CAM server using cs378x (camd35 over tcp) protocol or newcamd protocol. https://georgi.unixsol.org/programs/tsdecrypt/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tsdecrypt.c 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /*
  2. * tsdecrypt
  3. * Copyright (C) 2011-2012 Unix Solutions Ltd.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License (COPYING file) for more details.
  13. *
  14. */
  15. #include <stdlib.h>
  16. #include <unistd.h>
  17. #include <getopt.h>
  18. #include <string.h>
  19. #include <sys/types.h>
  20. #include <sys/stat.h>
  21. #include <signal.h>
  22. #include <fcntl.h>
  23. #include <errno.h>
  24. #include <syslog.h>
  25. #include <sys/resource.h>
  26. #include <openssl/rand.h>
  27. #include "libfuncs/libfuncs.h"
  28. #include "data.h"
  29. #include "util.h"
  30. #include "csa.h"
  31. #include "camd.h"
  32. #include "process.h"
  33. #include "udp.h"
  34. #include "notify.h"
  35. #define FIRST_REPORT_SEC 3
  36. #define PROGRAM_NAME "tsdecrypt"
  37. static const char *program_id = PROGRAM_NAME " v" VERSION " (" GIT_VER ", build " BUILD_ID " " DLIB ")";
  38. static int keep_running = 1;
  39. static FILE *log_file = NULL;
  40. static char *log_filename = NULL;
  41. static int local_syslog = 0;
  42. static int remote_syslog = 0;
  43. static void do_log(FILE *f, time_t now, const char *msg) {
  44. char date[64];
  45. struct tm tm;
  46. localtime_r(&now, &tm);
  47. strftime(date, sizeof(date), "%F %H:%M:%S", localtime_r(&now, &tm));
  48. fprintf(f, "%s | %s", date, msg);
  49. }
  50. static void LOG_func(const char *msg) {
  51. time_t now = time(NULL);
  52. do_log(stderr, now, msg);
  53. if (log_file)
  54. do_log(log_file, now, msg);
  55. if (local_syslog)
  56. syslog(LOG_INFO, msg, strlen(msg));
  57. if (remote_syslog)
  58. LOG(msg);
  59. }
  60. static const char short_options[] = "i:d:N:Sl:L:F:I:RzM:T:W:O:o:t:rk:g:upwxyc:C:Y:Q:A:s:U:P:B:eZ:Ef:X:H:G:KJ:D:jbhV";
  61. // Unused short options: amnqv0123456789
  62. static const struct option long_options[] = {
  63. { "ident", required_argument, NULL, 'i' },
  64. { "daemon", required_argument, NULL, 'd' },
  65. { "syslog", no_argument, NULL, 'S' },
  66. { "syslog-host", required_argument, NULL, 'l' },
  67. { "syslog-port", required_argument, NULL, 'L' },
  68. { "log-file", required_argument, NULL, 'F' },
  69. { "notify-program", required_argument, NULL, 'N' },
  70. { "input", required_argument, NULL, 'I' },
  71. { "input-rtp", no_argument, NULL, 'R' },
  72. { "input-ignore-disc", no_argument, NULL, 'z' },
  73. { "input-service", required_argument, NULL, 'M' },
  74. { "input-buffer", required_argument, NULL, 'T' },
  75. { "input-dump", required_argument, NULL, 'W' },
  76. { "output", required_argument, NULL, 'O' },
  77. { "output-intf", required_argument, NULL, 'o' },
  78. { "output-ttl", required_argument, NULL, 't' },
  79. { "output-rtp", no_argument, NULL, 'r' },
  80. { "output-rtp-ssrc", required_argument, NULL, 'k' },
  81. { "output-tos", required_argument, NULL, 'g' },
  82. { "no-output-on-error", no_argument, NULL, 'u' },
  83. { "no-output-filter", no_argument, NULL, 'p' },
  84. { "output-nit-pass", no_argument, NULL, 'y' },
  85. { "output-eit-pass", no_argument, NULL, 'w' },
  86. { "output-tdt-pass", no_argument, NULL, 'x' },
  87. { "ca-system", required_argument, NULL, 'c' },
  88. { "caid", required_argument, NULL, 'C' },
  89. { "const-cw", required_argument, NULL, 'Y' },
  90. { "biss-key", required_argument, NULL, 'Q' },
  91. { "camd-proto", required_argument, NULL, 'A' },
  92. { "camd-server", required_argument, NULL, 's' },
  93. { "camd-user", required_argument, NULL, 'U' },
  94. { "camd-pass", required_argument, NULL, 'P' },
  95. { "camd-des-key", required_argument, NULL, 'B' },
  96. { "emm", no_argument, NULL, 'e' },
  97. { "emm-pid", required_argument, NULL, 'Z' },
  98. { "emm-only", no_argument, NULL, 'E' },
  99. { "emm-report-time", required_argument, NULL, 'f' },
  100. { "ecm-pid", required_argument, NULL, 'X' },
  101. { "ecm-report-time", required_argument, NULL, 'H' },
  102. { "ecm-irdeto-type", required_argument, NULL, 'G' },
  103. { "ecm-no-log", no_argument , NULL, 'K' },
  104. { "cw-warn-time", required_argument, NULL, 'J' },
  105. { "debug", required_argument, NULL, 'D' },
  106. { "pid-report", no_argument, NULL, 'j' },
  107. { "bench", no_argument, NULL, 'b' },
  108. { "help", no_argument, NULL, 'h' },
  109. { "version", no_argument, NULL, 'V' },
  110. { 0, 0, 0, 0 }
  111. };
  112. static void show_help(struct ts *ts) {
  113. printf("%s\n", program_id);
  114. printf("Copyright (C) 2011-2012 Unix Solutions Ltd.\n");
  115. printf("\n");
  116. printf(" Usage: " PROGRAM_NAME " [opts]\n");
  117. printf("\n");
  118. printf("Main options:\n");
  119. printf(" -i --ident <server> | Format PROVIDER/CHANNEL. Default: empty\n");
  120. printf(" -d --daemon <pidfile> | Daemonize program and write pid file.\n");
  121. printf(" -N --notify-program <prg> | Execute <prg> to report events. Default: empty\n");
  122. printf("\n");
  123. printf("Input options:\n");
  124. printf(" -I --input <source> | Where to read from. File or multicast address.\n");
  125. printf(" . -I 224.0.0.1:5000 (multicast receive)\n");
  126. printf(" . -I file.ts (read from file)\n");
  127. printf(" . -I - (read from stdin) (default)\n");
  128. printf(" -R --input-rtp | Enable RTP input\n");
  129. printf(" -z --input-ignore-disc | Do not report discontinuty errors in input.\n");
  130. printf(" -M --input-service <srvid> | Choose service id when input is MPTS.\n");
  131. printf(" -T --input-buffer <ms> | Set input buffer time in ms. Default: %u\n", ts->input_buffer_time);
  132. printf(" -W --input-dump <filename> | Save input stream in file.\n");
  133. printf("\n");
  134. printf("Output options:\n");
  135. printf(" -O --output <dest> | Where to send output. File or multicast address.\n");
  136. printf(" . -O 239.0.0.1:5000 (multicast send)\n");
  137. printf(" . -O file.ts (write to file)\n");
  138. printf(" . -O - (write to stdout) (default)\n");
  139. printf(" -o --output-intf <addr> | Set multicast output interface. Default: %s\n", inet_ntoa(ts->output.intf));
  140. printf(" -t --output-ttl <ttl> | Set multicast ttl. Default: %d\n", ts->output.ttl);
  141. printf(" -r --output-rtp | Enable RTP output.\n");
  142. printf(" -k --output-rtp-ssrc <id> | Set RTP SSRC. Default: %u\n", ts->rtp_ssrc);
  143. printf(" -g --output-tos <tos> | Set TOS value of output packets. Default: none\n");
  144. printf(" -u --no-output-on-error | Do not output data when the code word is missing.\n");
  145. printf(" -p --no-output-filter | Disable output filtering. Default: %s\n", ts->pid_filter ? "enabled" : "disabled");
  146. printf(" -y --output-nit-pass | Pass through NIT.\n");
  147. printf(" -w --output-eit-pass | Pass through EIT (EPG).\n");
  148. printf(" -x --output-tdt-pass | Pass through TDT/TOT.\n");
  149. printf("\n");
  150. printf("CA options:\n");
  151. printf(" -c --ca-system <ca_sys> | Process input EMM/ECM from <ca_sys>.\n");
  152. printf(" | Valid systems are: CONAX (default), CRYPTOWORKS,\n");
  153. printf(" . IRDETO, SECA (MEDIAGUARD), VIACCESS,\n");
  154. printf(" . VIDEOGUARD (NDS), NAGRA, DRECRYPT and BULCRYPT.\n");
  155. printf(" -C --caid <caid> | Set CAID. Default: Taken from --ca-system.\n");
  156. printf(" -Y --const-cw <codeword> | Set constant code word for decryption.\n");
  157. printf(" . Example cw: a1a2a3a4a5a6a7a8b1b2b3b4b5b6b7b8\n");
  158. printf(" -Q --biss-key <biss-key> | Set BISS key for decryption.\n");
  159. printf(" . Example key: 112233445566\n");
  160. printf("\n");
  161. printf("CAMD server options:\n");
  162. printf(" -A --camd-proto <proto> | Set CAMD network protocol.\n");
  163. printf(" . Valid protocols are: CS378X (default) and NEWCAMD\n");
  164. printf(" -s --camd-server <addr> | Set CAMD server ip_address:port (1.2.3.4:2233).\n");
  165. printf(" -U --camd-user <user> | Set CAMD server user. Default: %s\n", ts->camd.user);
  166. printf(" -P --camd-pass <pass> | Set CAMD server password. Default: %s\n", ts->camd.pass);
  167. printf(" -B --camd-des-key <key> | Set DES key for newcamd protocol.\n");
  168. printf(" . Default: %s\n", ts->camd.newcamd.hex_des_key);
  169. printf("\n");
  170. printf("EMM options:\n");
  171. printf(" -e --emm | Enable sending EMM's to CAMD. Default: %s\n", ts->emm_send ? "enabled" : "disabled");
  172. printf(" -E --emm-only | Send only EMMs to CAMD, skipping ECMs and without\n");
  173. printf(" . decoding the input stream.\n");
  174. printf(" -Z --emm-pid <pid> | Force EMM pid. Default: none\n");
  175. printf(" -f --emm-report-time <sec> | Report each <sec> seconds how much EMMs have been\n");
  176. printf(" . received/processed. Set <sec> to 0 to disable\n");
  177. printf(" . the reports. Default: %d sec\n", ts->emm_report_interval);
  178. printf("\n");
  179. printf("ECM options:\n");
  180. printf(" -X --ecm-pid <pid> | Force ECM pid. Default: none\n");
  181. printf(" -H --ecm-report-time <sec> | Report each <sec> how much ECMs and CWs have been\n");
  182. printf(" . processed/skipped. Set <sec> to 0 to disable\n");
  183. printf(" . the reports. Default: %d sec\n", ts->ecm_report_interval);
  184. printf(" -G --ecm-irdeto-type <int> | Process IRDETO ECMs with type X /0-3/. Default: %d\n", ts->irdeto_ecm);
  185. printf(" -K --ecm-no-log | Disable ECM and code words logging.\n");
  186. printf(" -J --cw-warn-time <sec> | Warn if no valid code word has been received.\n");
  187. printf(" . Set <sec> to 0 to disable. Default: %d sec\n", ts->cw_warn_sec);
  188. printf("\n");
  189. printf("Logging options:\n");
  190. printf(" -S --syslog | Log messages using syslog.\n");
  191. printf(" -l --syslog-host <host> | Syslog server address. Default: disabled\n");
  192. printf(" -L --syslog-port <port> | Syslog server port. Default: %d\n", ts->syslog_port);
  193. printf(" -F --log-file <filename> | Log to file <filename>.\n");
  194. printf(" -D --debug <level> | Message debug level.\n");
  195. printf(" . 0 = default messages\n");
  196. printf(" . 1 = show PSI tables\n");
  197. printf(" . 2 = show EMMs\n");
  198. printf(" . 3 = show duplicate ECMs\n");
  199. printf(" . 4 = packet debug\n");
  200. printf(" . 5 = packet debug + packet dump\n");
  201. printf("\n");
  202. printf("Misc options:\n");
  203. printf(" -j --pid-report | Report how much packets were received.\n");
  204. printf(" -b --bench | Benchmark decrypton.\n");
  205. printf(" -h --help | Show help screen.\n");
  206. printf(" -V --version | Show program version.\n");
  207. printf("\n");
  208. }
  209. static int parse_io_param(struct io *io, char *opt, int open_flags, mode_t open_mode) {
  210. io->type = WTF_IO;
  211. char *p = strrchr(opt, ':');
  212. if (!p) {
  213. io->type = FILE_IO;
  214. if (strcmp(opt, "-") != 0) {
  215. io->fd = open(opt, open_flags, open_mode);
  216. if (io->fd < 0) {
  217. fprintf(stderr, "ERROR: Can not open file (%s): %s\n", opt, strerror(errno));
  218. exit(EXIT_FAILURE);
  219. }
  220. }
  221. io->fname = strdup(opt);
  222. return 0;
  223. }
  224. *p = 0x00;
  225. io->type = NET_IO;
  226. io->port = atoi(p + 1);
  227. if (inet_aton(opt, &io->addr) == 0)
  228. return 1;
  229. return 0;
  230. }
  231. static void parse_options(struct ts *ts, int argc, char **argv) {
  232. int j, i, ca_err = 0, server_err = 1, input_addr_err = 0, output_addr_err = 0, output_intf_err = 0, ident_err = 0, port_set = 0;
  233. while ((j = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) {
  234. char *p = NULL;
  235. switch (j) {
  236. case 'i': // -- ident
  237. ts->ident = optarg;
  238. break;
  239. case 'd': // --daemon
  240. ts->pidfile = optarg;
  241. break;
  242. case 'N': // --notify-program
  243. ts->notify_program = optarg;
  244. break;
  245. case 'S': // --syslog
  246. ts->syslog_active = 1;
  247. ts->syslog_remote = 0;
  248. break;
  249. case 'l': // --syslog-host
  250. ts->syslog_host = optarg;
  251. ts->syslog_active = 1;
  252. ts->syslog_remote = 1;
  253. break;
  254. case 'L': // --syslog-port
  255. ts->syslog_port = atoi(optarg);
  256. break;
  257. case 'F': // --log-file
  258. log_filename = optarg;
  259. break;
  260. case 'I': // --input
  261. input_addr_err = parse_io_param(&ts->input, optarg, O_RDONLY, 0);
  262. break;
  263. case 'R': // --input-rtp
  264. ts->rtp_input = !ts->rtp_input;
  265. break;
  266. case 'z': // --input-ignore-disc
  267. ts->ts_discont = !ts->ts_discont;
  268. break;
  269. case 'M': // --input-service
  270. ts->forced_service_id = strtoul(optarg, NULL, 0) & 0xffff;
  271. break;
  272. case 'T': // --input-buffer
  273. ts->input_buffer_time = strtoul(optarg, NULL, 0);
  274. break;
  275. case 'W': // --input-dump
  276. ts->input_dump_filename = optarg;
  277. break;
  278. case 'O': // --output
  279. output_addr_err = parse_io_param(&ts->output, optarg,
  280. O_CREAT | O_WRONLY | O_TRUNC,
  281. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  282. break;
  283. case 'o': // --output-intf
  284. if (inet_aton(optarg, &ts->output.intf) == 0)
  285. output_intf_err = 1;
  286. break;
  287. case 't': // --output-ttl
  288. ts->output.ttl = atoi(optarg);
  289. break;
  290. case 'r': // --output-rtp
  291. ts->rtp_output = 1;
  292. break;
  293. case 'k': // --output-rtp-ssrc
  294. ts->rtp_ssrc = strtoul(optarg, NULL, 0);
  295. break;
  296. case 'g': // --output-tos
  297. ts->output.tos = (uint8_t)strtol(optarg, NULL, 0);
  298. break;
  299. case 'u': // --no-output-on-error
  300. ts->no_output_on_error = !ts->no_output_on_error;
  301. break;
  302. case 'p': // --no-output-filter
  303. ts->pid_filter = !ts->pid_filter;
  304. break;
  305. case 'y': // --output-nit-pass
  306. ts->nit_passthrough = !ts->nit_passthrough;
  307. break;
  308. case 'w': // --output-eit-pass
  309. ts->eit_passthrough = !ts->eit_passthrough;
  310. break;
  311. case 'x': // --output-tdt-pass
  312. ts->tdt_passthrough = !ts->tdt_passthrough;
  313. break;
  314. case 'c': // --ca-system
  315. if (strcasecmp("IRDETO", optarg) == 0)
  316. ts->req_CA_sys = CA_IRDETO;
  317. else if (strcasecmp("CONNAX", optarg) == 0 || strcasecmp("CONAX", optarg) == 0)
  318. ts->req_CA_sys = CA_CONAX;
  319. else if (strcasecmp("CRYPTOWORKS", optarg) == 0)
  320. ts->req_CA_sys = CA_CRYPTOWORKS;
  321. else if (strcasecmp("SECA", optarg) == 0 || strcasecmp("MEDIAGUARD", optarg) == 0)
  322. ts->req_CA_sys = CA_SECA;
  323. else if (strcasecmp("VIACCESS", optarg) == 0)
  324. ts->req_CA_sys = CA_VIACCESS;
  325. else if (strcasecmp("VIDEOGUARD", optarg) == 0 || strcasecmp("NDS", optarg) == 0)
  326. ts->req_CA_sys = CA_VIDEOGUARD;
  327. else if (strcasecmp("NAGRA", optarg) == 0)
  328. ts->req_CA_sys = CA_NAGRA;
  329. else if (strcasecmp("DRE-CRYPT", optarg) == 0 || strcasecmp("DRECRYPT", optarg) == 0)
  330. ts->req_CA_sys = CA_DRECRYPT;
  331. else if (strcasecmp("BULCRYPT", optarg) == 0)
  332. ts->req_CA_sys = CA_BULCRYPT;
  333. else
  334. ca_err = 1;
  335. break;
  336. case 'C': // --caid
  337. ts->forced_caid = strtoul(optarg, NULL, 0) & 0xffff;
  338. break;
  339. case 'Y': // --const-cw
  340. ts->camd.constant_codeword = 1;
  341. if (strlen(optarg) > 2 && optarg[0] == '0' && optarg[1] == 'x')
  342. optarg += 2;
  343. if (strlen(optarg) != CODEWORD_LENGTH * 2) {
  344. fprintf(stderr, "ERROR: Constant code word should be %u characters long.\n", CODEWORD_LENGTH * 2);
  345. exit(EXIT_FAILURE);
  346. }
  347. if (decode_hex_string(optarg, ts->camd.key->cw, strlen(optarg)) < 0) {
  348. fprintf(stderr, "ERROR: Invalid hex string for constant code word: %s\n", optarg);
  349. exit(EXIT_FAILURE);
  350. }
  351. camd_set_cw(ts, ts->camd.key->cw, 0);
  352. ts->camd.key->is_valid_cw = 1;
  353. break;
  354. case 'Q': // --biss-key
  355. ts->camd.constant_codeword = 1;
  356. if (strlen(optarg) > 2 && optarg[0] == '0' && optarg[1] == 'x')
  357. optarg += 2;
  358. uint8_t *key = ts->camd.key->cw;
  359. // Sometimes the BISS keys are entered with their checksums already calculated (16 symbols, 8 bytes)
  360. // This is the same as constant cw with the same key for even and odd
  361. if (strlen(optarg) == (BISSKEY_LENGTH + 2) * 2) {
  362. if (decode_hex_string(optarg, key, strlen(optarg)) < 0) {
  363. fprintf(stderr, "ERROR: Invalid hex string for BISS key: %s\n", optarg);
  364. exit(EXIT_FAILURE);
  365. }
  366. } else {
  367. // BISS key without checksum (12 symbols, 6 bytes)
  368. if (strlen(optarg) != BISSKEY_LENGTH * 2) {
  369. fprintf(stderr, "ERROR: BISS key should be %u characters long.\n", BISSKEY_LENGTH * 2);
  370. exit(EXIT_FAILURE);
  371. }
  372. if (decode_hex_string(optarg, key, strlen(optarg)) < 0) {
  373. fprintf(stderr, "ERROR: Invalid hex string for BISS key: %s\n", optarg);
  374. exit(EXIT_FAILURE);
  375. }
  376. // Calculate BISS KEY crc
  377. memmove(key + 4, key + 3, 3);
  378. key[3] = (uint8_t)(key[0] + key[1] + key[2]);
  379. key[7] = (uint8_t)(key[4] + key[5] + key[6]);
  380. }
  381. // Even and odd keys are the same
  382. memcpy(key + 8, key, 8);
  383. camd_set_cw(ts, ts->camd.key->cw, 0);
  384. ts->camd.key->is_valid_cw = 1;
  385. break;
  386. case 'A': // --camd-proto
  387. if (strcasecmp(optarg, "cs378x") == 0) {
  388. camd_proto_cs378x(&ts->camd.ops);
  389. } else if (strcasecmp(optarg, "newcamd") == 0) {
  390. camd_proto_newcamd(&ts->camd.ops);
  391. } else {
  392. fprintf(stderr, "Unknown CAMD protocol: %s\n", optarg);
  393. exit(EXIT_FAILURE);
  394. }
  395. break;
  396. case 's': // --camd-server
  397. p = strrchr(optarg, ':');
  398. if (p) {
  399. *p = 0x00;
  400. ts->camd.server_port = atoi(p + 1);
  401. port_set = 1;
  402. }
  403. if (inet_aton(optarg, &ts->camd.server_addr) == 0)
  404. server_err = 1;
  405. else
  406. server_err = 0;
  407. break;
  408. case 'U': // --camd-user
  409. if (strlen(optarg) < 64)
  410. ts->camd.user = optarg;
  411. break;
  412. case 'P': // --camd-pass
  413. ts->camd.pass = optarg;
  414. break;
  415. case 'B': // --camd-des-key
  416. if (strlen(optarg) > 2 && optarg[0] == '0' && optarg[1] == 'x')
  417. optarg += 2;
  418. if (strlen(optarg) != DESKEY_LENGTH) {
  419. fprintf(stderr, "ERROR: des key should be %u characters long.\n", DESKEY_LENGTH);
  420. exit(EXIT_FAILURE);
  421. }
  422. strncpy(ts->camd.newcamd.hex_des_key, optarg, sizeof(ts->camd.newcamd.hex_des_key) - 1);
  423. ts->camd.newcamd.hex_des_key[sizeof(ts->camd.newcamd.hex_des_key) - 1] = 0;
  424. break;
  425. case 'e': // --emm
  426. ts->emm_send = !ts->emm_send;
  427. break;
  428. case 'Z': // --emm-pid
  429. ts->forced_emm_pid = strtoul(optarg, NULL, 0) & 0x1fff;
  430. break;
  431. case 'E': // --emm-only
  432. ts->emm_only = 1;
  433. ts->emm_send = 1;
  434. break;
  435. case 'f': // --emm-report-time
  436. ts->emm_report_interval = strtoul(optarg, NULL, 10);
  437. if (ts->emm_report_interval > 86400)
  438. ts->emm_report_interval = 86400;
  439. break;
  440. case 'X': // --ecm-pid
  441. ts->forced_ecm_pid = strtoul(optarg, NULL, 0) & 0x1fff;
  442. break;
  443. case 'H': // --ecm-report-time
  444. ts->ecm_report_interval = strtoul(optarg, NULL, 10);
  445. if (ts->ecm_report_interval > 86400)
  446. ts->ecm_report_interval = 86400;
  447. break;
  448. case 'G': // --ecm-irdeto-type
  449. ts->irdeto_ecm = atoi(optarg);
  450. break;
  451. case 'K': // --ecm-no-log
  452. ts->ecm_cw_log = !ts->ecm_cw_log;
  453. break;
  454. case 'J': // --cw-warn-time
  455. ts->cw_warn_sec = strtoul(optarg, NULL, 10);
  456. if (ts->cw_warn_sec > 86400)
  457. ts->cw_warn_sec = 86400;
  458. ts->cw_last_warn= ts->cw_last_warn + ts->cw_warn_sec;
  459. break;
  460. case 'D': // --debug
  461. ts->debug_level = atoi(optarg);
  462. if (ts->debug_level > 0)
  463. ts->pid_report = 1;
  464. break;
  465. case 'j': // --pid-report
  466. ts->pid_report = 1;
  467. break;
  468. case 'b': // --bench
  469. csa_benchmark();
  470. exit(EXIT_SUCCESS);
  471. case 'h': // --help
  472. show_help(ts);
  473. exit(EXIT_SUCCESS);
  474. case 'V': // --version
  475. printf("%s\n", program_id);
  476. exit(EXIT_SUCCESS);
  477. }
  478. }
  479. if (!ts->ident) {
  480. if (ts->syslog_active || ts->notify_program)
  481. ident_err = 1;
  482. }
  483. // Constant codeword is special. Disable conflicting options
  484. if (ts->camd.constant_codeword) {
  485. server_err = 0; // No server settings are required
  486. ts->forced_caid = 0;
  487. ts->forced_ecm_pid = 0;
  488. ts->forced_emm_pid = 0;
  489. ts->emm_send = 0;
  490. ts->emm_report_interval = 0;
  491. ts->ecm_report_interval = 0;
  492. ts->cw_warn_sec = 0;
  493. }
  494. if (ident_err || ca_err || server_err || input_addr_err || output_addr_err || ts->input.type == WTF_IO || ts->output.type == WTF_IO) {
  495. show_help(ts);
  496. if (ident_err)
  497. fprintf(stderr, "ERROR: Ident is not set, please use --ident option.\n");
  498. if (ca_err)
  499. fprintf(stderr, "ERROR: Requested CA system is unsupported.\n");
  500. if (server_err)
  501. fprintf(stderr, "ERROR: CAMD server IP address is not set or it is invalid.\n");
  502. if (input_addr_err)
  503. fprintf(stderr, "ERROR: Input IP address is invalid.\n");
  504. if (output_addr_err)
  505. fprintf(stderr, "ERROR: Output IP address is invalid.\n");
  506. if (output_intf_err)
  507. fprintf(stderr, "ERROR: Output interface address is invalid.\n");
  508. exit(EXIT_FAILURE);
  509. }
  510. if (decode_hex_string(ts->camd.newcamd.hex_des_key, ts->camd.newcamd.bin_des_key, DESKEY_LENGTH) < 0) {
  511. fprintf(stderr, "ERROR: Invalid hex string for des key: %s\n", ts->camd.newcamd.hex_des_key);
  512. exit(EXIT_FAILURE);
  513. }
  514. if (ts->camd.ops.proto == CAMD_NEWCAMD && !port_set) {
  515. fprintf(stderr, "ERROR: CAMD server port is not set. Use --camd-server %s:xxxx to set the port.\n", inet_ntoa(ts->camd.server_addr));
  516. exit(EXIT_FAILURE);
  517. }
  518. if (log_filename) {
  519. log_file = fopen(log_filename, "a");
  520. if (!log_file) {
  521. fprintf(stderr, "ERROR: Can't open log file %s: %s\n", log_filename, strerror(errno));
  522. exit(EXIT_FAILURE);
  523. }
  524. }
  525. if (ts->ident)
  526. ts_LOGf("Ident : %s\n", ts->ident);
  527. if (ts->notify_program)
  528. ts_LOGf("Notify prg : %s\n", ts->notify_program);
  529. if (ts->pidfile)
  530. ts_LOGf("Daemonize : %s pid file.\n", ts->pidfile);
  531. if (ts->syslog_active) {
  532. if (ts->syslog_remote)
  533. ts_LOGf("Syslog : %s:%d\n", ts->syslog_host, ts->syslog_port);
  534. else
  535. ts_LOGf("Syslog : enabled\n");
  536. } else
  537. ts_LOGf("Syslog : disabled\n");
  538. if (!ts->camd.constant_codeword) {
  539. if (ts->forced_caid)
  540. ts->req_CA_sys = ts_get_CA_sys(ts->forced_caid);
  541. if (!ts->forced_caid)
  542. ts_LOGf("CA System : %s\n", ts_get_CA_sys_txt(ts->req_CA_sys));
  543. else
  544. ts_LOGf("CA System : %s | CAID: 0x%04x (%d)\n",
  545. ts_get_CA_sys_txt(ts->req_CA_sys),
  546. ts->forced_caid, ts->forced_caid);
  547. } else {
  548. char cw_even[64], cw_odd[64];
  549. ts_hex_dump_buf(cw_even, sizeof(cw_even), ts->key.cw , 8, 0);
  550. ts_hex_dump_buf(cw_odd , sizeof(cw_odd ), ts->key.cw + 8, 8, 0);
  551. ts_LOGf("Constant CW: even = %s\n", cw_even);
  552. ts_LOGf("Constant CW: odd = %s\n", cw_odd);
  553. }
  554. if (ts->input.type == NET_IO) {
  555. ts_LOGf("Input addr : %s://%s:%u/\n",
  556. ts->rtp_input ? "rtp" : "udp",
  557. inet_ntoa(ts->input.addr), ts->input.port);
  558. if (ts->input_buffer_time) {
  559. ts_LOGf("Input buff : %u ms\n", ts->input_buffer_time);
  560. }
  561. } else if (ts->input.type == FILE_IO) {
  562. ts_LOGf("Input file : %s\n", ts->input.fd == 0 ? "STDIN" : ts->input.fname);
  563. }
  564. if (ts->input_dump_filename) {
  565. ts->input_dump_file = fopen(ts->input_dump_filename, "w");
  566. if (ts->input_dump_file)
  567. ts_LOGf("Input dump : %s\n", ts->input_dump_filename);
  568. else
  569. ts_LOGf("Input dump : %s | ERROR: %s\n", ts->input_dump_filename, strerror(errno));
  570. }
  571. if (ts->forced_service_id)
  572. ts_LOGf("Service id : 0x%04x (%d)\n",
  573. ts->forced_service_id, ts->forced_service_id);
  574. if (ts->req_CA_sys == CA_IRDETO)
  575. ts_LOGf("Irdeto ECM : %d\n", ts->irdeto_ecm);
  576. if (!ts->emm_only)
  577. {
  578. if (ts->output.type == NET_IO) {
  579. ts_LOGf("Output addr: %s://%s:%u/\n",
  580. ts->rtp_output ? "rtp" : "udp",
  581. inet_ntoa(ts->output.addr), ts->output.port);
  582. ts_LOGf("Output intf: %s\n", inet_ntoa(ts->output.intf));
  583. ts_LOGf("Output ttl : %d\n", ts->output.ttl);
  584. if (ts->output.tos > -1)
  585. ts_LOGf("Output TOS : %u (0x%02x)\n", ts->output.tos, ts->output.tos);
  586. if (ts->rtp_output) {
  587. ts_LOGf("RTP SSRC : %u (0x%04x)\n",
  588. ts->rtp_ssrc, ts->rtp_ssrc);
  589. // It is recommended that RTP seqnum starts with random number
  590. RAND_bytes((unsigned char *)&(ts->rtp_seqnum), 2);
  591. }
  592. } else if (ts->output.type == FILE_IO) {
  593. ts_LOGf("Output file: %s\n", ts->output.fd == 1 ? "STDOUT" : ts->output.fname);
  594. }
  595. ts_LOGf("Out filter : %s (%s)%s\n",
  596. ts->pid_filter ? "enabled" : "disabled",
  597. ts->pid_filter ? "output only service related PIDs" : "output everything",
  598. ts->no_output_on_error ? " (No output on CW error)" : ""
  599. );
  600. if (ts->pid_filter) {
  601. if (ts->nit_passthrough)
  602. ts_LOGf("Out filter : Pass through NIT.\n");
  603. if (ts->eit_passthrough)
  604. ts_LOGf("Out filter : Pass through EIT (EPG).\n");
  605. if (ts->tdt_passthrough)
  606. ts_LOGf("Out filter : Pass through TDT/TOT.\n");
  607. }
  608. }
  609. if (!ts->camd.constant_codeword) {
  610. ts_LOGf("CAMD proto : %s\n", ts->camd.ops.ident);
  611. ts_LOGf("CAMD addr : tcp://%s:%u/\n", inet_ntoa(ts->camd.server_addr), ts->camd.server_port);
  612. ts_LOGf("CAMD user : %s\n", ts->camd.user);
  613. ts_LOGf("CAMD pass : %s\n", ts->camd.pass);
  614. if (ts->camd.ops.proto == CAMD_NEWCAMD)
  615. ts_LOGf("CAMD deskey: %s\n", ts->camd.newcamd.hex_des_key);
  616. }
  617. ts_LOGf("TS discont : %s\n", ts->ts_discont ? "report" : "ignore");
  618. ts->threaded = !(ts->input.type == FILE_IO && ts->input.fd != 0);
  619. if (ts->emm_send && ts->emm_report_interval)
  620. ts_LOGf("EMM report : %d sec\n", ts->emm_report_interval);
  621. if (ts->emm_send && ts->emm_report_interval == 0)
  622. ts_LOGf("EMM report : disabled\n");
  623. if (ts->forced_emm_pid)
  624. ts_LOGf("EMM pid : 0x%04x (%d)\n", ts->forced_emm_pid, ts->forced_emm_pid);
  625. if (ts->emm_only) {
  626. ts_LOGf("EMM only : %s\n", ts->emm_only ? "yes" : "no");
  627. } else {
  628. if (!ts->camd.constant_codeword)
  629. ts_LOGf("EMM send : %s\n", ts->emm_send ? "enabled" : "disabled");
  630. ts_LOGf("Decoding : %s\n", ts->threaded ? "threaded" : "single thread");
  631. }
  632. if (!ts->emm_only && ts->ecm_report_interval)
  633. ts_LOGf("ECM report : %d sec\n", ts->emm_report_interval);
  634. if (!ts->emm_only && ts->ecm_report_interval == 0 && !ts->camd.constant_codeword)
  635. ts_LOGf("ECM report : disabled\n");
  636. if (ts->forced_ecm_pid)
  637. ts_LOGf("ECM pid : 0x%04x (%d)\n", ts->forced_ecm_pid, ts->forced_ecm_pid);
  638. if (!ts->emm_only && ts->cw_warn_sec)
  639. ts_LOGf("CW warning : %d sec\n", ts->cw_warn_sec);
  640. if (!ts->emm_only && ts->cw_warn_sec && !ts->camd.constant_codeword)
  641. ts_LOGf("CW warning : disabled\n");
  642. if (!ts->ecm_cw_log && !ts->camd.constant_codeword)
  643. ts_LOGf("ECM/CW log : disabled\n");
  644. if (ts->ident) {
  645. int len = strlen(ts->ident);
  646. for (i = 0; i < len; i++) {
  647. if (ts->ident[i] == '/')
  648. ts->ident[i] = '-';
  649. }
  650. }
  651. }
  652. static void report_emms(struct ts *ts, time_t now) {
  653. ts_LOGf("EMM | Received %u and processed %u in %lu seconds.\n",
  654. ts->emm_seen_count,
  655. ts->emm_processed_count,
  656. now - ts->emm_last_report);
  657. if (ts->emm_seen_count == 0) {
  658. notify(ts, "NO_EMM_RECEIVED", "No EMMs were received in last %lu seconds.",
  659. now - ts->emm_last_report);
  660. }
  661. ts->emm_last_report = now;
  662. ts->emm_seen_count = 0;
  663. ts->emm_processed_count = 0;
  664. }
  665. static void report_ecms(struct ts *ts, time_t now) {
  666. ts_LOGf("ECM | Received %u (%u dup) and processed %u in %lu seconds.\n",
  667. ts->ecm_seen_count,
  668. ts->ecm_duplicate_count,
  669. ts->ecm_processed_count,
  670. now - ts->ecm_last_report);
  671. ts->ecm_last_report = now;
  672. ts->ecm_seen_count = 0;
  673. ts->ecm_duplicate_count = 0;
  674. ts->ecm_processed_count = 0;
  675. }
  676. static void report_cw_warn(struct ts *ts, time_t now) {
  677. if (now - ts->key.ts > 1) {
  678. notify(ts, "NO_CODE_WORD", "No valid code word was received in %ld sec.",
  679. now - ts->key.ts);
  680. ts_LOGf("CW | *ERR* No valid code word was received for %ld seconds!\n",
  681. now - ts->key.ts);
  682. }
  683. ts->cw_last_warn = now;
  684. ts->cw_next_warn = now + ts->cw_warn_sec;
  685. }
  686. static void do_reports(struct ts *ts) {
  687. static int first_emm_report = 1;
  688. static int first_ecm_report = 1;
  689. time_t now = time(NULL);
  690. if (ts->emm_send && ts->emm_report_interval) {
  691. if (first_emm_report && now >= ts->emm_last_report) {
  692. first_emm_report = 0;
  693. ts->emm_last_report -= FIRST_REPORT_SEC;
  694. report_emms(ts, now);
  695. } else if ((time_t)(ts->emm_last_report + ts->emm_report_interval) <= now) {
  696. report_emms(ts, now);
  697. }
  698. }
  699. if (!ts->emm_only && ts->ecm_report_interval) {
  700. if (first_ecm_report && now >= ts->ecm_last_report) {
  701. first_ecm_report = 0;
  702. ts->ecm_last_report -= FIRST_REPORT_SEC;
  703. report_ecms(ts, now);
  704. } else if ((time_t)(ts->ecm_last_report + ts->ecm_report_interval) <= now) {
  705. report_ecms(ts, now);
  706. }
  707. }
  708. if (!ts->emm_only && !ts->key.is_valid_cw) {
  709. if (ts->cw_warn_sec && now >= ts->cw_next_warn) {
  710. report_cw_warn(ts, now);
  711. }
  712. }
  713. }
  714. void signal_quit(int sig) {
  715. if (!keep_running)
  716. raise(sig);
  717. keep_running = 0;
  718. ts_LOGf("Killed %s with signal %d\n", program_id, sig);
  719. signal(sig, SIG_DFL);
  720. }
  721. #define RTP_HDR_SZ 12
  722. static uint8_t ts_packet[FRAME_SIZE + RTP_HDR_SZ];
  723. static uint8_t rtp_hdr[2][RTP_HDR_SZ];
  724. static struct ts ts;
  725. int main(int argc, char **argv) {
  726. ssize_t readen;
  727. int have_data = 1;
  728. int ntimeouts = 0;
  729. time_t timeout_start = time(NULL);
  730. int rtp_hdr_pos = 0, num_packets = 0;
  731. struct rlimit rl;
  732. if (getrlimit(RLIMIT_STACK, &rl) == 0) {
  733. if (rl.rlim_cur > THREAD_STACK_SIZE) {
  734. rl.rlim_cur = THREAD_STACK_SIZE;
  735. setrlimit(RLIMIT_STACK, &rl);
  736. }
  737. }
  738. memset(rtp_hdr[0], 0, RTP_HDR_SZ);
  739. memset(rtp_hdr[1], 0, RTP_HDR_SZ);
  740. data_init(&ts);
  741. ts_set_log_func(LOG_func);
  742. parse_options(&ts, argc, argv);
  743. if (ts.pidfile)
  744. daemonize(ts.pidfile);
  745. if (ts.syslog_active) {
  746. if (ts.syslog_remote) {
  747. log_init(ts.ident, 1, 1, ts.syslog_host, ts.syslog_port);
  748. remote_syslog = 1;
  749. } else {
  750. openlog(ts.ident, LOG_NDELAY | LOG_PID, LOG_USER);
  751. local_syslog = 1;
  752. }
  753. }
  754. ts.notify = notify_alloc(&ts);
  755. ts_LOGf("Start %s\n", program_id);
  756. notify(&ts, "START", "Starting %s", program_id);
  757. if (ts.input.type == NET_IO && udp_connect_input(&ts.input) < 1)
  758. goto EXIT;
  759. if (ts.output.type == NET_IO && udp_connect_output(&ts.output) < 1)
  760. goto EXIT;
  761. signal(SIGCHLD, SIG_IGN);
  762. signal(SIGPIPE, SIG_IGN);
  763. signal(SIGINT , signal_quit);
  764. signal(SIGTERM, signal_quit);
  765. if (ts.threaded) {
  766. pthread_create(&ts.decode_thread, &ts.thread_attr, &decode_thread, &ts);
  767. pthread_create(&ts.write_thread , &ts.thread_attr, &write_thread , &ts);
  768. }
  769. ts.emm_last_report = time(NULL) + FIRST_REPORT_SEC;
  770. ts.ecm_last_report = time(NULL) + FIRST_REPORT_SEC;
  771. camd_start(&ts);
  772. do {
  773. if (!ts.camd.constant_codeword)
  774. do_reports(&ts);
  775. if (ts.input.type == NET_IO) {
  776. set_log_io_errors(0);
  777. if (!ts.rtp_input) {
  778. readen = fdread_ex(ts.input.fd, (char *)ts_packet, FRAME_SIZE, 250, 4, 1);
  779. } else {
  780. readen = fdread_ex(ts.input.fd, (char *)ts_packet, FRAME_SIZE + RTP_HDR_SZ, 250, 4, 1);
  781. if (readen > RTP_HDR_SZ) {
  782. memcpy(rtp_hdr[rtp_hdr_pos], ts_packet, RTP_HDR_SZ);
  783. memmove(ts_packet, ts_packet + RTP_HDR_SZ, FRAME_SIZE);
  784. readen -= RTP_HDR_SZ;
  785. uint16_t ssrc = (rtp_hdr[rtp_hdr_pos][2] << 8) | rtp_hdr[rtp_hdr_pos][3];
  786. uint16_t pssrc = (rtp_hdr[!rtp_hdr_pos][2] << 8) | rtp_hdr[!rtp_hdr_pos][3];
  787. rtp_hdr_pos = !rtp_hdr_pos;
  788. if (pssrc + 1 != ssrc && (ssrc != 0 && pssrc != 0xffff) && num_packets > 2)
  789. if (ts.ts_discont)
  790. ts_LOGf("--- | RTP discontinuity last_ssrc %5d, curr_ssrc %5d, lost %d packet\n",
  791. pssrc, ssrc, ((ssrc - pssrc)-1) & 0xffff);
  792. num_packets++;
  793. }
  794. }
  795. set_log_io_errors(1);
  796. if (readen < 0) {
  797. ts_LOGf("--- | Input read timeout.\n");
  798. if (!ntimeouts) {
  799. timeout_start = time(NULL);
  800. notify(&ts, "INPUT_TIMEOUT", "Read timeout on input %s://%s:%u/",
  801. ts.rtp_input ? "rtp" : "udp",
  802. inet_ntoa(ts.input.addr), ts.input.port);
  803. }
  804. ntimeouts++;
  805. } else {
  806. if (ntimeouts && readen > 0) {
  807. notify(&ts, "INPUT_OK", "Data is available on input %s://%s:%u/ after %ld seconds timeout.",
  808. ts.rtp_input ? "rtp" : "udp",
  809. inet_ntoa(ts.input.addr), ts.input.port,
  810. (time(NULL) - timeout_start) + 2); // Timeout is detected when ~2 seconds there is no incoming data
  811. ntimeouts = 0;
  812. }
  813. }
  814. } else {
  815. readen = read(ts.input.fd, ts_packet, FRAME_SIZE);
  816. have_data = !(readen <= 0);
  817. }
  818. if (readen > 0) {
  819. if (ts.input_dump_file)
  820. fwrite(ts_packet, readen, 1, ts.input_dump_file);
  821. process_packets(&ts, ts_packet, readen);
  822. }
  823. if (!keep_running)
  824. break;
  825. } while (have_data);
  826. EXIT:
  827. camd_stop(&ts);
  828. if (ts.threaded) {
  829. ts.decode_stop = 1;
  830. ts.write_stop = 1;
  831. if (ts.decode_thread)
  832. pthread_join(ts.decode_thread, NULL);
  833. if (ts.write_thread)
  834. pthread_join(ts.write_thread, NULL);
  835. }
  836. show_pid_report(&ts);
  837. notify_sync(&ts, "STOP", "Stopping %s", program_id);
  838. ts_LOGf("Stop %s\n", program_id);
  839. if (ts.syslog_active) {
  840. if (ts.syslog_remote)
  841. log_close();
  842. else
  843. closelog();
  844. }
  845. if (ts.input_dump_file)
  846. fclose(ts.input_dump_file);
  847. if (ts.pidfile)
  848. unlink(ts.pidfile);
  849. if (log_file)
  850. fclose(log_file);
  851. notify_free(&ts.notify);
  852. data_free(&ts);
  853. exit(EXIT_SUCCESS);
  854. }