source: trunk/module-cccam.c@ 4012

Last change on this file since 4012 was 4012, checked in by schlocke, 10 years ago

cccam: added full cccam 2.2.x support !!

  • Property svn:mime-type set to text/plain
File size: 95.4 KB
Line 
1#include <string.h>
2#include <stdlib.h>
3#include "globals.h"
4#include "module-cccam.h"
5#include <time.h>
6#include "reader-common.h"
7#include <poll.h>
8
9extern int pthread_mutexattr_settype(pthread_mutexattr_t *__attr, int __kind); //Needs extern defined???
10
11//Mode names for CMD_05 command:
12const char *cmd05_mode_name[] = { "UNKNOWN", "PLAIN", "AES", "CC_CRYPT", "RC4",
13 "LEN=0" };
14
15//Mode names for CMD_0C command:
16const char *cmd0c_mode_name[] = { "NONE", "RC6", "RC4", "CC_CRYPT", "AES", "IDEA" };
17
18static uint8 cc_node_id[8];
19
20#define getprefix() ((struct cc_data *)(cl->cc))->prefix
21
22
23void cc_init_crypt(struct cc_crypt_block *block, uint8 *key, int len) {
24 int i = 0;
25 uint8 j = 0;
26
27 for (i = 0; i < 256; i++) {
28 block->keytable[i] = i;
29 }
30
31 for (i = 0; i < 256; i++) {
32 j += key[i % len] + block->keytable[i];
33 SWAPC(&block->keytable[i], &block->keytable[j]);
34 }
35
36 block->state = *key;
37 block->counter = 0;
38 block->sum = 0;
39}
40
41void cc_crypt(struct cc_crypt_block *block, uint8 *data, int len,
42 cc_crypt_mode_t mode) {
43 int i;
44 uint8 z;
45
46 for (i = 0; i < len; i++) {
47 block->counter++;
48 block->sum += block->keytable[block->counter];
49 SWAPC(&block->keytable[block->counter], &block->keytable[block->sum]);
50 z = data[i];
51 data[i] = z ^ block->keytable[(block->keytable[block->counter]
52 + block->keytable[block->sum]) & 0xff];
53 data[i] ^= block->state;
54 if (!mode)
55 z = data[i];
56 block->state = block->state ^ z;
57 }
58}
59
60void cc_rc4_crypt(struct cc_crypt_block *block, uint8 *data, int len,
61 cc_crypt_mode_t mode) {
62 int i;
63 uint8 z;
64
65 for (i = 0; i < len; i++) {
66 block->counter++;
67 block->sum += block->keytable[block->counter];
68 SWAPC(&block->keytable[block->counter], &block->keytable[block->sum]);
69 z = data[i];
70 data[i] = z ^ block->keytable[(block->keytable[block->counter]
71 + block->keytable[block->sum]) & 0xff];
72 if (!mode)
73 z = data[i];
74 block->state = block->state ^ z;
75 }
76}
77
78void cc_xor(uint8 *buf) {
79 const char cccam[] = "CCcam";
80 uint8 i;
81
82 for (i = 0; i < 8; i++) {
83 buf[8 + i] = i * buf[i];
84 if (i <= 5) {
85 buf[i] ^= cccam[i];
86 }
87 }
88}
89
90void cc_cw_crypt(struct s_client *cl, uint8 *cws, uint32 cardid) {
91 struct cc_data *cc = cl->cc;
92 uint64 node_id;
93 uint8 tmp;
94 int i;
95
96 if (cl->typ != 'c') {
97 node_id = b2ll(8, cc->node_id);
98 } else {
99 node_id = b2ll(8, cc->peer_node_id);
100 }
101
102 for (i = 0; i < 16; i++) {
103 tmp = cws[i] ^ (node_id >> (4 * i));
104 if (i & 1)
105 tmp = ~tmp;
106 cws[i] = (cardid >> (2 * i)) ^ tmp;
107 }
108}
109
110void cc_cw_crypt_cmd0c(struct s_client *cl, uint8 *cws) {
111 struct cc_data *cc = cl->cc;
112 uint8 out[16];
113
114 switch (cc->cmd0c_mode) {
115 case MODE_CMD_0x0C_NONE: { // none additional encryption
116 break;
117 }
118 case MODE_CMD_0x0C_RC6 : { //RC6
119 rc6_block_decrypt((unsigned int *) cws,
120 (unsigned int *) &out, cc->cmd0c_RC6_cryptkey);
121 memcpy(cws, &out, 16);
122 break;
123 }
124 case MODE_CMD_0x0C_RC4: { // RC4
125 cc_rc4_crypt(&cc->cmd0c_cryptkey, cws, 16, ENCRYPT);
126 break;
127 }
128 case MODE_CMD_0x0C_CC_CRYPT: { // cc_crypt
129 cc_crypt(&cc->cmd0c_cryptkey, cws, 16, DECRYPT);
130 cws[0] ^= 0xF0;
131 cws[15] ^= 0xF0;
132 break;
133 }
134 case MODE_CMD_0x0C_AES: { // AES
135 AES_decrypt((unsigned char *) cws,
136 (unsigned char *) &out, &cc->cmd0c_AES_key);
137 memcpy(cws, &out, 16);
138 break;
139 }
140 case MODE_CMD_0x0C_IDEA : { //IDEA
141 uint8 cws_in[8];
142 int i;
143
144 memcpy(&cws_in, cws, 8);
145 idea_ecb_encrypt(cws_in, out, &cc->cmd0c_IDEA_dkey);
146 memcpy(&cws_in, cws + 8, 8);
147 idea_ecb_encrypt(cws_in, out + 8, &cc->cmd0c_IDEA_dkey);
148
149 //final cws[8-15]:
150 for (i = 8; i < 16; i++)
151 out[i] ^= cws[i-8];
152
153 memcpy(cws, &out, 16);
154 break;
155 }
156 }
157}
158
159void set_cmd0c_cryptkey(struct s_client *cl, uint8 *key, uint8 len) {
160 struct cc_data *cc = cl->cc;
161 uint8 key_buf[32];
162
163 memset(&key_buf, 0, sizeof(key_buf));
164
165 if (len > 32)
166 len = 32;
167
168 memcpy(key_buf, key, len);
169
170 switch (cc->cmd0c_mode) {
171
172 case MODE_CMD_0x0C_NONE : { //NONE
173 break;
174 }
175 case MODE_CMD_0x0C_RC6 : { //RC6
176 rc6_key_setup(key_buf, 32, cc->cmd0c_RC6_cryptkey);
177 break;
178 }
179
180 case MODE_CMD_0x0C_RC4: //RC4
181 case MODE_CMD_0x0C_CC_CRYPT: { //CC_CRYPT
182 cc_init_crypt(&cc->cmd0c_cryptkey, key_buf, 32);
183 break;
184 }
185
186 case MODE_CMD_0x0C_AES: { //AES
187 memset(&cc->cmd0c_AES_key, 0, sizeof(cc->cmd0c_AES_key));
188 AES_set_decrypt_key((unsigned char *) key_buf, 256, &cc->cmd0c_AES_key);
189 break;
190 }
191
192 case MODE_CMD_0x0C_IDEA : { //IDEA
193 IDEA_KEY_SCHEDULE ekey;
194 uint8 key_buf_IDEA[16];
195 memcpy(&key_buf_IDEA, &key_buf, 16);
196
197 idea_set_encrypt_key(key_buf_IDEA, &ekey);
198 idea_set_decrypt_key(&ekey,&cc->cmd0c_IDEA_dkey);
199 break;
200 }
201 }
202}
203
204int sid_eq(struct cc_srvid *srvid1, struct cc_srvid *srvid2) {
205 return (srvid1->sid == srvid2->sid && (srvid1->ecmlen == srvid2->ecmlen || !srvid1->ecmlen || !srvid2->ecmlen));
206}
207
208int is_sid_blocked(struct cc_card *card, struct cc_srvid *srvid_blocked) {
209 LL_ITER *it = ll_iter_create(card->badsids);
210 struct cc_srvid *srvid;
211 while ((srvid = ll_iter_next(it))) {
212 if (sid_eq(srvid, srvid_blocked)) {
213 ll_iter_release(it);
214 return 1;
215 }
216 }
217 ll_iter_release(it);
218 return 0;
219}
220
221int is_good_sid(struct cc_card *card, struct cc_srvid *srvid_good) {
222 LL_ITER *it = ll_iter_create(card->goodsids);
223 struct cc_srvid *srvid;
224 while ((srvid = ll_iter_next(it))) {
225 if (sid_eq(srvid, srvid_good)) {
226 ll_iter_release(it);
227 return 1;
228 }
229 }
230 ll_iter_release(it);
231 return 0;
232}
233
234void add_sid_block(struct s_client *cl __attribute__((unused)), struct cc_card *card,
235 struct cc_srvid *srvid_blocked) {
236 if (is_sid_blocked(card, srvid_blocked))
237 return;
238
239 struct cc_srvid *srvid = malloc(sizeof(struct cc_srvid));
240 if (srvid) {
241 *srvid = *srvid_blocked;
242 ll_append(card->badsids, srvid);
243 cs_debug_mask(D_TRACE, "%s added sid block %04X(%d) for card %08x",
244 getprefix(), srvid_blocked->sid, srvid_blocked->ecmlen,
245 card->id);
246 }
247}
248
249void remove_sid_block(struct cc_card *card, struct cc_srvid *srvid_blocked) {
250 LL_ITER *it = ll_iter_create(card->badsids);
251 struct cc_srvid *srvid;
252 while ((srvid = ll_iter_next(it)))
253 if (sid_eq(srvid, srvid_blocked))
254 ll_iter_remove_data(it);
255 ll_iter_release(it);
256}
257
258void remove_good_sid(struct cc_card *card, struct cc_srvid *srvid_good) {
259 LL_ITER *it = ll_iter_create(card->goodsids);
260 struct cc_srvid *srvid;
261 while ((srvid = ll_iter_next(it)))
262 if (sid_eq(srvid, srvid_good))
263 ll_iter_remove_data(it);
264 ll_iter_release(it);
265}
266
267void add_good_sid(struct s_client *cl __attribute__((unused)), struct cc_card *card,
268 struct cc_srvid *srvid_good) {
269 if (is_good_sid(card, srvid_good))
270 return;
271
272 remove_sid_block(card, srvid_good);
273 struct cc_srvid *srvid = malloc(sizeof(struct cc_srvid));
274 if (srvid) {
275 memcpy(srvid, srvid_good, sizeof(struct cc_srvid));
276 ll_append(card->goodsids, srvid);
277 cs_debug_mask(D_TRACE, "%s added good sid %04X(%d) for card %08x",
278 getprefix(), srvid_good->sid, srvid_good->ecmlen, card->id);
279 }
280}
281
282void free_current_cards(LLIST *current_cards) {
283 LL_ITER *it = ll_iter_create(current_cards);
284 struct cc_current_card *c;
285 while ((c = ll_iter_next(it)))
286 c = ll_iter_remove(it);
287 ll_iter_release(it);
288}
289
290/**
291 * reader
292 * clears and frees values for reinit
293 */
294void cc_cli_close(struct s_client *cl, int call_conclose) {
295 cs_debug_mask(D_FUT, "cc_cli_close in");
296 struct s_reader *rdr = cl->reader;
297 struct cc_data *cc = cl->cc;
298 if (!rdr || !cc)
299 return;
300
301 rdr->tcp_connected = 0;
302 rdr->card_status = NO_CARD;
303 rdr->available = 0;
304 rdr->card_system = 0;
305 rdr->ncd_msgid = 0;
306 rdr->last_s = rdr->last_g = 0;
307
308 if (cc->mode == CCCAM_MODE_NORMAL && call_conclose)
309 network_tcp_connection_close(cl, cl->udp_fd);
310 else {
311 if (cl->udp_fd)
312 close(cl->udp_fd);
313 cl->udp_fd = 0;
314 cl->pfd = 0;
315 }
316
317 cc->just_logged_in = 0;
318 free_current_cards(cc->current_cards);
319 cs_debug_mask(D_FUT, "cc_cli_close out");
320}
321
322struct cc_extended_ecm_idx *add_extended_ecm_idx(struct s_client *cl,
323 uint8 send_idx, ushort ecm_idx, struct cc_card *card,
324 struct cc_srvid srvid) {
325 struct cc_data *cc = cl->cc;
326 struct cc_extended_ecm_idx *eei =
327 malloc(sizeof(struct cc_extended_ecm_idx));
328 eei->send_idx = send_idx;
329 eei->ecm_idx = ecm_idx;
330 eei->card = card;
331 eei->srvid = srvid;
332 ll_append(cc->extended_ecm_idx, eei);
333 //cs_debug_mask(D_TRACE, "%s add extended ecm-idx: %d:%d", getprefix(), send_idx, ecm_idx);
334 return eei;
335}
336
337struct cc_extended_ecm_idx *get_extended_ecm_idx(struct s_client *cl,
338 uint8 send_idx, int remove) {
339 struct cc_data *cc = cl->cc;
340 struct cc_extended_ecm_idx *eei;
341 LL_ITER *it = ll_iter_create(cc->extended_ecm_idx);
342 while ((eei = ll_iter_next(it))) {
343 if (eei->send_idx == send_idx) {
344 if (remove)
345 ll_iter_remove(it);
346 //cs_debug_mask(D_TRACE, "%s get by send-idx: %d FOUND: %d",
347 // getprefix(), send_idx, eei->ecm_idx);
348 ll_iter_release(it);
349 return eei;
350 }
351 }
352 ll_iter_release(it);
353 cs_debug_mask(D_TRACE, "%s get by send-idx: %d NOT FOUND", getprefix(),
354 send_idx);
355 return NULL;
356}
357
358struct cc_extended_ecm_idx *get_extended_ecm_idx_by_idx(struct s_client *cl,
359 ushort ecm_idx, int remove) {
360 struct cc_data *cc = cl->cc;
361 struct cc_extended_ecm_idx *eei;
362 LL_ITER *it = ll_iter_create(cc->extended_ecm_idx);
363 while ((eei = ll_iter_next(it))) {
364 if (eei->ecm_idx == ecm_idx) {
365 if (remove)
366 ll_iter_remove(it);
367 //cs_debug_mask(D_TRACE, "%s get by ecm-idx: %d FOUND: %d",
368 // getprefix(), ecm_idx, eei->send_idx);
369 ll_iter_release(it);
370 return eei;
371 }
372 }
373 ll_iter_release(it);
374 cs_debug_mask(D_TRACE, "%s get by ecm-idx: %d NOT FOUND", getprefix(),
375 ecm_idx);
376 return NULL;
377}
378
379void cc_reset_pending(struct s_client *cl, int ecm_idx) {
380 int i = 0;
381 for (i = 0; i < CS_MAXPENDING; i++) {
382 if (cl->ecmtask[i].idx == ecm_idx && cl->ecmtask[i].rc == 101)
383 cl->ecmtask[i].rc = 100; //Mark unused
384 }
385}
386
387void free_extended_ecm_idx_by_card(struct s_client *cl, struct cc_card *card) {
388 struct cc_data *cc = cl->cc;
389 struct cc_extended_ecm_idx *eei;
390 LL_ITER *it = ll_iter_create(cc->extended_ecm_idx);
391 while ((eei = ll_iter_next(it))) {
392 if (eei->card == card) {
393 cc_reset_pending(cl, eei->ecm_idx);
394 ll_iter_remove_data(it);
395 }
396 }
397 ll_iter_release(it);
398}
399
400void free_extended_ecm_idx(struct cc_data *cc) {
401 struct cc_extended_ecm_idx *eei;
402 LL_ITER *it = ll_iter_create(cc->extended_ecm_idx);
403 while ((eei = ll_iter_next(it)))
404 ll_iter_remove_data(it);
405 ll_iter_release(it);
406}
407
408/**
409 * reader
410 * closes the connection and reopens it.
411 */
412//static void cc_cycle_connection() {
413// cc_cli_close();
414// cc_cli_init();
415//}
416
417/**
418 * reader+server:
419 * receive a message
420 */
421int cc_msg_recv(struct s_client *cl, uint8 *buf) {
422 struct s_reader *rdr = (cl->typ == 'c') ? NULL : cl->reader;
423
424 int len;
425 uint8 netbuf[CC_MAXMSGSIZE + 4];
426 struct cc_data *cc = cl->cc;
427
428 int handle = cl->udp_fd;
429
430 if (handle <= 0)
431 return -1;
432
433 len = recv(handle, netbuf, 4, MSG_WAITALL);
434 if (cl->typ != 'c')
435 rdr->last_g = time(NULL);
436
437 if (len != 4) { // invalid header length read
438 if (len <= 0)
439 cs_log("%s disconnected by remote server", getprefix());
440 else
441 cs_log("%s invalid header length (expected 4, read %d)", getprefix(), len);
442 return -1;
443 }
444
445 cc_crypt(&cc->block[DECRYPT], netbuf, 4, DECRYPT);
446 //cs_ddump(netbuf, 4, "cccam: decrypted header:");
447
448 cc->g_flag = netbuf[0];
449
450 int size = (netbuf[2] << 8) | netbuf[3];
451 if (size) { // check if any data is expected in msg
452 if (size > CC_MAXMSGSIZE - 2) {
453 cs_log("%s message too big (size=%d)", getprefix(), size);
454 return 0;
455 }
456
457 len = recv(handle, netbuf + 4, size, MSG_WAITALL); // read rest of msg
458 if (cl->typ != 'c')
459 rdr->last_g = time(NULL);
460
461 if (len != size) {
462 if (len <= 0)
463 cs_log("%s disconnected by remote", getprefix());
464 else
465 cs_log("%s invalid message length read (expected %d, read %d)",
466 getprefix(), size, len);
467 return -1;
468 }
469
470 cc_crypt(&cc->block[DECRYPT], netbuf + 4, len, DECRYPT);
471 len += 4;
472 }
473
474 cs_ddump(netbuf, len, "cccam: full decrypted msg, len=%d:", len);
475
476 memcpy(buf, netbuf, len);
477 return len;
478}
479
480/**
481 * reader+server
482 * send a message
483 */
484int cc_cmd_send(struct s_client *cl, uint8 *buf, int len, cc_msg_type_t cmd) {
485 if (!cl->udp_fd) //disconnected
486 return -1;
487
488 struct s_reader *rdr = (cl->typ == 'c') ? NULL : cl->reader;
489
490 int n;
491 uint8 netbuf[len + 4];
492 struct cc_data *cc = cl->cc;
493
494 memset(netbuf, 0, len + 4);
495
496 if (cmd == MSG_NO_HEADER) {
497 memcpy(netbuf, buf, len);
498 } else {
499 // build command message
500 netbuf[0] = cc->g_flag; // flags??
501 netbuf[1] = cmd & 0xff;
502 netbuf[2] = len >> 8;
503 netbuf[3] = len & 0xff;
504 if (buf)
505 memcpy(netbuf + 4, buf, len);
506 len += 4;
507 }
508
509 cs_ddump(netbuf, len, "cccam: send:");
510 cc_crypt(&cc->block[ENCRYPT], netbuf, len, ENCRYPT);
511
512 n = send(cl->udp_fd, netbuf, len, 0);
513 if (rdr)
514 rdr->last_s = time(NULL);
515
516 if (n != len) {
517 if (rdr)
518 cc_cli_close(cl, TRUE);
519 }
520
521 return n;
522}
523
524#define CC_DEFAULT_VERSION 1
525char *version[] = { "2.0.11", "2.1.1", "2.1.2", "2.1.3", "2.1.4", "2.2.0", "2.2.1", "" };
526char *build[] = { "2892", "2971", "3094", "3165", "3191", "3290", "3316", "" };
527
528/**
529 * reader+server
530 * checks the cccam-version in the configuration
531 */
532void cc_check_version(char *cc_version, char *cc_build) {
533 int i;
534 for (i = 0; strlen(version[i]); i++) {
535 if (!memcmp(cc_version, version[i], strlen(version[i]))) {
536 memcpy(cc_build, build[i], strlen(build[i]) + 1);
537 cs_debug("cccam: auto build set for version: %s build: %s",
538 cc_version, cc_build);
539 return;
540 }
541 }
542 memcpy(cc_version, version[CC_DEFAULT_VERSION], strlen(
543 version[CC_DEFAULT_VERSION]));
544 memcpy(cc_build, build[CC_DEFAULT_VERSION], strlen(
545 build[CC_DEFAULT_VERSION]));
546
547 cs_debug("cccam: auto version set: %s build: %s", cc_version, cc_build);
548}
549
550/**
551 * reader
552 * sends own version information to the CCCam server
553 */
554int cc_send_cli_data(struct s_client *cl) {
555 struct s_reader *rdr = cl->reader;
556
557 int i;
558 struct cc_data *cc = cl->cc;
559
560 cs_debug("cccam: send client data");
561
562 memcpy(cc->node_id, cc_node_id, sizeof(cc_node_id));
563
564 uint8 buf[CC_MAXMSGSIZE];
565 memset(buf, 0, CC_MAXMSGSIZE);
566
567 memcpy(buf, rdr->r_usr, sizeof(rdr->r_usr));
568 memcpy(buf + 20, cc->node_id, 8);
569 buf[28] = rdr->cc_want_emu; // <-- Client want to have EMUs, 0 - NO; 1 - YES
570 memcpy(buf + 29, rdr->cc_version, sizeof(rdr->cc_version)); // cccam version (ascii)
571 memcpy(buf + 61, rdr->cc_build, sizeof(rdr->cc_build)); // build number (ascii)
572
573 cs_log("%s sending own version: %s, build: %s", getprefix(),
574 rdr->cc_version, rdr->cc_build);
575
576 i = cc_cmd_send(cl, buf, 20 + 8 + 6 + 26 + 4 + 28 + 1, MSG_CLI_DATA);
577
578 return i;
579}
580
581/**
582 * server
583 * sends version information to the client
584 */
585int cc_send_srv_data(struct s_client *cl) {
586 struct cc_data *cc = cl->cc;
587
588 cs_debug("cccam: send server data");
589
590 memcpy(cc->node_id, cc_node_id, sizeof(cc_node_id));
591
592 uint8 buf[CC_MAXMSGSIZE];
593 memset(buf, 0, CC_MAXMSGSIZE);
594
595 memcpy(buf, cc->node_id, 8);
596 char cc_build[7];
597 cc_check_version((char *) cfg->cc_version, cc_build);
598 memcpy(buf + 8, cfg->cc_version, sizeof(cfg->cc_version)); // cccam version (ascii)
599 memcpy(buf + 40, cc_build, sizeof(cc_build)); // build number (ascii)
600
601 cs_log("%s version: %s, build: %s nodeid: %s", getprefix(),
602 cfg->cc_version, cc_build, cs_hexdump(0, cc->peer_node_id, 8));
603
604 return cc_cmd_send(cl, buf, 0x48, MSG_SRV_DATA);
605}
606
607/**
608 * reader
609 * retrieves the next waiting ecm request
610 */
611int cc_get_nxt_ecm(struct s_client *cl) {
612 int n, i;
613 time_t t;
614
615 t = time(NULL);
616 n = -1;
617 for (i = 0; i < CS_MAXPENDING; i++) {
618 if ((t - (ulong) cl->ecmtask[i].tps.time > ((cfg->ctimeout + 500)
619 / 1000) + 1) && (cl->ecmtask[i].rc >= 10)) // drop timeouts
620 {
621 cl->ecmtask[i].rc = 0;
622 }
623
624 if (cl->ecmtask[i].rc >= 10 && cl->ecmtask[i].rc != 101) { // stil active and waiting
625 // search for the ecm with the lowest time, this should be the next to go
626 if (n < 0 || cl->ecmtask[n].tps.time - cl->ecmtask[i].tps.time < 0) {
627
628 //check for already pending:
629 if (((struct cc_data*)cl->cc)->extended_mode) {
630 int j,found;
631 for (found=j=0;j<CS_MAXPENDING;j++) {
632 if (i!=j && cl->ecmtask[j].rc == 101 &&
633 cl->ecmtask[i].caid==cl->ecmtask[j].caid &&
634 cl->ecmtask[i].ecmd5==cl->ecmtask[j].ecmd5) {
635 found=1;
636 break;
637 }
638 }
639 if (!found)
640 n = i;
641 }
642 else
643 n = i;
644 }
645 }
646 }
647 return n;
648}
649
650/**
651 * sends the secret cmd05 answer to the server
652 */
653int send_cmd05_answer(struct s_client *cl) {
654 struct s_reader *rdr = cl->reader;
655 struct cc_data *cc = cl->cc;
656 if (!cc->cmd05_active || !rdr->available) //exit if not in cmd05 or waiting for ECM answer
657 return 0;
658
659 cc->cmd05_active--;
660 if (cc->cmd05_active)
661 return 0;
662
663 uint8 *data = cc->cmd05_data;
664 cc_cmd05_mode cmd05_mode = MODE_UNKNOWN;
665
666 // by Project:Keynation
667 switch (cc->cmd05_data_len) {
668 case 0: { //payload 0, return with payload 0!
669 cc_cmd_send(cl, NULL, 0, MSG_CMD_05);
670 cmd05_mode = MODE_LEN0;
671 break;
672 }
673 case 256: {
674 cmd05_mode = cc->cmd05_mode;
675 switch (cmd05_mode) {
676 case MODE_PLAIN: { //Send plain unencrypted back
677 cc_cmd_send(cl, data, 256, MSG_CMD_05);
678 break;
679 }
680 case MODE_AES: { //encrypt with received aes128 key:
681 AES_KEY key;
682 uint8 aeskey[16];
683 uint8 out[256];
684
685 memcpy(aeskey, cc->cmd05_aeskey, 16);
686 memset(&key, 0, sizeof(key));
687
688 AES_set_encrypt_key((unsigned char *) &aeskey, 128, &key);
689 int i;
690 for (i = 0; i < 256; i += 16)
691 AES_encrypt((unsigned char *) data + i, (unsigned char *) &out
692 + i, &key);
693
694 cc_cmd_send(cl, out, 256, MSG_CMD_05);
695 break;
696 }
697 case MODE_CC_CRYPT: { //encrypt with cc_crypt:
698 cc_crypt(&cc->cmd05_cryptkey, data, 256, ENCRYPT);
699 cc_cmd_send(cl, data, 256, MSG_CMD_05);
700 break;
701 }
702 case MODE_RC4_CRYPT: {//special xor crypt:
703 cc_rc4_crypt(&cc->cmd05_cryptkey, data, 256, DECRYPT);
704 cc_cmd_send(cl, data, 256, MSG_CMD_05);
705 break;
706 }
707 default:
708 cmd05_mode = MODE_UNKNOWN;
709 }
710 break;
711 }
712 default:
713 cmd05_mode = MODE_UNKNOWN;
714 }
715
716 //unhandled types always needs cycle connection after 50 ECMs!!
717 if (cmd05_mode == MODE_UNKNOWN) {
718 cc_cmd_send(cl, NULL, 0, MSG_CMD_05);
719 if (!cc->max_ecms) { //max_ecms already set?
720 cc->max_ecms = 50;
721 cc->ecm_counter = 0;
722 }
723 }
724 cs_debug_mask(D_TRACE, "%s sending CMD_05 back! MODE: %s len=%d",
725 getprefix(), cmd05_mode_name[cmd05_mode], cc->cmd05_data_len);
726
727 cc->cmd05NOK = 1;
728 return 1;
729}
730
731struct cc_current_card *cc_find_current_card(struct cc_data *cc,
732 struct cc_card *card) {
733 LL_ITER *it = ll_iter_create(cc->current_cards);
734 struct cc_current_card *c;
735 while ((c = ll_iter_next(it)))
736 if (c->card == card) {
737 ll_iter_release(it);
738 return c;
739 }
740 ll_iter_release(it);
741 return NULL;
742}
743
744struct cc_current_card *cc_find_current_card_by_srvid(struct cc_data *cc,
745 ushort caid, ulong prov, struct cc_srvid *srvid) {
746 LL_ITER *it = ll_iter_create(cc->current_cards);
747 struct cc_current_card *c;
748 while ((c = ll_iter_next(it)))
749 if (c->card->caid == caid && c->prov == prov
750 && sid_eq(&c->srvid, srvid)) {
751 ll_iter_release(it);
752 return c;
753 }
754 ll_iter_release(it);
755 return NULL;
756}
757
758void cc_remove_current_card(struct cc_data *cc,
759 struct cc_current_card *current_card) {
760 LL_ITER *it = ll_iter_create(cc->current_cards);
761 struct cc_current_card *c;
762 while ((c = ll_iter_next(it)))
763 if (c == current_card)
764 ll_iter_remove_data(it);
765 ll_iter_release(it);
766}
767
768int get_UA_len(uint16 caid) {
769 int len = 0;
770 switch (caid >> 8) {
771 case 0x0D://CRYPTOWORKS:
772 len = 5;
773 break;
774 case 0x0B: //CONAX:
775 len = 6;
776 break;
777 case 0x06:
778 case 0x17: //IRDETO:
779 len = 8;
780 break;
781 case 0x4B: //TONGFANG:
782 len = 4;
783 break;
784 case 0x09: //VIDEOGUARD:
785 len = 4;
786 break;
787 case 0x18: //NAGRA:
788 len = 4;
789 break;
790 case 0x05: //VIACCESS:
791 len = 5;
792 break;
793 case 0x4A: //DRE:
794 len = 6;
795 break;
796 case 0x01: //SECA:
797 len = 6;
798 break;
799 default:
800 len = 8;
801 break;
802 }
803 return len;
804}
805
806int get_UA_ofs(uint16 caid) {
807 int ofs = 0;
808 switch (caid >> 8) {
809 case 0x4B: //TONGFANG:
810 ofs = 2;
811 break;
812 case 0x09: //VIDEOGUARD:
813 ofs = 2;
814 break;
815 case 0x18: //NAGRA:
816 ofs = 2;
817 break;
818 case 0x4A: //DRE:
819 ofs = 2;
820 break;
821 }
822 return ofs;
823}
824
825void cc_UA_oscam2cccam(uint8 *in, uint8 *out, uint16 caid) {
826 int len = get_UA_len(caid);
827 int ofs = get_UA_ofs(caid);
828 memset(out, 0, 8);
829 memcpy(out+8-len, in+ofs, len); //set UA trailing/leading zeros
830}
831
832void cc_UA_cccam2oscam(uint8 *in, uint8 *out, uint16 caid) {
833 int len = get_UA_len(caid);
834 int ofs_oscam = get_UA_ofs(caid);
835 int ofs_cccam = 0;
836 int i;
837 for (i=0;i<(8-len);i++) {
838 if (!in[ofs_cccam]) //ignore leading "00"
839 ofs_cccam++;
840 else
841 break;
842 }
843 memset(out, 0, 8);
844 memcpy(out+ofs_oscam, in+ofs_cccam, len);
845}
846
847void cc_SA_oscam2cccam(uint8 *in, uint8 *out) {
848 // out[0] = in[3];
849 // out[1] = in[2];
850 // out[2] = in[1];
851 // out[3] = in[0];
852 memcpy(out, in, 4);
853}
854
855void cc_SA_cccam2oscam(uint8 *in, uint8 *out) {
856 // out[0] = in[3];
857 // out[1] = in[2];
858 // out[2] = in[1];
859 // out[3] = in[0];
860 memcpy(out, in, 4);
861}
862
863int cc_UA_valid(uint8 *ua) {
864 int i;
865 for (i = 0; i < 8; i++)
866 if (ua[i])
867 return 1;
868 return 0;
869}
870
871/**
872 * Updates AU Data: UA (Unique ID / Hexserial) und SA (Shared ID - Provider)
873 */
874void set_au_data(struct s_client *cl __attribute__((unused)), struct s_reader *rdr, struct cc_card *card, ECM_REQUEST *cur_er) {
875 if (rdr->audisabled || !cc_UA_valid(card->hexserial))
876 return;
877
878 rdr->card_system = get_cardsystem(card->caid);
879 cc_UA_cccam2oscam(card->hexserial, rdr->hexserial, rdr->caid[0]);
880
881 cs_debug_mask(D_EMM,
882 "%s au info: caid %04X card system: %d UA: %s",
883 getprefix(), card->caid, rdr->card_system, cs_hexdump(0,
884 rdr->hexserial, 8));
885
886 rdr->nprov = 0;
887 LL_ITER *it2 = ll_iter_create(card->providers);
888 struct cc_provider *provider;
889 int p = 0;
890 while ((provider = ll_iter_next(it2))) {
891 if (!cur_er || provider->prov == cur_er->prid) {
892 memcpy(&rdr->prid[p], &provider->prov, sizeof(provider->prov));
893 cc_SA_cccam2oscam(provider->sa, rdr->sa[p]);
894
895 cs_debug_mask(D_EMM, "%s au info: provider: %06lX:%02X%02X%02X%02X", getprefix(),
896 provider->prov,
897 provider->sa[0], provider->sa[1], provider->sa[2],
898 provider->sa[3]);
899
900 p++;
901 rdr->nprov = p;
902 if (p >= CS_MAXPROV) break;
903 }
904 }
905 ll_iter_release(it2);
906}
907
908/**
909 * reader
910 * sends a ecm request to the connected CCCam Server
911 */
912int cc_send_ecm(struct s_client *cl, ECM_REQUEST *er, uchar *buf) {
913 cs_debug_mask(D_FUT, "cc_send_ecm in");
914 struct s_reader *rdr = cl->reader;
915
916 //cs_debug_mask(D_TRACE, "%s cc_send_ecm", getprefix());
917 if (!rdr->tcp_connected)
918 cc_cli_connect(cl);
919
920 int n, h = -1;
921 struct cc_data *cc = cl->cc;
922 struct cc_card *card;
923 struct cc_current_card *current_card;
924 LL_ITER *it;
925 ECM_REQUEST *cur_er;
926 struct timeb cur_time;
927 cs_ftime(&cur_time);
928
929 if (!cc || (cl->pfd < 1) || !rdr->tcp_connected) {
930 if (er) {
931 er->rc = 0;
932 er->rcEx = 0x27;
933 cs_debug_mask(D_TRACE, "%s server not init! ccinit=%d pfd=%d",
934 rdr->label, cc ? 1 : 0, cl->pfd);
935 write_ecm_answer(rdr, er);
936 }
937 //cc_cli_close(cl);
938 cs_debug_mask(D_FUT, "cc_send_ecm out");
939 return 0;
940 }
941
942 if (rdr->tcp_connected != 2) {
943 cs_debug_mask(D_TRACE, "%s Waiting for CARDS", getprefix());
944 return 0;
945 }
946
947 //No Card? Waiting for shares
948 if (!ll_count(cc->cards)) {
949 rdr->fd_error++;
950 cs_debug_mask(D_TRACE, "%s NO CARDS!", getprefix());
951 return 0;
952 }
953
954 cc->just_logged_in = 0;
955
956 if (!cc->extended_mode) {
957 //Without extended mode, only one ecm at a time could be send
958 //this is a limitation of "O" CCCam
959 if (pthread_mutex_trylock(&cc->ecm_busy) == EBUSY) { //Unlock by NOK or ECM ACK
960 cs_debug_mask(D_TRACE,
961 "%s ecm trylock: ecm busy, retrying later after msg-receive",
962 getprefix());
963
964 struct timeb timeout;
965 timeout = cc->ecm_time;
966 unsigned int tt = cfg->ctimeout * 4;
967 timeout.time += tt / 1000;
968 timeout.millitm += tt % 1000;
969
970 if (comp_timeb(&cur_time, &timeout) < 0) { //TODO: Configuration?
971 return 0; //pending send...
972 } else {
973 cs_debug_mask(D_TRACE,
974 "%s unlocked-cycleconnection! timeout %ds",
975 getprefix(), tt / 1000);
976 //cc_cycle_connection();
977 cc_cli_close(cl, TRUE);
978 cs_debug_mask(D_FUT, "cc_send_ecm out");
979 return 0;
980 }
981 }
982 cs_debug("cccam: ecm trylock: got lock");
983 }
984 cc->ecm_time = cur_time;
985 rdr->available = cc->extended_mode;
986
987 //Search next ECM to send:
988 if ((n = cc_get_nxt_ecm(cl)) < 0) {
989 if (!cc->extended_mode) {
990 rdr->available = 1;
991 pthread_mutex_unlock(&cc->ecm_busy);
992 }
993 cs_debug("%s no ecm pending!", getprefix());
994 if (!cc_send_pending_emms(cl))
995 send_cmd05_answer(cl);
996 cs_debug_mask(D_FUT, "cc_send_ecm out");
997 return 0; // no queued ecms
998 }
999 cur_er = &cl->ecmtask[n];
1000 cur_er->rc = 101; //mark ECM as already send
1001 cs_debug("cccam: ecm-task %d", cur_er->idx);
1002
1003 if (buf)
1004 memcpy(buf, cur_er->ecm, cur_er->l);
1005
1006 struct cc_srvid cur_srvid;
1007 cur_srvid.sid = cur_er->srvid;
1008 cur_srvid.ecmlen = cur_er->l;
1009
1010 pthread_mutex_lock(&cc->cards_busy);
1011 //search cache:
1012 current_card = cc_find_current_card_by_srvid(cc, cur_er->caid,
1013 cur_er->prid, &cur_srvid);
1014 if (current_card) {
1015 if (!current_card->card || is_sid_blocked(current_card->card,
1016 &cur_srvid)) {
1017 cc_remove_current_card(cc, current_card);
1018 current_card = NULL;
1019 }
1020 }
1021 if (current_card)
1022 card = current_card->card;
1023 else
1024 card = NULL;
1025
1026 //then check all other cards
1027 if (!card) {
1028 it = ll_iter_create(cc->cards);
1029 struct cc_card *ncard;
1030 while ((ncard = ll_iter_next(it))) {
1031 if (ncard->caid == cur_er->caid) { // caid matches
1032 if (is_sid_blocked(ncard, &cur_srvid))
1033 continue;
1034
1035 if (!ncard->providers || !ncard->providers->initial) { //card has no providers:
1036 if (h < 0 || ncard->hop < h || (ncard->hop == h
1037 && cc_UA_valid(ncard->hexserial))) {
1038 // ncard is closer
1039 card = ncard;
1040 h = ncard->hop; // ncard has been matched
1041 }
1042
1043 }
1044 else { //card has providers
1045 LL_ITER *it2 = ll_iter_create(ncard->providers);
1046 struct cc_provider *provider;
1047 while ((provider = ll_iter_next(it2))) {
1048 if (!cur_er->prid || !provider->prov || provider->prov
1049 == cur_er->prid) { // provid matches
1050 if (h < 0 || ncard->hop < h || (ncard->hop == h
1051 && cc_UA_valid(ncard->hexserial))) {
1052 // ncard is closer
1053 card = ncard;
1054 h = ncard->hop; // ncard has been matched
1055 }
1056 }
1057 }
1058 ll_iter_release(it2);
1059 }
1060 }
1061 }
1062 ll_iter_release(it);
1063 }
1064
1065 if (card) {
1066 if (!current_card) {
1067 current_card = malloc(sizeof(struct cc_current_card));
1068 current_card->card = card;
1069 current_card->prov = cur_er->prid;
1070 current_card->srvid = cur_srvid;
1071 ll_insert_at(cc->current_cards, current_card, 0);
1072 }
1073
1074 card->time = time((time_t) 0);
1075 uint8 ecmbuf[CC_MAXMSGSIZE];
1076 memset(ecmbuf, 0, CC_MAXMSGSIZE);
1077
1078 // build ecm message
1079 ecmbuf[0] = card->caid >> 8;
1080 ecmbuf[1] = card->caid & 0xff;
1081 ecmbuf[2] = cur_er->prid >> 24;
1082 ecmbuf[3] = cur_er->prid >> 16;
1083 ecmbuf[4] = cur_er->prid >> 8;
1084 ecmbuf[5] = cur_er->prid & 0xff;
1085 ecmbuf[6] = card->id >> 24;
1086 ecmbuf[7] = card->id >> 16;
1087 ecmbuf[8] = card->id >> 8;
1088 ecmbuf[9] = card->id & 0xff;
1089 ecmbuf[10] = cur_er->srvid >> 8;
1090 ecmbuf[11] = cur_er->srvid & 0xff;
1091 ecmbuf[12] = cur_er->l & 0xff;
1092 memcpy(ecmbuf + 13, cur_er->ecm, cur_er->l);
1093
1094 uint8 send_idx = 1;
1095 if (cc->extended_mode) {
1096 cc->server_ecm_idx++;
1097 if (cc->server_ecm_idx >= 256)
1098 cc->server_ecm_idx = 1;
1099 cc->g_flag = cc->server_ecm_idx; //Flag is used as index!
1100 send_idx = cc->g_flag;
1101 }
1102
1103 add_extended_ecm_idx(cl, send_idx, cur_er->idx, card, cur_srvid);
1104
1105 rdr->cc_currenthops = card->hop;
1106
1107 cs_log(
1108 "%s sending ecm for sid %04X(%d) to card %08x, hop %d, ecmtask %d",
1109 getprefix(), cur_er->srvid, cur_er->l, card->id, card->hop,
1110 cur_er->idx);
1111 cc_cmd_send(cl, ecmbuf, cur_er->l + 13, MSG_CW_ECM); // send ecm
1112
1113 //For EMM
1114 set_au_data(cl, rdr, card, cur_er);
1115 pthread_mutex_unlock(&cc->cards_busy);
1116 cs_debug_mask(D_FUT, "cc_send_ecm out");
1117 return 0;
1118 } else {
1119 //When connecting, it could happen than ecm requests come before all cards are received.
1120 //So if the last Message was a MSG_NEW_CARD, this "card receiving" is not already done
1121 //if this happens, we do not autoblock it and do not set rc status
1122 //So fallback could resolve it
1123 if (cc->last_msg != MSG_NEW_CARD && cc->last_msg != MSG_NEW_CARD_SIDINFO && !cc->just_logged_in) {
1124 cs_log("%s no suitable card on server", getprefix());
1125
1126 cur_er->rc = 0;
1127 cur_er->rcEx = 0x27;
1128 write_ecm_answer(rdr, cur_er);
1129 //cur_er->rc = 1;
1130 //cur_er->rcEx = 0;
1131 //cs_sleepms(300);
1132 rdr->last_s = rdr->last_g;
1133
1134 //reopen all blocked sids for this srvid:
1135 it = ll_iter_create(cc->cards);
1136 while ((card = ll_iter_next(it))) {
1137 if (card->caid == cur_er->caid) { // caid matches
1138 LL_ITER *it2 = ll_iter_create(card->badsids);
1139 struct cc_srvid *srvid;
1140 while ((srvid = ll_iter_next(it2)))
1141 if (sid_eq(srvid, &cur_srvid))
1142 ll_iter_remove_data(it2);
1143 ll_iter_release(it2);
1144 }
1145 }
1146 ll_iter_release(it);
1147 }
1148 }
1149 pthread_mutex_unlock(&cc->cards_busy);
1150 if (!cc->extended_mode) {
1151 rdr->available = 1;
1152 pthread_mutex_unlock(&cc->ecm_busy);
1153 }
1154 cs_debug_mask(D_FUT, "cc_send_ecm out");
1155 return -1;
1156}
1157
1158/*
1159 int cc_abort_user_ecms(){
1160 int n, i;
1161 time_t t;//, tls;
1162 struct cc_data *cc = rdr->cc;
1163
1164 t=time((time_t *)0);
1165 for (i=1,n=1; i<CS_MAXPENDING; i++)
1166 {
1167 if ((t-cl->ecmtask[i].tps.time > ((cfg->ctimeout + 500) / 1000) + 1) &&
1168 (cl->ecmtask[i].rc>=10)) // drop timeouts
1169 {
1170 cl->ecmtask[i].rc=0;
1171 }
1172 int td=abs(1000*(ecmtask[i].tps.time-cc->found->tps.time)+ecmtask[i].tps.millitm-cc->found->tps.millitm);
1173 if (ecmtask[i].rc>=10 && ecmtask[i].cidx==cc->found->cidx && &ecmtask[i]!=cc->found){
1174 cs_log("aborting idx:%d caid:%04x client:%d timedelta:%d",ecmtask[i].idx,ecmtask[i].caid,ecmtask[i].cidx,td);
1175 ecmtask[i].rc=0;
1176 ecmtask[i].rcEx=7;
1177 write_ecm_answer(rdr, fd_c2m, &ecmtask[i]);
1178 }
1179 }
1180 return n;
1181
1182 }
1183 */
1184
1185int cc_send_pending_emms(struct s_client *cl) {
1186 cs_debug_mask(D_FUT, "cc_send_pending_emms in");
1187 struct s_reader *rdr = cl->reader;
1188 struct cc_data *cc = cl->cc;
1189
1190 LL_ITER *it = ll_iter_create(cc->pending_emms);
1191 uint8 *emmbuf;
1192 int size = 0;
1193 if ((emmbuf = ll_iter_next(it))) {
1194 if (!cc->extended_mode) {
1195 if (pthread_mutex_trylock(&cc->ecm_busy) == EBUSY) { //Unlock by NOK or ECM ACK
1196 ll_iter_release(it);
1197 return 0; //send later with cc_send_ecm
1198 }
1199 rdr->available = 0;
1200 }
1201 size = emmbuf[11] + 12;
1202
1203 cc->just_logged_in = 0;
1204 cs_ftime(&cc->ecm_time);
1205
1206 cs_debug_mask(D_EMM, "%s emm send for card %08X", getprefix(), b2i(4,
1207 emmbuf + 7));
1208
1209 cc_cmd_send(cl, emmbuf, size, MSG_EMM_ACK); // send emm
1210
1211 ll_iter_remove_data(it);
1212 }
1213 ll_iter_release(it);
1214
1215 cs_debug_mask(D_FUT, "cc_send_pending_emms out");
1216 return size;
1217}
1218
1219/**
1220 * READER only:
1221 * find card by hexserial
1222 * */
1223struct cc_card *get_card_by_hexserial(struct s_client *cl, uint8 *hexserial,
1224 uint16 caid) {
1225 struct cc_data *cc = cl->cc;
1226 LL_ITER *it = ll_iter_create(cc->cards);
1227 struct cc_card *card;
1228 while ((card = ll_iter_next(it)))
1229 if (card->caid == caid && memcmp(card->hexserial, hexserial, 8) == 0) { //found it!
1230 break;
1231 }
1232 ll_iter_release(it);
1233 return card;
1234}
1235
1236/**
1237 * EMM Procession
1238 * Copied from http://85.17.209.13:6100/file/8ec3c0c5d257/systems/cardclient/cccam2.c
1239 * ProcessEmm
1240 * */
1241int cc_send_emm(EMM_PACKET *ep) {
1242 cs_debug_mask(D_FUT, "cc_send_emm in");
1243 struct s_client *cl = cur_client();
1244 struct s_reader *rdr = cl->reader;
1245
1246 if (!rdr->tcp_connected)
1247 cc_cli_connect(cl);
1248
1249 struct cc_data *cc = cl->cc;
1250
1251 if (!cc || (cl->pfd < 1) || !rdr->tcp_connected) {
1252 cs_log("%s server not init! ccinit=%d pfd=%d", getprefix(), cc ? 1 : 0,
1253 cl->pfd);
1254 return 0;
1255 }
1256 if (rdr->audisabled) {
1257 cs_log("%s au is disabled", getprefix());
1258 return 0;
1259 }
1260
1261 ushort caid = b2i(2, ep->caid);
1262
1263 //Last used card is first card of current_cards:
1264 pthread_mutex_lock(&cc->cards_busy);
1265 LL_ITER *it = ll_iter_create(cc->current_cards);
1266 struct cc_current_card *current_card;
1267 while ((current_card = ll_iter_next(it)))
1268 if (current_card->card->caid == caid && cc_UA_valid(current_card->card->hexserial))
1269 break; //found it
1270 ll_iter_release(it);
1271
1272 struct cc_card *emm_card = (current_card != NULL) ? current_card->card
1273 : NULL;
1274
1275 if (!emm_card) {
1276 uint8 hs[8];
1277 cc_UA_oscam2cccam(ep->hexserial, hs, caid);
1278 emm_card = get_card_by_hexserial(cl, hs, caid);
1279 }
1280
1281 if (!emm_card) { //Card for emm not found!
1282 cs_log("%s emm for client %8X not possible, no card found!",
1283 getprefix(), ep->client->thread);
1284 pthread_mutex_unlock(&cc->cards_busy);
1285 return 0;
1286 }
1287
1288 cs_debug_mask(D_EMM,
1289 "%s emm received for client %8X caid %04X for card %08X",
1290 getprefix(), ep->client->thread, caid, emm_card->id);
1291
1292 int size = ep->l + 12;
1293 uint8 *emmbuf = malloc(size);
1294 memset(emmbuf, 0, size);
1295
1296 // build ecm message
1297 emmbuf[0] = ep->caid[0];
1298 emmbuf[1] = ep->caid[1];
1299 emmbuf[2] = 0;
1300 emmbuf[3] = ep->provid[0];
1301 emmbuf[4] = ep->provid[1];
1302 emmbuf[5] = ep->provid[2];
1303 emmbuf[6] = ep->provid[3];
1304 emmbuf[7] = emm_card->id >> 24;
1305 emmbuf[8] = emm_card->id >> 16;
1306 emmbuf[9] = emm_card->id >> 8;
1307 emmbuf[10] = emm_card->id & 0xff;
1308 emmbuf[11] = ep->l;
1309 memcpy(emmbuf + 12, ep->emm, ep->l);
1310
1311 pthread_mutex_unlock(&cc->cards_busy);
1312
1313 ll_append(cc->pending_emms, emmbuf);
1314 cc_send_pending_emms(cl);
1315
1316 cs_debug_mask(D_FUT, "cc_send_emm out");
1317 return 1;
1318}
1319
1320void cc_free_card(struct cc_card *card) {
1321 if (!card)
1322 return;
1323
1324 ll_destroy_data(card->providers);
1325 ll_destroy_data(card->badsids);
1326 ll_destroy_data(card->goodsids);
1327 ll_destroy_data(card->remote_nodes);
1328
1329 free(card);
1330}
1331
1332/**
1333 * Server:
1334 * Adds a cccam-carddata buffer to the list of reported carddatas
1335 */
1336void cc_add_reported_carddata(LLIST *reported_carddatas, struct cc_card *card) {
1337 ll_append(reported_carddatas, card);
1338}
1339
1340int cc_clear_reported_carddata(struct s_client *cl, LLIST *reported_carddatas, LLIST *except,
1341 int send_removed) {
1342 int i=0;
1343 LL_ITER *it = ll_iter_create(reported_carddatas);
1344 struct cc_card *card;
1345 while ((card = ll_iter_next(it))) {
1346 struct cc_card *card2 = NULL;
1347 if (except) {
1348 LL_ITER *it2 = ll_iter_create(except);
1349 while ((card2 = ll_iter_next(it2))) {
1350 if (card == card2)
1351 break;
1352 }
1353 ll_iter_release(it2);
1354 }
1355
1356 if (!card2) {
1357 if (send_removed) {
1358 uint8 buf[4];
1359 buf[0] = card->id >>24;
1360 buf[1] = card->id >>16;
1361 buf[2] = card->id >>8;
1362 buf[3] = card->id & 0xFF;
1363 cc_cmd_send(cl, buf, 4, MSG_CARD_REMOVED);
1364 }
1365 cc_free_card(card);
1366 i++;
1367 }
1368 ll_iter_remove(it);
1369 }
1370 ll_iter_release(it);
1371 return i;
1372}
1373
1374int cc_free_reported_carddata(struct s_client *cl, LLIST *reported_carddatas, LLIST *except,
1375 int send_removed) {
1376 int i=0;
1377 if (reported_carddatas) {
1378 i = cc_clear_reported_carddata(cl, reported_carddatas, except, send_removed);
1379 ll_destroy(reported_carddatas);
1380 }
1381 return i;
1382}
1383
1384void cc_free_cardlist(LLIST *card_list, int destroy_list) {
1385 if (card_list) {
1386 LL_ITER *it = ll_iter_create(card_list);
1387 struct cc_card *card;
1388 while ((card = ll_iter_next(it))) {
1389 cc_free_card(card);
1390 ll_iter_remove(it);
1391 }
1392 ll_iter_release(it);
1393 if (destroy_list)
1394 ll_destroy_data(card_list);
1395 }
1396}
1397
1398/**
1399 * Clears and free the cc datas
1400 */
1401void cc_free(struct s_client *cl) {
1402 struct cc_data *cc = cl->cc;
1403 if (!cc)
1404 return;
1405
1406 cs_debug_mask(D_FUT, "cc_free in");
1407 cc_free_cardlist(cc->cards, TRUE);
1408 cc_free_reported_carddata(cl, cc->reported_carddatas, NULL, FALSE);
1409 ll_destroy_data(cc->pending_emms);
1410 free_current_cards(cc->current_cards);
1411 ll_destroy(cc->current_cards);
1412 if (cc->extended_ecm_idx)
1413 free_extended_ecm_idx(cc);
1414 pthread_mutex_destroy(&cc->lock);
1415 pthread_mutex_destroy(&cc->ecm_busy);
1416 pthread_mutex_destroy(&cc->cards_busy);
1417 free(cc->prefix);
1418 free(cc);
1419 cl->cc=NULL;
1420 cs_debug_mask(D_FUT, "cc_free out");
1421}
1422
1423int is_null_dcw(uint8 *dcw) {
1424 int i;
1425 for (i = 0; i < 15; i++)
1426 if (dcw[i])
1427 return 0;
1428 return 1;
1429}
1430
1431/*int is_dcw_corrupted(uchar *dcw)
1432 {
1433 int i;
1434 int c, cs;
1435
1436 for (i=0; i<16; i+=4)
1437 {
1438 c = (dcw[i] + dcw[i+1] + dcw[i+2]) & 0xFF;
1439 cs = dcw[i+3];
1440 if (cs!=c) return (1);
1441 }
1442 return 0;
1443 }
1444*/
1445
1446int check_extended_mode(struct s_client *cl, char *msg) {
1447 //Extended mode: if PARTNER String is ending with [PARAM], extended mode is activated
1448 //For future compatibilty the syntax should be compatible with
1449 //[PARAM1,PARAM2...PARAMn]
1450 //
1451 // EXT: Extended ECM Mode: Multiple ECMs could be send and received
1452 // ECMs are numbered, Flag (byte[0] is the index
1453 //
1454 // SID: Exchange of good sids/bad sids activated (like cccam 2.2.x)
1455 // card exchange command MSG_NEW_CARD_SIDINFO instead MSG_NEW_CARD is used
1456 //
1457
1458 struct cc_data *cc = cl->cc;
1459 int has_param = 0;
1460 char *p = strtok(msg, "[");
1461 while (p) {
1462 p = strtok(NULL, ",]");
1463 if (p && strncmp(p, "EXT", 3) == 0) {
1464 cc->extended_mode = 1;
1465 cs_log("%s extended ECM mode", getprefix());
1466 has_param = 1;
1467 }
1468 else if (p && strncmp(p, "SID", 3)==0) {
1469 cc->cccam220 = 1;
1470 cs_log("%s extra SID mode", getprefix());
1471 has_param = 1;
1472 }
1473 }
1474 return has_param;
1475}
1476
1477void cc_idle() {
1478 cs_debug_mask(D_FUT, "cc_idle in");
1479 struct s_client *cl = cur_client();
1480 struct s_reader *rdr = cl->reader;
1481 struct cc_data *cc = cl->cc;
1482 if (!rdr || !rdr->tcp_connected || !cl || !cc)
1483 return;
1484
1485 if (rdr->cc_keepalive) {
1486 if (cc->answer_on_keepalive + 55 <= time(NULL)) {
1487 cc_cmd_send(cl, NULL, 0, MSG_KEEPALIVE);
1488 cs_debug("cccam: keepalive");
1489 cc->answer_on_keepalive = time(NULL);
1490 }
1491 }
1492 else
1493 {
1494 int rto = abs(rdr->last_s - rdr->last_g);
1495 if (rto >= (rdr->tcp_rto*60))
1496 network_tcp_connection_close(cl, cl->udp_fd);
1497 }
1498 cs_debug_mask(D_FUT, "cc_idle out");
1499}
1500
1501struct cc_card *read_card(uint8 *buf, int ext) {
1502 struct cc_card *card = malloc(sizeof(struct cc_card));
1503 memset(card, 0, sizeof(struct cc_card));
1504
1505 int nprov, nassign = 0, nreject = 0, offset = 21;
1506
1507 card->providers = ll_create();
1508 card->badsids = ll_create();
1509 card->goodsids = ll_create();
1510 card->remote_nodes = ll_create();
1511 card->id = b2i(4, buf);
1512 card->remote_id = b2i(4, buf + 4);
1513 card->caid = b2i(2, buf + 8);
1514 card->hop = buf[10];
1515 card->maxdown = buf[11];
1516 memcpy(card->hexserial, buf + 12, 8); //HEXSERIAL!!
1517
1518 //cs_debug("cccam: card %08x added, caid %04X, hop %d, key %s, count %d",
1519 // card->id, card->caid, card->hop, cs_hexdump(0, card->hexserial, 8),
1520 // ll_count(cc->cards));
1521
1522 nprov = buf[20];
1523
1524 if (ext) {
1525 nassign = buf[21];
1526 nreject = buf[22];
1527
1528 offset += 2;
1529 }
1530
1531 int i;
1532 for (i = 0; i < nprov; i++) { // providers
1533 struct cc_provider *prov = malloc(sizeof(struct cc_provider));
1534 prov->prov = b2i(3, buf + offset);
1535 memcpy(prov->sa, buf + offset + 3, 4);
1536 cs_debug(" prov %d, %06x, sa %08x", i + 1, prov->prov, b2i(4,
1537 prov->sa));
1538
1539 ll_append(card->providers, prov);
1540 offset+=7;
1541 }
1542
1543 uint8 *ptr = buf + offset;
1544
1545 if (ext) {
1546 for (i = 0; i < nassign; i++) {
1547 uint16_t sid = b2i(2, ptr);
1548 cs_debug(" assigned sid = %04X, added to good sid list", sid);
1549
1550 struct cc_srvid *srvid = malloc(sizeof(struct cc_srvid));
1551 srvid->sid = sid;
1552 srvid->ecmlen = 0;
1553 ll_append(card->goodsids, srvid);
1554 ptr+=2;
1555 }
1556
1557 for (i = 0; i < nreject; i++) {
1558 uint16_t sid = b2i(2, ptr);
1559 cs_debug(" rejected sid = %04X, added to sid block list", sid);
1560
1561 struct cc_srvid *srvid = malloc(sizeof(struct cc_srvid));
1562 srvid->sid = sid;
1563 srvid->ecmlen = 0;
1564 ll_append(card->badsids, srvid);
1565 ptr+=2;
1566 }
1567 }
1568
1569 int remote_count = ptr[0];
1570 ptr++;
1571 for (i = 0; i < remote_count; i++) {
1572 uint8 *remote_node = malloc(8);
1573 memcpy(remote_node, ptr, 8);
1574 ll_append(card->remote_nodes, remote_node);
1575 ptr+=8;
1576 }
1577 return card;
1578}
1579
1580#define READ_CARD_TIMEOUT 100
1581
1582int write_card(struct cc_data *cc, uint8 *buf, struct cc_card *card, int add_own, int ext) {
1583 memset(buf, 0, CC_MAXMSGSIZE);
1584 buf[0] = card->id >> 24;
1585 buf[1] = card->id >> 16;
1586 buf[2] = card->id >> 8;
1587 buf[3] = card->id & 0xff;
1588 buf[4] = card->remote_id >> 24;
1589 buf[5] = card->remote_id >> 16;
1590 buf[6] = card->remote_id >> 8;
1591 buf[7] = card->remote_id & 0xFF;
1592 buf[8] = card->caid >> 8;
1593 buf[9] = card->caid & 0xff;
1594 buf[10] = card->hop;
1595 buf[11] = card->maxdown;
1596 memcpy(buf + 12, card->hexserial, 8);
1597
1598 //with cccam 2.2.0 we have assigned and rejected sids:
1599 int ofs = ext?23:21;
1600
1601 //write providers:
1602 LL_ITER *it = ll_iter_create(card->providers);
1603 struct cc_provider *prov;
1604 while ((prov = ll_iter_next(it))) {
1605 ulong prid = prov->prov;
1606 buf[ofs+0] = prid >> 16;
1607 buf[ofs+1] = prid >> 8;
1608 buf[ofs+2] = prid & 0xFF;
1609 memcpy(buf + ofs + 3, prov->sa, 4);
1610 buf[20]++;
1611 ofs+=7;
1612 }
1613 ll_iter_release(it);
1614
1615 //write sids only if cccam 2.2.0:
1616 if (ext) {
1617 //assigned sids:
1618 it = ll_iter_create(card->goodsids);
1619 struct cc_srvid *srvid;
1620 while ((srvid = ll_iter_next(it))) {
1621 buf[ofs+0] = srvid->sid >> 8;
1622 buf[ofs+1] = srvid->sid & 0xFF;
1623 ofs+=2;
1624 buf[21]++; //nassign
1625 }
1626 ll_iter_release(it);
1627
1628 //reject sids:
1629 it = ll_iter_create(card->badsids);
1630 while ((srvid = ll_iter_next(it))) {
1631 buf[ofs+0] = srvid->sid >> 8;
1632 buf[ofs+1] = srvid->sid & 0xFF;
1633 ofs+=2;
1634 buf[22]++; //nreject
1635 }
1636 ll_iter_release(it);
1637 }
1638
1639 //write remote nodes
1640 int nremote_ofs = ofs;
1641 ofs++;
1642 it = ll_iter_create(card->remote_nodes);
1643 uint8 *remote_node;
1644 while ((remote_node = ll_iter_next(it))) {
1645 memcpy(buf+ofs, remote_node, 8);
1646 ofs+=8;
1647 buf[nremote_ofs]++;
1648 }
1649 ll_iter_release(it);
1650 if (add_own) {
1651 memcpy(buf+ofs, cc->node_id, 8);
1652 ofs+=8;
1653 buf[nremote_ofs]++;
1654 }
1655 return ofs;
1656}
1657
1658void cc_card_removed(struct s_client *cl, uint32 shareid) {
1659 struct cc_data *cc = cl->cc;
1660 struct cc_card *card;
1661 pthread_mutex_lock(&cc->cards_busy);
1662 LL_ITER *it = ll_iter_create(cc->cards);
1663
1664 while ((card = ll_iter_next(it))) {
1665 if (card->id == shareid) {// && card->sub_id == b2i (3, buf + 9)) {
1666 //cs_debug("cccam: card %08x removed, caid %04X, count %d",
1667 // card->id, card->caid, ll_count(cc->cards));
1668 struct cc_card *next_card = ll_iter_peek(it, 0);
1669 ll_iter_remove(it);
1670 struct cc_current_card *current_card;
1671 while ((current_card = cc_find_current_card(cc, card))) {
1672 cs_debug_mask(D_TRACE, "%s current card %08x removed!",
1673 getprefix(), card->id);
1674 cc_remove_current_card(cc, current_card);
1675 }
1676 free_extended_ecm_idx_by_card(cl, card);
1677 cc_free_card(card);
1678 card = next_card;
1679 cc->cards_modified++;
1680 //break;
1681 }
1682 }
1683 ll_iter_release(it);
1684 pthread_mutex_unlock(&cc->cards_busy);
1685}
1686
1687void move_card_to_end(struct s_client * cl, struct cc_card *card_to_move) {
1688
1689 struct cc_data *cc = cl->cc;
1690
1691 LL_ITER *it = ll_iter_create(cc->cards);
1692 struct cc_card *card;
1693 while ((card = ll_iter_next(it))) {
1694 if (card == card_to_move) {
1695 ll_iter_remove(it);
1696 break;
1697 }
1698 }
1699 ll_iter_release(it);
1700 if (card) {
1701 cs_debug_mask(D_TRACE, "%s CMD05: Moving card %08X to the end...", getprefix(), card_to_move->id);
1702 //cleaning current cards:
1703 it = ll_iter_create(cc->cards);
1704 struct cc_current_card *current_card;
1705 while ((current_card = cc_find_current_card(cc, card))) {
1706 cc_remove_current_card(cc, current_card);
1707 }
1708 ll_iter_release(it);
1709 free_extended_ecm_idx_by_card(cl, card);
1710
1711 ll_append(cc->cards, card_to_move);
1712 }
1713}
1714
1715int same_first_node(struct cc_card *card1, struct cc_card *card2) {
1716 uint8 * node1 = card1->remote_nodes->obj;
1717 uint8 * node2 = card2->remote_nodes->obj;
1718
1719 if (!node1 && !node2) return 1; //both NULL, same!
1720
1721 if (!node1 || !node2) return 0; //one NULL, not same!
1722
1723 return !memcmp(node1, node2, 8); //same?
1724}
1725
1726int same_card(struct cc_card *card1, struct cc_card *card2) {
1727 return (card1->caid == card2->caid &&
1728 card1->remote_id == card2->remote_id &&
1729 same_first_node(card1, card2) &&
1730 memcmp(card1->hexserial, card2->hexserial, sizeof(card1->hexserial))==0);
1731}
1732
1733
1734void check_peer_changed(struct cc_data *cc, uint8 *node_id, uint8 *version) {
1735 if (memcmp(cc->peer_node_id, node_id, 8) != 0 || memcmp(cc->peer_version, version, 8) != 0) {
1736 //Remote Id has changed, clear cached data:
1737 cc_free_cardlist(cc->cards, FALSE);
1738 free_current_cards(cc->current_cards);
1739 }
1740}
1741
1742/**
1743 * if idents defined on an cccam reader, the cards caid+provider are checked.
1744 * return 1 a) if no ident defined b) card is in identlist
1745 * 0 if card is not in identlist
1746 *
1747 * a card is in the identlist, if the cards caid is matching and mininum a provider is matching
1748 **/
1749int chk_ident(FTAB *ftab, struct cc_card *card) {
1750
1751 int j, k;
1752 int res = 1;
1753
1754 if (ftab && ftab->filts) {
1755 for (j = 0; j < ftab->nfilts; j++) {
1756 if (ftab->filts[j].caid) {
1757 res = 0;
1758 if (ftab->filts[j].caid==card->caid) { //caid matches!
1759
1760 int nprids = ftab->filts[j].nprids;
1761 if (!nprids) // No Provider ->Ok
1762 return 1;
1763
1764
1765 LL_ITER *it = ll_iter_create(card->providers);
1766 struct cc_provider *prov;
1767
1768 while ((prov = ll_iter_next(it))) {
1769 for (k = 0; k < nprids; k++) {
1770 ulong prid = ftab->filts[j].prids[k];
1771 if (prid == prov->prov) { //Provider matches
1772 ll_iter_release(it);
1773 return 1;
1774 }
1775 }
1776 }
1777 ll_iter_release(it);
1778 }
1779 }
1780 }
1781 }
1782 return res;
1783}
1784
1785
1786/*void fix_dcw(uchar *dcw)
1787{
1788 int i;
1789 for (i=0; i<16; i+=4)
1790 {
1791 dcw[i+3] = (dcw[i] + dcw[i+1] + dcw[i+2]) & 0xFF;
1792 }
1793}*/
1794
1795void addParam(char *param, char *value)
1796{
1797 if (strlen(param) < 4)
1798 strcat(param, value);
1799 else {
1800 strcat(param, ",");
1801 strcat(param, value);
1802 }
1803}
1804
1805int cc_parse_msg(struct s_client *cl, uint8 *buf, int l) {
1806 cs_debug_mask(D_FUT, "cc_parse_msg in %d", buf[1]);
1807 struct s_reader *rdr = (cl->typ == 'c') ? NULL : cl->reader;
1808
1809 int ret = buf[1];
1810 struct cc_data *cc = cl->cc;
1811
1812 cs_debug("%s parse_msg=%d", getprefix(), buf[1]);
1813
1814 uint8 *data = buf + 4;
1815 memcpy(&cc->receive_buffer, data, l - 4);
1816 cc->last_msg = buf[1];
1817 switch (buf[1]) {
1818 case MSG_CLI_DATA:
1819 cs_debug("cccam: client data ack");
1820 break;
1821 case MSG_SRV_DATA:
1822 l -= 4;
1823 cs_log("%s MSG_SRV_DATA (payload=%d, hex=%02X)", getprefix(), l, l);
1824 data = (uint8*) &cc->receive_buffer;
1825
1826 if (l == 0x48) { //72 bytes: normal server data
1827 check_peer_changed(cc, data, data+8);
1828
1829 memcpy(cc->peer_node_id, data, 8);
1830 memcpy(cc->peer_version, data + 8, 8);
1831
1832 memcpy(cc->cmd0b_aeskey, cc->peer_node_id, 8);
1833 memcpy(cc->cmd0b_aeskey + 8, cc->peer_version, 8);
1834
1835 strncpy(cc->remote_version, (char*)data+8, sizeof(cc->remote_version)-1);
1836 strncpy(cc->remote_build, (char*)data+40, sizeof(cc->remote_build)-1);
1837
1838 cs_log("%s srv %s running v%s (%s)", getprefix(), cs_hexdump(0,
1839 cc->peer_node_id, 8), cc->remote_version, cc->remote_build);
1840
1841 if (!cc->is_oscam_cccam) {//Allready discovered oscam-cccam:
1842 uint16 sum = 0x1234;
1843 uint16 recv_sum = (cc->peer_node_id[6] << 8)
1844 | cc->peer_node_id[7];
1845 int i;
1846 for (i = 0; i < 6; i++) {
1847 sum += cc->peer_node_id[i];
1848 }
1849 //Create special data to detect oscam-cccam:
1850 cc->is_oscam_cccam = sum == recv_sum;
1851 }
1852 //Trick: when discovered partner is an Oscam Client, then we send him our version string:
1853 if (cc->is_oscam_cccam) {
1854 sprintf((char*) buf,
1855 "PARTNER: OSCam v%s, build #%s (%s) [EXT,SID]", CS_VERSION,
1856 CS_SVN_VERSION, CS_OSTYPE);
1857 cc_cmd_send(cl, buf, strlen((char*) buf) + 1, MSG_CW_NOK1);
1858 }
1859
1860 cc->cmd05_mode = MODE_PLAIN;
1861 //
1862 //Keyoffset is payload-size:
1863 //
1864 } else if (l >= 0x00 && l <= 0x0F) {
1865 cc->cmd05_offset = l;
1866 //
1867 //16..43 bytes: RC4 encryption:
1868 //
1869 } else if ((l >= 0x10 && l <= 0x1f) || (l >= 0x24 && l <= 0x2b)) {
1870 cc_init_crypt(&cc->cmd05_cryptkey, data, l);
1871 cc->cmd05_mode = MODE_RC4_CRYPT;
1872 //
1873 //32 bytes: set AES128 key for CMD_05, Key=16 bytes offset keyoffset
1874 //
1875 } else if (l == 0x20) {
1876 memcpy(cc->cmd05_aeskey, data + cc->cmd05_offset, 16);
1877 cc->cmd05_mode = MODE_AES;
1878 //
1879 //33 bytes: xor-algo mit payload-bytes, offset keyoffset
1880 //
1881 } else if (l == 0x21) {
1882 cc_init_crypt(&cc->cmd05_cryptkey, data + cc->cmd05_offset, l);
1883 cc->cmd05_mode = MODE_CC_CRYPT;
1884 //
1885 //34 bytes: cmd_05 plain back
1886 //
1887 } else if (l == 0x22) {
1888 cc->cmd05_mode = MODE_PLAIN;
1889 //
1890 //35 bytes: Unknown!! 2 256 byte keys exchange
1891 //
1892 } else if (l == 0x23) {
1893 cc->cmd05_mode = MODE_UNKNOWN;
1894 //cycle_connection(); //Absolute unknown handling!
1895 cc_cli_close(cl, TRUE);
1896 //
1897 //44 bytes: set aes128 key, Key=16 bytes [Offset=len(password)]
1898 //
1899 } else if (l == 0x2c) {
1900 memcpy(cc->cmd05_aeskey, data + strlen(rdr->r_pwd), 16);
1901 cc->cmd05_mode = MODE_AES;
1902 //
1903 //45 bytes: set aes128 key, Key=16 bytes [Offset=len(username)]
1904 //
1905 } else if (l == 0x2d) {
1906 memcpy(cc->cmd05_aeskey, data + strlen(rdr->r_usr), 16);
1907 cc->cmd05_mode = MODE_AES;
1908 //
1909 //Unknown!!
1910 //
1911 } else {
1912 cs_log(
1913 "%s received improper MSG_SRV_DATA! No change to current mode, mode=%d",
1914 getprefix(), cc->cmd05_mode);
1915 break;
1916 }
1917 cs_debug_mask(D_TRACE, "%s MSG_SRV_DATA MODE=%s, len=%d", getprefix(),
1918 cmd05_mode_name[cc->cmd05_mode], l);
1919
1920 break;
1921 case MSG_NEW_CARD_SIDINFO:
1922 case MSG_NEW_CARD: {
1923 if (buf[14] >= rdr->cc_maxhop)
1924 break;
1925
1926 if (!chk_ctab(b2i(2, buf + 12), &rdr->ctab))
1927 break;
1928
1929 rdr->tcp_connected = 2; //we have card
1930 rdr->card_status = CARD_INSERTED;
1931
1932 pthread_mutex_lock(&cc->cards_busy);
1933
1934 struct cc_card *card = read_card(data, buf[1]==MSG_NEW_CARD_SIDINFO);
1935
1936 //Check if this card is from us:
1937 LL_ITER *it = ll_iter_create(card->remote_nodes);
1938 uint8 *remote_id;
1939 while ((remote_id = ll_iter_next(it))) {
1940 if (memcmp(remote_id, cc_node_id, sizeof(cc_node_id)) == 0) { //this card is from us!
1941 cs_debug_mask(D_TRACE, "filtered card because of recursive nodeid: id=%08X, caid=%04X", card->id, card->caid);
1942 cc_free_card(card);
1943 card=NULL;
1944 break;
1945 }
1946 }
1947 ll_iter_release(it);
1948
1949 //Check Ident filter:
1950 if (card) {
1951 if (!chk_ident(&rdr->ftab, card)) {
1952 cc_free_card(card);
1953 card=NULL;
1954 }
1955 }
1956
1957 if (card) {
1958 //Check if we already have this card:
1959 it = ll_iter_create(cc->cards);
1960 struct cc_card *old_card;
1961 while ((old_card = ll_iter_next(it))) {
1962 if (old_card->id == card->id || //we aready have this card, delete it
1963 same_card(old_card, card)) {
1964 cc_free_card(card);
1965 card = old_card;
1966 break;
1967 }
1968 }
1969 ll_iter_release(it);
1970
1971 card->time = time((time_t) 0);
1972 if (!old_card) {
1973 card->hop++; //inkrementing hop
1974 ll_append(cc->cards, card);
1975 set_au_data(cl, rdr, card, NULL);
1976 cc->cards_modified++;
1977 }
1978 }
1979
1980 pthread_mutex_unlock(&cc->cards_busy);
1981
1982 break;
1983 }
1984
1985 case MSG_CARD_REMOVED: {
1986 cc_card_removed(cl, b2i(4, buf + 4));
1987 break;
1988 }
1989
1990 case MSG_CW_NOK1:
1991 case MSG_CW_NOK2:
1992 if (l > 4) {
1993 //Received NOK with payload:
1994 char *msg = (char*) buf + 4;
1995 cs_log("%s %s", getprefix(), msg);
1996
1997 //Check for PARTNER connection:
1998 if (!cc->is_oscam_cccam && strncmp(msg, "PARTNER:", 8) == 0) {
1999 //When Data starts with "PARTNER:" we have an Oscam-cccam-compatible client/server!
2000 cc->is_oscam_cccam = 1;
2001 strncpy(cc->remote_oscam, msg+9, sizeof(cc->remote_oscam)-1);
2002
2003 int has_param = check_extended_mode(cl, msg);
2004
2005 //send params back. At the moment there is only "EXT"
2006 char param[14];
2007 if (!has_param)
2008 param[0] = 0;
2009 else {
2010 strcpy(param, " [");
2011 if (cc->extended_mode)
2012 addParam(param, "EXT");
2013 if (cc->cccam220)
2014 addParam(param, "SID");
2015 strcat(param, "]");
2016 }
2017
2018 sprintf((char*) buf, "PARTNER: OSCam v%s, build #%s (%s)%s",
2019 CS_VERSION, CS_SVN_VERSION, CS_OSTYPE, param);
2020 cc_cmd_send(cl, buf, strlen((char*) buf) + 1, MSG_CW_NOK1);
2021 } else if (cc->is_oscam_cccam)
2022 check_extended_mode(cl, msg);
2023 cs_debug_mask(D_FUT, "cc_parse_msg out");
2024 return ret;
2025 }
2026
2027 if (cl->typ == 'c') //for reader only
2028 return ret;
2029
2030 if (cc->just_logged_in)
2031 return -1; // reader restart needed
2032
2033 pthread_mutex_lock(&cc->cards_busy);
2034 struct cc_extended_ecm_idx *eei = get_extended_ecm_idx(cl,
2035 cc->extended_mode ? cc->g_flag : 1, TRUE);
2036 if (!eei) {
2037 cs_log("%s received extended ecm NOK id %d but not found!",
2038 getprefix(), cc->g_flag);
2039 }
2040 else
2041 {
2042 ushort ecm_idx = eei->ecm_idx;
2043 struct cc_card *card = eei->card;
2044 struct cc_srvid srvid = eei->srvid;
2045 free(eei);
2046
2047 if (card) {
2048 if (buf[1] == MSG_CW_NOK1) //MSG_CW_NOK1: share no more available
2049 cc_card_removed(cl, card->id);
2050 else if (cc->cmd05NOK) {
2051 move_card_to_end(cl, card);
2052 add_sid_block(cl, card, &srvid);
2053 }
2054 else if (!is_good_sid(card, &srvid)) //MSG_CW_NOK2: can't decode
2055 add_sid_block(cl, card, &srvid);
2056 else
2057 remove_good_sid(card, &srvid);
2058
2059 //retry ecm:
2060 int i = 0;
2061 for (i = 0; i < CS_MAXPENDING; i++) {
2062 if (cl->ecmtask[i].idx == ecm_idx && cl->ecmtask[i].rc == 101)
2063 cl->ecmtask[i].rc = 100; //Mark unused
2064 }
2065 } else
2066 cs_log("%S NOK: NO CARD!", getprefix());
2067 }
2068 cc->cmd05NOK = 0;
2069 pthread_mutex_unlock(&cc->cards_busy);
2070
2071 if (!cc->extended_mode) {
2072 rdr->available = 1;
2073 pthread_mutex_unlock(&cc->ecm_busy);
2074 }
2075
2076 cc_send_ecm(cl, NULL, NULL);
2077 break;
2078
2079 case MSG_CW_ECM:
2080 cc->just_logged_in = 0;
2081 if (cl->typ == 'c') { //SERVER:
2082 ECM_REQUEST *er;
2083
2084 struct cc_card *server_card = malloc(sizeof(struct cc_card));
2085 memset(server_card, 0, sizeof(struct cc_card));
2086 server_card->id = buf[10] << 24 | buf[11] << 16 | buf[12] << 8
2087 | buf[13];
2088 server_card->caid = b2i(2, data);
2089
2090 if ((er = get_ecmtask())) {
2091 er->caid = b2i(2, buf + 4);
2092 er->srvid = b2i(2, buf + 14);
2093 er->l = buf[16];
2094 memcpy(er->ecm, buf + 17, er->l);
2095 er->prid = b2i(4, buf + 6);
2096 cc->server_ecm_pending++;
2097 er->idx = ++cc->server_ecm_idx;
2098
2099 cs_debug_mask(
2100 D_TRACE,
2101 "%s ECM request from client: caid %04x srvid %04x(%d) prid %06x",
2102 getprefix(), er->caid, er->srvid, er->l, er->prid);
2103
2104 struct cc_srvid srvid;
2105 srvid.sid = er->srvid;
2106 srvid.ecmlen = er->l;
2107 add_extended_ecm_idx(cl, cc->extended_mode ? cc->g_flag : 1,
2108 er->idx, server_card, srvid);
2109
2110 get_cw(cl, er);
2111
2112 } else {
2113 cs_debug_mask(D_TRACE, "%s NO ECMTASK!!!!", getprefix());
2114 free(server_card);
2115 }
2116
2117 } else { //READER:
2118 pthread_mutex_lock(&cc->cards_busy);
2119
2120 struct cc_extended_ecm_idx *eei = get_extended_ecm_idx(cl,
2121 cc->extended_mode ? cc->g_flag : 1, TRUE);
2122 if (eei == NULL) {
2123 cs_log("%s received extended ecm id %d but not found!",
2124 getprefix(), cc->g_flag);
2125 }
2126 else
2127 {
2128 ushort ecm_idx = eei->ecm_idx;
2129 struct cc_card *card = eei->card;
2130 struct cc_srvid srvid = eei->srvid;
2131 free(eei);
2132
2133 if (card) {
2134
2135 if (!cc->extended_mode) {
2136 cc_cw_crypt(cl, buf + 4, card->id);
2137 cc_cw_crypt_cmd0c(cl, buf + 4);
2138 }
2139
2140 memcpy(cc->dcw, buf + 4, 16);
2141 //fix_dcw(cc->dcw);
2142 if (!cc->extended_mode)
2143 cc_crypt(&cc->block[DECRYPT], buf + 4, l - 4, ENCRYPT); // additional crypto step
2144
2145 if (is_null_dcw(cc->dcw)) {
2146 cs_log("%s null dcw received! sid=%04X(%d)", getprefix(),
2147 srvid.sid, srvid.ecmlen);
2148 add_sid_block(cl, card, &srvid);
2149 //ecm retry:
2150 int i = 0;
2151 for (i = 0; i < CS_MAXPENDING; i++) {
2152 if (cl->ecmtask[i].idx == ecm_idx && cl->ecmtask[i].rc==101)
2153 cl->ecmtask[i].rc = 100; //Mark unused
2154 }
2155
2156 buf[1] = MSG_CW_NOK2; //So it's really handled like a nok!
2157 } else {
2158 cc->recv_ecmtask = ecm_idx;
2159 cs_debug_mask(D_TRACE, "%s cws: %d %s", getprefix(),
2160 ecm_idx, cs_hexdump(0, cc->dcw, 16));
2161 add_good_sid(cl, card, &srvid);
2162
2163 //check response time, if > fallbacktime, switch cards!
2164 struct timeb tpe;
2165 cs_ftime(&tpe);
2166 ulong cwlastresptime = 1000*(tpe.time-cc->ecm_time.time)+tpe.millitm-cc->ecm_time.millitm;
2167 if (cwlastresptime > cfg->ftimeout) {
2168 cs_log("%s card %04X is too slow, moving to the end...", getprefix(), card->id);
2169 move_card_to_end(cl, card);
2170 }
2171
2172 }
2173 } else {
2174 cs_log(
2175 "%s warning: ECM-CWS respond by CCCam server without current card!",
2176 getprefix());
2177 }
2178 }
2179 pthread_mutex_unlock(&cc->cards_busy);
2180
2181 if (!cc->extended_mode) {
2182 rdr->available = 1;
2183 pthread_mutex_unlock(&cc->ecm_busy);
2184 }
2185
2186 //cc_abort_user_ecms();
2187
2188 cc_send_ecm(cl, NULL, NULL);
2189
2190 if (cc->max_ecms)
2191 cc->ecm_counter++;
2192 }
2193 break;
2194
2195 case MSG_KEEPALIVE:
2196 cc->just_logged_in = 0;
2197 if (cl->typ != 'c') {
2198 cs_debug("cccam: keepalive ack");
2199 } else {
2200 //Checking if last answer is one minute ago:
2201 if (cc->answer_on_keepalive + 55 <= time(NULL)) {
2202 cc_cmd_send(cl, NULL, 0, MSG_KEEPALIVE);
2203 cs_debug("cccam: keepalive");
2204 cc->answer_on_keepalive = time(NULL);
2205 }
2206 }
2207 break;
2208
2209 case MSG_CMD_05:
2210 if (cl->typ != 'c') {
2211 cc->just_logged_in = 0;
2212 l = l - 4;//Header Length=4 Byte
2213
2214 cs_log("%s MSG_CMD_05 recvd, payload length=%d mode=%d",
2215 getprefix(), l, cc->cmd05_mode);
2216 cc->cmd05_active = 1;
2217 cc->cmd05_data_len = l;
2218 memcpy(&cc->cmd05_data, buf + 4, l);
2219 if (rdr->available && ll_count(cc->cards))
2220 send_cmd05_answer(cl);
2221 }
2222 break;
2223 case MSG_CMD_0B: {
2224 // by Project:Keynation
2225 /*cs_log("%s MSG_CMD_0B received, cycle connection (payload=%d)!", getprefix(), l-4);*/
2226 cs_debug_mask(D_TRACE, "%s MSG_CMD_0B received (payload=%d)!",
2227 getprefix(), l - 4);
2228 cs_ddump(buf, l, "%s content: len=%d", getprefix(), l);
2229
2230 AES_KEY key;
2231 uint8 aeskey[16];
2232 uint8 out[16];
2233
2234 memcpy(aeskey, cc->cmd0b_aeskey, 16);
2235 memset(&key, 0, sizeof(key));
2236
2237 cs_ddump(aeskey, 16, "%s CMD_0B AES key:", getprefix());
2238 cs_ddump(data, 16, "%s CMD_0B received data:", getprefix());
2239
2240 AES_set_encrypt_key((unsigned char *) &aeskey, 128, &key);
2241 AES_encrypt((unsigned char *) data, (unsigned char *) &out, &key);
2242
2243 cs_debug_mask(D_TRACE, "%s sending CMD_0B! ", getprefix());
2244 cs_ddump(out, 16, "%s CMD_0B out:", getprefix());
2245 cc_cmd_send(cl, out, 16, MSG_CMD_0B);
2246
2247 break;
2248 }
2249
2250 case MSG_CMD_0C: { //New CCCAM 2.2.0 Server/Client fake check!
2251 int len = l-4;
2252
2253 if (cl->typ == 'c') { //Only im comming from "client"
2254 cs_debug_mask(D_TRACE, "%s MSG_CMD_0C received (payload=%d)!", getprefix(), len);
2255 cs_ddump(buf, l, "%s content: len=%d", getprefix(), l);
2256
2257 uint8 bytes[0x20];
2258 if (len < 0x20) //if less then 0x20 bytes, clear others:
2259 memset(data+len, 0, 0x20-len);
2260
2261 //change first 0x10 bytes to the second:
2262 memcpy(bytes, data+0x10, 0x10);
2263 memcpy(bytes+0x10, data, 0x10);
2264
2265 //xor data:
2266 int i;
2267 for (i=0;i<0x20;i++)
2268 bytes[i] ^= (data[i] & 0x7F);
2269
2270 //key is now the 16bit hash of md5:
2271 uint8 md5hash[0x10];
2272 MD5(data, 0x20, md5hash);
2273 memcpy(bytes, md5hash, 0x10);
2274
2275 cs_debug_mask(D_TRACE, "%s sending CMD_0C! ", getprefix());
2276 cs_ddump(bytes, 0x20, "%s CMD_0C out:", getprefix());
2277 cc_cmd_send(cl, bytes, 0x20, MSG_CMD_0C);
2278 }
2279 else //reader
2280 {
2281 // by Project:Keynation
2282 uint8 CMD_0x0C_Command = data[0];
2283
2284 if (CMD_0x0C_Command > 4) {
2285 cc->cmd0c_mode = MODE_CMD_0x0C_NONE;
2286 break;
2287 }
2288
2289 switch (CMD_0x0C_Command) {
2290
2291 case 0 : { //RC6
2292 cc->cmd0c_mode = MODE_CMD_0x0C_RC6;
2293 break;
2294 }
2295
2296 case 1: { //RC4
2297 cc->cmd0c_mode = MODE_CMD_0x0C_RC4;
2298 break;
2299 }
2300
2301 case 2: { //CC_CRYPT
2302 cc->cmd0c_mode = MODE_CMD_0x0C_CC_CRYPT;
2303 break;
2304 }
2305
2306 case 3: { //AES
2307 cc->cmd0c_mode = MODE_CMD_0x0C_AES;
2308 break;
2309 }
2310
2311 case 4 : { //IDEA
2312 cc->cmd0c_mode = MODE_CMD_0x0C_IDEA;
2313 break;
2314 }
2315 }
2316
2317 cs_log("%s received MSG_CMD_0C from server! CMD_0x0C_CMD=%d, MODE=%s! Message data: %s",
2318 getprefix(), CMD_0x0C_Command, cmd0c_mode_name[cc->cmd0c_mode], cs_hexdump(0, data, len));
2319
2320 set_cmd0c_cryptkey(cl, data, len);
2321 }
2322 break;
2323 }
2324
2325 case MSG_CMD_0D: { //key update for the active cmd0x0c algo
2326 int len = l-4;
2327 if (cc->cmd0c_mode == MODE_CMD_0x0C_NONE)
2328 break;
2329
2330 set_cmd0c_cryptkey(cl, data, len);
2331
2332 cs_log("%s received MSG_CMD_0D from server! MODE=%s! Message data: %s",
2333 getprefix(), cmd0c_mode_name[cc->cmd0c_mode], cs_hexdump(0, data, len));
2334 break;
2335 }
2336
2337 case MSG_CMD_0E: {
2338 cs_log("cccam 2.2.0 commands not implemented");
2339 //Unkwon commands...need workout algo
2340 if (cl->typ == 'c') //client connection
2341 {
2342 //switching to an oder version and then disconnect...
2343 strcpy(cfg->cc_version, version[0]);
2344 ret = -1;
2345 }
2346 else //reader connection
2347 {
2348 strcpy(cl->reader->cc_version, version[0]);
2349 strcpy(cl->reader->cc_build, build[0]);
2350 cc_cli_close(cl, TRUE);
2351 }
2352 break;
2353 }
2354
2355 case MSG_EMM_ACK: {
2356 cc->just_logged_in = 0;
2357 if (cl->typ == 'c') { //EMM Request received
2358 cc_cmd_send(cl, NULL, 0, MSG_EMM_ACK); //Send back ACK
2359 if (l > 4) {
2360 cs_debug_mask(D_EMM, "%s EMM Request received!", getprefix());
2361
2362 if (!cl->aureader) {
2363 cs_debug_mask(
2364 D_EMM,
2365 "%s EMM Request discarded because au is not assigned to an reader!",
2366 getprefix());
2367 return MSG_EMM_ACK;
2368 }
2369
2370 EMM_PACKET *emm = malloc(sizeof(EMM_PACKET));
2371 memset(emm, 0, sizeof(EMM_PACKET));
2372 emm->caid[0] = buf[4];
2373 emm->caid[1] = buf[5];
2374 emm->provid[0] = buf[7];
2375 emm->provid[1] = buf[8];
2376 emm->provid[2] = buf[9];
2377 emm->provid[3] = buf[10];
2378 //emm->hexserial[0] = buf[11];
2379 //emm->hexserial[1] = buf[12];
2380 //emm->hexserial[2] = buf[13];
2381 //emm->hexserial[3] = buf[14];
2382 emm->l = buf[15];
2383 memcpy(emm->emm, buf + 16, emm->l);
2384 //emm->type = UNKNOWN;
2385 //emm->cidx = cs_idx;
2386 do_emm(cl, emm);
2387 free(emm);
2388 }
2389 } else { //Our EMM Request Ack!
2390 cs_debug_mask(D_EMM, "%s EMM ACK!", getprefix());
2391 if (!cc->extended_mode) {
2392 rdr->available = 1;
2393 pthread_mutex_unlock(&cc->ecm_busy);
2394 }
2395 cc_send_ecm(cl, NULL, NULL);
2396 }
2397 break;
2398 }
2399 default:
2400 cs_ddump(buf, l, "%s unhandled msg: %d len=%d", getprefix(), buf[1], l);
2401 break;
2402 }
2403
2404 if (cc->max_ecms && (cc->ecm_counter > cc->max_ecms)) {
2405 cs_log("%s max ecms (%d) reached, cycle connection!", getprefix(),
2406 cc->max_ecms);
2407 //cc_cycle_connection();
2408 cc_cli_close(cl, TRUE);
2409 //cc_send_ecm(NULL, NULL);
2410 }
2411 cs_debug_mask(D_FUT, "cc_parse_msg out");
2412 return ret;
2413}
2414
2415/**
2416 * Reader: write dcw to receive
2417 */
2418int cc_recv_chk(struct s_client *cl, uchar *dcw, int *rc, uchar *buf, int UNUSED(n)) {
2419 cs_debug_mask(D_FUT, "cc_recv_chk in");
2420 struct cc_data *cc = cl->cc;
2421
2422 if (buf[1] == MSG_CW_ECM) {
2423 memcpy(dcw, cc->dcw, 16);
2424 cs_debug("cccam: recv chk - MSG_CW %d - %s", cc->recv_ecmtask,
2425 cs_hexdump(0, dcw, 16));
2426 *rc = 1;
2427 cs_debug_mask(D_FUT, "cc_recv_chk out");
2428 return (cc->recv_ecmtask);
2429 } else if ((buf[1] == (MSG_CW_NOK1)) || (buf[1] == (MSG_CW_NOK2))) {
2430 cs_debug_mask(D_FUT, "cc_recv_chk out");
2431 return -1;
2432 }
2433
2434 cs_debug_mask(D_FUT, "cc_recv_chk out");
2435 return (-1);
2436}
2437
2438//int is_softfail(int rc)
2439//{
2440// //see oscam.c send_dcw() for a full list
2441// switch(rc)
2442// {
2443// case 5: // 5 = timeout
2444// case 6: // 6 = sleeping
2445// case 7: // 7 = fake
2446// case 10:// 10= no card
2447// case 11:// 11= expdate
2448// case 12:// 12= disabled
2449// case 13:// 13= stopped
2450// case 14:// 100= unhandled
2451// return TRUE;
2452// }
2453// return FALSE;
2454//}
2455
2456
2457
2458/**
2459 * Server: send DCW to client
2460 */
2461void cc_send_dcw(struct s_client *cl, ECM_REQUEST *er) {
2462 cs_debug_mask(D_FUT, "cc_send_dcw in");
2463 uchar buf[16];
2464 struct cc_data *cc = cl->cc;
2465
2466 memset(buf, 0, sizeof(buf));
2467
2468 struct cc_extended_ecm_idx *eei = get_extended_ecm_idx_by_idx(cl, er->idx,
2469 TRUE);
2470
2471 if (er->rc <= 3 && eei && eei->card) {
2472 memcpy(buf, er->cw, sizeof(buf));
2473 //fix_dcw(buf);
2474 cs_debug_mask(D_TRACE, "%s send cw: %s cpti: %d", getprefix(),
2475 cs_hexdump(0, buf, 16), er->cpti);
2476 if (!cc->extended_mode)
2477 cc_cw_crypt(cl, buf, eei->card->id);
2478 else
2479 cc->g_flag = eei->send_idx;
2480 cc_cmd_send(cl, buf, 16, MSG_CW_ECM);
2481 if (!cc->extended_mode)
2482 cc_crypt(&cc->block[ENCRYPT], buf, 16, ENCRYPT); // additional crypto step
2483 free(eei->card);
2484 } else {
2485 cs_debug_mask(D_TRACE, "%s send cw: NOK cpti: %d", getprefix(),
2486 er->cpti);
2487
2488 if (eei && cc->extended_mode)
2489 cc->g_flag = eei->send_idx;
2490
2491 int nok;
2492 if (!eei || !eei->card)
2493 nok = MSG_CW_NOK1; //share no more available
2494 else
2495 nok = MSG_CW_NOK2; //can't decode
2496 cc_cmd_send(cl, NULL, 0, nok);
2497 }
2498 cc->server_ecm_pending--;
2499 free(eei);
2500 cs_debug_mask(D_FUT, "cc_send_dcw out");
2501}
2502
2503int cc_recv(struct s_client *cl, uchar *buf, int l) {
2504 int n;
2505 uchar *cbuf;
2506 struct cc_data *cc = cl->cc;
2507
2508 if (buf == NULL || l <= 0)
2509 return -1;
2510 cbuf = malloc(l);
2511 memcpy(cbuf, buf, l); // make a copy of buf
2512
2513 pthread_mutex_lock(&cc->lock);
2514
2515 n = cc_msg_recv(cl, cbuf); // recv and decrypt msg
2516
2517 //cs_ddump(cbuf, n, "cccam: received %d bytes from %s", n, remote_txt());
2518 cl->last = time((time_t *) 0);
2519
2520 if (n <= 0) {
2521 cs_log("%s connection closed by %s", getprefix(), remote_txt());
2522 n = -1;
2523 } else if (n < 4) {
2524 cs_log("%s packet to small (%d bytes)", getprefix(), n);
2525 n = -1;
2526 } else {
2527 // parse it and write it back, if we have received something of value
2528 n = cc_parse_msg(cl, cbuf, n);
2529 memcpy(buf, cbuf, l);
2530 }
2531
2532 pthread_mutex_unlock(&cc->lock);
2533
2534 NULLFREE(cbuf);
2535
2536 if (n == -1) {
2537 if (cl->typ != 'c')
2538 cc_cli_close(cl, TRUE);
2539 }
2540
2541 return n;
2542}
2543
2544struct s_auth *get_account(char *usr) {
2545 struct s_auth *account;
2546 for (account = cfg->account; account; account = account->next) {
2547 if (strcmp(usr, account->usr) == 0) {
2548 return account;
2549 }
2550 }
2551 return NULL;
2552}
2553
2554/**
2555 * This function checks for hexserial changes on cards.
2556 * We update the share-list if a card has changed
2557 */
2558ulong get_reader_hexserial_crc(struct s_client *cl) {
2559 if (!cl->aureader)
2560 return 0;
2561
2562 ulong crc = 0;
2563 struct s_reader *rdr;
2564 for (rdr = first_reader; rdr; rdr = rdr->next) {
2565 if (rdr->enable && !rdr->deleted && rdr->client && !rdr->audisabled)
2566 crc += crc32(0, rdr->hexserial, 8);
2567 }
2568 return crc;
2569}
2570
2571ulong get_reader_prid(struct s_reader *rdr, int j) {
2572 ulong prid;
2573 if (!(rdr->typ & R_IS_CASCADING)) { // Read cardreaders have 4-byte Providers
2574 prid = (rdr->prid[j][0] << 24) | (rdr->prid[j][1] << 16)
2575 | (rdr->prid[j][2] << 8) | (rdr->prid[j][3] & 0xFF);
2576 } else { // Cascading/Network-reader 3-bytes Providers
2577 prid = (rdr->prid[j][0] << 16) | (rdr->prid[j][1] << 8)
2578 | (rdr->prid[j][2] & 0xFF);
2579 }
2580 return prid;
2581}
2582
2583void copy_sids(LLIST *dst, LLIST *src) {
2584 LL_ITER *it_src = ll_iter_create(src);
2585 LL_ITER *it_dst = ll_iter_create(dst);
2586 struct cc_srvid *srvid_src;
2587 struct cc_srvid *srvid_dst;
2588 while ((srvid_src=ll_iter_next(it_src))) {
2589 ll_iter_reset(it_dst);
2590 while ((srvid_dst=ll_iter_next(it_dst))) {
2591 if (sid_eq(srvid_src, srvid_dst))
2592 break;
2593 }
2594 if (!srvid_dst) {
2595 srvid_dst = malloc(sizeof(struct cc_srvid));
2596 memcpy(srvid_dst, srvid_src, sizeof(struct cc_srvid));
2597 ll_append(dst, srvid_dst);
2598 }
2599 }
2600 ll_iter_release(it_dst);
2601 ll_iter_release(it_src);
2602}
2603
2604int add_card_providers(struct cc_card *dest_card, struct cc_card *card,
2605 int copy_remote_nodes) {
2606 int modified = 0;
2607
2608 //1. Copy nonexisting providers, ignore double:
2609 struct cc_provider *prov_info;
2610 LL_ITER *it_dst, *it_src = ll_iter_create(card->providers);
2611 struct cc_provider *provider;
2612 while ((provider = ll_iter_next(it_src))) {
2613 it_dst = ll_iter_create(dest_card->providers);
2614 while ((prov_info = ll_iter_next(it_dst))) {
2615 if (prov_info->prov == provider->prov)
2616 break;
2617 }
2618 ll_iter_release(it_dst);
2619 if (!prov_info) {
2620 struct cc_provider *prov_new = malloc(sizeof(struct cc_provider));
2621 memcpy(prov_new, provider, sizeof(struct cc_provider));
2622 ll_append(dest_card->providers, prov_new);
2623 modified = 1;
2624 }
2625 }
2626 ll_iter_release(it_src);
2627
2628 if (copy_remote_nodes) {
2629 //2. Copy nonexisting remote_nodes, ignoring existing:
2630 it_src = ll_iter_create(card->remote_nodes);
2631 uint8 *remote_node;
2632 uint8 *remote_node2;
2633 while ((remote_node = ll_iter_next(it_src))) {
2634 it_dst = ll_iter_create(dest_card->remote_nodes);
2635 while ((remote_node2 = ll_iter_next(it_dst))) {
2636 if (memcmp(remote_node, remote_node2, 8) == 0)
2637 break;
2638 }
2639 ll_iter_release(it_dst);
2640 if (!remote_node2) {
2641 uint8* remote_node_new = malloc(8);
2642 memcpy(remote_node_new, remote_node, 8);
2643 ll_append(dest_card->remote_nodes, remote_node_new);
2644 modified = 1;
2645 }
2646 }
2647 ll_iter_release(it_src);
2648 }
2649 return modified;
2650}
2651
2652struct cc_card *create_card(struct cc_card *card) {
2653 struct cc_card *card2 = malloc(sizeof(struct cc_card));
2654 if (card)
2655 memcpy(card2, card, sizeof(struct cc_card));
2656 else
2657 memset(card2, 0, sizeof(struct cc_card));
2658 card2->providers = ll_create();
2659 card2->badsids = ll_create();
2660 card2->goodsids = ll_create();
2661 card2->remote_nodes = ll_create();
2662
2663 if (card) {
2664 copy_sids(card2->goodsids, card->goodsids);
2665 copy_sids(card2->badsids, card->badsids);
2666 }
2667
2668 return card2;
2669}
2670
2671struct cc_card *create_card2(struct s_reader *rdr, int j, uint16 caid, uint8 hop, uint8 reshare) {
2672
2673 struct cc_card *card = create_card(NULL);
2674 uint8 rid[4];
2675 rid[3] = rdr->cc_id >> 24;
2676 rid[2] = rdr->cc_id >> 16;
2677 rid[1] = j >> 8;
2678 rid[0] = j & 0xFF;
2679 memcpy(&card->remote_id, rid, 4);
2680 card->caid = caid;
2681 card->hop = hop;
2682 card->maxdown = reshare;
2683 return card;
2684}
2685
2686/**
2687 * Adds a new card to a cardlist.
2688 */
2689int add_card_to_serverlist(struct s_reader *rdr, struct s_client *cl, LLIST *cardlist, struct cc_card *card, int reshare) {
2690
2691 if (!chk_ident(&cl->ftab, card))
2692 return 0;
2693 if (rdr && !chk_ident(&rdr->client->ftab, card))
2694 return 0;
2695
2696 struct cc_data *cc = cl->cc;
2697 int modified = 0;
2698 LL_ITER *it = ll_iter_create(cardlist);
2699 struct cc_card *card2;
2700
2701 //Minimize all, transmit just CAID
2702 if (cfg->cc_minimize_cards == MINIMIZE_CAID) {
2703 while ((card2 = ll_iter_next(it)))
2704 if (card2->caid == card->caid)
2705 break;
2706 if (!card2) {
2707 card2 = create_card(card);
2708 card2->hop = card->hop;
2709 card2->remote_id = card->remote_id;
2710 card2->maxdown = reshare;
2711 ll_append(cardlist, card2);
2712 modified = 1;
2713
2714 //Null-Provider for all Providers!
2715 struct cc_provider *prov_new = malloc(sizeof(struct cc_provider));
2716 memset(prov_new, 0, sizeof(struct cc_provider));
2717 ll_append(card2->providers, prov_new);
2718 } else {
2719 if (card->hop < card2->hop) {
2720 card2->hop = card->hop;
2721 modified = 1;
2722 }
2723 else cc->card_dup_count++;
2724 }
2725
2726 } else if (cfg->cc_minimize_cards == MINIMIZE_HOPS) {
2727 while ((card2 = ll_iter_next(it))) {
2728 if (card2->caid == card->caid && ll_count(card2->providers)
2729 < CS_MAXPROV)
2730 break;
2731 }
2732 if (!card2) {
2733 card2 = create_card(card);
2734 card2->hop = card->hop;
2735 card2->remote_id = card->remote_id;
2736 card2->maxdown = reshare;
2737 ll_append(cardlist, card2);
2738 modified = 1;
2739 } else {
2740 if (card->hop < card2->hop) {
2741 card2->hop = card->hop;
2742 modified = 1;
2743 }
2744 else cc->card_dup_count++;
2745
2746 }
2747 if (add_card_providers(card2, card, 0))
2748 modified = 1;
2749 } else { //just remove duplicate cards
2750 while ((card2 = ll_iter_next(it))) {
2751 if (same_card(card, card2))
2752 break;
2753 }
2754 if (card2 && card2->hop > card->hop) {
2755 cc_free_card(card2);
2756 ll_iter_remove(it);
2757 card2 = NULL;
2758 cc->card_dup_count++;
2759 }
2760 if (!card2) {
2761 card2 = create_card(card);
2762 card2->hop = card->hop;
2763 card2->remote_id = card->remote_id;
2764 card2->maxdown = reshare;
2765 ll_append(cardlist, card2);
2766 modified = 1;
2767 if (add_card_providers(card2, card, 1))
2768 modified = 1;
2769 }
2770 else cc->card_dup_count++;
2771 }
2772 ll_iter_release(it);
2773 return modified;
2774}
2775
2776int find_reported_card(struct s_client * cl, struct cc_card *card1)
2777{
2778 struct cc_data *cc = cl->cc;
2779
2780 LL_ITER *it = ll_iter_create(cc->reported_carddatas);
2781 struct cc_card *card2;
2782 while ((card2 = ll_iter_next(it))) {
2783 if (same_card(card1, card2)) {
2784 card1->id = card2->id; //Set old id !!
2785 cc_free_card(card2);
2786 ll_iter_remove(it);
2787 ll_iter_release(it);
2788 return 1; //Old card and new card are equal!
2789 }
2790 }
2791 ll_iter_release(it);
2792 return 0; //Card not found
2793}
2794
2795int report_card(struct s_client *cl, struct cc_card *card, LLIST *new_reported_carddatas)
2796{
2797 int res = 0;
2798 struct cc_data *cc = cl->cc;
2799 int ext = cc->cccam220;
2800 if (!find_reported_card(cl, card)) { //Add new card:
2801 uint8 buf[CC_MAXMSGSIZE];
2802 if (!cc->report_carddata_id)
2803 cc->report_carddata_id = 0x64;
2804 card->id = cc->report_carddata_id;
2805 cc->report_carddata_id++;
2806
2807 int len = write_card(cc, buf, card, TRUE, ext);
2808 res = cc_cmd_send(cl, buf, len, ext?MSG_NEW_CARD_SIDINFO:MSG_NEW_CARD);
2809 cc->card_added_count++;
2810 }
2811 cc_add_reported_carddata(new_reported_carddatas, card);
2812 return res;
2813}
2814
2815/**
2816 * Server:
2817 * Reports all caid/providers to the connected clients
2818 * returns 1=ok, 0=error
2819 */
2820int cc_srv_report_cards(struct s_client *cl) {
2821 int j;
2822 uint k;
2823 uint8 hop = 0;
2824 int reshare, usr_reshare, reader_reshare, maxhops, flt = 0;
2825
2826 struct cc_data *cc = cl->cc;
2827
2828 struct s_auth *account = get_account(cl->usr);
2829 if (account) {
2830 maxhops = account->cccmaxhops;
2831 usr_reshare = account->cccreshare;
2832 } else {
2833 maxhops = 10;
2834 usr_reshare = cfg->cc_reshare;
2835 }
2836
2837 LLIST *server_cards = ll_create();
2838 if (!cc->reported_carddatas)
2839 cc->reported_carddatas = ll_create();
2840 LLIST *new_reported_carddatas = ll_create();
2841
2842 cc->card_added_count = 0;
2843 cc->card_removed_count = 0;
2844 cc->card_dup_count = 0;
2845
2846 int isau = (cl->aureader)?1:0;
2847
2848 struct s_reader *rdr;
2849 for (rdr = first_reader; rdr; rdr = rdr->next) {
2850 if (!rdr->fd || !rdr->enable || rdr->deleted)
2851 continue;
2852 if (!(rdr->grp & cl->grp))
2853 continue;
2854 reader_reshare = rdr->cc_reshare;
2855
2856 reshare = (reader_reshare < usr_reshare) ? reader_reshare : usr_reshare;
2857 if (reshare < 0)
2858 continue;
2859
2860 if (!rdr->cc_id) {
2861 int r = get_ridx(rdr) + 0x64;
2862 rdr->cc_id = r << 24 | r << 16 | fast_rnd() << 8 | fast_rnd();
2863 }
2864
2865 int au_allowed = !rdr->audisabled && isau;
2866
2867 flt = 0;
2868 if (rdr->typ != R_CCCAM && rdr->ftab.filts) {
2869 for (j = 0; j < CS_MAXFILTERS; j++) {
2870 if (rdr->ftab.filts[j].caid &&
2871 chk_ctab(rdr->ftab.filts[j].caid, &cl->ctab)) {
2872 int ignore = 0;
2873 ushort caid = rdr->ftab.filts[j].caid;
2874 struct cc_card *card = create_card2(rdr, j, caid, hop, reshare);
2875 //Setting UA: (Unique Address):
2876 if (au_allowed)
2877 cc_UA_oscam2cccam(rdr->hexserial, card->hexserial, caid);
2878 //cs_log("Ident CCcam card report caid: %04X readr %s subid: %06X", rdr->ftab.filts[j].caid, rdr->label, rdr->cc_id);
2879 for (k = 0; k < rdr->ftab.filts[j].nprids; k++) {
2880 struct cc_provider *prov = malloc(sizeof(struct cc_provider));
2881 memset(prov, 0, sizeof(struct cc_provider));
2882 prov->prov = rdr->ftab.filts[j].prids[k];
2883 if (!chk_srvid_by_caid_prov(cl, caid, prov->prov, 0)) {
2884 ignore = 1;
2885 }
2886 //cs_log("Ident CCcam card report provider: %02X%02X%02X", buf[21 + (k*7)]<<16, buf[22 + (k*7)], buf[23 + (k*7)]);
2887 if (au_allowed) {
2888 int l;
2889 for (l = 0; l < rdr->nprov; l++) {
2890 ulong rprid = get_reader_prid(rdr, l);
2891 if (rprid == prov->prov)
2892 cc_SA_oscam2cccam(&rdr->sa[l][0], prov->sa);
2893 }
2894 }
2895 ll_append(card->providers, prov);
2896 }
2897
2898 if (!ignore) add_card_to_serverlist(rdr, cl, server_cards, card, reshare);
2899 else cc_free_card(card);
2900 flt = 1;
2901 }
2902 }
2903 }
2904
2905 if (rdr->typ != R_CCCAM && !rdr->caid[0] && !flt) {
2906 flt = 0;
2907 for (j = 0; j < CS_MAXCAIDTAB; j++) {
2908 //cs_log("CAID map CCcam card report caid: %04X cmap: %04X", rdr->ctab.caid[j], rdr->ctab.cmap[j]);
2909 ushort lcaid = rdr->ctab.caid[j];
2910
2911 if (!lcaid || (lcaid == 0xFFFF))
2912 lcaid = rdr->ctab.cmap[j];
2913
2914 if (lcaid && (lcaid != 0xFFFF)) {
2915 struct cc_card *card = create_card2(rdr, j, lcaid, hop, reshare);
2916 if (au_allowed)
2917 cc_UA_oscam2cccam(rdr->hexserial, card->hexserial, lcaid);
2918
2919 if (chk_ctab(lcaid, &cl->ctab))
2920 add_card_to_serverlist(rdr, cl, server_cards, card, reshare);
2921 else
2922 cc_free_card(card);
2923 flt = 1;
2924 }
2925 }
2926 }
2927
2928 if (rdr->typ != R_CCCAM && rdr->caid[0] && !flt && chk_ctab(rdr->caid[0], &cl->ctab)) {
2929 //cs_log("tcp_connected: %d card_status: %d ", rdr->tcp_connected, rdr->card_status);
2930 ushort caid = rdr->caid[0];
2931 struct cc_card *card = create_card2(rdr, 0, caid, hop, reshare);
2932 if (au_allowed)
2933 cc_UA_oscam2cccam(rdr->hexserial, card->hexserial, caid);
2934 for (j = 0; j < rdr->nprov; j++) {
2935 ulong prid = get_reader_prid(rdr, j);
2936 struct cc_provider *prov = malloc(sizeof(struct cc_provider));
2937 memset(prov, 0, sizeof(struct cc_provider));
2938 prov->prov = prid;
2939 //cs_log("Ident CCcam card report provider: %02X%02X%02X", buf[21 + (k*7)]<<16, buf[22 + (k*7)], buf[23 + (k*7)]);
2940 if (au_allowed) {
2941 int l; //Setting SA (Shared Addresses):
2942 for (l = 0; l < rdr->nprov; l++) {
2943 ulong rprid = get_reader_prid(rdr, l);
2944 if (rprid == prid)
2945 cc_SA_oscam2cccam(&rdr->sa[l][0], prov->sa);
2946 }
2947 }
2948 ll_append(card->providers, prov);
2949 //cs_log("Main CCcam card report provider: %02X%02X%02X%02X", buf[21+(j*7)], buf[22+(j*7)], buf[23+(j*7)], buf[24+(j*7)]);
2950 }
2951 if ((rdr->tcp_connected || rdr->card_status == CARD_INSERTED) /*&& !rdr->cc_id*/) {
2952 //rdr->cc_id = b2i(3, buf + 5);
2953 add_card_to_serverlist(rdr, cl, server_cards, card, reshare);
2954 }
2955 else
2956 cc_free_card(card);
2957 }
2958
2959 if (rdr->typ == R_CCCAM && !flt) {
2960
2961 cs_debug_mask(D_TRACE, "%s asking reader %s for cards...",
2962 getprefix(), rdr->label);
2963
2964 struct cc_card *card;
2965 struct s_client *rc = rdr->client;
2966 struct cc_data *rcc = rc->cc;
2967
2968 int count = 0;
2969 if (rcc && rcc->cards) {
2970 pthread_mutex_lock(&rcc->cards_busy);
2971
2972 LL_ITER *it = ll_iter_create(rcc->cards);
2973 while ((card = ll_iter_next(it))) {
2974 if (card->hop <= maxhops && chk_ctab(card->caid, &cl->ctab)
2975 && chk_ctab(card->caid, &rdr->ctab)) {
2976
2977 if ((cfg->cc_ignore_reshare || card->maxdown > 0)) {
2978 int ignore = 0;
2979
2980 LL_ITER *it2 = ll_iter_create(card->providers);
2981 struct cc_provider *prov;
2982 while ((prov = ll_iter_next(it2))) {
2983 ulong prid = prov->prov;
2984 if (!chk_srvid_by_caid_prov(cl, card->caid,
2985 prid, 0) || !chk_srvid_by_caid_prov(
2986 rdr->client, card->caid, prid, 0)) {
2987 ignore = 1;
2988 break;
2989 }
2990 }
2991 ll_iter_release(it2);
2992
2993 if (!ignore) { //Filtered by service
2994 int new_reshare =
2995 cfg->cc_ignore_reshare ? reshare
2996 : (card->maxdown - 1);
2997 if (new_reshare > reshare)
2998 new_reshare = reshare;
2999 add_card_to_serverlist(rdr, cl, server_cards, card,
3000 new_reshare);
3001 count++;
3002 }
3003 }
3004 }
3005 }
3006 ll_iter_release(it);
3007 pthread_mutex_unlock(&rcc->cards_busy);
3008 }
3009 cs_debug_mask(D_TRACE, "%s got %d cards from %s", getprefix(),
3010 count, rdr->label);
3011 }
3012 }
3013
3014 int ok = TRUE;
3015 //report reshare cards:
3016 //cs_debug_mask(D_TRACE, "%s reporting %d cards", getprefix(), ll_count(server_cards));
3017 LL_ITER *it = ll_iter_create(server_cards);
3018 struct cc_card *card;
3019 while (ok && (card = ll_iter_next(it))) {
3020 //cs_debug_mask(D_TRACE, "%s card %d caid %04X hop %d", getprefix(), card->id, card->caid, card->hop);
3021
3022 ok =report_card(cl, card, new_reported_carddatas) >= 0;
3023 ll_iter_remove(it);
3024 }
3025 ll_iter_release(it);
3026 cc_free_cardlist(server_cards, TRUE);
3027
3028 //remove unsed, remaining cards:
3029 cc->card_removed_count += cc_free_reported_carddata(cl, cc->reported_carddatas, new_reported_carddatas, ok);
3030 cc->reported_carddatas = new_reported_carddatas;
3031
3032 cs_log("%s reported/updated +%d/-%d/dup %d of %d cards to client", getprefix(),
3033 cc->card_added_count, cc->card_removed_count, cc->card_dup_count, ll_count(cc->reported_carddatas));
3034 return ok;
3035}
3036
3037void cc_init_cc(struct cc_data *cc) {
3038 pthread_mutexattr_t mta;
3039 pthread_mutexattr_init(&mta);
3040#if defined(OS_CYGWIN32) || defined(OS_HPUX) || defined(OS_FREEBSD) || defined(OS_MACOSX)
3041 pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE);
3042#else
3043 pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE_NP);
3044#endif
3045 pthread_mutex_init(&cc->lock, NULL); //No recursive lock
3046 pthread_mutex_init(&cc->ecm_busy, NULL); //No recusive lock
3047 pthread_mutex_init(&cc->cards_busy, &mta); //Recursive lock
3048}
3049
3050/**
3051 * Starting readers to get cards:
3052 **/
3053int cc_srv_wakeup_readers(struct s_client *cl) {
3054 int wakeup = 0;
3055 struct s_reader *rdr;
3056 for (rdr = first_reader; rdr; rdr = rdr->next) {
3057 if (rdr->typ != R_CCCAM)
3058 continue;
3059 if (!rdr->fd || !rdr->enable || rdr->deleted || rdr->tcp_connected == 2)
3060 continue;
3061 if (!(rdr->grp & cl->grp))
3062 continue;
3063 if (rdr->cc_keepalive) //if reader has keepalive but is NOT connected, reader can't connect. so don't ask him
3064 continue;
3065
3066 //This wakeups the reader:
3067 uchar dummy;
3068 write_to_pipe(rdr->fd, PIP_ID_CIN, &dummy, sizeof(dummy));
3069 wakeup++;
3070 }
3071 return wakeup;
3072}
3073
3074int cc_cards_modified() {
3075 int modified = 0;
3076 struct s_reader *rdr;
3077 for (rdr = first_reader; rdr; rdr = rdr->next) {
3078 if (rdr->typ == R_CCCAM && rdr->fd && rdr->enable && !rdr->deleted) {
3079 struct s_client *clr = rdr->client;
3080 if (clr->cc) {
3081 struct cc_data *ccr = clr->cc;
3082 modified += ccr->cards_modified;
3083 }
3084 }
3085 }
3086 return modified;
3087}
3088
3089int check_cccam_compat(struct cc_data *cc) {
3090 int res = 0;
3091 if (strcmp(cfg->cc_version, "2.2.0") == 0 || strcmp(cfg->cc_version, "2.2.1") == 0) {
3092
3093 if (strcmp(cc->remote_version, "2.2.0") == 0 || strcmp(cc->remote_version, "2.2.1") == 0) {
3094 res = 1;
3095 }
3096 }
3097 return res;
3098}
3099
3100int cc_srv_connect(struct s_client *cl) {
3101 cs_debug_mask(D_FUT, "cc_srv_connect in");
3102 int i, wait_for_keepalive;
3103 ulong cmi;
3104 uint8 buf[CC_MAXMSGSIZE];
3105 uint8 data[16];
3106 char usr[21], pwd[21];
3107 struct s_auth *account;
3108 struct cc_data *cc = cl->cc;
3109 uchar mbuf[1024];
3110
3111 memset(usr, 0, sizeof(usr));
3112 memset(pwd, 0, sizeof(pwd));
3113
3114 //SS: Use last cc data for faster reconnects:
3115 if (!cc) {
3116 // init internals data struct
3117 cc = malloc(sizeof(struct cc_data));
3118 if (cc == NULL) {
3119 cs_log("cannot allocate memory");
3120 return -1;
3121 }
3122
3123 cl->cc = cc;
3124 memset(cl->cc, 0, sizeof(struct cc_data));
3125 cc->extended_ecm_idx = ll_create();
3126
3127 cc_init_cc(cc);
3128 }
3129 cc->server_ecm_pending = 0;
3130 cc->extended_mode = 0;
3131
3132 //Create checksum for "O" cccam:
3133 for (i = 0; i < 12; i++) {
3134 data[i] = fast_rnd();
3135 }
3136 for (i = 0; i < 4; i++) {
3137 data[12 + i] = (data[i] + data[4 + i] + data[8 + i]) & 0xff;
3138 }
3139
3140 send(cl->udp_fd, data, 16, 0);
3141
3142 cc_xor(data); // XOR init bytes with 'CCcam'
3143
3144 SHA_CTX ctx;
3145 SHA1_Init(&ctx);
3146 SHA1_Update(&ctx, data, 16);
3147 SHA1_Final(buf, &ctx);
3148
3149 cc_init_crypt(&cc->block[ENCRYPT], buf, 20);
3150 cc_crypt(&cc->block[ENCRYPT], data, 16, DECRYPT);
3151 cc_init_crypt(&cc->block[DECRYPT], data, 16);
3152 cc_crypt(&cc->block[DECRYPT], buf, 20, DECRYPT);
3153
3154 if ((i = recv(cl->pfd, buf, 20, MSG_WAITALL)) == 20) {
3155 cs_ddump(buf, 20, "cccam: recv:");
3156 cc_crypt(&cc->block[DECRYPT], buf, 20, DECRYPT);
3157 cs_ddump(buf, 20, "cccam: hash:");
3158 } else
3159 return -1;
3160
3161 // receive username
3162 if ((i = recv(cl->pfd, buf, 20, MSG_WAITALL)) == 20) {
3163 cc_crypt(&cc->block[DECRYPT], buf, 20, DECRYPT);
3164
3165 strncpy(usr, (char *) buf, sizeof(usr));
3166
3167 //test for nonprintable characters:
3168 for (i = 0; i < 20; i++) {
3169 if (usr[i] > 0 && usr[i] < 0x20) { //found nonprintable char
3170 cs_debug("illegal username received");
3171 return -1;
3172 }
3173 }
3174 cs_ddump(buf, 20, "cccam: username '%s':", usr);
3175 } else
3176 return -1;
3177
3178 cl->crypted = 1;
3179
3180 for (account = cfg->account; account; account = account->next) {
3181 if (strcmp(usr, account->usr) == 0) {
3182 strncpy(pwd, account->pwd, sizeof(pwd));
3183 break;
3184 }
3185 }
3186
3187 if (cs_auth_client(cl, account, NULL)) { //cs_auth_client returns 0 if account is valid/active/accessible
3188 cs_log("account '%s' not found!", usr);
3189 return -1;
3190 }
3191
3192 if (!cc->prefix)
3193 cc->prefix = malloc(strlen(cl->usr)+20);
3194 sprintf(cc->prefix, "cccam(s) %s: ", cl->usr);
3195
3196 // receive passwd / 'CCcam'
3197 cc_crypt(&cc->block[DECRYPT], (uint8 *) pwd, strlen(pwd), DECRYPT);
3198 if ((i = recv(cl->pfd, buf, 6, MSG_WAITALL)) == 6) {
3199 cc_crypt(&cc->block[DECRYPT], buf, 6, DECRYPT);
3200 cs_ddump(buf, 6, "cccam: pwd check '%s':", buf);
3201 } else
3202 return -1;
3203
3204 //Starting readers to get cards:
3205 int wakeup = cc_srv_wakeup_readers(cl);
3206
3207 // send passwd ack
3208 memset(buf, 0, 20);
3209 memcpy(buf, "CCcam\0", 6);
3210 cs_ddump(buf, 20, "cccam: send ack:");
3211 cc_crypt(&cc->block[ENCRYPT], buf, 20, ENCRYPT);
3212 send(cl->pfd, buf, 20, 0);
3213
3214 // recv cli data
3215 memset(buf, 0, sizeof(buf));
3216 i = cc_msg_recv(cl, buf);
3217 if (i < 0)
3218 return -1;
3219 cs_ddump(buf, i, "cccam: cli data:");
3220 memcpy(cc->peer_node_id, buf + 24, 8);
3221
3222 strncpy(cc->remote_version, (char*)buf+33, sizeof(cc->remote_version)-1);
3223 strncpy(cc->remote_build, (char*)buf+65, sizeof(cc->remote_build)-1);
3224
3225 cs_log("%s client '%s' (%s) running v%s (%s)", getprefix(), buf + 4,
3226 cs_hexdump(0, cc->peer_node_id, 8), cc->remote_version, cc->remote_build);
3227
3228 // send cli data ack
3229 cc_cmd_send(cl, NULL, 0, MSG_CLI_DATA);
3230
3231 if (cc_send_srv_data(cl) < 0)
3232 return -1;
3233
3234 cc->cccam220 = check_cccam_compat(cc);
3235
3236 // report cards
3237 ulong hexserial_crc = get_reader_hexserial_crc(cl);
3238
3239 if (wakeup > 0) //give readers time to get cards:
3240 cs_sleepms(500);
3241
3242 if (!cc_srv_report_cards(cl))
3243 return -1;
3244 cs_ftime(&cc->ecm_time);
3245
3246 cmi = 0;
3247 wait_for_keepalive = 0;
3248 // check for client timeout, if timeout occurs try to send keepalive
3249 while (cl->pfd)
3250 {
3251 i = process_input(mbuf, sizeof(mbuf), 10); //cfg->cmaxidle);
3252 if (i == -9) {
3253 cmi += 10;
3254 if (cfg->cmaxidle && cmi >= cfg->cmaxidle) {
3255 cmi = 0;
3256 if (!cl->ncd_keepalive && !cfg->cc_keep_connected) {
3257 cs_debug_mask(D_TRACE, "%s keepalive after maxidle is reached",
3258 getprefix());
3259 break; //Disconnect client
3260 }
3261 else if (cc->extended_mode) //special handling for "oscam"-cccam clients:
3262 {
3263 if (cc_cmd_send(cl, NULL, 0, MSG_KEEPALIVE) < 0)
3264 break;
3265 cs_debug("cccam: keepalive");
3266 cc->answer_on_keepalive = time(NULL);
3267 wait_for_keepalive = 1;
3268 continue;
3269 }
3270 }
3271 if (wait_for_keepalive)
3272 break; //got no answer -> disconnect
3273
3274 } else if (i <= 0)
3275 break; //Disconnected by client
3276 else { //data is parsed!
3277 cmi = 0;
3278 wait_for_keepalive = 0;
3279 }
3280 if (cc->mode != CCCAM_MODE_NORMAL || cl->dup)
3281 break; //mode wrong or duplicate user -->disconect
3282
3283 if (!cc->server_ecm_pending) {
3284 struct timeb timeout;
3285 struct timeb cur_time;
3286 cs_ftime(&cur_time);
3287 timeout = cc->ecm_time;
3288 timeout.time += cfg->cc_update_interval;
3289
3290 int needs_card_updates = (cfg->cc_update_interval >= 0)
3291 && comp_timeb(&cur_time, &timeout) > 0;
3292
3293 if (needs_card_updates) {
3294 cc->ecm_time = cur_time;
3295 ulong new_hexserial_crc = get_reader_hexserial_crc(cl);
3296 int cards_modified = cc_cards_modified();
3297 if (new_hexserial_crc != hexserial_crc || cards_modified
3298 != cc->cards_modified) {
3299 cs_debug_mask(D_TRACE, "%s update share list",
3300 getprefix());
3301
3302 hexserial_crc = new_hexserial_crc;
3303 cc->cards_modified = cards_modified;
3304
3305 if (!cc_srv_report_cards(cl))
3306 return -1;
3307 }
3308 }
3309 }
3310 }
3311
3312 cs_debug_mask(D_FUT, "cc_srv_connect out");
3313 return 0;
3314}
3315
3316void * cc_srv_init(struct s_client *cl) {
3317 cl->thread = pthread_self();
3318 pthread_setspecific(getclient, cl);
3319
3320 cs_debug_mask(D_FUT, "cc_srv_init in");
3321 cl->pfd = cl->udp_fd;
3322 if (cc_srv_connect(cl) < 0)
3323 cs_log("cccam: %d failed errno: %d (%s)", __LINE__, errno, strerror(
3324 errno));
3325 cc_cleanup(cl);
3326 cs_debug_mask(D_FUT, "cc_srv_init out");
3327 cs_disconnect_client(cl);
3328 return NULL; //suppress compiler warning
3329}
3330
3331int cc_cli_connect(struct s_client *cl) {
3332 cs_debug_mask(D_FUT, "cc_cli_connect in");
3333 struct s_reader *rdr = cl->reader;
3334 struct cc_data *cc = cl->cc;
3335
3336 if (cc && cc->mode != CCCAM_MODE_NORMAL)
3337 return -99;
3338
3339 if (!cl->udp_fd) {
3340 cc_cli_init_int(cl);
3341 return -1; // cc_cli_init_int calls cc_cli_connect, so exit here!
3342 }
3343
3344 if (is_connect_blocked(rdr)) {
3345 cs_log("%s connection blocked, retrying later", rdr->label);
3346 return -1;
3347 }
3348
3349 int handle, n;
3350 uint8 data[20];
3351 uint8 hash[SHA_DIGEST_LENGTH];
3352 uint8 buf[CC_MAXMSGSIZE];
3353 char pwd[64];
3354
3355 // check cred config
3356 if (rdr->device[0] == 0 || rdr->r_pwd[0] == 0 || rdr->r_usr[0] == 0
3357 || rdr->r_port == 0) {
3358 cs_log("%s configuration error!", rdr->label);
3359 return -5;
3360 }
3361
3362 // connect
3363 handle = network_tcp_connection_open();
3364 if (handle <= 0) {
3365 cs_log("%s network connect error!", rdr->label);
3366 return -1;
3367 }
3368 if (errno == EISCONN) {
3369 cc_cli_close(cl, FALSE);
3370
3371 block_connect(rdr);
3372 return -1;
3373 }
3374
3375 // get init seed
3376 if ((n = recv(handle, data, 16, MSG_WAITALL)) != 16) {
3377 int err = errno;
3378 cs_log("%s server does not return 16 bytes (n=%d, handle=%d, udp_fd=%d, errno=%d)",
3379 rdr->label, n, handle, cl->udp_fd, err);
3380 block_connect(rdr);
3381 return -2;
3382 }
3383
3384 if (!cc) {
3385 // init internals data struct
3386 cc = malloc(sizeof(struct cc_data));
3387 if (cc == NULL) {
3388 cs_log("%s cannot allocate memory", rdr->label);
3389 return -1;
3390 }
3391 memset(cc, 0, sizeof(struct cc_data));
3392 cc->cards = ll_create();
3393 cl->cc = cc;
3394 cc->pending_emms = ll_create();
3395 cc->extended_ecm_idx = ll_create();
3396 cc->current_cards = ll_create();
3397 cc_init_cc(cc);
3398 } else {
3399 if (cc->cards) {
3400 LL_ITER *it = ll_iter_create(cc->cards);
3401 struct cc_card *card;
3402 while ((card = ll_iter_next(it))) {
3403 cc_free_card(card);
3404 ll_iter_remove(it);
3405 }
3406 ll_iter_release(it);
3407 }
3408 if (cc->current_cards)
3409 free_current_cards(cc->current_cards);
3410 if (cc->extended_ecm_idx)
3411 free_extended_ecm_idx(cc);
3412
3413 pthread_mutex_trylock(&cc->ecm_busy);
3414 pthread_mutex_unlock(&cc->ecm_busy);
3415 }
3416 if (!cc->prefix)
3417 cc->prefix = malloc(strlen(cl->reader->label)+20);
3418 sprintf(cc->prefix, "cccam(r) %s: ", cl->reader->label);
3419
3420 cc->ecm_counter = 0;
3421 cc->max_ecms = 0;
3422 cc->cmd05_mode = MODE_UNKNOWN;
3423 cc->cmd05_offset = 0;
3424 cc->cmd05_active = 0;
3425 cc->cmd05_data_len = 0;
3426 cc->answer_on_keepalive = time(NULL);
3427 cc->extended_mode = 0;
3428 memset(&cc->cmd05_data, 0, sizeof(cc->cmd05_data));
3429
3430 cs_ddump(data, 16, "cccam: server init seed:");
3431
3432 uint16 sum = 0x1234;
3433 uint16 recv_sum = (data[14] << 8) | data[15];
3434 int i;
3435 for (i = 0; i < 14; i++) {
3436 sum += data[i];
3437 }
3438 //Create special data to detect oscam-cccam:
3439 cc->is_oscam_cccam = sum == recv_sum;
3440
3441 cc_xor(data); // XOR init bytes with 'CCcam'
3442
3443 SHA_CTX ctx;
3444 SHA1_Init(&ctx);
3445 SHA1_Update(&ctx, data, 16);
3446 SHA1_Final(hash, &ctx);
3447
3448 cs_ddump(hash, sizeof(hash), "cccam: sha1 hash:");
3449
3450 //initialisate crypto states
3451 cc_init_crypt(&cc->block[DECRYPT], hash, 20);
3452 cc_crypt(&cc->block[DECRYPT], data, 16, DECRYPT);
3453 cc_init_crypt(&cc->block[ENCRYPT], data, 16);
3454 cc_crypt(&cc->block[ENCRYPT], hash, 20, DECRYPT);
3455
3456 cc_cmd_send(cl, hash, 20, MSG_NO_HEADER); // send crypted hash to server
3457
3458 memset(buf, 0, sizeof(buf));
3459 memcpy(buf, rdr->r_usr, strlen(rdr->r_usr));
3460 cs_ddump(buf, 20, "cccam: username '%s':", buf);
3461 cc_cmd_send(cl, buf, 20, MSG_NO_HEADER); // send usr '0' padded -> 20 bytes
3462
3463 memset(buf, 0, sizeof(buf));
3464 memset(pwd, 0, sizeof(pwd));
3465
3466 cs_debug("cccam: 'CCcam' xor");
3467 memcpy(buf, "CCcam", 5);
3468 strncpy(pwd, rdr->r_pwd, sizeof(pwd) - 1);
3469 cc_crypt(&cc->block[ENCRYPT], (uint8 *) pwd, strlen(pwd), ENCRYPT);
3470 cc_cmd_send(cl, buf, 6, MSG_NO_HEADER); // send 'CCcam' xor w/ pwd
3471
3472 if ((n = recv(handle, data, 20, MSG_WAITALL)) != 20) {
3473 cs_log("%s login failed, pwd ack not received (n = %d)", getprefix(), n);
3474 return -2;
3475 }
3476 cc_crypt(&cc->block[DECRYPT], data, 20, DECRYPT);
3477 cs_ddump(data, 20, "cccam: pwd ack received:");
3478
3479 if (memcmp(data, buf, 5)) { // check server response
3480 cs_log("%s login failed, usr/pwd invalid", getprefix());
3481 return -2;
3482 } else {
3483 cs_debug_mask(D_TRACE, "%s login succeeded", getprefix());
3484 }
3485
3486 cs_debug("cccam: last_s=%d, last_g=%d", rdr->last_s, rdr->last_g);
3487
3488 cl->pfd = cl->udp_fd;
3489 cs_debug("cccam: pfd=%d", cl->pfd);
3490
3491 if (cc_send_cli_data(cl) <= 0) {
3492 cs_log("%s login failed, could not send client data", getprefix());
3493 return -3;
3494 }
3495
3496 rdr->caid[0] = rdr->ftab.filts[0].caid;
3497 rdr->nprov = rdr->ftab.filts[0].nprids;
3498 for (n = 0; n < rdr->nprov; n++) {
3499 rdr->availkeys[n][0] = 1;
3500 rdr->prid[n][0] = rdr->ftab.filts[0].prids[n] >> 24;
3501 rdr->prid[n][1] = rdr->ftab.filts[0].prids[n] >> 16;
3502 rdr->prid[n][2] = rdr->ftab.filts[0].prids[n] >> 8;
3503 rdr->prid[n][3] = rdr->ftab.filts[0].prids[n] & 0xff;
3504 }
3505
3506 rdr->card_status = CARD_NEED_INIT;
3507 rdr->last_g = rdr->last_s = time((time_t *) 0);
3508 rdr->tcp_connected = 1;
3509 rdr->available = 1;
3510
3511 cc->just_logged_in = 1;
3512
3513 cs_debug_mask(D_FUT, "cc_cli_connect out");
3514 return 0;
3515}
3516
3517int cc_cli_init_int(struct s_client *cl) {
3518 cs_debug_mask(D_FUT, "cc_cli_init_int");
3519 struct s_reader *rdr = cl->reader;
3520 if (rdr->tcp_connected)
3521 return 1;
3522
3523 struct protoent *ptrp;
3524 int p_proto;
3525
3526 cl->pfd = 0;
3527 if (rdr->r_port <= 0) {
3528 cs_log("%s invalid port %d for server %s", rdr->label, rdr->r_port,
3529 rdr->device);
3530 return 1;
3531 }
3532 if ((ptrp = getprotobyname("tcp")))
3533 p_proto = ptrp->p_proto;
3534 else
3535 p_proto = 6;
3536
3537 // cl->ip = 0;
3538 // memset((char *) &loc_sa, 0, sizeof(loc_sa));
3539 // loc_sa.sin_family = AF_INET;
3540 //#ifdef LALL
3541 // if (cfg->serverip[0])
3542 // loc_sa.sin_addr.s_addr = inet_addr(cfg->serverip);
3543 // else
3544 //#endif
3545 // loc_sa.sin_addr.s_addr = INADDR_ANY;
3546 // loc_sa.sin_port = htons(rdr->l_port);
3547
3548 if (cl->udp_fd)
3549 cc_cli_close(cl, FALSE);
3550
3551 if ((cl->udp_fd = socket(PF_INET, SOCK_STREAM, p_proto)) <= 0) {
3552 cs_log("%s Socket creation failed (errno=%d, socket=%d)", rdr->label,
3553 errno, cl->udp_fd);
3554 return 1;
3555 }
3556 //cs_log("%s 1 socket created: cs_idx=%d, fd=%d errno=%d", getprefix(), cs_idx, cl->udp_fd, errno);
3557
3558#ifdef SO_PRIORITY
3559 if (cfg->netprio)
3560 setsockopt(cl->udp_fd, SOL_SOCKET, SO_PRIORITY,
3561 (void *)&cfg->netprio, sizeof(ulong));
3562#endif
3563 rdr->tcp_ito = 1; //60sec...This now invokes ph_idle()
3564 if (rdr->cc_maxhop <= 0)
3565 rdr->cc_maxhop = 10;
3566
3567 memset((char *) &cl->udp_sa, 0, sizeof(cl->udp_sa));
3568 cl->udp_sa.sin_family = AF_INET;
3569 cl->udp_sa.sin_port = htons((u_short) rdr->r_port);
3570
3571 if (rdr->tcp_rto <= 2)
3572 rdr->tcp_rto = 2; // timeout to 120s
3573 cs_debug("cccam: timeout set to: %d", rdr->tcp_rto);
3574 cc_check_version(rdr->cc_version, rdr->cc_build);
3575 cs_log("proxy reader: %s (%s:%d) cccam v%s build %s, maxhop: %d",
3576 rdr->label, rdr->device, rdr->r_port, rdr->cc_version,
3577 rdr->cc_build, rdr->cc_maxhop);
3578
3579 cs_debug_mask(D_FUT, "cc_cli_init_int out");
3580 return 0;
3581}
3582
3583int cc_cli_init(struct s_client *cl) {
3584 struct cc_data *cc = cl->cc;
3585 struct s_reader *reader = cl->reader;
3586
3587 if ((cc && cc->mode == CCCAM_MODE_SHUTDOWN) || !cl->reader->enable || cl->reader->deleted)
3588 return -1;
3589
3590 int res = cc_cli_init_int(cl); //Create socket
3591
3592 if (res == 0 && reader && (reader->cc_keepalive || !cl->cc) && !reader->tcp_connected) {
3593
3594 cc_cli_connect(cl); //connect to remote server
3595
3596 while (!reader->tcp_connected && reader->cc_keepalive && cfg->reader_restart_seconds > 0) {
3597
3598 if ((cc && cc->mode == CCCAM_MODE_SHUTDOWN) || !cl->reader->enable || cl->reader->deleted)
3599 return -1;
3600
3601 if (!reader->tcp_connected) {
3602 cc_cli_close(cl, FALSE);
3603 res = cc_cli_init_int(cl);
3604 if (res)
3605 return res;
3606 }
3607 cs_log("%s restarting reader in %d seconds", reader->label, cfg->reader_restart_seconds);
3608 cs_sleepms(cfg->reader_restart_seconds*1000);
3609 cs_log("%s restarting reader...", reader->label);
3610 cc_cli_connect(cl);
3611 }
3612 }
3613 return res;
3614}
3615
3616/**
3617 * return 1 if we are able to send requests:
3618 *
3619 */
3620int cc_available(struct s_reader *rdr, int checktype) {
3621 struct s_client *cl = rdr->client;
3622
3623 //cs_debug_mask(D_TRACE, "checking reader %s availibility", rdr->label);
3624 if (!cl->cc || rdr->tcp_connected != 2 || rdr->card_status != CARD_INSERTED) {
3625 //Two cases:
3626 // 1. Keepalive ON but not connected: Do NOT send requests,
3627 // because we can't connect - problem of full running pipes
3628 // 2. Keepalive OFF but not connected: Send requests to connect
3629 // pipe won't run full, because we are reading from pipe to
3630 // get the ecm request
3631 return !rdr->cc_keepalive; //Not connected? Connect!
3632 }
3633
3634 if (checktype == AVAIL_CHECK_LOADBALANCE && !rdr->available) {
3635 cs_debug_mask(D_TRACE, "checking reader %s availibility=0 (unavail)",
3636 rdr->label);
3637 return 0; //We are processing EMMs/ECMs
3638 }
3639
3640 return 1;
3641}
3642
3643/**
3644 *
3645 *
3646 **/
3647void cc_card_info() {
3648 cs_debug_mask(D_FUT, "cc_card_info in");
3649 struct s_client *cl = cur_client();
3650 struct s_reader *rdr = cl->reader;
3651
3652 if (rdr && !rdr->tcp_connected)
3653 cc_cli_connect(cl);
3654 cs_debug_mask(D_FUT, "cc_card_info out");
3655}
3656
3657void cc_cleanup(struct s_client *cl) {
3658 cs_debug_mask(D_FUT, "cc_cleanup in");
3659 struct cc_data *cc = cl->cc;
3660 if (cc) cc->mode = CCCAM_MODE_SHUTDOWN;
3661
3662 if (cl->typ != 'c') {
3663 cc_cli_close(cl, FALSE); // we need to close open fd's
3664 }
3665 cc_free(cl);
3666 cs_debug_mask(D_FUT, "cc_cleanup out");
3667}
3668
3669void module_cccam(struct s_module *ph) {
3670 strcpy(ph->desc, "cccam");
3671 ph->type = MOD_CONN_TCP;
3672 ph->logtxt = ", crypted";
3673 ph->watchdog = 1;
3674 ph->recv = cc_recv;
3675 ph->cleanup = cc_cleanup;
3676 ph->c_multi = 1;
3677 ph->c_init = cc_cli_init;
3678 ph->c_idle = cc_idle;
3679 ph->c_recv_chk = cc_recv_chk;
3680 ph->c_send_ecm = cc_send_ecm;
3681 ph->c_send_emm = cc_send_emm;
3682 ph->s_ip = cfg->cc_srvip;
3683 ph->s_handler = cc_srv_init;
3684 ph->send_dcw = cc_send_dcw;
3685 ph->c_available = cc_available;
3686 ph->c_card_info = cc_card_info;
3687 static PTAB ptab; //since there is always only 1 cccam server running, this is threadsafe
3688 ptab.ports[0].s_port = cfg->cc_port;
3689 ph->ptab = &ptab;
3690 ph->ptab->nports = 1;
3691 ph->num = R_CCCAM;
3692
3693 //Partner Detection:
3694 init_rnd();
3695 uint16 sum = 0x1234; //This is our checksum
3696 int i;
3697 for (i = 0; i < 6; i++) {
3698 cc_node_id[i] = fast_rnd();
3699 sum += cc_node_id[i];
3700 }
3701 cc_node_id[6] = sum >> 8;
3702 cc_node_id[7] = sum & 0xff;
3703}
Note: See TracBrowser for help on using the repository browser.