source: trunk/module-cccam.c@ 4023

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

cccam: fixed IDEA cipher key set

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