- fix Building without Nagra not possible at Nagra_Merlin https://trac.streamboard...
[oscam.git] / oscam-ecm.c
blob4bccafcff7c7eed8d17a5d8def2cd89216b33a63
1 #define MODULE_LOG_PREFIX "ecm"
3 #include "globals.h"
4 #include "cscrypt/md5.h"
5 #include "module-anticasc.h"
6 #include "module-cacheex.h"
7 #include "module-led.h"
8 #include "module-stat.h"
9 #include "module-webif.h"
10 #include "module-cw-cycle-check.h"
11 #include "module-gbox.h"
12 #include "oscam-cache.h"
13 #include "oscam-chk.h"
14 #include "oscam-client.h"
15 #include "oscam-config.h"
16 #include "oscam-ecm.h"
17 #include "oscam-garbage.h"
18 #include "oscam-failban.h"
19 #include "oscam-net.h"
20 #include "oscam-time.h"
21 #include "oscam-lock.h"
22 #include "oscam-string.h"
23 #include "oscam-work.h"
24 #include "reader-common.h"
25 #include "module-cccam-data.h"
26 #ifdef CS_CACHEEX_AIO
27 #include "oscam-hashtable.h"
28 #endif
30 extern CS_MUTEX_LOCK ecmcache_lock;
31 extern struct ecm_request_t *ecmcwcache;
32 extern uint32_t ecmcwcache_size;
33 extern int32_t exit_oscam;
35 extern CS_MUTEX_LOCK ecm_pushed_deleted_lock;
36 extern struct ecm_request_t *ecm_pushed_deleted;
38 static pthread_mutex_t cw_process_sleep_cond_mutex;
39 static pthread_cond_t cw_process_sleep_cond;
40 static int cw_process_wakeups;
41 int64_t ecmc_next, cache_next, msec_wait = 3000;
43 #ifdef CS_CACHEEX_AIO
44 // ecm-cache
45 typedef struct ecm_cache
47 struct timeb first_recv_time;// time of first cw received
48 struct timeb upd_time; // updated time. Update time at each cw got
49 uint32_t csp_hash;
50 node ht_node;
51 node ll_node;
52 } ECM_CACHE;
54 static pthread_rwlock_t ecm_cache_lock;
55 static hash_table ht_ecm_cache;
56 static list ll_ecm_cache;
57 static int8_t ecm_cache_init_done = 0;
59 void free_ecm_cache(void)
61 deinitialize_hash_table(&ht_ecm_cache);
62 pthread_rwlock_destroy(&ecm_cache_lock);
65 void init_ecm_cache(void)
67 #ifdef CS_CACHEEX
68 if(cfg.cw_cache_size > 0 || cfg.cw_cache_memory > 0)
70 init_hash_table(&ht_ecm_cache, &ll_ecm_cache);
71 if (pthread_rwlock_init(&ecm_cache_lock,NULL) != 0)
72 { cs_log("Error creating lock ecm_cache_lock!"); }
73 else
74 { ecm_cache_init_done = 1; }
76 #endif
79 static uint8_t time_sort(ECM_CACHE *a, ECM_CACHE *b)
81 if (((int64_t)(a->upd_time.time) * 1000ull + (int64_t) a->upd_time.millitm) == ((int64_t)(b->upd_time.time) * 1000ull + (int64_t) b->upd_time.millitm)) return 0;
82 return (((int64_t)(a->upd_time.time) * 1000ull + (int64_t) a->upd_time.millitm) > ((int64_t)(b->upd_time.time) * 1000ull + (int64_t) b->upd_time.millitm)) ? -1 : 1;
85 static int compare_csp_hash_ecmcache(const void *arg, const void *obj)
87 uint32_t h = ((const ECM_CACHE*)obj)->csp_hash;
88 return memcmp(arg, &h, 4);
91 void ecm_cache_cleanup(bool force)
93 if(!ecm_cache_init_done)
94 { return; }
96 SAFE_RWLOCK_WRLOCK(&ecm_cache_lock);
98 ECM_CACHE *ecm_cache;
99 node *i, *i_next;
100 uint32_t ll_c = 0;
101 uint32_t ll_ten_percent = (uint)tommy_list_count(&ll_ecm_cache)*0.1; // 10 percent of cache
103 if(!force)
104 sort_list(&ll_ecm_cache, time_sort);
106 i = get_first_node_list(&ll_ecm_cache);
107 while(i)
109 i_next = i->next;
111 ecm_cache = get_data_from_node(i);
113 if(!ecm_cache)
115 i = i_next;
116 continue;
118 if(!force)
120 ++ll_c;
122 if(ll_c < ll_ten_percent)
124 remove_elem_list(&ll_ecm_cache, &ecm_cache->ll_node);
125 remove_elem_hash_table(&ht_ecm_cache, &ecm_cache->ht_node);
126 NULLFREE(ecm_cache);
128 else{
129 break;
132 else{
133 remove_elem_list(&ll_ecm_cache, &ecm_cache->ll_node);
134 remove_elem_hash_table(&ht_ecm_cache, &ecm_cache->ht_node);
135 NULLFREE(ecm_cache);
137 i = i_next;
140 SAFE_RWLOCK_UNLOCK(&ecm_cache_lock);
142 #endif
144 void fallback_timeout(ECM_REQUEST *er)
146 if(er->rc >= E_UNHANDLED && er->stage < 4)
148 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} fallback timeout! (stage: %d)", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid, er->stage);
149 debug_ecm(D_TRACE, "fallback for %s %s", username(er->client), buf);
150 while(er->stage < 4) // if preferlocalcards=1 and no answer from locals, initial stage will be 2! We need to reach stage=4 to call fallback's.
152 request_cw_from_readers(er, 0);
157 void ecm_timeout(ECM_REQUEST *er)
159 if(!er->readers_timeout_check)
161 er->readers_timeout_check = 1;
163 if(check_client(er->client) && er->rc >= E_UNHANDLED)
165 debug_ecm(D_TRACE, "timeout for %s %s", username(er->client), buf);
167 // set timeout for readers not answering
168 struct s_ecm_answer *ea_list;
169 for(ea_list = er->matching_rdr; ea_list; ea_list = ea_list->next)
171 if((ea_list->status & (REQUEST_SENT | REQUEST_ANSWERED)) == REQUEST_SENT) // Request sent, but no answer!
173 write_ecm_answer(ea_list->reader, er, E_TIMEOUT, 0, NULL, NULL, 0, NULL); // set timeout for readers not answered!
177 // send timeout to client!
178 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} client timeout! ", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid);
179 er->rc = E_TIMEOUT;
180 er->rcEx = 0;
181 send_dcw(er->client, er);
186 void increment_n_request(struct s_client *cl)
188 if(check_client(cl))
190 cl->n_request[1]++;
191 first_client->n_request[1]++;
195 uint8_t checkCWpart(uint8_t *cw, int8_t part)
197 uint8_t eo = part ? 8 : 0;
198 int8_t i;
199 for(i = 0; i < 8; i++)
200 if(cw[i + eo]) { return 1; }
201 return 0;
204 void update_n_request(void)
206 struct s_client *cl;
208 cs_readlock(__func__, &clientlist_lock);
209 for(cl = first_client->next; cl; cl = cl->next)
211 #ifdef CS_CACHEEX
212 if(check_client(cl) && get_module(cl)->num != R_CSP && cl->typ == 'c' && !cl->dup && cl->account && cl->account->cacheex.mode<=1) //no cacheex 2/3 client
213 #else
214 if(check_client(cl) && get_module(cl)->num != R_CSP && cl->typ == 'c' && !cl->dup)
215 #endif
217 cl->n_request[0] = cl->n_request[1];
218 cl->n_request[1] = 0;
220 else
222 cl->n_request[0] = 0;
223 cl->n_request[1] = 0;
227 first_client->n_request[0] = first_client->n_request[1];
228 first_client->n_request[1] = 0;
230 cs_readunlock(__func__, &clientlist_lock);
233 static void *cw_process(void)
235 set_thread_name(__func__);
236 int64_t time_to_check_fbtimeout, time_to_check_ctimeout, next_check, n_request_next;
237 struct timeb t_now, tbc, ecmc_time, cache_time, n_request_time;
238 ECM_REQUEST *er = NULL;
239 time_t ecm_maxcachetime;
241 #ifdef CS_CACHEEX
242 int64_t time_to_check_cacheex_wait_time;
243 int64_t time_to_check_cacheex_mode1_delay;
244 #endif
246 cs_pthread_cond_init(__func__, &cw_process_sleep_cond_mutex, &cw_process_sleep_cond);
248 #ifdef CS_ANTICASC
249 int32_t ac_next;
250 struct timeb ac_time;
251 cs_ftime(&ac_time);
252 add_ms_to_timeb(&ac_time, cfg.ac_stime * 60 * 1000);
253 #endif
255 cs_ftime(&ecmc_time);
256 add_ms_to_timeb(&ecmc_time, 1000);
257 cs_ftime(&cache_time);
258 add_ms_to_timeb(&cache_time, 3000);
259 cs_ftime(&n_request_time);
260 add_ms_to_timeb(&n_request_time, 60 * 1000);
262 while(!exit_oscam)
264 if(cw_process_wakeups == 0) // No waiting wakeups, proceed to sleep
266 sleepms_on_cond(__func__, &cw_process_sleep_cond_mutex, &cw_process_sleep_cond, msec_wait);
268 cw_process_wakeups = 0; // We've been woken up, reset the counter
269 if(exit_oscam)
270 { break; }
272 next_check = 0;
273 #ifdef CS_ANTICASC
274 ac_next = 0;
275 #endif
276 ecmc_next = 0;
277 cache_next = 0;
278 msec_wait = 0;
280 cs_ftime(&t_now);
281 cs_readlock(__func__, &ecmcache_lock);
282 for(er = ecmcwcache; er; er = er->next)
285 if((er->from_cacheex || er->from_csp) // ignore ecms from cacheex/csp
286 || er->readers_timeout_check // ignore already checked
287 || !check_client(er->client)) // ignore ecm of killed clients
289 continue;
292 if(er->rc >= E_UNHANDLED)
294 #ifdef CS_CACHEEX
295 // cacheex_wait_time
296 if(er->cacheex_wait_time && !er->cacheex_wait_time_expired)
298 tbc = er->tps;
299 time_to_check_cacheex_mode1_delay = 0;
300 time_to_check_cacheex_wait_time = add_ms_to_timeb_diff(&tbc, lb_auto_timeout(er, er->cacheex_wait_time));
302 if(comp_timeb(&t_now, &tbc) >= 0)
304 add_job(er->client, ACTION_CACHEEX_TIMEOUT, (void *)er, 0);
305 time_to_check_cacheex_wait_time = 0;
308 else if(er->cacheex_mode1_delay && !er->stage && er->cacheex_reader_count>0)
310 // check for cacheex_mode1_delay
311 tbc = er->tps;
312 time_to_check_cacheex_mode1_delay = add_ms_to_timeb_diff(&tbc, lb_auto_timeout(er, er->cacheex_mode1_delay));
314 if(comp_timeb(&t_now, &tbc) >= 0)
316 add_job(er->client, ACTION_CACHEEX1_DELAY, (void *)er, 0);
317 time_to_check_cacheex_mode1_delay = 0;
321 if(!next_check || (time_to_check_cacheex_wait_time > 0 && time_to_check_cacheex_wait_time < next_check))
322 { next_check = time_to_check_cacheex_wait_time; }
324 if(!next_check || (time_to_check_cacheex_mode1_delay > 0 && time_to_check_cacheex_mode1_delay < next_check))
325 { next_check = time_to_check_cacheex_mode1_delay; }
327 #endif
328 if(er->stage < 4)
330 // fbtimeout
331 tbc = er->tps;
332 time_to_check_fbtimeout = add_ms_to_timeb_diff(&tbc, lb_auto_timeout(er, get_fallbacktimeout(er->caid)));
334 if(comp_timeb(&t_now, &tbc) >= 0)
336 add_job(er->client, ACTION_FALLBACK_TIMEOUT, (void *)er, 0);
337 time_to_check_fbtimeout = 0;
340 if(!next_check || (time_to_check_fbtimeout > 0 && time_to_check_fbtimeout < next_check))
341 { next_check = time_to_check_fbtimeout; }
345 // clienttimeout
346 if(!er->readers_timeout_check) // ecm stays in cache at least ctimeout+2seconds!
348 tbc = er->tps;
349 time_to_check_ctimeout = add_ms_to_timeb_diff(&tbc, lb_auto_timeout(er, cfg.ctimeout));
351 if(comp_timeb(&t_now, &tbc) >= 0)
353 add_job(er->client, ACTION_CLIENT_TIMEOUT, (void *)er, 0);
354 time_to_check_ctimeout = 0;
357 if(!next_check || (time_to_check_ctimeout > 0 && time_to_check_ctimeout < next_check))
358 { next_check = time_to_check_ctimeout; }
361 cs_readunlock(__func__, &ecmcache_lock);
362 #ifdef CS_ANTICASC
363 if(cfg.ac_enabled && (ac_next = comp_timeb(&ac_time, &t_now)) <= 10)
365 ac_do_stat();
366 cs_ftime(&ac_time);
367 ac_next = add_ms_to_timeb_diff(&ac_time, cfg.ac_stime * 60 * 1000);
369 #endif
370 if((ecmc_next = comp_timeb(&ecmc_time, &t_now)) <= 10)
372 uint32_t count = 0;
373 struct ecm_request_t *ecm, *ecmt = NULL, *prv;
375 cs_readlock(__func__, &ecmcache_lock);
376 for(ecm = ecmcwcache, prv = NULL; ecm; prv = ecm, ecm = ecm->next, count++)
378 ecm_maxcachetime = t_now.time - ((cfg.ctimeout + 500) / 1000 + 3); // to be sure no more access er!
380 if(ecm->tps.time < ecm_maxcachetime)
382 cs_readunlock(__func__, &ecmcache_lock);
383 cs_writelock(__func__, &ecmcache_lock);
384 ecmt = ecm;
385 if(prv)
386 { prv->next = NULL; }
387 else
388 { ecmcwcache = NULL; }
389 cs_writeunlock(__func__, &ecmcache_lock);
390 break;
393 if(!ecmt)
394 { cs_readunlock(__func__, &ecmcache_lock); }
395 ecmcwcache_size = count;
397 while(ecmt)
399 ecm = ecmt->next;
400 free_ecm(ecmt);
401 ecmt = ecm;
404 #ifdef CS_CACHEEX
405 ecmt=NULL;
406 cs_readlock(__func__, &ecm_pushed_deleted_lock);
407 for(ecm = ecm_pushed_deleted, prv = NULL; ecm; prv = ecm, ecm = ecm->next)
409 ecm_maxcachetime = t_now.time - ((cfg.ctimeout + 500) / 1000 + 3);
410 if(ecm->tps.time < ecm_maxcachetime)
412 cs_readunlock(__func__, &ecm_pushed_deleted_lock);
413 cs_writelock(__func__, &ecm_pushed_deleted_lock);
414 ecmt = ecm;
415 if(prv)
416 { prv->next = NULL; }
417 else
418 { ecm_pushed_deleted = NULL; }
419 cs_writeunlock(__func__, &ecm_pushed_deleted_lock);
420 break;
423 if(!ecmt)
424 { cs_readunlock(__func__, &ecm_pushed_deleted_lock); }
426 while(ecmt)
428 ecm = ecmt->next;
429 free_push_in_ecm(ecmt);
430 ecmt = ecm;
432 #endif
434 cs_ftime(&ecmc_time);
435 ecmc_next = add_ms_to_timeb_diff(&ecmc_time, 1000);
438 if((cache_next = comp_timeb(&cache_time, &t_now)) <= 10)
440 cleanup_cache(false);
441 cacheex_cleanup_hitcache(false);
443 cs_ftime(&cache_time);
444 cache_next = add_ms_to_timeb_diff(&cache_time, 3000);
447 if((n_request_next = comp_timeb(&n_request_time, &t_now)) <= 10)
449 update_n_request();
450 cs_ftime(&n_request_time);
451 n_request_next = add_ms_to_timeb_diff(&n_request_time, 60 * 1000);
454 msec_wait = next_check;
455 #ifdef CS_ANTICASC
456 if(!msec_wait || (ac_next > 0 && ac_next < msec_wait))
457 { msec_wait = ac_next; }
458 #endif
459 if(!msec_wait || (ecmc_next > 0 && ecmc_next < msec_wait))
460 { msec_wait = ecmc_next; }
462 if(!msec_wait || (cache_next > 0 && cache_next < msec_wait))
463 { msec_wait = cache_next; }
465 if(!msec_wait || (n_request_next > 0 && n_request_next < msec_wait))
466 { msec_wait = n_request_next; }
468 if(!msec_wait)
469 { msec_wait = 3000; }
471 cleanupcwcycle();
474 return NULL;
477 void cw_process_thread_start(void)
479 start_thread("cw_process", (void *) &cw_process, NULL, NULL, 1, 1);
482 void cw_process_thread_wakeup(void)
484 cw_process_wakeups++; // Do not sleep...
485 SAFE_COND_SIGNAL(&cw_process_sleep_cond);
488 void convert_to_beta(struct s_client *cl, ECM_REQUEST *er, uint16_t caidto)
490 static uint8_t headerN3[10] = { 0xc7, 0x00, 0x00, 0x00, 0x01, 0x10, 0x10, 0x00, 0x87, 0x12 };
491 static uint8_t headerN2[10] = { 0xc9, 0x00, 0x00, 0x00, 0x01, 0x10, 0x10, 0x00, 0x48, 0x12 };
493 er->ocaid = er->caid;
494 er->caid = caidto;
495 er->prid = 0;
496 er->ecmlen = er->ecm[2] + 3;
498 memmove(er->ecm + 13, er->ecm + 3, er->ecmlen - 3);
500 if(er->ecmlen > 0x88)
502 memcpy(er->ecm + 3, headerN3, 10);
503 if(er->ecm[0] == 0x81)
504 { er->ecm[12] += 1; }
505 er->ecm[1] = 0x70;
507 else
509 memcpy(er->ecm + 3, headerN2, 10);
512 er->ecmlen += 10;
513 er->ecm[2] = er->ecmlen - 3;
514 er->btun = 1;
516 cl->cwtun++;
517 cl->account->cwtun++;
518 first_client->cwtun++;
520 cs_log_dbg(D_TRACE, "ECM converted ocaid from 0x%04X to BetaCrypt caid 0x%04X for service id 0x%04X",
521 er->ocaid, caidto, er->srvid);
524 void convert_to_nagra(struct s_client *cl, ECM_REQUEST *er, uint16_t caidto)
526 cs_log_dbg(D_TRACE, "convert_to_nagra");
527 er->ocaid = er->caid;
528 er->caid = caidto;
529 er->prid = 0;
530 er->ecmlen = er->ecm[2] + 3;
532 // not sure
533 if(er->ecmlen < 0x52)
534 { er->ecm[1] = 0x30; }
536 memmove(er->ecm + 3, er->ecm + 13, er->ecmlen - 3);
538 er->ecmlen -= 10;
539 er->ecm[2] = er->ecmlen - 3;
540 er->btun = 1;
542 cl->cwtun++;
543 cl->account->cwtun++;
544 first_client->cwtun++;
546 cs_log_dbg(D_TRACE, "ECM converted ocaid from: 0x%04X to Nagra: 0x04%X for service id:0x04%X",
547 er->ocaid, caidto, er->srvid);
550 void cs_betatunnel(ECM_REQUEST *er)
552 int32_t i;
553 struct s_client *cl = cur_client();
554 uint32_t mask_all = 0xFFFF;
555 TUNTAB *ttab = &cl->ttab;
557 for(i = 0; i < ttab->ttnum; i++)
559 if((er->caid == ttab->ttdata[i].bt_caidfrom) && ((er->srvid == ttab->ttdata[i].bt_srvid) || (ttab->ttdata[i].bt_srvid) == mask_all))
561 if(chk_is_betatunnel_caid(er->caid) == 1 && er->ocaid == 0x0000)
563 convert_to_nagra(cl, er, ttab->ttdata[i].bt_caidto);
565 else if(er->ocaid == 0x0000)
567 convert_to_beta(cl, er, ttab->ttdata[i].bt_caidto);
569 return;
574 static void remove_ecm_from_reader(ECM_REQUEST *ecm)
576 int32_t i;
577 struct s_ecm_answer *ea = ecm->matching_rdr;
578 while(ea)
580 if((ea->status & REQUEST_SENT) && !(ea->status & REQUEST_ANSWERED))
582 // we found a outstanding reader, clean it:
583 struct s_reader *rdr = ea->reader;
584 if(rdr)
586 struct s_client *cl = rdr->client;
587 if(check_client(cl))
589 ECM_REQUEST *ecmtask = cl->ecmtask;
590 if(ecmtask)
592 for(i = 0; i < cfg.max_pending; ++i)
594 if(ecmtask[i].parent == ecm)
596 ecmtask[i].client = NULL;
597 cacheex_set_csp_lastnode(&ecmtask[i]);
604 ea = ea->next;
608 void free_ecm(ECM_REQUEST *ecm)
610 struct s_ecm_answer *ea, *nxt;
611 cacheex_free_csp_lastnodes(ecm);
612 gbox_free_cards_pending(ecm);
613 // remove this ecm from reader queue to avoid segfault on very late answers (when ecm is already disposed)
614 // first check for outstanding answers:
615 remove_ecm_from_reader(ecm);
616 // free matching_rdr list:
617 ea = ecm->matching_rdr;
618 ecm->matching_rdr = NULL;
619 while(ea)
621 nxt = ea->next;
622 cs_lock_destroy(__func__, &ea->ecmanswer_lock);
623 add_garbage(ea);
624 ea = nxt;
626 if(ecm->src_data)
627 { add_garbage(ecm->src_data); }
628 add_garbage(ecm);
632 void free_push_in_ecm(ECM_REQUEST *ecm)
634 cacheex_free_csp_lastnodes(ecm);
635 gbox_free_cards_pending(ecm);
636 if(ecm->src_data)
637 { NULLFREE(ecm->src_data); }
638 NULLFREE(ecm);
641 ECM_REQUEST *get_ecmtask(void)
643 ECM_REQUEST *er = NULL;
644 struct s_client *cl = cur_client();
645 if(!cl)
646 { return NULL; }
647 if(!cs_malloc(&er, sizeof(ECM_REQUEST)))
648 { return NULL; }
649 cs_ftime(&er->tps);
650 er->rc = E_UNHANDLED;
651 er->client = cl;
652 er->grp = 0; // no readers/cacheex-clients answers yet
653 //cs_log("client %s ECMTASK %d module %s", username(cl), n, get_module(cl)->desc);
654 return er;
657 void cleanup_ecmtasks(struct s_client *cl)
659 if(!cl) { return; }
661 ECM_REQUEST *ecm;
663 // remove this clients ecm from queue. because of cache, just null the client:
664 cs_readlock(__func__, &ecmcache_lock);
665 for(ecm = ecmcwcache; ecm && cl; ecm = ecm->next)
667 if(ecm->client == cl)
669 ecm->client = NULL;
672 cs_readunlock(__func__, &ecmcache_lock);
674 // remove client from rdr ecm-queue:
675 cs_readlock(__func__, &readerlist_lock);
676 struct s_reader *rdr = first_active_reader;
677 while(rdr)
679 if(check_client(rdr->client) && rdr->client->ecmtask)
681 int i;
682 for(i = 0; (i < cfg.max_pending) && cl; i++)
684 ecm = &rdr->client->ecmtask[i];
685 if(ecm->client == cl)
687 ecm->client = NULL;
691 rdr = rdr->next;
693 cs_readunlock(__func__, &readerlist_lock);
697 static void add_cascade_data(struct s_client *client, ECM_REQUEST *er)
699 if(!client->cascadeusers)
700 { client->cascadeusers = ll_create("cascade_data"); }
701 LLIST *l = client->cascadeusers;
702 LL_ITER it = ll_iter_create(l);
703 time_t now = time(NULL);
704 struct s_cascadeuser *cu;
705 int8_t found = 0;
706 while((cu = ll_iter_next(&it)))
708 if(er->caid == cu->caid && er->prid == cu->prid && er->srvid == cu->srvid) // found it
710 if(cu->time < now)
711 { cu->cwrate = now - cu->time; }
712 cu->time = now;
713 found = 1;
715 else if(cu->time + 60 < now) // old
716 { ll_iter_remove_data(&it); }
719 if(!found) // add it if not found
721 if(!cs_malloc(&cu, sizeof(struct s_cascadeuser)))
722 { return; }
723 cu->caid = er->caid;
724 cu->prid = er->prid;
725 cu->srvid = er->srvid;
726 cu->time = now;
727 ll_append(l, cu);
731 static int32_t is_double_check_caid(ECM_REQUEST *er, FTAB *double_check_caid)
733 if(!double_check_caid->nfilts) { return 1; }
735 int32_t i, k;
736 for(i = 0; i < double_check_caid->nfilts; i++)
738 uint16_t tcaid = double_check_caid->filts[i].caid;
739 if(tcaid && (tcaid == er->caid || (tcaid < 0x0100 && (er->caid >> 8) == tcaid))) // caid match
741 int32_t nprids = double_check_caid->filts[i].nprids;
742 if(!nprids) // No Provider ->Ok
743 { return 1; }
745 for(k = 0; k < nprids; k++)
747 uint32_t prid = double_check_caid->filts[i].prids[k];
748 if(prid == er->prid) // Provider matches
749 { return 1; }
754 return 0;
757 struct s_ecm_answer *get_ecm_answer(struct s_reader *reader, ECM_REQUEST *er)
759 if(!er || !reader) { return NULL; }
761 struct s_ecm_answer *ea;
763 for(ea = er->matching_rdr; ea; ea = ea->next)
765 if(ea->reader == reader)
767 return ea;
770 return NULL;
773 void distribute_ea(struct s_ecm_answer *ea)
775 struct s_ecm_answer *ea_temp;
777 for(ea_temp = ea->pending; ea_temp; ea_temp = ea_temp->pending_next)
779 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} [distribute_ea] send ea (%s) by reader %s answering for client %s", (check_client(ea_temp->er->client) ? ea_temp->er->client->account->usr : "-"), ea_temp->er->caid, ea_temp->er->prid, ea_temp->er->srvid, ea->rc==E_FOUND?"OK":"NOK", ea_temp->reader->label, (check_client(ea->er->client) ? ea->er->client->account->usr : "-"));
780 #ifdef CS_CACHEEX_AIO
781 if(ea->rc==E_FOUND && ea->er->localgenerated)
782 ea_temp->er->localgenerated = 1;
783 #endif
784 // e.g. we cannot send timeout, because "ea_temp->er->client" could wait/ask other readers! Simply set not_found if different from E_FOUND!
785 write_ecm_answer(ea_temp->reader, ea_temp->er, (ea->rc==E_FOUND? E_FOUND : E_NOTFOUND), ea->rcEx, ea->cw, NULL, ea->tier, &ea->cw_ex);
789 int32_t send_dcw(struct s_client *client, ECM_REQUEST *er)
791 if(!check_client(client) || client->typ != 'c')
792 { return 0; }
794 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} [send_dcw] rc %d from reader %s", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid, er->rc, er->selected_reader ? er->selected_reader->label : "-");
796 static const char stageTxt[] = { '0', 'C', 'L', 'P', 'F', 'X' };
797 static const char *stxt[] = { "found", "cache1", "cache2", "cache3", "not found", "timeout", "sleeping",
798 "fake", "invalid", "corrupt", "no card", "expdate", "disabled", "stopped" };
800 static const char *stxtEx[16] = {"", "group", "caid", "ident", "class", "chid", "queue", "peer", "sid", "", "", "", "", "", "", ""};
801 static const char *stxtWh[16] = {"", "user ", "reader ", "server ", "lserver ", "", "", "", "", "", "", "", "" , "" , "", ""};
802 #ifdef CS_CACHEEX_AIO
803 char sby[100] = "", sreason[35] = "", scwcinfo[32] = "", schaninfo[CS_SERVICENAME_SIZE] = "", srealecmtime[50]="";
804 #else
805 char sby[100] = "", sreason[32] = "", scwcinfo[32] = "", schaninfo[CS_SERVICENAME_SIZE] = "", srealecmtime[50]="";
806 #endif
807 char erEx[32] = "";
808 char usrname[38] = "";
809 char channame[28];
810 struct timeb tpe;
812 snprintf(usrname, sizeof(usrname) - 1, "%s", username(client));
814 #ifdef WITH_DEBUG
815 if(cs_dblevel & D_CLIENTECM)
817 char buf[ECM_FMT_LEN];
818 char ecmd5[17 * 3];
819 char cwstr[17 * 3];
820 format_ecm(er, buf, ECM_FMT_LEN);
821 cs_hexdump(0, er->ecmd5, 16, ecmd5, sizeof(ecmd5));
822 cs_hexdump(0, er->cw, 16, cwstr, sizeof(cwstr));
823 #ifdef CS_CACHEEX
824 char csphash[5 * 3];
825 cs_hexdump(0, (void *)&er->csp_hash, 4, csphash, sizeof(csphash));
826 cs_log_dbg(D_CLIENTECM, "Client %s csphash %s cw %s rc %d %s", username(client), csphash, cwstr, er->rc, buf);
827 #else
828 cs_log_dbg(D_CLIENTECM, "Client %s cw %s rc %d %s", username(client), cwstr, er->rc, buf);
829 #endif
831 #endif
833 struct s_reader *er_reader = er->selected_reader; // responding reader
834 struct s_ecm_answer *ea_orig = get_ecm_answer(er_reader, er);
837 // check if ecm_answer from pending's
838 if(ea_orig && ea_orig->is_pending && er->rc == E_FOUND)
839 { er->rc = E_CACHE2; }
842 // check if answer from cacheex-1 reader
843 if(er->rc == E_FOUND && er_reader && cacheex_reader(er_reader)) // so add hit to cacheex mode 1 readers
845 er->rc = E_CACHEEX;
848 // real ecm time
849 if(ea_orig && !ea_orig->is_pending && er->rc == E_FOUND
850 && (
851 #ifdef CS_CACHEEX
852 er->cacheex_wait_time ||
853 #endif
854 (ea_orig->status & READER_FALLBACK)))
856 snprintf(srealecmtime, sizeof(srealecmtime) - 1, " (real %d ms)", ea_orig->ecm_time);
860 if(er->rc == E_TIMEOUT)
862 #ifdef CS_CACHEEX
863 if(!er->from_cacheex1_client) // cosmetic: show "by" readers only for "normal" clients
865 #endif
866 struct s_ecm_answer *ea_list;
867 int32_t ofs = 0;
869 for(ea_list = er->matching_rdr; ea_list; ea_list = ea_list->next)
871 if(ea_list->reader && ofs < (int32_t)sizeof(sby) && ((ea_list->status & REQUEST_SENT) && (ea_list->rc == E_TIMEOUT || ea_list->rc >= E_99))) //Request send, but no cw answered!
873 ofs += snprintf(sby + ofs, sizeof(sby) - ofs - 1, "%s%s", ofs ? "," : " by ", ea_list->reader->label);
877 if(er->ocaid && ofs < (int32_t)sizeof(sby))
878 { snprintf(sby + ofs, sizeof(sby) - ofs - 1, "(btun %04X)", er->ocaid); }
880 #ifdef CS_CACHEEX
882 #endif
884 else if(er_reader)
886 // add marker to reader if ECM_REQUEST was betatunneled
887 if(er->ocaid)
888 { snprintf(sby, sizeof(sby) - 1, " by %s(btun %04X)", er_reader->label, er->ocaid); }
889 else
890 { snprintf(sby, sizeof(sby) - 1, " by %s", er_reader->label); }
892 #ifdef CS_CACHEEX
893 else if(er->cacheex_src) // only for cacheex mode-3 clients (no mode-1 or mode-2 because reader is set!) and csp
895 char *cex_name = "-";
896 if(check_client(er->cacheex_src) && er->cacheex_src->account)
898 if(er->cacheex_src->account->usr[0] != '\0')
899 cex_name = er->cacheex_src->account->usr;
900 else
901 cex_name = "csp";
904 if(er->ocaid)
906 snprintf(sby, sizeof(sby) - 1, " by %s(btun %04X)", cex_name, er->ocaid);
908 else
910 snprintf(sby, sizeof(sby) - 1, " by %s", cex_name);
913 #endif
915 if(er->rc < E_NOTFOUND)
917 er->rcEx = 0;
918 memset(er->msglog, 0, MSGLOGSIZE); // remove reader msglog from previous requests that failed, founds never give back msglog!
921 if(er->rcEx)
922 { snprintf(erEx, sizeof(erEx) - 1, "rejected %s%s", stxtWh[er->rcEx >> 4], stxtEx[er->rcEx & 0xf]); }
924 get_servicename_or_null(client, er->srvid, er->prid, er->caid, channame, sizeof(channame));
925 if(!channame[0])
927 schaninfo[0] = '\0';
929 else
931 snprintf(schaninfo, sizeof(schaninfo) - 1, " - %s", channame);
934 if(er->msglog[0])
935 { snprintf(sreason, sizeof(sreason) - 1, " (%.26s)", er->msglog); }
936 #ifdef CW_CYCLE_CHECK
937 if(er->cwc_msg_log[0])
938 { snprintf(scwcinfo, sizeof(scwcinfo) - 1, " (%.26s)", er->cwc_msg_log); }
939 #endif
941 cs_ftime(&tpe);
943 #ifdef CS_CACHEEX
944 int cx = 0;
945 if(er->rc >= E_CACHEEX && er->cacheex_wait_time && er->cacheex_wait_time_expired)
947 cx = snprintf ( sreason, sizeof sreason, " (wait_time over)");
950 if(er->cw_count>1)
952 #ifdef CS_CACHEEX_AIO
953 if(er->cw_count > 0x0F000000 || er->localgenerated)
955 uint32_t cw_count_cleaned = er->cw_count ^ 0x0F000000;
956 if(cw_count_cleaned > 1)
957 snprintf(sreason+cx, (sizeof sreason)-cx, " (cw count %d) (lg)", cw_count_cleaned);
958 else
959 snprintf(sreason+cx, (sizeof sreason)-cx, " (lg)");
961 else
963 #endif
965 snprintf (sreason+cx, (sizeof sreason)-cx, " (cw count %d)", er->cw_count);
967 #ifdef CS_CACHEEX_AIO
971 else
973 if(er->localgenerated)
974 snprintf(sreason+cx, (sizeof sreason)-cx, " (lg)");
975 #endif
978 #endif
980 client->cwlastresptime = comp_timeb(&tpe, &er->tps);
982 time_t now = time(NULL);
983 webif_client_add_lastresponsetime(client, client->cwlastresptime, now, er->rc); // add to ringbuffer
985 if(er_reader)
987 struct s_client *er_cl = er_reader->client;
988 if(check_client(er_cl))
990 er_cl->cwlastresptime = client->cwlastresptime;
991 webif_client_add_lastresponsetime(er_cl, client->cwlastresptime, now, er->rc);
992 er_cl->last_providptr = client->last_providptr;
993 er_cl->last_srvidptr = client->last_srvidptr;
997 webif_client_init_lastreader(client, er, er_reader, stxt);
999 client->last = now;
1001 //cs_log_dbg(D_TRACE, "CHECK rc=%d er->cacheex_src=%s", er->rc, username(er->cacheex_src));
1002 switch(er->rc)
1004 case E_FOUND:
1006 client->cwfound++;
1007 client->account->cwfound++;
1008 first_client->cwfound++;
1009 break;
1011 case E_CACHE1:
1012 case E_CACHE2:
1013 case E_CACHEEX:
1015 client->cwcache++;
1016 client->account->cwcache++;
1017 first_client->cwcache++;
1018 #ifdef CS_CACHEEX
1019 if(check_client(er->cacheex_src))
1021 first_client->cwcacheexhit++;
1022 er->cacheex_src->cwcacheexhit++;
1023 if(er->cacheex_src->account)
1024 { er->cacheex_src->account->cwcacheexhit++; }
1026 #endif
1027 break;
1029 case E_NOTFOUND:
1030 case E_CORRUPT:
1031 case E_NOCARD:
1033 if(er->rcEx)
1035 client->cwignored++;
1036 client->account->cwignored++;
1037 first_client->cwignored++;
1039 else
1041 client->cwnot++;
1042 client->account->cwnot++;
1043 first_client->cwnot++;
1045 break;
1047 case E_TIMEOUT:
1049 client->cwtout++;
1050 client->account->cwtout++;
1051 first_client->cwtout++;
1052 break;
1054 default:
1056 client->cwignored++;
1057 client->account->cwignored++;
1058 first_client->cwignored++;
1062 #ifdef CS_ANTICASC
1063 // [zaplist] ACoSC anticascading
1064 if(cfg.acosc_enabled)
1066 int8_t max_active_sids = 0;
1067 int8_t zap_limit = 0;
1068 int8_t penalty = 0;
1069 int32_t penalty_duration = 0;
1070 int32_t delay = 0;
1071 int8_t max_ecms_per_minute = 0;
1072 char *info1 = NULL;
1073 char *info2 = NULL;
1074 char *info3 = NULL;
1075 char *info4 = NULL;
1076 char *info5 = NULL;
1077 char *info6 = NULL;
1079 // **global or user value?
1080 cs_writelock(__func__, &clientlist_lock);
1082 max_active_sids = client->account->acosc_max_active_sids == -1 ? cfg.acosc_max_active_sids : client->account->acosc_max_active_sids;
1083 info1 = client->account->acosc_max_active_sids == -1 ? "Globalvalue" : "Uservalue";
1085 zap_limit = client->account->acosc_zap_limit == -1 ? cfg.acosc_zap_limit : client->account->acosc_zap_limit;
1086 info5 = client->account->acosc_zap_limit == -1 ? "Globalvalue" : "Uservalue";
1088 penalty = client->account->acosc_penalty == -1 ? cfg.acosc_penalty : client->account->acosc_penalty;
1089 info2 = client->account->acosc_penalty == -1 ? "Globalvalue" : "Uservalue";
1091 penalty_duration = client->account->acosc_penalty_duration == -1 ? cfg.acosc_penalty_duration : client->account->acosc_penalty_duration;
1092 info3 = client->account->acosc_penalty_duration == -1 ? "Globalvalue" : "Uservalue";
1094 delay = client->account->acosc_delay == -1 ? cfg.acosc_delay : client->account->acosc_delay;
1095 info4 = client->account->acosc_delay == -1 ? "Globalvalue" : "Uservalue";
1097 max_ecms_per_minute = client->account->acosc_max_ecms_per_minute == -1 ? cfg.acosc_max_ecms_per_minute : client->account->acosc_max_ecms_per_minute;
1098 info6 = client->account->acosc_max_ecms_per_minute == -1 ? "Globalvalue" : "Uservalue";
1100 //**
1102 if((er->rc < E_NOTFOUND && max_active_sids > 0) || zap_limit > 0 || max_ecms_per_minute > 0)
1104 int8_t k = 0;
1105 int8_t active_sid_count = 0;
1106 time_t zaptime = time(NULL);
1108 if(client->account->acosc_penalty_active == 4 && client->account->acosc_penalty_until <= zaptime) // reset penalty_active
1110 client->account->acosc_penalty_active = 0;
1111 client->account->acosc_penalty_until = 0;
1114 if(client->account->acosc_penalty_active == 0 && max_active_sids > 0)
1116 for(k=0; k<15 ; k++)
1118 if(zaptime-30 < client->client_zap_list[k].lasttime && client->client_zap_list[k].request_stage == 10)
1120 cs_log_dbg(D_TRACE, "[zaplist] ACoSC for Client: %s more then 10 ECM's for %04X@%06X/%04X/%04X", username(client), client->client_zap_list[k].caid, client->client_zap_list[k].provid, client->client_zap_list[k].chid, client->client_zap_list[k].sid);
1121 active_sid_count ++;
1124 cs_log_dbg(D_TRACE, "[zaplist] ACoSC for Client: %s active_sid_count= %i with more than 10 followed ECM's (mas:%i (%s))", username(client), active_sid_count, max_active_sids, info1);
1127 if(client->account->acosc_penalty_active == 0 && max_active_sids > 0 && active_sid_count > max_active_sids) //max_active_sids reached
1129 client->account->acosc_penalty_active = 1;
1130 client->account->acosc_penalty_until = zaptime + penalty_duration;
1133 if(client->account->acosc_penalty_active == 0 && zap_limit > 0 && client->account->acosc_user_zap_count > zap_limit) // zap_limit reached
1135 client->account->acosc_penalty_active = 2;
1136 client->account->acosc_penalty_until = zaptime + penalty_duration;
1139 if(client->account->acosc_penalty_active == 0 && max_ecms_per_minute > 0 && client->n_request[1] >= max_ecms_per_minute && penalty != 4) // max ecms per minute reached
1141 client->account->acosc_penalty_active = 3;
1142 client->account->acosc_penalty_until = zaptime + penalty_duration;
1145 if(client->account->acosc_penalty_active == 0 && max_ecms_per_minute > 0 && client->n_request[1] > 0 && penalty == 4) // max ecms per minute with hidecards penalty
1147 client->account->acosc_penalty_active = 3;
1148 client->account->acosc_penalty_until = zaptime + penalty_duration;
1151 if(client->account->acosc_penalty_active > 0)
1153 if(client->account->acosc_penalty_active == 4)
1154 { cs_log_dbg(D_TRACE, "[zaplist] ACoSC for Client: %s penalty_duration: %ld seconds left(%s)", username(client), client->account->acosc_penalty_until - zaptime, info3); }
1156 int16_t lt = get_module(client)->listenertype;
1157 switch(penalty)
1159 case 1: // NULL CW
1160 er->rc = E_FAKE; // E_FAKE give only a status fake not a NULL cw
1161 er->rcEx = E2_WRONG_CHKSUM;
1162 if(client->account->acosc_penalty_active == 1)
1163 { cs_log("[zaplist] ACoSC for Client: %s max_activ_sids reached: %i:%i(%s) penalty: 1(%s) send null CW", username(client), active_sid_count, max_active_sids, info1, info2); }
1164 if(client->account->acosc_penalty_active == 2)
1165 { cs_log("[zaplist] ACoSC for Client: %s zap_limit reached: %i:%i(%s) penalty: 1(%s) send null CW", username(client), client->account->acosc_user_zap_count, zap_limit, info5, info2); }
1166 if(client->account->acosc_penalty_active == 3)
1167 { cs_log("[maxecms] ACoSC for Client: %s max_ecms_per_minute reached: ecms_last_minute=%i ecms_now=%i max=%i(%s) penalty: 1(%s) send null CW", username(client), client->n_request[0], client->n_request[1], max_ecms_per_minute, info6, info2); }
1168 break;
1170 case 2: // ban
1171 if(lt != LIS_DVBAPI)
1173 if(client->account->acosc_penalty_active == 1)
1174 { cs_log("[zaplist] ACoSC for Client: %s max_activ_sids reached: %i:%i(%s) penalty: 2(%s) BAN Client - Kill and set Client to failban list for %i sec.", username(client), active_sid_count, max_active_sids, info1, info2, penalty_duration); }
1175 if(client->account->acosc_penalty_active == 2)
1176 { cs_log("[zaplist] ACoSC for Client: %s zap_limit reached: %i:%i(%s) penalty: 2(%s) BAN Client - Kill and set Client to failban list for %i sec.", username(client), client->account->acosc_user_zap_count, zap_limit, info5, info2, penalty_duration); }
1177 if(client->account->acosc_penalty_active == 3)
1178 { cs_log("[maxecms] ACoSC for Client: %s max_ecms_per_minute reached: ecms_last_minute=%i ecms_now=%i max=%i(%s) penalty: 2(%s) BAN Client - Kill and set Client to failban list for %i sec.", username(client), client->n_request[0], client->n_request[1], max_ecms_per_minute, info6, info2, penalty_duration); }
1179 cs_add_violation_acosc(client, client->account->usr, penalty_duration);
1180 add_job(client, ACTION_CLIENT_KILL, NULL, 0);
1182 else
1184 cs_log("[zaplist] ACoSC for Client: %s %i:%i(%s) penalty: 2(%s) BAN Client - don't Ban dvbapi user only stop decoding", username(client), active_sid_count, max_active_sids, info1, info2);
1186 er->rc = E_DISABLED;
1187 break;
1189 case 3: // delay
1190 if(client->account->acosc_penalty_active == 1)
1191 { cs_log("[zaplist] ACoSC for Client: %s max_activ_sids reached: %i:%i(%s) penalty: 3(%s) delay CW: %ims(%s)", username(client), active_sid_count, max_active_sids, info1, info2, delay, info4); }
1192 if(client->account->acosc_penalty_active == 2)
1193 { cs_log("[zaplist] ACoSC for Client: %s zap_limit reached: %i:%i(%s) penalty: 3(%s) delay CW: %ims(%s)", username(client), client->account->acosc_user_zap_count, zap_limit, info5, info2, delay, info4); }
1194 if(client->account->acosc_penalty_active == 3)
1195 { cs_log("[maxecms] ACoSC for Client: %s max_ecms_per_minute reached: ecms_last_minute=%i ecms_now=%i max=%i(%s) penalty: 3(%s) delay CW: %ims(%s)", username(client), client->n_request[0], client->n_request[1], max_ecms_per_minute, info6, info2, delay, info4); }
1196 cs_writeunlock(__func__, &clientlist_lock);
1197 cs_sleepms(delay);
1198 cs_writelock(__func__, &clientlist_lock);
1199 client->cwlastresptime += delay;
1200 snprintf(sreason, sizeof(sreason)-1, " (%d ms penalty delay)", delay);
1201 break;
1202 case 4: // hidecards
1203 if(client->account->acosc_penalty_active == 3)
1205 cs_log("[maxecms] ACoSC for Client: %s ecms_last_minute=%i ecms_now=%i max=%i(%s) penalty: 4(%s) hidecards - hidecards to the client for %i sec", username(client), client->n_request[0], client->n_request[1], max_ecms_per_minute, info6, info2, penalty_duration);
1206 client->start_hidecards = 1;
1208 break;
1209 default: // logging
1210 if(client->account->acosc_penalty_active == 1)
1211 { cs_log("[zaplist] ACoSC for Client: %s max_activ_sids reached: %i:%i(%s) penalty: 0(%s) only logging", username(client), active_sid_count, max_active_sids, info1, info2); }
1212 if(client->account->acosc_penalty_active == 2)
1213 { cs_log("[zaplist] ACoSC for Client: %s zap_limit reached: %i:%i(%s) penalty: 0(%s) only logging", username(client), client->account->acosc_user_zap_count, zap_limit, info5, info2); }
1214 if(client->account->acosc_penalty_active == 3)
1215 { cs_log("[maxecms] ACoSC for Client: %s max_ecms_per_minute reached: ecms_last_minute=%i ecms_now=%i max=%i(%s) penalty: 0(%s) only logging", username(client), client->n_request[0], client->n_request[1], max_ecms_per_minute, info6, info2); }
1216 break;
1218 client->account->acosc_user_zap_count = 0; // we got already a penalty
1219 client->account->acosc_penalty_active = 3;
1220 client->account->acosc_penalty_active = 4;
1223 cs_writeunlock(__func__, &clientlist_lock);
1225 #endif
1227 if(cfg.double_check && er->rc <= E_CACHE2 && er->selected_reader && is_double_check_caid(er, &cfg.double_check_caid))
1229 if(er->checked == 0) // First CW, save it and wait for next one
1231 er->checked = 1;
1232 er->origin_reader = er->selected_reader;
1233 memcpy(er->cw_checked, er->cw, sizeof(er->cw));
1234 cs_log("DOUBLE CHECK FIRST CW by %s idx %d cpti %d", er->origin_reader->label, er->idx, er->msgid);
1236 else if(er->origin_reader != er->selected_reader) // Second (or third and so on) cw. We have to compare
1238 if(memcmp(er->cw_checked, er->cw, sizeof(er->cw)) == 0)
1240 er->checked++;
1241 cs_log("DOUBLE CHECKED! %d. CW by %s idx %d cpti %d", er->checked, er->selected_reader->label, er->idx, er->msgid);
1243 else
1245 cs_log("DOUBLE CHECKED NONMATCHING! %d. CW by %s idx %d cpti %d", er->checked, er->selected_reader->label, er->idx, er->msgid);
1248 if(er->checked < 2) // less as two same cw? mark as pending!
1250 er->rc = E_UNHANDLED;
1251 goto ESC;
1255 ac_chk(client, er, 1);
1256 int32_t is_fake = 0;
1257 if(er->rc == E_FAKE)
1259 is_fake = 1;
1260 er->rc = E_FOUND;
1263 get_module(client)->send_dcw(client, er);
1265 add_cascade_data(client, er);
1267 if(is_fake)
1268 { er->rc = E_FAKE; }
1270 #ifdef CS_ANTICASC
1271 cs_writelock(__func__, &clientlist_lock);
1272 if(client->start_hidecards)
1274 client->start_hidecards = 0;
1275 add_job(client, ACTION_CLIENT_HIDECARDS, NULL, 0);
1277 cs_writeunlock(__func__, &clientlist_lock);
1278 #endif
1280 if(!(er->rc == E_SLEEPING && client->cwlastresptime == 0))
1282 char buf[ECM_FMT_LEN];
1283 format_ecm(er, buf, ECM_FMT_LEN);
1284 if(er->reader_avail == 1 || er->stage == 0)
1286 cs_log("%s (%s): %s (%d ms)%s%s%s%s", usrname, buf, er->rcEx ? erEx : stxt[er->rc],
1287 client->cwlastresptime, sby, schaninfo, sreason, scwcinfo);
1289 else
1291 cs_log("%s (%s): %s (%d ms)%s (%c/%d/%d/%d)%s%s%s%s", usrname, buf, er->rcEx ? erEx : stxt[er->rc],
1292 client->cwlastresptime, sby, stageTxt[er->stage], er->reader_requested,
1293 (er->reader_count + er->fallback_reader_count), er->reader_avail, schaninfo,
1294 srealecmtime, sreason, scwcinfo);
1298 cs_log_dump_dbg(D_ATR, er->cw, 16, "cw:");
1299 led_status_cw_not_found(er);
1301 ESC:
1303 return 0;
1307 * write_ecm_request():
1309 static int32_t write_ecm_request(struct s_reader *rdr, ECM_REQUEST *er)
1311 add_job(rdr->client, ACTION_READER_ECM_REQUEST, (void *)er, 0);
1312 return 1;
1316 * sends the ecm request to the readers
1317 * ECM_REQUEST er : the ecm
1318 * er->stage: 0 = no reader asked yet
1319 * 2 = ask only local reader (skipped without preferlocalcards)
1320 * 3 = ask any non fallback reader
1321 * 4 = ask fallback reader
1323 void request_cw_from_readers(ECM_REQUEST *er, uint8_t stop_stage)
1325 struct s_ecm_answer *ea;
1326 int8_t sent = 0;
1328 if(er->stage >= 4) { return; }
1330 while(1)
1332 if(stop_stage && er->stage >= stop_stage) { return; }
1334 er->stage++;
1336 #ifdef CS_CACHEEX
1337 if(er->stage == 1 && er->preferlocalcards==2)
1338 { er->stage++; }
1339 #else
1340 if(er->stage == 1)
1341 { er->stage++; }
1342 #endif
1344 if(er->stage == 2 && !er->preferlocalcards)
1345 { er->stage++; }
1347 for(ea = er->matching_rdr; ea; ea = ea->next)
1349 switch(er->stage)
1351 #ifdef CS_CACHEEX
1352 case 1:
1354 // Cache-Exchange
1355 if((ea->status & REQUEST_SENT) ||
1356 (ea->status & (READER_CACHEEX | READER_ACTIVE)) != (READER_CACHEEX | READER_ACTIVE))
1357 { continue; }
1358 break;
1360 #endif
1361 case 2:
1363 // only local reader
1364 if((ea->status & REQUEST_SENT) ||
1365 (ea->status & (READER_ACTIVE | READER_FALLBACK | READER_LOCAL)) != (READER_ACTIVE | READER_LOCAL))
1366 { continue; }
1367 break;
1369 case 3:
1371 // any non fallback reader not asked yet
1372 if((ea->status & REQUEST_SENT) ||
1373 (ea->status & (READER_ACTIVE | READER_FALLBACK)) != READER_ACTIVE)
1374 { continue; }
1375 break;
1377 default:
1379 // only fallbacks
1380 if((ea->status & REQUEST_SENT) ||
1381 (ea->status & (READER_ACTIVE | READER_FALLBACK)) != (READER_ACTIVE | READER_FALLBACK))
1382 { continue; }
1383 break;
1387 struct s_reader *rdr = ea->reader;
1388 #ifdef WITH_DEBUG
1389 if (cs_dblevel & (D_TRACE | D_CSP))
1391 char ecmd5[17 * 3];
1392 cs_hexdump(0, er->ecmd5, 16, ecmd5, sizeof(ecmd5));
1393 cs_log_dbg(D_TRACE | D_CSP, "request_cw stage=%d to reader %s ecm hash=%s", er->stage, rdr ? rdr->label : "", ecmd5);
1395 #endif
1396 ea->status |= REQUEST_SENT;
1397 cs_ftime(&ea->time_request_sent);
1399 er->reader_requested++;
1401 write_ecm_request(ea->reader, er);
1403 // set sent=1 only if reader is active/connected. If not, switch to next stage!
1404 if(!sent && rdr)
1406 struct s_client *rcl = rdr->client;
1407 if(check_client(rcl))
1409 if(rcl->typ == 'r' && rdr->card_status == CARD_INSERTED)
1410 { sent = 1; }
1411 else if(rcl->typ == 'p' && (rdr->card_status == CARD_INSERTED || rdr->tcp_connected))
1412 { sent = 1; }
1416 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} [write_ecm_request] reader %s --> SENT %d", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid, rdr ? ea->reader->label : "-", sent);
1419 if(sent || er->stage >= 4)
1420 { break; }
1424 void add_cache_from_reader(ECM_REQUEST *er, struct s_reader *rdr, uint32_t csp_hash, uint8_t *ecmd5, uint8_t *cw, int16_t caid, int32_t prid, int16_t srvid
1425 #ifdef CS_CACHEEX_AIO
1426 , int32_t ecm_time
1427 #endif
1430 ECM_REQUEST *ecm;
1431 if (cs_malloc(&ecm, sizeof(ECM_REQUEST)))
1433 cs_ftime(&ecm->tps);
1435 ecm->cwc_cycletime = er->cwc_cycletime;
1436 ecm->cwc_next_cw_cycle = er->cwc_next_cw_cycle;
1437 memcpy(ecm->ecm, er->ecm, sizeof(ecm->ecm)); // ecm[0] is pushed to cacheexclients so we need a copy from it
1438 ecm->caid = caid;
1439 ecm->prid = prid;
1440 ecm->srvid = srvid;
1441 memcpy(ecm->ecmd5, ecmd5, CS_ECMSTORESIZE);
1442 ecm->csp_hash = csp_hash;
1443 ecm->rc = E_FOUND;
1444 memcpy(ecm->cw, cw, sizeof(ecm->cw));
1445 ecm->grp = rdr->grp;
1446 ecm->selected_reader = rdr;
1447 #ifdef CS_CACHEEX_AIO
1448 ecm->ecm_time = ecm_time;
1449 ecm->localgenerated = er->localgenerated;
1450 #endif
1451 #ifdef CS_CACHEEX
1452 if(rdr && cacheex_reader(rdr))
1453 { ecm->cacheex_src = rdr->client; } //so adds hits to reader
1454 #endif
1456 add_cache(ecm); //add cw to cache
1458 #ifdef CS_CACHEEX
1459 cs_writelock(__func__, &ecm_pushed_deleted_lock);
1460 ecm->next = ecm_pushed_deleted;
1461 ecm_pushed_deleted = ecm;
1462 cs_writeunlock(__func__, &ecm_pushed_deleted_lock);
1463 #else
1464 NULLFREE(ecm);
1465 #endif
1469 void chk_dcw(struct s_ecm_answer *ea)
1471 if(!ea || !ea->er)
1472 { return; }
1474 ECM_REQUEST *ert = ea->er;
1475 struct s_ecm_answer *ea_list;
1476 struct s_reader *eardr = ea->reader;
1477 if(!ert || !eardr)
1478 { return; }
1480 // ecm request already answered!
1481 if(ert->rc < E_99)
1483 #ifdef CS_CACHEEX
1484 if(ea && ert->rc < E_NOTFOUND && ea->rc < E_NOTFOUND && memcmp(ea->cw, ert->cw, sizeof(ert->cw)) != 0)
1486 char cw1[16 * 3 + 2], cw2[16 * 3 + 2];
1487 #ifdef WITH_DEBUG
1488 if(cs_dblevel & D_TRACE)
1490 cs_hexdump(0, ea->cw, 16, cw1, sizeof(cw1));
1491 cs_hexdump(0, ert->cw, 16, cw2, sizeof(cw2));
1493 #endif
1494 char ip1[20] = "", ip2[20] = "";
1495 if(ea->reader && check_client(ea->reader->client)) { cs_strncpy(ip1, cs_inet_ntoa(ea->reader->client->ip), sizeof(ip1)); }
1496 if(ert->cacheex_src) { cs_strncpy(ip2, cs_inet_ntoa(ert->cacheex_src->ip), sizeof(ip2)); }
1497 else if(ert->selected_reader && check_client(ert->selected_reader->client)) { cs_strncpy(ip2, cs_inet_ntoa(ert->selected_reader->client->ip), sizeof(ip2)); }
1499 ECM_REQUEST *er = ert;
1500 debug_ecm(D_TRACE, "WARNING2: Different CWs %s from %s(%s)<>%s(%s): %s<>%s", buf,
1501 username(ea->reader ? ea->reader->client : ert->client), ip1,
1502 er->cacheex_src ? username(er->cacheex_src) : (ert->selected_reader ? ert->selected_reader->label : "unknown/csp"), ip2,
1503 cw1, cw2);
1505 #endif
1507 return;
1510 #ifdef CS_CACHEEX
1511 /* if answer from cacheex-1 reader, not send answer to client!
1512 * thread check_cache will check counter and send answer to client!
1513 * Anyway, we should check if we have to go to oher stage (>1)
1516 if(eardr && cacheex_reader(eardr))
1518 // if wait_time, and not wait_time expired and wait_time due to hitcache(or awtime>0),
1519 // we have to wait cacheex timeout before call other readers (stage>1)
1520 if(cacheex_reader(eardr) && !ert->cacheex_wait_time_expired && ert->cacheex_hitcache)
1521 { return; }
1523 int8_t cacheex_left = 0;
1524 uint8_t has_cacheex = 0;
1525 if(ert->stage == 1)
1527 for(ea_list = ert->matching_rdr; ea_list; ea_list = ea_list->next)
1529 cs_readlock(__func__, &ea_list->ecmanswer_lock);
1530 if(((ea_list->status & (READER_CACHEEX | READER_FALLBACK | READER_ACTIVE))) == (READER_CACHEEX | READER_ACTIVE))
1531 { has_cacheex = 1; }
1532 if((!(ea_list->status & READER_FALLBACK) && ((ea_list->status & (REQUEST_SENT | REQUEST_ANSWERED | READER_CACHEEX | READER_ACTIVE)) == (REQUEST_SENT | READER_CACHEEX | READER_ACTIVE))) || ea_list->rc < E_NOTFOUND)
1533 { cacheex_left++; }
1534 cs_readunlock(__func__, &ea_list->ecmanswer_lock);
1537 if(has_cacheex && !cacheex_left) { request_cw_from_readers(ert, 0); }
1540 return;
1542 #endif
1544 int32_t reader_left = 0, local_left = 0, reader_not_flb_left = 0, has_not_fallback = 0, has_local = 0;
1545 ert->selected_reader = eardr;
1547 switch(ea->rc)
1549 case E_FOUND:
1550 memcpy(ert->cw, ea->cw, 16);
1551 ert->cw_ex = ea->cw_ex;
1552 ert->rcEx = 0;
1553 ert->rc = ea->rc;
1554 ert->grp |= eardr->grp;
1555 #ifdef HAVE_DVBAPI
1556 ert->adapter_index = ea->er->adapter_index;
1557 #endif
1558 break;
1560 case E_INVALID:
1561 case E_NOTFOUND:
1563 // check if there are other readers to ask, and if not send NOT_FOUND to client
1564 ert->rcEx = ea->rcEx;
1565 cs_strncpy(ert->msglog, ea->msglog, sizeof(ert->msglog));
1567 for(ea_list = ert->matching_rdr; ea_list; ea_list = ea_list->next)
1569 cs_readlock(__func__, &ea_list->ecmanswer_lock);
1571 if((!(ea_list->status & READER_FALLBACK) && ((ea_list->status & (REQUEST_SENT | REQUEST_ANSWERED | READER_LOCAL | READER_ACTIVE)) == (REQUEST_SENT | READER_LOCAL | READER_ACTIVE))) || ea_list->rc < E_NOTFOUND)
1572 { local_left++; }
1574 if((!(ea_list->status & READER_FALLBACK) && ((ea_list->status & (REQUEST_SENT | REQUEST_ANSWERED | READER_ACTIVE)) == (REQUEST_SENT | READER_ACTIVE))) || ea_list->rc < E_NOTFOUND)
1575 { reader_not_flb_left++; }
1577 if(((ea_list->status & (REQUEST_ANSWERED | READER_ACTIVE)) == (READER_ACTIVE)) || ea_list->rc < E_NOTFOUND)
1578 { reader_left++; }
1580 if(((ea_list->status & (READER_FALLBACK | READER_ACTIVE))) == (READER_ACTIVE))
1581 { has_not_fallback = 1; }
1582 if(((ea_list->status & (READER_LOCAL | READER_FALLBACK | READER_ACTIVE))) == (READER_LOCAL | READER_ACTIVE))
1583 { has_local = 1; }
1585 cs_readunlock(__func__, &ea_list->ecmanswer_lock);
1588 switch(ert->stage)
1590 case 2: // only local reader (used only if preferlocalcards=1)
1592 if(has_local && !local_left) { request_cw_from_readers(ert, 0); }
1593 break;
1595 case 3:
1597 // any fallback reader not asked yet
1598 if(has_not_fallback && !reader_not_flb_left) { request_cw_from_readers(ert, 0); }
1599 break;
1603 if(!reader_left // no more matching reader
1604 #ifdef CS_CACHEEX
1605 && !cfg.wait_until_ctimeout
1606 #endif
1608 { ert->rc = E_NOTFOUND; } // so we set the return code
1610 break;
1613 case E_TIMEOUT: // if timeout, we have to send timeout to client: this is done by ecm_timeout callback
1614 return;
1615 break;
1617 case E_UNHANDLED:
1618 return;
1619 break;
1621 default:
1622 cs_log("unexpected ecm answer rc=%d.", ea->rc);
1623 return;
1624 break;
1627 if(ert->rc < E_99)
1628 send_dcw(ert->client, ert);
1631 uint32_t chk_provid(uint8_t *ecm, uint16_t caid)
1633 int32_t i, len, descriptor_length = 0;
1634 uint32_t provid = 0;
1636 switch(caid >> 8)
1638 case 0x01: // seca
1639 provid = b2i(2, ecm + 3);
1640 break;
1642 case 0x05: // viaccess
1643 i = (ecm[4] == 0xD2) ? ecm[5] + 2 : 0; // skip d2 nano
1644 if((ecm[5 + i] == 3) && ((ecm[4 + i] == 0x90) || (ecm[4 + i] == 0x40)))
1645 { provid = (b2i(3, ecm + 6 + i) & 0xFFFFF0); }
1647 i = (ecm[6] == 0xD2) ? ecm[7] + 2 : 0; // skip d2 nano long ecm
1648 if((ecm[7 + i] == 7) && ((ecm[6 + i] == 0x90) || (ecm[6 + i] == 0x40)))
1649 { provid = (b2i(3, ecm + 8 + i) & 0xFFFFF0); }
1650 break;
1652 case 0x0D: // cryptoworks
1653 len = (((ecm[1] & 0xf) << 8) | ecm[2]) + 3;
1654 for(i = 8; i < len; i += descriptor_length + 2)
1656 descriptor_length = ecm[i + 1];
1657 if(ecm[i] == 0x83)
1659 provid = (uint32_t)ecm[i + 2] & 0xFE;
1660 break;
1663 break;
1665 case 0x18: // nagra2
1666 if (caid == 0x1801) // more safety
1667 provid = b2i(2, ecm + 5);
1668 break;
1671 return provid;
1674 void update_chid(ECM_REQUEST *er)
1676 er->chid = get_subid(er);
1680 * This function writes the current CW from ECM struct to a cwl file.
1681 * The filename is re-calculated and file re-opened every time.
1682 * This will consume a bit cpu time, but nothing has to be stored between
1683 * each call. If not file exists, a header is prepended
1685 static void logCWtoFile(ECM_REQUEST *er, uint8_t *cw)
1687 FILE *pfCWL;
1688 char srvname[CS_SERVICENAME_SIZE];
1689 /* %s / %s _I %04X _ %s .cwl */
1690 char buf[256 + sizeof(srvname)];
1691 char date[9];
1692 uint8_t i, parity, writeheader = 0;
1693 struct tm timeinfo;
1696 * search service name for that id and change characters
1697 * causing problems in file name
1700 get_servicename(cur_client(), er->srvid, er->prid, er->caid, srvname, sizeof(srvname));
1702 for(i = 0; srvname[i]; i++)
1703 if(srvname[i] == ' ') { srvname[i] = '_'; }
1705 /* calc log file name */
1706 time_t walltime = cs_time();
1707 localtime_r(&walltime, &timeinfo);
1708 strftime(date, sizeof(date), "%Y%m%d", &timeinfo);
1709 snprintf(buf, sizeof(buf), "%s/%s_I%04X_%s.cwl", cfg.cwlogdir, date, er->srvid, srvname);
1711 /* open failed, assuming file does not exist, yet */
1712 if((pfCWL = fopen(buf, "r")) == NULL)
1714 writeheader = 1;
1716 else
1718 /* we need to close the file if it was opened correctly */
1719 fclose(pfCWL);
1722 if((pfCWL = fopen(buf, "a+")) == NULL)
1724 /* maybe this fails because the subdir does not exist. Is there a common function to create it?
1725 for the moment do not print32_t to log on every ecm
1726 cs_log(""error opening cw logfile for writing: %s (errno=%d %s)", buf, errno, strerror(errno)); */
1727 return;
1729 if(writeheader)
1731 /* no global macro for cardserver name :( */
1732 fprintf(pfCWL, "# OSCam cardserver v%s - https://trac.streamboard.tv/oscam/\n", CS_VERSION);
1733 fprintf(pfCWL, "# control word log file for use with tsdec offline decrypter\n");
1734 strftime(buf, sizeof(buf), "DATE %Y-%m-%d, TIME %H:%M:%S, TZ %Z\n", &timeinfo);
1735 fprintf(pfCWL, "# %s", buf);
1736 fprintf(pfCWL, "# CAID 0x%04X, SID 0x%04X, SERVICE \"%s\"\n", er->caid, er->srvid, srvname);
1739 parity = er->ecm[0] & 1;
1740 fprintf(pfCWL, "%d ", parity);
1741 for(i = parity * 8; i < 8 + parity * 8; i++)
1742 { fprintf(pfCWL, "%02X ", cw[i]); }
1743 /* better use incoming time er->tps rather than current time? */
1744 strftime(buf, sizeof(buf), "%H:%M:%S\n", &timeinfo);
1745 fprintf(pfCWL, "# %s", buf);
1746 fflush(pfCWL);
1747 fclose(pfCWL);
1750 int32_t write_ecm_answer(struct s_reader *reader, ECM_REQUEST *er, int8_t rc, uint8_t rcEx, uint8_t *cw, char *msglog, uint16_t used_cardtier, EXTENDED_CW* cw_ex)
1752 if(!reader || !er || !er->tps.time) { return 0; }
1754 // drop too late answers, to avoid seg fault --> only answer until tps.time+((cfg.ctimeout+500)/1000+1) is accepted
1755 time_t timeout = time(NULL) - ((cfg.ctimeout + 500) / 1000 + 1);
1756 if(er->tps.time < timeout) // < and NOT <=
1757 { return 0; }
1759 struct timeb now;
1760 cs_ftime(&now);
1762 #ifdef CS_CACHEEX_AIO
1763 uint8_t dontsetAnswered = 0;
1764 #endif
1765 uint8_t dontwriteStats = 0;
1767 if(er && er->parent)
1769 // parent is only set on reader->client->ecmtask[], but we want original er
1770 ECM_REQUEST *er_reader_cp = er;
1771 er = er->parent; // Now er is "original" ecm, before it was the reader-copy
1772 er_reader_cp->rc = rc;
1773 er_reader_cp->idx = 0;
1774 #ifdef CS_CACHEEX_AIO
1775 er->localgenerated = er_reader_cp->localgenerated;
1776 #endif
1778 timeout = time(NULL) - ((cfg.ctimeout + 500) / 1000 + 1);
1779 if(er->tps.time < timeout)
1780 { return 0; }
1783 #ifdef CS_CACHEEX_AIO
1784 if(rc < E_NOTFOUND && !er->localgenerated && (reader->cacheex.localgenerated_only_in || chk_lg_only(er, &reader->cacheex.lg_only_in_tab)) && !chk_srvid_localgenerated_only_exception(er))
1786 cs_log_dbg(D_CACHEEX, "reader: %s !er->localgenerated - rc: E_NOTFOUND set, no stats written for reader", reader ? reader->label : "-");
1787 rc = E_NOTFOUND;
1788 dontsetAnswered = 1;
1789 dontwriteStats = 1;
1791 #endif
1793 struct s_ecm_answer *ea = get_ecm_answer(reader, er);
1794 if(!ea) { return 0; }
1796 cs_writelock(__func__, &ea->ecmanswer_lock);
1798 if((ea->status & REQUEST_ANSWERED))
1800 cs_log_dbg(D_READER, "Reader %s already answer, skip this ecm answer!", reader ? reader->label : "-");
1801 cs_writeunlock(__func__, &ea->ecmanswer_lock);
1802 return 0;
1805 // Special checks for rc
1806 // Skip check for BISS1 - cw could be zero but still catch cw=0 by anticascading
1807 // Skip check for BISS2 - we use the extended cw, so the "simple" cw is always zero
1809 // bad/wrong chksum/ecm
1810 if(rc == E_NOTFOUND && rcEx == E2_WRONG_CHKSUM)
1812 cs_log_dbg(D_READER, "ECM for reader %s was bad/has a wrong chksum!", reader ? reader->label : "-");
1813 rc = E_INVALID;
1814 rcEx = E2_WRONG_CHKSUM;
1815 er->stage = 5;
1817 // dont write stats for bad/wrong chksum/ecm
1818 dontwriteStats = 1;
1820 // set all other matching_readers => inactive to skip them and dont spread the bad ecm
1821 struct s_ecm_answer *ea_list;
1822 for(ea_list = er->matching_rdr; ea_list; ea_list = ea_list->next)
1824 ea_list->status &= ~(READER_ACTIVE | READER_FALLBACK);
1828 if(rc < E_NOTFOUND && cw && chk_is_null_CW(cw) && !caid_is_biss(er->caid))
1830 rc = E_NOTFOUND;
1831 cs_log_dbg(D_TRACE | D_LB, "WARNING: reader %s send fake cw, set rc=E_NOTFOUND!", reader ? reader->label : "-");
1834 if(rc < E_NOTFOUND && cw && !chk_halfCW(er,cw))
1836 rc = E_NOTFOUND;
1837 cs_log_dbg(D_TRACE | D_LB, "WARNING: reader %s send wrong swapped NDS cw, set rc=E_NOTFOUND!", reader ? reader->label : "-");
1840 if(reader && cw && rc < E_NOTFOUND)
1842 if(!cfg.disablecrccws && !reader->disablecrccws)
1844 if(!chk_if_ignore_checksum(er, &cfg.disablecrccws_only_for) && !chk_if_ignore_checksum(er, &reader->disablecrccws_only_for))
1846 uint8_t i, c;
1847 for(i = 0; i < 16; i += 4)
1849 c = ((cw[i] + cw[i + 1] + cw[i + 2]) & 0xff);
1851 if(cw[i + 3] != c)
1853 uint8_t nano = 0x00;
1854 if(er->caid == 0x100 && er->ecm[5] > 0x00)
1856 nano = er->ecm[5]; // seca nano protection
1859 if(reader->dropbadcws && !nano) // only drop controlword if no cw encryption is applied
1861 rc = E_NOTFOUND;
1862 rcEx = E2_WRONG_CHKSUM;
1863 break;
1865 else
1867 if(!nano) // only fix checksum if no cw encryption is applied (nano = 0)
1869 cs_log_dbg(D_TRACE, "notice: changed dcw checksum byte cw[%i] from %02x to %02x", i + 3, cw[i + 3], c);
1870 cw[i + 3] = c;
1872 else
1874 if(i == 12) // there are servers delivering correct controlwords but with failing last cw checksum (on purpose?!)
1876 cs_log_dbg(D_TRACE,"NANO%02d: BAD PEER DETECTED, oscam has fixed the last cw crc that wasn't matching!", nano);
1877 cw[i + 3] = c; // fix the last controlword
1879 else
1881 cs_log_dbg(D_TRACE,"NANO%02d: not fixing the crc of this cw since its still encrypted!", nano);
1882 break; // crc failed so stop!
1889 else
1891 cs_log_dbg(D_TRACE, "notice: CW checksum check disabled for %04X:%06X", er->caid, er->prid);
1894 else
1896 cs_log_dbg(D_TRACE, "notice: CW checksum check disabled");
1899 if(chk_if_ignore_checksum(er, &reader->disablecrccws_only_for) && caid_is_videoguard(er->caid)
1900 #ifdef CS_CACHEEX_AIO
1901 && !chk_srvid_disablecrccws_only_for_exception(er)
1902 #endif
1905 uint8_t k, csum;
1906 uint8_t hit = 0;
1907 uint8_t oe = checkCWpart(cw, 0) ? 0 : 8;
1908 for(k = 0; k < 8; k += 4)
1910 csum = ((cw[k + oe] + cw[k + oe + 1] + cw[k + oe + 2]) & 0xff);
1911 if(cw[k + oe + 3] == csum)
1913 hit++;
1916 if(hit > 1)
1918 char ecmd5s[17 * 3];
1919 cs_hexdump(0, er->ecmd5, 16, ecmd5s, sizeof(ecmd5s));
1920 if(reader->dropbadcws)
1922 rc = E_NOTFOUND;
1923 rcEx = E2_WRONG_CHKSUM;
1924 cs_log("Probably got bad CW from reader: %s, caid %04X, srvid %04X (%s) - dropping CW, lg: %i", reader->label, er->caid, er->srvid, ecmd5s
1925 #ifdef CS_CACHEEX_AIO
1926 , er->localgenerated);
1927 #else
1928 , 0);
1929 #endif
1931 else
1933 cs_log("Probably got bad CW from reader: %s, caid %04X, srvid %04X (%s), lg: %i", reader->label, er->caid, er->srvid, ecmd5s
1934 #ifdef CS_CACHEEX_AIO
1935 , er->localgenerated);
1936 #else
1937 , 0);
1938 #endif
1945 #ifdef CW_CYCLE_CHECK
1946 uint8_t cwc_ct = er->cwc_cycletime > 0 ? er->cwc_cycletime : 0;
1947 uint8_t cwc_ncwc = er->cwc_next_cw_cycle < 2 ? er->cwc_next_cw_cycle : 2;
1948 if(!checkcwcycle(er->client, er, reader, cw, rc, cwc_ct, cwc_ncwc))
1950 #ifdef CS_CACHEEX_AIO
1951 if(!er->localgenerated)
1953 #endif
1954 rc = E_NOTFOUND;
1955 rcEx = E2_WRONG_CHKSUM;
1956 cs_log_dbg(D_CACHEEX | D_CWC | D_LB, "{client %s, caid %04X, srvid %04X} [write_ecm_answer] cyclecheck failed! Reader: %s set rc: %i", (er->client ? er->client->account->usr : "-"), er->caid, er->srvid, reader ? reader->label : "-", rc);
1958 #ifdef CS_CACHEEX_AIO
1960 else
1962 cs_log_dbg(D_CACHEEX | D_CWC | D_LB, "{client %s, caid %04X, srvid %04X} [write_ecm_answer] cyclecheck failed! Reader: %s set rc: %i -> lg-flagged CW -> do nothing", (er->client ? er->client->account->usr : "-"), er->caid, er->srvid, reader ? reader->label : "-", rc);
1964 #endif
1966 else { cs_log_dbg(D_CACHEEX | D_CWC | D_LB, "{client %s, caid %04X, srvid %04X} [write_ecm_answer] cyclecheck passed! Reader: %s rc: %i", (er->client ? er->client->account->usr : "-"), er->caid, er->srvid, reader ? reader->label : "-", rc); }
1967 #endif
1968 //END -- SPECIAL CHECKs for rc
1970 #ifdef CS_CACHEEX_AIO
1971 if(!dontsetAnswered)
1973 #endif
1974 ea->status |= REQUEST_ANSWERED;
1975 #ifdef CS_CACHEEX_AIO
1977 #endif
1978 ea->rc = rc;
1979 ea->ecm_time = comp_timeb(&now, &ea->time_request_sent);
1980 if(ea->ecm_time < 1) { ea->ecm_time = 1; } // set ecm_time 1 if answer immediately
1981 ea->rcEx = rcEx;
1982 if(cw) { memcpy(ea->cw, cw, 16); }
1983 if(msglog) { memcpy(ea->msglog, msglog, MSGLOGSIZE); }
1984 ea->tier = used_cardtier;
1985 if(cw_ex)
1987 ea->cw_ex = *cw_ex;
1990 cs_writeunlock(__func__, &ea->ecmanswer_lock);
1992 struct timeb tpe;
1993 cs_ftime(&tpe);
1994 int32_t ntime = comp_timeb(&tpe, &er->tps);
1995 if(ntime < 1) { ntime = 1; }
1996 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} [write_ecm_answer] reader %s rc %d, ecm time %d ms (%d ms)", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid, reader ? reader->label : "-", rc, ea->ecm_time, ntime);
1998 // send ea for ecm request
1999 int32_t res = 0;
2000 struct s_client *cl = er->client;
2001 if(check_client(cl))
2003 res = 1;
2004 add_job(er->client, ACTION_ECM_ANSWER_READER, ea, 0); // chk_dcw
2007 // distribute ea for pendings
2008 if(ea->pending) // has pending ea
2009 { distribute_ea(ea); }
2012 if(!ea->is_pending) // not for pending ea - only once for ea
2014 // cache update
2015 // Skip check for BISS1 - cw could be indeed zero
2016 // Skip check for BISS2 - we use the extended cw, so the "simple" cw is always zero
2017 if(ea && (ea->rc < E_NOTFOUND) && (!chk_is_null_CW(ea->cw) && !caid_is_biss(er->caid)))
2019 #ifdef CS_CACHEEX_AIO
2020 int32_t ecmtime = ea->ecm_time;
2022 if(er->cacheex_wait_time_expired && er->cacheex_wait_time)
2023 ecmtime = ea->ecm_time + er->cacheex_wait_time;
2024 #endif
2025 add_cache_from_reader(er, reader, er->csp_hash, er->ecmd5, ea->cw, er->caid, er->prid, er->srvid
2026 #ifdef CS_CACHEEX_AIO
2027 , ecmtime);
2028 #else
2030 #endif
2033 if(!dontwriteStats)
2035 // readers stats for LB
2036 send_reader_stat(reader, er, ea, ea->rc);
2039 // reader checks
2040 #ifdef WITH_DEBUG
2041 if(cs_dblevel & D_TRACE)
2043 char ecmd5[17 * 3];
2044 cs_hexdump(0, er->ecmd5, 16, ecmd5, sizeof(ecmd5));
2045 rdr_log_dbg(reader, D_TRACE, "ecm answer for ecm hash %s rc=%d", ecmd5, ea->rc);
2047 #endif
2048 // Update reader stats:
2049 if(ea->rc == E_FOUND)
2051 if(cfg.cwlogdir != NULL)
2052 { logCWtoFile(er, ea->cw); } // CWL logging only if cwlogdir is set in config
2054 reader->ecmsok++;
2055 #ifdef CS_CACHEEX_AIO
2056 if(er->localgenerated)
2057 reader->ecmsoklg++;
2058 #endif
2059 reader->webif_ecmsok++;
2060 #ifdef CS_CACHEEX
2061 struct s_client *eacl = reader->client;
2062 if(cacheex_reader(reader) && check_client(eacl))
2064 eacl->cwcacheexgot++;
2065 cacheex_add_stats(eacl, ea->er->caid, ea->er->srvid, ea->er->prid, 1
2066 #ifdef CS_CACHEEX_AIO
2067 , er->localgenerated);
2068 #else
2070 #endif
2071 first_client->cwcacheexgot++;
2072 #ifdef CS_CACHEEX_AIO
2073 if(er->localgenerated)
2075 eacl->cwcacheexgotlg++;
2076 first_client->cwcacheexgotlg++;
2078 #endif
2080 #endif
2082 else if(ea->rc == E_NOTFOUND)
2084 reader->ecmsnok++;
2085 reader->webif_ecmsnok++;
2086 if(reader->ecmnotfoundlimit && reader->ecmsnok >= reader->ecmnotfoundlimit)
2088 rdr_log(reader, "ECM not found limit reached %u. Restarting the reader.",
2089 reader->ecmsnok);
2090 reader->ecmsnok = 0; // Reset the variable
2091 reader->ecmshealthnok = 0; // Reset the variable
2092 add_job(reader->client, ACTION_READER_RESTART, NULL, 0);
2096 // this fixes big oscam mistake
2097 // wrong reader status on web info aka not counted timeouts which dispalyed
2098 // reader info 100 percent OK but reader had a ton of unhandled timeouts!
2099 else if(ea->rc == E_TIMEOUT)
2101 #ifdef WITH_LB
2102 STAT_QUERY q;
2103 readerinfofix_get_stat_query(er, &q);
2104 READER_STAT *s;
2105 s = readerinfofix_get_add_stat(reader, &q);
2106 if (s)
2108 cs_log_dbg(D_LB, "inc fail {client %s, caid %04X, prid %06X, srvid %04X} [write_ecm_answer] reader %s rc %d, ecm time %d ms (%d ms)", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid, reader ? reader->label : "-", rc, ea->ecm_time, ntime);
2109 readerinfofix_inc_fail(s); // now increase fail factor for unhandled timeouts
2111 #endif
2112 reader->ecmstout++; // now append timeouts to the readerinfo timeout count
2113 reader->webif_ecmstout++;
2116 // Reader ECMs Health Try (by Pickser)
2117 if(reader->ecmsok != 0 || reader->ecmsnok != 0 || reader->ecmstout != 0)
2119 reader->ecmshealthok = ((double) reader->ecmsok / (reader->ecmsok + reader->ecmsnok + reader->ecmstout)) * 100;
2120 #ifdef CS_CACHEEX_AIO
2121 reader->ecmshealthoklg = ((double) reader->ecmsoklg / (reader->ecmsok + reader->ecmsnok + reader->ecmstout)) * 100;
2122 #endif
2123 reader->ecmshealthnok = ((double) reader->ecmsnok / (reader->ecmsok + reader->ecmsnok + reader->ecmstout)) * 100;
2124 reader->ecmshealthtout = ((double) reader->ecmstout / (reader->ecmsok + reader->ecmsnok + reader->ecmstout)) * 100;
2127 if(rc == E_FOUND && reader->resetcycle > 0)
2129 reader->resetcounter++;
2130 if(reader->resetcounter > reader->resetcycle)
2132 reader->resetcounter = 0;
2133 rdr_log(reader, "Resetting reader, resetcyle of %d ecms reached", reader->resetcycle);
2134 reader->card_status = CARD_NEED_INIT;
2135 cardreader_reset(cl);
2140 return res;
2143 // chid calculation from module stat to here
2144 // to improve the quickfix concerning ecm chid info and extend it
2145 // to all client requests wereby the chid is known in module stat
2147 uint32_t get_subid(ECM_REQUEST *er)
2149 if(!er->ecmlen)
2150 { return 0; }
2152 uint32_t id = 0;
2153 switch(er->caid >> 8)
2155 case 0x01: // seca
2156 id = b2i(2, er->ecm + 7);
2157 break;
2159 case 0x05: // viaccess
2160 id = b2i(2, er->ecm + 8);
2161 break;
2163 case 0x06: // irdeto
2164 id = b2i(2, er->ecm + 6);
2165 break;
2167 case 0x09: // videoguard
2168 id = b2i(2, er->ecm + 11);
2169 break;
2171 case 0x4A: // DRE-Crypt, Bulcrypt, Tongfang and others?
2172 if(!caid_is_bulcrypt(er->caid) && !caid_is_dre(er->caid))
2173 { id = b2i(2, er->ecm + 6); }
2174 break;
2176 return id;
2179 static void set_readers_counter(ECM_REQUEST *er)
2181 struct s_ecm_answer *ea;
2183 er->reader_count = 0;
2184 er->fallback_reader_count = 0;
2185 er->localreader_count = 0;
2186 er->cacheex_reader_count = 0;
2188 for(ea = er->matching_rdr; ea; ea = ea->next)
2190 if(ea->status & READER_ACTIVE)
2192 if(!(ea->status & READER_FALLBACK))
2193 { er->reader_count++; }
2194 else
2195 { er->fallback_reader_count++; }
2197 if(cacheex_reader(ea->reader))
2198 { er->cacheex_reader_count++; }
2199 else if(is_localreader(ea->reader, er))
2200 { er->localreader_count++; }
2205 void write_ecm_answer_fromcache(struct s_write_from_cache *wfc)
2207 ECM_REQUEST *er = NULL;
2208 ECM_REQUEST *ecm = NULL;
2210 er = wfc->er_new;
2211 ecm = wfc->er_cache;
2213 #ifdef CS_CACHEEX_AIO
2214 if(ecm->localgenerated || (ecm->cw_count > 0x0F000000))
2215 er->localgenerated = 1;
2216 #endif
2218 int8_t rc_orig = er->rc;
2220 er->grp |= ecm->grp; // update group
2221 #ifdef CS_CACHEEX
2222 if(ecm->from_csp) { er->csp_answered = 1; } // update er as answered by csp (csp have no group)
2223 #endif
2225 if(er->rc >= E_NOTFOUND)
2227 #ifdef CS_CACHEEX
2228 if(ecm->cacheex_src) // from cacheex or csp
2230 er->rc = E_CACHEEX;
2232 else
2233 #endif
2234 { er->rc=E_CACHE1; } // from normal readers
2236 memcpy(er->cw, ecm->cw, 16);
2237 er->selected_reader = ecm->selected_reader;
2238 er->cw_count = ecm->cw_count;
2240 #ifdef CS_CACHEEX
2241 // here we should be sure cex client has not been freed!
2242 if(ecm->cacheex_src && is_valid_client(ecm->cacheex_src) && !ecm->cacheex_src->kill)
2244 er->cacheex_src = ecm->cacheex_src;
2245 er->cwc_cycletime = ecm->cwc_cycletime;
2246 er->cwc_next_cw_cycle = ecm->cwc_next_cw_cycle;
2248 else
2250 er->cacheex_src = NULL;
2253 int8_t cacheex = check_client(er->client) && er->client->account ? er->client->account->cacheex.mode : 0;
2254 if(cacheex == 1 && check_client(er->client))
2256 cacheex_add_stats(er->client, er->caid, er->srvid, er->prid, 0
2257 #ifdef CS_CACHEEX_AIO
2258 , er->localgenerated);
2259 #else
2261 #endif
2262 er->client->cwcacheexpush++;
2263 if(er->client->account)
2264 { er->client->account->cwcacheexpush++; }
2265 first_client->cwcacheexpush++;
2267 #ifdef CS_CACHEEX_AIO
2268 if(er->localgenerated)
2270 er->client->cwcacheexpushlg++;
2271 first_client->cwcacheexpushlg++;
2273 #endif
2276 #endif
2278 #ifdef CS_CACHEEX
2279 if(cfg.delay && cacheex!=1) // No delay on cacheexchange mode 1 client!
2280 { cs_sleepms(cfg.delay); }
2281 #else
2282 if(cfg.delay)
2283 { cs_sleepms(cfg.delay); }
2284 #endif
2286 if(rc_orig == E_UNHANDLED)
2288 cs_log_dbg(D_LB,"{client %s, caid %04X, prid %06X, srvid %04X} [write_ecm_answer_fromcache] found cw in CACHE (count %d)!", (check_client(er->client)?er->client->account->usr:"-"),er->caid, er->prid, er->srvid,
2289 #ifdef CS_CACHEEX_AIO
2290 (er->cw_count > 0x0F000000) ? er->cw_count ^= 0x0F000000 : er->cw_count);
2291 #else
2292 er->cw_count);
2293 #endif
2294 send_dcw(er->client, er);
2299 #ifdef CS_CACHEEX_AIO
2300 static bool ecm_cache_check(ECM_REQUEST *er)
2302 if(ecm_cache_init_done && cfg.ecm_cache_droptime > 0)
2304 ECM_CACHE *ecm_cache = NULL;
2305 SAFE_RWLOCK_WRLOCK(&ecm_cache_lock);
2306 ecm_cache = find_hash_table(&ht_ecm_cache, &er->csp_hash, sizeof(uint32_t), &compare_csp_hash_ecmcache);
2307 if(!ecm_cache)
2309 // ecm_cache-size(count/memory) pre-check
2311 (cfg.ecm_cache_size && (cfg.ecm_cache_size > tommy_hashlin_count(&ht_ecm_cache)))
2312 || (cfg.ecm_cache_memory && (cfg.ecm_cache_memory*1024*1024 > tommy_hashlin_memory_usage(&ht_ecm_cache)))
2315 if(cs_malloc(&ecm_cache, sizeof(ECM_CACHE)))
2317 ecm_cache->csp_hash = er->csp_hash;
2318 cs_ftime(&ecm_cache->first_recv_time);
2319 cs_ftime(&ecm_cache->upd_time);
2321 tommy_hashlin_insert(&ht_ecm_cache, &ecm_cache->ht_node, ecm_cache, tommy_hash_u32(0, &er->csp_hash, sizeof(er->csp_hash)));
2322 tommy_list_insert_tail(&ll_ecm_cache, &ecm_cache->ll_node, ecm_cache);
2324 SAFE_RWLOCK_UNLOCK(&ecm_cache_lock);
2325 return true;
2327 else{
2328 SAFE_RWLOCK_UNLOCK(&ecm_cache_lock);
2329 cs_log("[ecm_cache] ERROR: NO added HASH to ecm_cache!!");
2330 return false;
2333 else{
2334 // clean cache call;
2335 SAFE_RWLOCK_UNLOCK(&ecm_cache_lock);
2336 ecm_cache_cleanup(true);
2337 return false;
2340 // ecm found
2341 else{
2342 int64_t gone_diff = 0;
2343 gone_diff = comp_timeb(&er->tps, &ecm_cache->first_recv_time);
2344 cs_ftime(&ecm_cache->upd_time);
2346 if(gone_diff >= cfg.ecm_cache_droptime * 1000)
2348 cs_log_dbg(D_CW_CACHE, "[ecm_cache] ECM drop, current ecm_cache_size: %i - ecm_cache-mem-size: %i MiB", count_hash_table(&ht_ecm_cache), (int)(tommy_hashlin_memory_usage(&ht_ecm_cache)/1024/1024));
2349 SAFE_RWLOCK_UNLOCK(&ecm_cache_lock);
2350 return false;
2354 SAFE_RWLOCK_UNLOCK(&ecm_cache_lock);
2355 return true;
2357 else{
2358 cs_log_dbg(D_CW_CACHE,"[ecm_cache] ecm_cache_init_done %i cfg.ecm_cache_size: %"PRIu32" cfg.ecm_cache_memory %"PRIu32" MiB", ecm_cache_init_done, cfg.ecm_cache_size, cfg.ecm_cache_memory);
2359 return true;
2362 #endif
2364 void get_cw(struct s_client *client, ECM_REQUEST *er)
2366 #ifdef CS_CACHEEX_AIO
2367 cacheex_update_hash(er);
2368 if(!ecm_cache_check(er))
2370 er->rc = E_INVALID;
2371 send_dcw(client, er);
2372 free_ecm(er);
2373 return;
2375 #endif
2376 cs_log_dump_dbg(D_ATR, er->ecm, er->ecmlen, "get cw for ecm:");
2377 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} [get_cw] NEW REQUEST!", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid);
2378 increment_n_request(client);
2380 int32_t i, j, m;
2381 time_t now = time((time_t *)0);
2382 uint32_t line = 0;
2383 uint16_t sct_len;
2385 er->client = client;
2386 er->rc = E_UNHANDLED; // set default rc status to unhandled
2387 er->cwc_next_cw_cycle = 2; // set it to: we dont know
2389 // user was on freetv or didn't request for some time
2390 // so we reset lastswitch to get correct stats/webif display
2391 if(now - client->lastecm > cfg.hideclient_to) { client->lastswitch = 0; }
2392 client->lastecm = now;
2394 if(client == first_client || !client ->account || client->account == first_client->account)
2396 // DVBApi+serial is allowed to request anonymous accounts:
2397 int16_t listenertype = get_module(client)->listenertype;
2398 if(listenertype != LIS_DVBAPI && listenertype != LIS_SERIAL)
2400 er->rc = E_INVALID;
2401 er->rcEx = E2_GLOBAL;
2402 snprintf(er->msglog, sizeof(er->msglog), "invalid user account %s", username(client));
2406 // ecmlen must be 0 (no ecm) or >2 (because SCT_LEN() needs at least 3 bytes)
2407 if(er->ecmlen < 0 || er->ecmlen == 1 || er->ecmlen == 2)
2409 er->rc = E_INVALID;
2410 er->rcEx = E2_GLOBAL;
2411 snprintf(er->msglog, sizeof(er->msglog), "ECM size %d invalid, ignored! client %s", er->ecmlen, username(client));
2414 if(er->ecmlen > MAX_ECM_SIZE)
2416 er->rc = E_INVALID;
2417 er->rcEx = E2_GLOBAL;
2418 snprintf(er->msglog, sizeof(er->msglog), "ECM size %d > Max ECM size %d, ignored! client %s", er->ecmlen, MAX_ECM_SIZE, username(client));
2421 if(er->ecmlen > 2)
2423 sct_len = SCT_LEN(er->ecm);
2424 if(sct_len > er->ecmlen || sct_len < 4)
2426 er->rc = E_INVALID;
2427 er->rcEx = E2_GLOBAL;
2428 snprintf(er->msglog, sizeof(er->msglog), "Real ECM size %d > ECM size %d, ignored! client %s", sct_len, er->ecmlen, username(client));
2430 er->ecmlen = sct_len;
2433 if(!client->grp)
2435 er->rc = E_INVALID;
2436 er->rcEx = E2_GROUP;
2437 snprintf(er->msglog, sizeof(er->msglog), "invalid user group %s", username(client));
2440 // add chid for all client requests as in module stat
2441 update_chid(er);
2443 // betacrypt ecm with nagra header
2444 if(chk_is_betatunnel_caid(er->caid) == 1 && (er->ecmlen == 0x89 || er->ecmlen == 0x4A) && er->ecm[3] == 0x07 && (er->ecm[4] == 0x84 || er->ecm[4] == 0x45))
2446 if(er->caid == 0x1702)
2448 er->caid = 0x1833;
2450 else
2452 check_lb_auto_betatunnel_mode(er);
2454 cs_log_dbg(D_TRACE, "Quickfix remap beta->nagra: 0x%X, 0x%X, 0x%X, 0x%X", er->caid, er->ecmlen, er->ecm[3], er->ecm[4]);
2457 // nagra ecm with betacrypt header 1801, 1833, 1834, 1835
2458 if(chk_is_betatunnel_caid(er->caid) == 2 && (er->ecmlen == 0x93 || er->ecmlen == 0x54) && er->ecm[13] == 0x07 && (er->ecm[14] == 0x84 || er->ecm[14] == 0x45))
2460 if(er->caid == 0x1833)
2462 er->caid = 0x1702;
2464 else
2466 er->caid = 0x1722;
2468 cs_log_dbg(D_TRACE, "Quickfix remap nagra->beta: 0x%X, 0x%X, 0x%X, 0x%X", er->caid, er->ecmlen, er->ecm[13], er->ecm[44]);
2471 // Ariva quickfix (invalid nagra provider)
2472 if(((er->caid & 0xFF00) == 0x1800) && er->prid > 0x00FFFF)
2473 { er->prid = 0; }
2475 // Check for invalid provider, extract provider out of ecm:
2476 uint32_t prid = chk_provid(er->ecm, er->caid);
2477 if(!er->prid)
2479 er->prid = prid;
2481 else
2483 if(prid && prid != er->prid)
2485 cs_log_dbg(D_TRACE, "provider fixed: %04X@%06X to %04X@%06X", er->caid, er->prid, er->caid, prid);
2486 er->prid = prid;
2490 #ifdef MODULE_NEWCAMD
2491 // Set providerid for newcamd clients if none is given
2492 if(!er->prid && client->ncd_server)
2494 int32_t pi = client->port_idx;
2495 if(pi >= 0 && cfg.ncd_ptab.nports && cfg.ncd_ptab.nports >= pi && cfg.ncd_ptab.ports[pi].ncd)
2496 { er->prid = cfg.ncd_ptab.ports[pi].ncd->ncd_ftab.filts[0].prids[0]; }
2498 #endif
2500 // CAID not supported or found
2501 if(!er->caid)
2503 er->rc = E_INVALID;
2504 er->rcEx = E2_CAID;
2505 snprintf(er->msglog, MSGLOGSIZE, "CAID not supported or found");
2508 // user expired
2509 if(client->expirationdate && client->expirationdate < client->lastecm)
2510 { er->rc = E_EXPDATE; }
2512 // out of timeframe
2513 if(client->allowedtimeframe_set)
2515 struct tm acttm;
2516 localtime_r(&now, &acttm);
2517 int32_t curday = acttm.tm_wday;
2518 char *dest = strstr(weekdstr,"ALL");
2519 int32_t all_idx = (dest - weekdstr) / 3;
2520 uint8_t allowed = 0;
2522 // checkout if current time is allowed in the current day
2523 allowed = CHECK_BIT(client->allowedtimeframe[curday][acttm.tm_hour][acttm.tm_min / 30], (acttm.tm_min % 30));
2525 // or checkout if current time is allowed for all days
2526 allowed |= CHECK_BIT(client->allowedtimeframe[all_idx][acttm.tm_hour][acttm.tm_min / 30], (acttm.tm_min % 30));
2528 if(!(allowed))
2530 er->rc = E_EXPDATE;
2532 cs_log_dbg(D_TRACE, "Check Timeframe - result: %d, day:%s time: %02dH%02d, allowed: %s\n", er->rc, shortDay[curday], acttm.tm_hour, acttm.tm_min, allowed ? "true" : "false");
2535 // user disabled
2536 if(client->disabled != 0)
2538 if(client->failban & BAN_DISABLED)
2540 cs_add_violation(client, client->account->usr);
2541 cs_disconnect_client(client);
2543 er->rc = E_DISABLED;
2546 if(!chk_global_whitelist(er, &line))
2548 debug_ecm(D_TRACE, "whitelist filtered: %s (%s) line %d", username(client), buf, line);
2549 er->rc = E_INVALID;
2552 #ifdef CS_CACHEEX
2553 if(client->account && client->account->cacheex.mode == 2 && !client->account->cacheex.allow_request)
2555 er->rc = E_INVALID;
2556 snprintf(er->msglog, MSGLOGSIZE, "invalid request from cacheex-2 client");
2558 #endif
2560 // rc < 100 -> ecm error
2561 if(er->rc >= E_UNHANDLED)
2563 m = er->caid;
2564 i = er->srvid;
2566 if(i != client->last_srvid || !client->lastswitch)
2568 if(cfg.usrfileflag)
2569 { cs_statistics(client); }
2570 client->lastswitch = now;
2573 // user sleeping
2574 if(client->tosleep && (now - client->lastswitch > client->tosleep))
2576 if(client->failban & BAN_SLEEPING)
2578 cs_add_violation(client, client->account->usr);
2579 cs_disconnect_client(client);
2581 if(client->c35_sleepsend != 0)
2583 er->rc = E_STOPPED; // send sleep command CMD08 {00 255}
2585 else
2587 er->rc = E_SLEEPING;
2591 client->last_srvid = i;
2592 client->last_caid = m;
2593 client->last_provid = er->prid;
2595 int32_t ecm_len = (((er->ecm[1] & 0x0F) << 8) | er->ecm[2]) + 3;
2597 for(j = 0; (j < 6) && (er->rc >= E_UNHANDLED); j++)
2599 switch(j)
2601 case 0:
2602 // fake (uniq)
2603 if(client->dup)
2604 { er->rc = E_FAKE; }
2605 break;
2607 case 1:
2608 // invalid (caid)
2609 if(!chk_bcaid(er, &client->ctab))
2611 er->rc = E_INVALID;
2612 er->rcEx = E2_CAID;
2613 snprintf(er->msglog, MSGLOGSIZE, "invalid caid 0x%04X", er->caid);
2615 break;
2617 case 2:
2618 // invalid (srvid)
2619 // matching srvids (or 0000) specified in betatunnel will bypass this filter
2620 if(!chk_srvid(client, er))
2622 if(!chk_on_btun(SRVID_ZERO, client, er))
2624 er->rc = E_INVALID;
2625 snprintf(er->msglog, MSGLOGSIZE, "invalid SID");
2628 break;
2630 case 3:
2631 // invalid (ufilters)
2632 if(!chk_ufilters(er))
2633 { er->rc = E_INVALID; }
2634 break;
2636 case 4:
2637 // invalid (sfilter)
2638 if(!chk_sfilter(er, &get_module(client)->ptab))
2639 { er->rc = E_INVALID; }
2640 break;
2642 case 5:
2643 // corrupt
2644 if((i = er->ecmlen - ecm_len))
2646 if(i > 0)
2648 cs_log_dbg(D_TRACE, "warning: ecm size adjusted from %d to %d", er->ecmlen, ecm_len);
2649 er->ecmlen = ecm_len;
2651 else
2652 { er->rc = E_CORRUPT; }
2654 break;
2659 // Check for odd/even byte
2660 // Don't check for BISS1 and BISS2 mode 1/E or fake caid (ECM is fake for them)
2661 // Don't check for BISS2 mode CA (ECM table is always 0x80)
2662 if(!caid_is_biss(er->caid) && !caid_is_fake(er->caid) && get_odd_even(er) == 0)
2664 cs_log_dbg(D_TRACE, "warning: ecm with null odd/even byte from %s", (check_client(er->client) ? er->client->account->usr : "-"));
2665 er->rc = E_INVALID;
2668 // not continue, send rc to client
2669 if(er->rc < E_UNHANDLED)
2671 send_dcw(client, er);
2672 free_ecm(er);
2673 return;
2677 #ifdef CS_CACHEEX
2678 int8_t cacheex = client->account ? client->account->cacheex.mode : 0;
2679 er->from_cacheex1_client = 0;
2680 if(cacheex == 1) {er->from_cacheex1_client = 1;}
2681 #endif
2684 // set preferlocalcards for this ecm request (actually, paramter
2685 // is per user based, maybe in fiture it will be caid based too)
2686 er->preferlocalcards = cfg.preferlocalcards;
2687 if(client->account && client->account->preferlocalcards > -1)
2689 er->preferlocalcards = client->account->preferlocalcards;
2691 if(er->preferlocalcards <0 || er->preferlocalcards >2) {er->preferlocalcards=0;}
2694 if(chk_is_betatunnel_caid(er->caid) && client->ttab.ttnum)
2696 cs_log_dump_dbg(D_TRACE, er->ecm, 13, "betatunnel? ecmlen=%d", er->ecmlen);
2697 cs_betatunnel(er);
2701 // ignore ecm...
2702 int32_t offset = 3;
2704 // ...and betacrypt header for cache md5 calculation
2705 if(caid_is_betacrypt(er->caid))
2706 { offset = 13; }
2708 uint8_t md5tmp[MD5_DIGEST_LENGTH];
2710 // store ECM in cache
2711 memcpy(er->ecmd5, MD5(er->ecm + offset, er->ecmlen - offset, md5tmp), CS_ECMSTORESIZE);
2712 cacheex_update_hash(er);
2713 ac_chk(client, er, 0);
2716 //******** CHECK IF FOUND ECM IN CACHE
2717 struct ecm_request_t *ecm = NULL;
2718 ecm = check_cache(er, client);
2719 if(ecm) // found in cache
2721 cs_log_dbg(D_LB,"{client %s, caid %04X, prid %06X, srvid %04X} [get_cw] cw found immediately in cache! ", (check_client(er->client)?er->client->account->usr:"-"),er->caid, er->prid, er->srvid);
2723 struct s_write_from_cache *wfc = NULL;
2724 if(!cs_malloc(&wfc, sizeof(struct s_write_from_cache)))
2726 NULLFREE(ecm);
2727 free_ecm(er);
2728 return;
2731 wfc->er_new = er;
2732 wfc->er_cache = ecm;
2733 write_ecm_answer_fromcache(wfc);
2734 NULLFREE(wfc);
2735 NULLFREE(ecm);
2736 free_ecm(er);
2738 return;
2741 // zaplist ACoSC
2742 #ifdef CS_ANTICASC
2743 if(cfg.acosc_enabled)
2745 cs_writelock(__func__, &clientlist_lock);
2746 insert_zaplist(er, client);
2747 cs_writeunlock(__func__, &clientlist_lock);
2749 #endif
2751 er->reader_avail = 0;
2752 er->readers = 0;
2754 struct s_ecm_answer *ea, *prv = NULL;
2755 struct s_reader *rdr;
2757 cs_readlock(__func__, &readerlist_lock);
2758 cs_readlock(__func__, &clientlist_lock);
2760 for(rdr = first_active_reader; rdr; rdr = rdr->next)
2762 uint8_t is_fallback = chk_is_fixed_fallback(rdr, er);
2763 int8_t match = matching_reader(er, rdr);
2765 if(!match) // if this reader does not match, check betatunnel for it
2766 match = lb_check_auto_betatunnel(er, rdr);
2768 if(match)
2770 er->reader_avail++;
2772 #ifdef CS_CACHEEX
2773 if(cacheex == 1 && !cacheex_reader(rdr)) // ex1-cl only ask ex1-rdr
2774 { continue; }
2775 #endif
2777 if(!cs_malloc(&ea, sizeof(struct s_ecm_answer)))
2778 { goto OUT; }
2780 #ifdef WITH_EXTENDED_CW
2781 // Correct CSA mode is CBC - default to that instead
2782 ea->cw_ex.algo_mode = CW_ALGO_MODE_CBC;
2783 #endif
2785 er->readers++;
2787 ea->reader = rdr;
2788 ea->er = er;
2789 ea->rc = E_UNHANDLED;
2790 if(prv)
2791 { prv->next = ea; }
2792 else
2793 { er->matching_rdr = ea; }
2794 prv = ea;
2796 ea->status = READER_ACTIVE;
2797 if(cacheex_reader(rdr))
2798 { ea->status |= READER_CACHEEX; }
2799 else if(is_localreader(rdr, er))
2800 { ea->status |= READER_LOCAL; }
2802 if(is_fallback && (!is_localreader(rdr, er) || (is_localreader(rdr, er) && !er->preferlocalcards)))
2803 { ea->status |= READER_FALLBACK; }
2805 ea->pending = NULL;
2806 ea->is_pending = false;
2807 cs_lock_create(__func__, &ea->ecmanswer_lock, "ecmanswer_lock", 5000);
2811 OUT:
2812 cs_readunlock(__func__, &clientlist_lock);
2813 cs_readunlock(__func__, &readerlist_lock);
2815 lb_set_best_reader(er);
2817 // set reader_count and fallback_reader_count
2818 set_readers_counter(er);
2820 // if preferlocalcards > 0, check if we have local readers selected:
2821 // if not, switch to preferlocalcards = 0 for this ecm
2822 if(er->preferlocalcards > 0)
2824 if(er->localreader_count == 0)
2826 er->preferlocalcards = 0;
2827 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} NO local readers, set preferlocalcards = %d",
2828 (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid, er->preferlocalcards);
2832 #ifdef CS_CACHEEX
2833 // WAIT_TIME
2834 uint32_t cacheex_wait_time = 0;
2835 uint32_t wait_time_no_hitcache = 0;
2836 uint32_t wait_time_hitcache = 0;
2838 if(client->account && !client->account->no_wait_time
2839 #ifdef CS_CACHEEX_AIO
2840 && !chk_srvid_no_wait_time(er)
2841 #endif
2842 && er->preferlocalcards<2)
2844 wait_time_no_hitcache = get_cacheex_wait_time(er,NULL); // NO check hitcache. Wait_time is dwtime, or, if 0, awtime.
2845 wait_time_hitcache = get_cacheex_wait_time(er,client); // check hitcache for calculating wait_time! If hitcache wait_time is biggest value between dwtime and awtime, else it's awtime.
2848 // If "normal" client and ex1-rdr>0, we cannot use hitcache for calculating wait_time because we cannot know if cw is available or not on ex1 server!
2849 (cacheex != 1 && er->cacheex_reader_count)
2851 /* Cw for ex1-cl comes from: INT. cache by "normal" readers (normal clients that ask normal readers), ex1-rdr and ex2-rdr and ex3-rdr.
2852 * If readers, we have to wait cws generating by normal clients asking normal readers and answers by ex1-rdr (cannot use hitcache).
2853 * If no readers, use hitcache for calculating wait_time.
2855 (cacheex == 1 && er->reader_avail)
2857 { cacheex_wait_time = wait_time_no_hitcache; }
2858 else
2859 { cacheex_wait_time = wait_time_hitcache; }
2862 cs_log_dbg(D_TRACE | D_CACHEEX, "[GET_CW] wait_time %d caid %04X prov %06X srvid %04X rc %d cacheex cl mode %d ex1rdr %d", cacheex_wait_time, er->caid, er->prid, er->srvid, er->rc, cacheex, er->cacheex_reader_count);
2863 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} [get_cw] wait_time %d - client cacheex mode %d, reader avail for ecm %d, hitcache %d, preferlocalcards %d", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid, cacheex_wait_time, cacheex == 1 ? 1 : 0, er->reader_avail, wait_time_hitcache ? 1 : 0, er->preferlocalcards);
2864 // END WAIT_TIME calculation
2866 if(!cacheex_wait_time && (er->reader_count + er->fallback_reader_count) == 0)
2867 #else
2868 if((er->reader_count + er->fallback_reader_count) == 0)
2869 #endif
2871 er->rc = E_NOTFOUND;
2872 if(!er->rcEx)
2873 { er->rcEx = E2_GROUP; }
2874 snprintf(er->msglog, MSGLOGSIZE, "no matching reader");
2875 cs_log_dbg(D_LB, "{client %s, caid %04X, prid %06X, srvid %04X} [get_cw] NO Readers and NO wait_time... not_found! ", (check_client(er->client) ? er->client->account->usr : "-"), er->caid, er->prid, er->srvid);
2876 send_dcw(client, er);
2877 free_ecm(er);
2878 return;
2881 //insert it in ecmcwcache!
2882 cs_writelock(__func__, &ecmcache_lock);
2883 er->next = ecmcwcache;
2884 ecmcwcache = er;
2885 ecmcwcache_size++;
2886 cs_writeunlock(__func__, &ecmcache_lock);
2888 er->rcEx = 0;
2889 #ifdef CS_CACHEEX
2890 er->cacheex_wait_time = 0;
2891 er->cacheex_wait_time_expired = 1;
2892 er->cacheex_hitcache = 0;
2893 er->cacheex_mode1_delay = 0;
2895 if(cacheex_wait_time) // wait time for cacheex
2897 er->cacheex_wait_time = cacheex_wait_time;
2898 er->cacheex_wait_time_expired = 0;
2899 er->cacheex_hitcache = wait_time_hitcache ? 1 : 0; // usefull only when cacheex mode 1 readers answers before wait_time and we have to decide if we have to wait until wait_time expires.
2900 er->cacheex_mode1_delay = get_cacheex_mode1_delay(er);
2902 if(!er->cacheex_mode1_delay && er->cacheex_reader_count > 0)
2904 request_cw_from_readers(er, 1); // setting stop_stage=1, we request only cacheex mode 1 readers. Others are requested at cacheex timeout!
2907 else
2908 #endif
2909 request_cw_from_readers(er, 0);
2911 #ifdef WITH_DEBUG
2912 if(D_CLIENTECM & cs_dblevel)
2914 char buf[ECM_FMT_LEN];
2915 format_ecm(er, buf, ECM_FMT_LEN);
2916 cs_log_dump_dbg(D_CLIENTECM, er->ecm, er->ecmlen, "Client %s ECM dump %s", username(client), buf);
2918 #endif
2920 cw_process_thread_wakeup();
2923 int32_t ecmfmt(char *result, size_t size, uint16_t caid, uint16_t onid, uint32_t prid, uint16_t chid, uint16_t pid,
2924 uint16_t srvid, uint16_t l, char *ecmd5hex, char *csphash, char *cw, uint16_t origin_peer, uint8_t distance, char *payload, char *tier)
2926 if(!cfg.ecmfmt)
2928 if(tier && payload)
2930 return snprintf(result, size, "%04X@%06X/%04X/%04X/%02X:%s:0F06%s:%s", caid, prid, chid, srvid, l, ecmd5hex, payload, tier);
2932 else if(tier)
2934 return snprintf(result, size, "%04X@%06X/%04X/%04X/%02X:%s:%s", caid, prid, chid, srvid, l, ecmd5hex, tier);
2936 else if(payload)
2938 return snprintf(result, size, "%04X@%06X/%04X/%04X/%02X:%s:0F06%s", caid, prid, chid, srvid, l, ecmd5hex, payload);
2940 else
2942 return snprintf(result, size, "%04X@%06X/%04X/%04X/%02X:%s", caid, prid, chid, srvid, l, ecmd5hex);
2946 #define ECMFMT_NUMBER 0
2947 #define ECMFMT_STRING 1
2948 #define ECMFMT_CHAR 2
2950 uint8_t type = 0;
2951 uint32_t ivalue = 0;
2952 char *ifmt = NULL, *sfmt = NULL;
2953 char *svalue = NULL, cvalue = '\0';
2954 uint8_t hide_if_zero = 0;
2955 char *c;
2956 uint32_t s = 0;
2958 for(c = cfg.ecmfmt; *c; c++)
2960 if(*c == '0')
2962 hide_if_zero = 1;
2963 continue;
2966 sfmt = NULL;
2968 switch(*c)
2970 case 't':
2971 type = ECMFMT_STRING;
2972 svalue = tier;
2973 if(tier == NULL && !hide_if_zero)
2975 type = ECMFMT_NUMBER;
2976 ifmt = "%04X";
2977 ivalue = 0;
2979 break;
2981 case 'c':
2982 type = ECMFMT_NUMBER;
2983 ifmt = "%04X";
2984 ivalue = caid;
2985 break;
2987 case 'o':
2988 type = ECMFMT_NUMBER;
2989 ifmt = "%04X";
2990 ivalue = onid;
2991 break;
2993 case 'p':
2994 type = ECMFMT_NUMBER;
2995 ifmt = "%06X";
2996 ivalue = prid;
2997 break;
2999 case 'i':
3000 type = ECMFMT_NUMBER;
3001 ifmt = "%04X";
3002 ivalue = chid;
3003 break;
3005 case 'd':
3006 type = ECMFMT_NUMBER;
3007 ifmt = "%04X";
3008 ivalue = pid;
3009 break;
3011 case 's':
3012 type = ECMFMT_NUMBER;
3013 ifmt = "%04X";
3014 ivalue = srvid;
3015 break;
3017 case 'l':
3018 type = ECMFMT_NUMBER;
3019 ifmt = "%02X";
3020 ivalue = l;
3021 break;
3023 case 'h':
3024 type = ECMFMT_STRING;
3025 svalue = ecmd5hex;
3026 break;
3028 case 'e':
3029 type = ECMFMT_STRING;
3030 svalue = csphash;
3031 break;
3033 case 'w':
3034 type = ECMFMT_STRING;
3035 svalue = cw;
3036 break;
3038 case 'j':
3039 type = ECMFMT_NUMBER;
3040 ifmt = "%02X";
3041 ivalue = distance;
3042 break;
3044 case 'g':
3045 type = ECMFMT_NUMBER;
3046 ifmt = "%04X";
3047 ivalue = origin_peer;
3048 break;
3050 case '\\':
3051 c++;
3052 type = ECMFMT_CHAR;
3053 cvalue = *c;
3055 if(cvalue == '\0')
3056 { return s; }
3057 break;
3059 case 'y':
3060 type = ECMFMT_STRING;
3061 svalue = payload;
3062 sfmt = "0F06%.06s";
3063 if(payload == NULL && !hide_if_zero)
3065 type = ECMFMT_NUMBER;
3066 ifmt = "0F06%06X";
3067 ivalue = 0;
3069 break;
3071 case 'Y':
3072 type = ECMFMT_STRING;
3073 svalue = payload;
3074 sfmt = "0F06%s";
3075 if(payload == NULL && !hide_if_zero)
3077 type = ECMFMT_NUMBER;
3078 ifmt = "0F06%12X";
3079 ivalue = 0;
3081 break;
3083 default:
3084 type = ECMFMT_CHAR;
3085 cvalue = *c;
3086 break;
3089 if(hide_if_zero)
3091 if(type == ECMFMT_NUMBER && ivalue == 0)
3093 hide_if_zero = 0;
3094 continue;
3096 else if(type == ECMFMT_STRING && svalue == NULL)
3098 hide_if_zero = 0;
3099 continue;
3103 switch(type)
3105 case ECMFMT_NUMBER:
3106 s += snprintf(result + s, size - s, ifmt, ivalue);
3107 break;
3109 case ECMFMT_STRING:
3110 s += snprintf(result + s, size - s , sfmt != NULL ? sfmt : "%s", svalue);
3111 break;
3113 case ECMFMT_CHAR:
3114 if(size - s > 1)
3116 result[s] = cvalue;
3117 result[s+1] = '\0';
3118 s++;
3120 break;
3122 default:
3123 break;
3127 return s;
3130 int32_t format_ecm(ECM_REQUEST *ecm, char *result, size_t size)
3132 char ecmd5hex[(16*2)+1];
3133 char csphash[(4*2)+1] = { 0 };
3134 char cwhex[(16*2)+1];
3135 char *payload = NULL;
3136 char *tier = NULL;
3137 #ifdef READER_VIDEOGUARD
3138 char payload_string[(6*2)+1];
3139 char tier_string[83];
3140 struct s_ecm_answer *ea;
3142 if(ecm->selected_reader && caid_is_videoguard(ecm->selected_reader->caid) && !is_network_reader(ecm->selected_reader))
3144 for(ea = ecm->matching_rdr; ea; ea = ea->next)
3146 if(ea->tier && (ea->status & REQUEST_ANSWERED) && !is_network_reader(ea->reader))
3148 get_tiername_defaultid(ea->tier, ecm->selected_reader->caid, tier_string);
3149 tier = tier_string;
3150 break;
3154 cs_hexdump(0, ecm->selected_reader->VgLastPayload, 6, payload_string, sizeof(payload_string));
3155 payload = payload_string;
3157 #endif
3158 cs_hexdump(0, ecm->ecmd5, 16, ecmd5hex, sizeof(ecmd5hex));
3159 #ifdef CS_CACHEEX
3160 cs_hexdump(0, (void *)&ecm->csp_hash, 4, csphash, sizeof(csphash));
3161 #endif
3162 cs_hexdump(0, ecm->cw, 16, cwhex, sizeof(cwhex));
3163 #ifdef MODULE_GBOX
3164 if(check_client(ecm->client) && get_module(ecm->client)->num == R_GBOX && ecm->gbox_ecm_dist)
3165 { return ecmfmt(result, size, ecm->caid, ecm->onid, ecm->prid, ecm->chid, ecm->pid, ecm->srvid, ecm->ecmlen, ecmd5hex, csphash, cwhex, ecm->gbox_ecm_src_peer, ecm->gbox_ecm_dist, payload, tier); }
3166 else if (ecm->selected_reader && ecm->selected_reader->typ == R_GBOX && !ecm->gbox_ecm_dist)
3167 { return ecmfmt(result, size, ecm->caid, ecm->onid, ecm->prid, ecm->chid, ecm->pid, ecm->srvid, ecm->ecmlen, ecmd5hex, csphash, cwhex, ecm->selected_reader->gbox_cw_src_peer, ecm->selected_reader->currenthops, payload, tier); }
3168 else
3169 #endif
3170 return ecmfmt(result, size, ecm->caid, ecm->onid, ecm->prid, ecm->chid, ecm->pid, ecm->srvid, ecm->ecmlen, ecmd5hex, csphash, cwhex, 0,
3171 ((ecm->selected_reader && ecm->selected_reader->currenthops) ? ecm->selected_reader->currenthops : 0), payload, tier);