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

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