source: trunk/module-cccam.c@ 4022

Last change on this file since 4022 was 4022, checked in by cogsi, 10 years ago

cccam cipher fixes

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