source: trunk/module-dvbapi.c@ 11537

Last change on this file since 11537 was 11537, checked in by nautilus7, 12 months ago

[dvbapi] Reworked "ca_pmt_cmd_id" skipping logic

According to the spec (https://www.dvb.org/resources/public/standards/En50221.V1.pdf), the "ca_pmt_cmd_id"
value shall be present inside the ES info loop. Unfortunately, each dvbapi client does each own thing. The
only reliable way to detect when this info is present in the CA PMT is to actually check its value, like it
was done in the old code.

Most boxes always send the typical value of 0x01 (ok_descrambling) and the above check works fine because
there is no descriptor_tag 0x01 to get confused with. On the contrary, for enigma2, values like 0x03 (query),
0x04 (not_selected) are possible (not yet, but soon). Skipping these higher values the same way will not work,
because descriptors with such tags can exist, so a different check is implemented for enigma2.

In practice, this commit fixes the VDR dvbapi plugin, as well as the enigma2 boxes with wrong dvbapi boxtype
setting ("none" instead on the correct "dreambox" - the setting is irrelevant now, but will make a difference
in the future, so make sure you set it correctly).

  • Property svn:eol-style set to LF
File size: 251.3 KB
Line 
1#define MODULE_LOG_PREFIX "dvbapi"
2
3#include "globals.h"
4
5#ifdef HAVE_DVBAPI
6
7#include "module-dvbapi.h"
8#include "module-cacheex.h"
9#include "module-dvbapi-azbox.h"
10#include "module-dvbapi-mca.h"
11#include "module-dvbapi-coolapi.h"
12#include "module-dvbapi-stapi.h"
13#include "module-dvbapi-chancache.h"
14#include "module-stat.h"
15#include "oscam-chk.h"
16#include "oscam-client.h"
17#include "oscam-config.h"
18#include "oscam-ecm.h"
19#include "oscam-emm.h"
20#include "oscam-files.h"
21#include "oscam-net.h"
22#include "oscam-reader.h"
23#include "oscam-string.h"
24#include "oscam-time.h"
25#include "oscam-work.h"
26#include "reader-irdeto.h"
27#include "cscrypt/md5.h"
28
29extern int32_t exit_oscam;
30
31#if defined (__CYGWIN__)
32#define F_NOTIFY 0
33#define F_SETSIG 0
34#define DN_MODIFY 0
35#define DN_CREATE 0
36#define DN_DELETE 0
37#define DN_MULTISHOT 0
38#endif
39
40static const char *get_stream_type_txt(uint8_t stream_type)
41{
42 switch(stream_type)
43 {
44 case 0x00: return "invalid";
45 case 0x01: return "MPEG-1 video";
46 case 0x02: return "MPEG-2 video"; // MPEG-1 (constrained parameter) or MPEG-2 video
47 case 0x03: return "MPEG-1 audio"; // MP1, MP2, MP3
48 case 0x04: return "MPEG-2 audio"; // MP1, MP2, MP3
49 case 0x05: return "MPEG-2 private sections";
50 case 0x06: return "MPEG-2 PES private data"; // AC-3, Enhanced AC-3, AC-4, DTS(-HD) audio, subtitles, etc (DVB) (depends on descriptor)
51 case 0x07: return "MHEG data";
52 case 0x08: return "DSM-CC data";
53 case 0x09: return "MPEG-2 over ATM data";
54 case 0x0A: return "DSM-CC data";
55 case 0x0B: return "DSM-CC data";
56 case 0x0C: return "DSM-CC data";
57 case 0x0D: return "DSM-CC data";
58 case 0x0E: return "MPEG-2 auxiliary data";
59 case 0x0F: return "MPEG-2 audio"; // AAC
60 case 0x10: return "MPEG-4 video";
61 case 0x11: return "MPEG-4 audio"; // AAC, HE AAC and AAC v2
62 case 0x12: return "MPEG-4 PES data";
63 case 0x13: return "MPEG-4 data";
64 case 0x14: return "DSM-CC data";
65 case 0x15: return "MPEG-7 MetaData";
66 case 0x16: return "MPEG-7 MetaData";
67 case 0x17: return "MPEG-7 MetaData";
68 case 0x18: return "MPEG-7 MetaData";
69 case 0x19: return "MPEG-7 MetaData";
70 case 0x1A: return "MPEG-2 IPMP data";
71 case 0x1B: return "AVC video";
72 case 0x1C: return "MPEG-4 audio"; // DST, ALS, SLS
73 case 0x24: return "HEVC video";
74 case 0x25: return "HEVC subset video";
75 case 0x2D: return "MPEG-H 3D audio"; // main stream
76 case 0x2E: return "MPEG-H 3D audio"; // auxiliary stream
77 case 0x42: return "Chinese video";
78 case 0x7F: return "IPMP data";
79 case 0x81: return "AC-3 audio (ATSC)"; // with descriptor tag 0x81
80 case 0x86: return "SCTE 35 data";
81 case 0x87: return "enhanced AC-3 audio (ATSC)";
82 //case 0x88: return "DTS-HD audio (ATSC 2.0)"; // fixme: has ATSC 2.0 ever been used?
83 //case 0x??: return "AC-4 audio (ATSC 3.0)"; // fixme: add the actual value when it gets published
84 //case 0x??: return "MPEG-H 3D audio (ATSC 3.0)"; // fixme: add the actual value when it gets published
85 case 0xD1: return "BBC Dirac video";
86 case 0xEA: return "VC-1 video";
87 default: return "user private";
88 }
89}
90
91static const char *get_descriptor_tag_txt(uint8_t descriptor_tag)
92{
93 switch(descriptor_tag)
94 {
95 // Valid in all MPEG contexts:
96 case 0x00: return "reserved";
97 case 0x01: return "forbidden";
98 case 0x02: return "video stream";
99 case 0x03: return "audio stream";
100 case 0x04: return "hierarchy";
101 case 0x05: return "registration";
102 case 0x06: return "data stream alignment";
103 case 0x07: return "target background grid";
104 case 0x08: return "video window";
105 case 0x09: return "CA";
106 case 0x0A: return "ISO 639 language";
107 case 0x0B: return "system clock";
108 case 0x0C: return "multiplex buffer utilization";
109 case 0x0D: return "copyright";
110 case 0x0E: return "maximum bitrate";
111 case 0x0F: return "private data indicator";
112 case 0x10: return "smoothing buffer";
113 case 0x11: return "STD";
114 case 0x12: return "IBP";
115 case 0x13: return "DSM-CC carousel identifier";
116 case 0x14: return "DSM-CC association tag";
117 case 0x15: return "DSM-CC deferred association tags";
118 case 0x17: return "DSM-CC NPT reference";
119 case 0x18: return "DSM-CC NPT endpoint";
120 case 0x19: return "DSM-CC stream mode";
121 case 0x1A: return "DSM-CC stream event";
122 case 0x1B: return "MPEG-4 video";
123 case 0x1C: return "MPEG-4 audio";
124 case 0x1D: return "IOD";
125 case 0x1E: return "SL";
126 case 0x1F: return "FMC";
127 case 0x20: return "External ES id";
128 case 0x21: return "MuxCode";
129 case 0x22: return "FmxBufferSize";
130 case 0x23: return "MultiplexBuffer";
131 case 0x24: return "Content labeling";
132 case 0x25: return "Metadata association";
133 case 0x26: return "Metadata";
134 case 0x27: return "Metadata STD";
135 case 0x28: return "AVC video";
136 case 0x29: return "MPEG-2 IPMP";
137 case 0x2A: return "AVC timing and HRD";
138 case 0x2B: return "MPEG-2 AAC Audio";
139 case 0x2C: return "FlexMuxTiming";
140 case 0x2D: return "MPEG-4 Text";
141 case 0x2E: return "MPEG-4 Audio Extension";
142 case 0x2F: return "Auxiliary Video Stream";
143 case 0x30: return "SVC Extension";
144 case 0x31: return "MVC Extension";
145 case 0x32: return "J2K Video";
146 case 0x33: return "MVC Operation Point";
147 case 0x34: return "MPEG-2 Stereoscopic Video Format";
148 case 0x35: return "Stereoscopic Program Info";
149 case 0x36: return "Stereoscopic Video Info";
150 case 0x37: return "Transport Profile";
151 case 0x38: return "HEVC Video";
152 case 0x3F: return "MPEG-2 Extension";
153 // Valid in DVB context:
154 case 0x45: return "VBI data";
155 case 0x46: return "VBI teletext";
156 case 0x51: return "mosaic";
157 case 0x52: return "stream identifier";
158 case 0x56: return "teletext";
159 case 0x59: return "subtitling"; // with stream type 0x06
160 case 0x5F: return "private data specifier";
161 case 0x60: return "service move";
162 case 0x65: return "scrambling";
163 case 0x66: return "data broadcast id";
164 case 0x6A: return "AC-3"; // with stream type 0x06
165 case 0x6B: return "ancillary data";
166 case 0x6F: return "application signalling";
167 case 0x70: return "adaptation field data";
168 case 0x74: return "related content";
169 case 0x78: return "ECM repetition rate";
170 case 0x7A: return "enhanced AC-3"; // with stream type 0x06
171 case 0x7B: return "DTS"; // with stream type 0x06
172 case 0x7C: return "AAC"; // with stream type 0x06
173 case 0x7D: return "XAIT location";
174 case 0x7F: return "DVB extension";
175 default: return "user private";
176 }
177}
178
179static const char *get_extension_descriptor_txt(uint8_t extension_tag)
180{
181 switch(extension_tag)
182 {
183 case 0x02: return "CP";
184 case 0x06: return "supplementary audio";
185 case 0x0E: return "DTS-HD"; // with stream type 0x06
186 case 0x0F: return "DTS Neural"; // with stream type 0x06
187 case 0x11: return "T2MI";
188 case 0x13: return "URI linkage";
189 case 0x15: return "AC-4"; // with stream type 0x06
190 case 0x18: return "protection message";
191 case 0x19: return "audio preselection";
192 case 0x20: return "TTML subtitling"; // (could become 0x1A, value in A038 draft seems weird)
193 default: return "Undefined";
194 }
195}
196
197void flush_read_fd(int32_t demux_id, int32_t num, int fd)
198{
199 if(!cfg.dvbapi_listenport && cfg.dvbapi_boxtype != BOXTYPE_PC_NODMX)
200 {
201 cs_log_dbg(D_DVBAPI,"Demuxer %d flushing stale input data of filter %d (fd:%d)", demux_id, num + 1, fd);
202
203 fd_set rd;
204 struct timeval t;
205 char buff[100];
206
207 t.tv_sec = 0;
208 t.tv_usec = 0;
209
210 FD_ZERO(&rd);
211 FD_SET(fd, &rd);
212
213 while(select(fd + 1, &rd, NULL, NULL, &t) > 0)
214 {
215 if(read(fd, buff, 100)) { ; }
216 }
217 }
218}
219
220static int dvbapi_ioctl(int fd, uint32_t request, ...)
221{
222 int ret = 0;
223 va_list args;
224 va_start(args, request);
225 if(!(cfg.dvbapi_boxtype == BOXTYPE_SAMYGO))
226 {
227 void *param = va_arg(args, void *);
228 ret = ioctl(fd, request, param);
229 }
230 else
231 {
232 switch(request)
233 {
234 case DMX_SET_FILTER:
235 {
236 struct dmx_sct_filter_params *sFP = va_arg(args, struct dmx_sct_filter_params *);
237 //fix filter for samygo
238 //note: we only have 14 available filter bytes (instead of 16) on samygo
239 memmove(&sFP->filter.filter[3], &sFP->filter.filter[1], 13);
240 memset(&sFP->filter.filter[1], 0, 2);
241 memmove(&sFP->filter.mask[3], &sFP->filter.mask[1], 13);
242 memset(&sFP->filter.mask[1], 0, 2);
243 // prepare packet
244 uint8_t packet[sizeof(request) + sizeof(struct dmx_sct_filter_params)];
245 memcpy(&packet, &request, sizeof(request));
246 memcpy(&packet[sizeof(request)], sFP, sizeof(struct dmx_sct_filter_params));
247 ret = send(fd, packet, sizeof(packet), 0);
248 break;
249 }
250
251 case DMX_SET_FILTER1:
252 {
253 cs_log("error: samygo does not support DMX_SET_FILTER1");
254 ret = -1;
255 break;
256 }
257
258 case DMX_STOP:
259 {
260 ret = send(fd, &request, sizeof(request), 0);
261 ret = 1;
262 break;
263 }
264
265 case CA_GET_DESCR_INFO:
266 {
267 ca_descr_info_t *ca_descr_info = va_arg(args, ca_descr_info_t *);
268 // preparing packet
269 uint8_t packet[sizeof(request) + sizeof(ca_descr_info_t)];
270 memcpy(&packet[0], &request, sizeof(request));
271 memcpy(&packet[sizeof(request)], ca_descr_info, sizeof(ca_descr_info_t));
272 // sending data to UDP
273 ret = send(fd, &packet[0], sizeof(packet), 0);
274 break;
275 }
276
277 case CA_SET_DESCR:
278 {
279 ca_descr_t *ca_descr = va_arg(args, ca_descr_t *);
280 // preparing packet
281 uint8_t packet[sizeof(request) + sizeof(ca_descr_t)];
282 memcpy(&packet[0], &request, sizeof(request));
283 memcpy(&packet[sizeof(request)], ca_descr, sizeof(ca_descr_t));
284 // sending data to UDP
285 ret = send(fd, &packet[0], sizeof(packet), 0);
286 break;
287 }
288
289 case CA_SET_PID:
290 {
291 ca_pid_t *ca_pid2 = va_arg(args, ca_pid_t *);
292 // preparing packet
293 uint8_t packet[sizeof(request) + sizeof(ca_pid_t)];
294 memcpy(&packet[0], &request, sizeof(request));
295 memcpy(&packet[sizeof(request)], ca_pid2, sizeof(ca_pid_t));
296 // sending data to UDP
297 ret = send(fd, &packet[0], sizeof(packet), 0);
298 break;
299 }
300
301 case CA_SET_DESCR_MODE:
302 {
303 cs_log("error: samygo does not support CA_SET_DESCR_MODE");
304 ret = -1;
305 break;
306 }
307
308 case CA_SET_DESCR_DATA:
309 {
310 cs_log("error: samygo does not support CA_SET_DESCR_DATA");
311 ret = -1;
312 break;
313 }
314 }
315
316 if(ret > 0) // send() may return larger than 1
317 {
318 ret = 1;
319 }
320 }
321#if defined(__powerpc__)
322 // Old dm500 boxes (ppc old) are using broken kernel, se we need some fixups
323 switch (request)
324 {
325 case DMX_STOP:
326 case CA_SET_DESCR:
327 case CA_SET_PID:
328 ret = 1;
329 }
330#endif
331 // FIXME: Workaround for su980 bug
332 // See: http://www.streamboard.tv/wbb2/thread.php?postid=533940
333 if(boxtype_is("su980"))
334 {
335 ret = 1;
336 }
337 va_end(args);
338 return ret;
339}
340
341// tunemm_caid_map
342#define FROM_TO 0
343#define TO_FROM 1
344
345int32_t pausecam = 0, disable_pmt_files = 0;
346
347DEMUXTYPE demux[MAX_DEMUX];
348struct s_dvbapi_priority *dvbapi_priority;
349struct s_client *dvbapi_client;
350
351const char *boxdesc[] = { "none", "dreambox", "duckbox", "ufs910", "dbox2", "ipbox", "ipbox-pmt",
352 "dm7000", "qboxhd", "coolstream", "neumo", "pc", "pc-nodmx", "samygo" };
353
354// when updating devices[BOX_COUNT] make sure to update these index defines
355#define BOX_INDEX_QBOXHD 0
356#define BOX_INDEX_DREAMBOX_DVBAPI3 1
357#define BOX_INDEX_COOLSTREAM 6
358
359static const struct box_devices devices[BOX_COUNT] =
360{
361 /* QboxHD (dvb-api-3)*/ { "/tmp/virtual_adapter/", "ca%d", "demux%d", "/tmp/camd.socket", DVBAPI_3 },
362 /* dreambox (dvb-api-3)*/ { "/dev/dvb/adapter%d/", "ca%d", "demux%d", "/tmp/camd.socket", DVBAPI_3 },
363 /* wetek (dvb-api-3)*/ { "/dev/dvb%d.", "ca%d", "demux%d", "/tmp/camd.socket", DVBAPI_3 },
364 /* dreambox (dvb-api-1)*/ { "/dev/dvb/card%d/", "ca%d", "demux%d", "/tmp/camd.socket", DVBAPI_1 },
365 /* neumo (dvb-api-1)*/ { "/dev/", "demuxapi", "demuxapi", "/tmp/camd.socket", DVBAPI_1 },
366#ifdef WITH_STAPI5
367 /* sh4 (stapi5)*/ { "/dev/stapi/", "stpti5_ioctl", "stpti5_ioctl", "/tmp/camd.socket", STAPI },
368#else
369 /* sh4 (stapi)*/ { "/dev/stapi/", "stpti4_ioctl", "stpti4_ioctl", "/tmp/camd.socket", STAPI },
370#endif
371 /* coolstream*/ { "/dev/cnxt/", "null", "null", "/tmp/camd.socket", COOLAPI },
372};
373
374static int32_t selected_box = -1;
375static int32_t selected_api = -1;
376static int32_t maxfilter = MAX_FILTER;
377static int32_t dir_fd = -1;
378static uint16_t last_client_proto_version = 0;
379static char *last_client_name = NULL;
380static uint32_t ca_descramblers_total = 0; // total number of available descramblers in box
381static uint32_t ca_descramblers_used = 0; // total number of used descramblers during decoding
382static int32_t ca_fd[CA_MAX]; // holds fd handle of all ca devices (0 not in use)
383static LLIST *ll_activestreampids; // list of all enabled streampids on ca devices
384static int32_t unassoc_fd[MAX_DEMUX];
385
386bool is_dvbapi_usr(char *usr)
387{
388 return streq(cfg.dvbapi_usr, usr);
389}
390
391struct s_emm_filter
392{
393 int32_t demux_id;
394 uint8_t filter[32];
395 uint16_t caid;
396 uint32_t provid;
397 uint16_t pid;
398 uint32_t num;
399 struct timeb time_started;
400};
401
402static LLIST *ll_emm_active_filter;
403static LLIST *ll_emm_inactive_filter;
404static LLIST *ll_emm_pending_filter;
405
406int32_t add_emmfilter_to_list(int32_t demux_id, uint8_t *filter, uint16_t caid, uint32_t provid, uint16_t emmpid, int32_t num, bool enable)
407{
408 if(!ll_emm_active_filter)
409 {
410 ll_emm_active_filter = ll_create("ll_emm_active_filter");
411 }
412
413 if(!ll_emm_inactive_filter)
414 {
415 ll_emm_inactive_filter = ll_create("ll_emm_inactive_filter");
416 }
417
418 if(!ll_emm_pending_filter)
419 {
420 ll_emm_pending_filter = ll_create("ll_emm_pending_filter");
421 }
422
423 struct s_emm_filter *filter_item;
424 if(!cs_malloc(&filter_item, sizeof(struct s_emm_filter)))
425 {
426 return 0;
427 }
428
429 filter_item->demux_id = demux_id;
430 memcpy(filter_item->filter, filter, 32);
431 filter_item->caid = caid;
432 filter_item->provid = provid;
433 filter_item->pid = emmpid;
434 filter_item->num = num;
435
436 if(enable)
437 {
438 cs_ftime(&filter_item->time_started);
439 }
440 else
441 {
442 memset(&filter_item->time_started, 0, sizeof(filter_item->time_started));
443 }
444
445 if(num > 0)
446 {
447 ll_append(ll_emm_active_filter, filter_item);
448 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d added to active emmfilters (CAID %04X PROVID %06X EMMPID %04X)",
449 filter_item->demux_id, filter_item->num, filter_item->caid, filter_item->provid, filter_item->pid);
450 }
451 else if(num < 0)
452 {
453 ll_append(ll_emm_pending_filter, filter_item);
454 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter added to pending emmfilters (CAID %04X PROVID %06X EMMPID %04X)",
455 filter_item->demux_id, filter_item->caid, filter_item->provid, filter_item->pid);
456 }
457 else
458 {
459 ll_append(ll_emm_inactive_filter, filter_item);
460 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter added to inactive emmfilters (CAID %04X PROVID %06X EMMPID %04X)",
461 filter_item->demux_id, filter_item->caid, filter_item->provid, filter_item->pid);
462 }
463 return 1;
464}
465
466int32_t is_emmfilter_in_list_internal(LLIST *ll, uint8_t *filter, uint16_t emmpid, uint32_t provid, uint16_t caid)
467{
468 struct s_emm_filter *filter_item;
469 LL_ITER itr;
470 if(ll_count(ll) > 0)
471 {
472 itr = ll_iter_create(ll);
473 while((filter_item = ll_iter_next(&itr)) != NULL)
474 {
475 if(!memcmp(filter_item->filter, filter, 32) && (filter_item->pid == emmpid)
476 && (filter_item->provid == provid) && (filter_item->caid == caid))
477 {
478 return 1;
479 }
480 }
481 }
482 return 0;
483}
484
485int32_t is_emmfilter_in_list(uint8_t *filter, uint16_t emmpid, uint32_t provid, uint16_t caid)
486{
487 if(!ll_emm_active_filter)
488 {
489 ll_emm_active_filter = ll_create("ll_emm_active_filter");
490 }
491
492 if(!ll_emm_inactive_filter)
493 {
494 ll_emm_inactive_filter = ll_create("ll_emm_inactive_filter");
495 }
496
497 if(!ll_emm_pending_filter)
498 {
499 ll_emm_pending_filter = ll_create("ll_emm_pending_filter");
500 }
501
502 if(is_emmfilter_in_list_internal(ll_emm_active_filter, filter, emmpid, provid, caid)
503 || is_emmfilter_in_list_internal(ll_emm_inactive_filter, filter, emmpid, provid, caid)
504 || is_emmfilter_in_list_internal(ll_emm_pending_filter, filter, emmpid, provid, caid))
505 {
506 return 1;
507 }
508 return 0;
509}
510
511struct s_emm_filter *get_emmfilter_by_filternum_internal(LLIST *ll, int32_t demux_id, uint32_t num)
512{
513 struct s_emm_filter *filter;
514 LL_ITER itr;
515 if(ll_count(ll) > 0)
516 {
517 itr = ll_iter_create(ll);
518 while((filter = ll_iter_next(&itr)))
519 {
520 if(filter->demux_id == demux_id && filter->num == num)
521 {
522 return filter;
523 }
524 }
525 }
526 return NULL;
527}
528
529struct s_emm_filter *get_emmfilter_by_filternum(int32_t demux_id, uint32_t num)
530{
531 if(!ll_emm_active_filter)
532 {
533 ll_emm_active_filter = ll_create("ll_emm_active_filter");
534 }
535
536 if(!ll_emm_inactive_filter)
537 {
538 ll_emm_inactive_filter = ll_create("ll_emm_inactive_filter");
539 }
540
541 if(!ll_emm_pending_filter)
542 {
543 ll_emm_pending_filter = ll_create("ll_emm_pending_filter");
544 }
545
546 struct s_emm_filter *emm_filter = NULL;
547
548 emm_filter = get_emmfilter_by_filternum_internal(ll_emm_active_filter, demux_id, num);
549 if(emm_filter)
550 {
551 return emm_filter;
552 }
553
554 emm_filter = get_emmfilter_by_filternum_internal(ll_emm_inactive_filter, demux_id, num);
555 if(emm_filter)
556 {
557 return emm_filter;
558 }
559
560 emm_filter = get_emmfilter_by_filternum_internal(ll_emm_pending_filter, demux_id, num);
561 if(emm_filter)
562 {
563 return emm_filter;
564 }
565
566 return NULL;
567}
568
569int8_t remove_emmfilter_from_list_internal(LLIST *ll, int32_t demux_id, uint16_t caid, uint32_t provid, uint16_t pid, uint32_t num)
570{
571 struct s_emm_filter *filter;
572 LL_ITER itr;
573
574 if(ll_count(ll) > 0)
575 {
576 itr = ll_iter_create(ll);
577 while((filter = ll_iter_next(&itr)))
578 {
579 if(filter->demux_id == demux_id && filter->caid == caid && filter->provid == provid && filter->pid == pid && filter->num == num)
580 {
581 ll_iter_remove_data(&itr);
582 return 1;
583 }
584 }
585 }
586 return 0;
587}
588
589void remove_emmfilter_from_list(int32_t demux_id, uint16_t caid, uint32_t provid, uint16_t pid, uint32_t num)
590{
591 if((ll_emm_active_filter && remove_emmfilter_from_list_internal(ll_emm_active_filter, demux_id, caid, provid, pid, num))
592 || (ll_emm_inactive_filter && remove_emmfilter_from_list_internal(ll_emm_inactive_filter, demux_id, caid, provid, pid, num))
593 || (ll_emm_pending_filter && remove_emmfilter_from_list_internal(ll_emm_pending_filter, demux_id, caid, provid, pid, num)))
594 {
595 return;
596 }
597}
598
599void dvbapi_net_add_str(uint8_t *packet, int *size, const char *str)
600{
601 uint8_t *str_len = &packet[*size]; // string length
602 *size += 1;
603 *str_len = snprintf((char *) &packet[*size], DVBAPI_MAX_PACKET_SIZE - *size, "%s", str);
604 *size += *str_len;
605}
606
607int32_t dvbapi_net_send(uint32_t request, int32_t socket_fd, uint32_t msgid, int32_t demux_id,
608 uint32_t filter_number, uint8_t *data, struct s_client *client, ECM_REQUEST *er, uint16_t client_proto_version)
609{
610 uint8_t packet[DVBAPI_MAX_PACKET_SIZE]; // maximum possible packet size
611 int32_t size = 0;
612 uint32_t u32;
613
614 // not connected?
615 if(socket_fd <= 0)
616 {
617 return 0;
618 }
619
620 // preparing packet - header
621 // in old protocol client expect this first byte as adapter index,
622 // changed in the new protocol to be always after request type (opcode)
623 if(client_proto_version <= 0)
624 {
625 packet[size++] = demux[demux_id].adapter_index; // adapter index - 1 byte
626 }
627 else if(client_proto_version >= 3)
628 {
629 packet[size++] = 0xa5; // message start
630 u32 = htonl(msgid);
631 memcpy(&packet[size], &u32, 4);
632 size += 4;
633 }
634
635 // type of request
636 u32 = request;
637 if(client_proto_version >= 1)
638 {
639 u32 = htonl(u32);
640 }
641 memcpy(&packet[size], &u32, 4);
642 size += 4;
643
644 // preparing packet - adapter index for proto >= 1
645 if((request != DVBAPI_SERVER_INFO) && client_proto_version >= 1)
646 {
647 packet[size++] = demux[demux_id].adapter_index; // adapter index - 1 byte
648 }
649
650 // struct with data
651 switch(request)
652 {
653 case DVBAPI_SERVER_INFO:
654 {
655 int16_t proto_version = htons(DVBAPI_PROTOCOL_VERSION); // our protocol version
656 char capabilities[128] = "\x00"; // two zero characters
657 memcpy(&packet[size], &proto_version, 2);
658 size += 2;
659 uint8_t *info_len = &packet[size]; // info string length
660 size += 1;
661
662 if(cfg.dvbapi_extended_cw_api == 1)
663 {
664 strcat(capabilities, ",e1mk"); // extended cw, key follows mode - supports CSA, DES, AES128
665 }
666
667 if(cfg.dvbapi_extended_cw_api == 2)
668 {
669 strcat(capabilities, ",e2"); // usage of DES algo signalled through PID index - CSA and DES only
670 }
671
672 *info_len = snprintf((char *) &packet[size], sizeof(packet) - size, "OSCam v%s, build r%s (%s); %s",
673 CS_VERSION, CS_SVN_VERSION, CS_TARGET, capabilities + 1);
674
675 size += *info_len;
676 break;
677 }
678
679 case DVBAPI_ECM_INFO:
680 {
681 if(er->rc >= E_NOTFOUND)
682 {
683 return 0;
684 }
685
686 int8_t hops = 0;
687
688 uint16_t sid = htons(er->srvid); // service ID (program number)
689 memcpy(&packet[size], &sid, 2);
690 size += 2;
691
692 uint16_t caid = htons(er->caid); // CAID
693 memcpy(&packet[size], &caid, 2);
694 size += 2;
695
696 uint16_t pid = htons(er->pid); // PID
697 memcpy(&packet[size], &pid, 2);
698 size += 2;
699
700 uint32_t prid = htonl(er->prid); // Provider ID
701 memcpy(&packet[size], &prid, 4);
702 size += 4;
703
704 uint32_t ecmtime = htonl(client->cwlastresptime); // ECM time
705 memcpy(&packet[size], &ecmtime, 4);
706 size += 4;
707
708 dvbapi_net_add_str(packet, &size, get_cardsystem_desc_by_caid(er->caid)); // cardsystem name
709
710 switch (er->rc)
711 {
712 case E_FOUND:
713 if(er->selected_reader)
714 {
715 dvbapi_net_add_str(packet, &size, er->selected_reader->label); // reader
716 if(is_network_reader(er->selected_reader))
717 {
718 dvbapi_net_add_str(packet, &size, er->selected_reader->device); // from
719 }
720 else
721 {
722 dvbapi_net_add_str(packet, &size, "local"); // from
723 }
724 dvbapi_net_add_str(packet, &size, reader_get_type_desc(er->selected_reader, 1)); // protocol
725 hops = er->selected_reader->currenthops;
726 }
727 break;
728
729 case E_CACHE1:
730 dvbapi_net_add_str(packet, &size, "Cache"); // reader
731 dvbapi_net_add_str(packet, &size, "cache1"); // from
732 dvbapi_net_add_str(packet, &size, "none"); // protocol
733 break;
734
735 case E_CACHE2:
736 dvbapi_net_add_str(packet, &size, "Cache"); // reader
737 dvbapi_net_add_str(packet, &size, "cache2"); // from
738 dvbapi_net_add_str(packet, &size, "none"); // protocol
739 break;
740
741 case E_CACHEEX:
742 dvbapi_net_add_str(packet, &size, "Cache"); // reader
743 dvbapi_net_add_str(packet, &size, "cache3"); // from
744 dvbapi_net_add_str(packet, &size, "none"); // protocol
745 break;
746 }
747 packet[size++] = hops; // hops
748 break;
749 }
750
751 case DVBAPI_CA_GET_DESCR_INFO:
752 {
753 int sct_cadescr_info_size = sizeof(ca_descr_info_t);
754 if(client_proto_version >= 1)
755 {
756 ca_descr_info_t *cadescr_info = (ca_descr_info_t *) data;
757 cadescr_info->num = htonl(cadescr_info->num);
758 cadescr_info->type = htonl(cadescr_info->type);
759 }
760 memcpy(&packet[size], data, sct_cadescr_info_size);
761 size += sct_cadescr_info_size;
762 break;
763 }
764
765 case DVBAPI_CA_SET_DESCR:
766 {
767 int sct_cadescr_size = sizeof(ca_descr_t);
768 if(client_proto_version >= 1)
769 {
770 ca_descr_t *cadesc = (ca_descr_t *) data;
771 cadesc->index = htonl(cadesc->index);
772 cadesc->parity = htonl(cadesc->parity);
773 }
774 memcpy(&packet[size], data, sct_cadescr_size);
775 size += sct_cadescr_size;
776 break;
777 }
778
779 case DVBAPI_CA_SET_PID:
780 {
781 int sct_capid_size = sizeof(ca_pid_t);
782 if(client_proto_version >= 1)
783 {
784 ca_pid_t *capid = (ca_pid_t *) data;
785 capid->pid = htonl(capid->pid);
786 capid->index = htonl(capid->index);
787 }
788 memcpy(&packet[size], data, sct_capid_size);
789 size += sct_capid_size;
790 break;
791 }
792
793 case DVBAPI_CA_SET_DESCR_MODE:
794 {
795 int sct_cadescr_mode_size = sizeof(ca_descr_mode_t);
796 if(client_proto_version >= 1)
797 {
798 ca_descr_mode_t *cadesc_mode = (ca_descr_mode_t *) data;
799 cadesc_mode->index = htonl(cadesc_mode->index);
800 cadesc_mode->algo = htonl(cadesc_mode->algo);
801 cadesc_mode->cipher_mode = htonl(cadesc_mode->cipher_mode);
802 }
803 memcpy(&packet[size], data, sct_cadescr_mode_size);
804 size += sct_cadescr_mode_size;
805 break;
806 }
807
808 case DVBAPI_CA_SET_DESCR_DATA:
809 {
810 ca_descr_data_t *cadesc_data = (ca_descr_data_t *) data;
811 uint32_t length = cadesc_data->length;
812 if(client_proto_version >= 1)
813 {
814 cadesc_data->index = htonl(cadesc_data->index);
815 cadesc_data->parity = htonl(cadesc_data->parity);
816 cadesc_data->data_type = htonl(cadesc_data->data_type);
817 cadesc_data->length = htonl(cadesc_data->length);
818 }
819 memcpy(&packet[size], &cadesc_data->index, 4);
820 memcpy(&packet[size + 4], &cadesc_data->parity, 4);
821 memcpy(&packet[size + 8], &cadesc_data->data_type, 4);
822 memcpy(&packet[size + 12], &cadesc_data->length, 4);
823 memcpy(&packet[size + 16], cadesc_data->data, length);
824 size += 16 + length;
825 break;
826 }
827
828 case DVBAPI_DMX_SET_FILTER:
829 case DVBAPI_DMX_STOP:
830 {
831 int32_t sct_filter_size = sizeof(struct dmx_sct_filter_params);
832 packet[size++] = demux_id; // demux id - 1 byte
833 packet[size++] = filter_number; // filter number - 1 byte
834 if(data) // filter data when starting
835 {
836 if(client_proto_version >= 1)
837 {
838 struct dmx_sct_filter_params *fp = (struct dmx_sct_filter_params *)data;
839 // adding all dmx_sct_filter_params structure fields
840 // one by one to avoid padding problems
841 uint16_t pid = htons(fp->pid);
842 memcpy(&packet[size], &pid, 2);
843 size += 2;
844 memcpy(&packet[size], fp->filter.filter, 16);
845 size += 16;
846 memcpy(&packet[size], fp->filter.mask, 16);
847 size += 16;
848 memcpy(&packet[size], fp->filter.mode, 16);
849 size += 16;
850 uint32_t timeout = htonl(fp->timeout);
851 memcpy(&packet[size], &timeout, 4);
852 size += 4;
853 uint32_t flags = htonl(fp->flags);
854 memcpy(&packet[size], &flags, 4);
855 size += 4;
856 }
857 else
858 {
859 memcpy(&packet[size], data, sct_filter_size); // dmx_sct_filter_params struct
860 size += sct_filter_size;
861 }
862 }
863 else // pid when stopping
864 {
865 if(client_proto_version >= 1)
866 {
867 uint16_t pid = htons(demux[demux_id].demux_fd[filter_number].pid);
868 memcpy(&packet[size], &pid, 2);
869 size += 2;
870 }
871 else
872 {
873 uint16_t pid = demux[demux_id].demux_fd[filter_number].pid;
874 packet[size++] = pid >> 8;
875 packet[size++] = pid & 0xff;
876 }
877 }
878 break;
879 }
880
881 default: // unknown request
882 {
883 cs_log("ERROR: dvbapi_net_send: invalid request");
884 return 0;
885 }
886 }
887 // sending
888 cs_log_dump_dbg(D_DVBAPI, packet, size, "Sending packet to dvbapi client (fd=%d):", socket_fd);
889 send(socket_fd, &packet, size, MSG_DONTWAIT);
890 // always returning success as the client could close socket
891 return 0;
892}
893
894int32_t dvbapi_set_filter(int32_t demux_id, int32_t api, uint16_t pid, uint16_t caid, uint32_t provid,
895 uint8_t *filt, uint8_t *mask, int32_t timeout, int32_t pidindex, int32_t type, int8_t add_to_emm_list)
896{
897 int32_t ret = -1, n = -1, i, filterfd = -1;
898
899 for(i = 0; i < maxfilter && demux[demux_id].demux_fd[i].fd > 0; i++) { ; }
900
901 if(i >= maxfilter)
902 {
903 cs_log_dbg(D_DVBAPI, "no free filter");
904 return -1;
905 }
906 n = i;
907
908 if(USE_OPENXCAS)
909 {
910 if(type == TYPE_ECM)
911 {
912 openxcas_set_caid(demux[demux_id].ECMpids[pidindex].CAID);
913 openxcas_set_ecm_pid(pid);
914 }
915
916 demux[demux_id].demux_fd[n].fd = DUMMY_FD;
917 demux[demux_id].demux_fd[n].pidindex = pidindex;
918 demux[demux_id].demux_fd[n].pid = pid;
919 demux[demux_id].demux_fd[n].caid = caid;
920 demux[demux_id].demux_fd[n].provid = provid;
921 demux[demux_id].demux_fd[n].type = type;
922 memcpy(demux[demux_id].demux_fd[n].filter, filt, 16); // copy filter to check later on if receiver delivered accordingly
923 memcpy(demux[demux_id].demux_fd[n].mask, mask, 16); // copy mask to check later on if receiver delivered accordingly
924 return 1;
925 }
926
927 switch(api)
928 {
929 case DVBAPI_3:
930 {
931 if(cfg.dvbapi_listenport || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
932 {
933 ret = filterfd = DUMMY_FD;
934 }
935 else
936 {
937 ret = filterfd = dvbapi_open_device(0, demux[demux_id].demux_index, demux[demux_id].adapter_index);
938 }
939
940 if(ret < 0)
941 {
942 return ret; // return if device cant be opened!
943 }
944
945 struct dmx_sct_filter_params sFP2;
946 memset(&sFP2, 0, sizeof(sFP2));
947 sFP2.pid = pid;
948 sFP2.timeout = timeout;
949 sFP2.flags = DMX_IMMEDIATE_START;
950
951 if(cfg.dvbapi_boxtype == BOXTYPE_NEUMO)
952 {
953 //DeepThought: on dgs/cubestation and neumo images, perhaps others
954 //the following code is needed to descramble
955 sFP2.filter.filter[0] = filt[0];
956 sFP2.filter.mask[0] = mask[0];
957 sFP2.filter.filter[1] = 0;
958 sFP2.filter.mask[1] = 0;
959 sFP2.filter.filter[2] = 0;
960 sFP2.filter.mask[2] = 0;
961 memcpy(sFP2.filter.filter + 3, filt + 1, 16 - 3);
962 memcpy(sFP2.filter.mask + 3, mask + 1, 16 - 3);
963
964 //DeepThought: in the drivers of the dgs/cubestation and neumo images,
965 //dvbapi 1 and 3 are somehow mixed. In the kernel drivers, the DMX_SET_FILTER
966 //ioctl expects to receive a dmx_sct_filter_params structure (DVBAPI 3) but
967 //due to a bug its sets the "positive mask" wrongly (they should be all 0).
968 //On the other hand, the DMX_SET_FILTER1 ioctl also uses the dmx_sct_filter_params
969 //structure, which is incorrect (it should be dmxSctFilterParams).
970 //The only way to get it right is to call DMX_SET_FILTER1 with the argument
971 //expected by DMX_SET_FILTER. Otherwise, the timeout parameter is not passed correctly.
972 ret = dvbapi_ioctl(filterfd, DMX_SET_FILTER1, &sFP2);
973 }
974 else
975 {
976 memcpy(sFP2.filter.filter, filt, 16);
977 memcpy(sFP2.filter.mask, mask, 16);
978 if(cfg.dvbapi_listenport || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
979 {
980 ret = dvbapi_net_send(DVBAPI_DMX_SET_FILTER,
981 demux[demux_id].socket_fd,
982 0,
983 demux_id,
984 n,
985 (uint8_t *) &sFP2,
986 NULL,
987 NULL,
988 demux[demux_id].client_proto_version);
989 }
990 else
991 {
992 ret = dvbapi_ioctl(filterfd, DMX_SET_FILTER, &sFP2);
993 }
994 }
995 break;
996 }
997
998 case DVBAPI_1:
999 {
1000 ret = filterfd = dvbapi_open_device(0, demux[demux_id].demux_index, demux[demux_id].adapter_index);
1001 if(ret < 0) { return ret; } // return if device cant be opened!
1002
1003 struct dmxSctFilterParams sFP1;
1004 memset(&sFP1, 0, sizeof(sFP1));
1005 sFP1.pid = pid;
1006 sFP1.timeout = timeout;
1007 sFP1.flags = DMX_IMMEDIATE_START;
1008 memcpy(sFP1.filter.filter, filt, 16);
1009 memcpy(sFP1.filter.mask, mask, 16);
1010 ret = dvbapi_ioctl(filterfd, DMX_SET_FILTER1, &sFP1);
1011 break;
1012 }
1013
1014#if defined(WITH_STAPI) || defined(WITH_STAPI5)
1015 case STAPI:
1016 {
1017 ret = filterfd = stapi_set_filter(demux_id, pid, filt, mask, n, demux[demux_id].pmt_file);
1018 if(ret <= 0)
1019 {
1020 ret = -1; // error setting filter!
1021 }
1022 break;
1023 }
1024#endif
1025
1026#if defined WITH_COOLAPI || defined WITH_COOLAPI2
1027 case COOLAPI:
1028 {
1029 ret = filterfd = coolapi_open_device(demux[demux_id].demux_index, demux_id);
1030 if(ret > 0)
1031 {
1032 ret = coolapi_set_filter(filterfd, n, pid, filt, mask, type);
1033 }
1034 else
1035 {
1036 ret = -1; // fail
1037 }
1038 break;
1039 }
1040#endif
1041
1042 default:
1043 break;
1044 }
1045
1046 if(ret != -1) // filter set successful
1047 {
1048 // only register if filter was set successful
1049 demux[demux_id].demux_fd[n].fd = filterfd;
1050 demux[demux_id].demux_fd[n].pidindex = pidindex;
1051 demux[demux_id].demux_fd[n].pid = pid;
1052 demux[demux_id].demux_fd[n].caid = caid;
1053 demux[demux_id].demux_fd[n].provid = provid;
1054 demux[demux_id].demux_fd[n].type = type;
1055
1056 // copy filter and mask to check later on if receiver delivered accordingly
1057 memcpy(demux[demux_id].demux_fd[n].filter, filt, 16);
1058 memcpy(demux[demux_id].demux_fd[n].mask, mask, 16);
1059
1060 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d started successfully (caid %04X provid %06X pid %04X)",
1061 demux_id, n + 1, caid, provid, pid);
1062
1063 if(type == TYPE_EMM && add_to_emm_list)
1064 {
1065 add_emmfilter_to_list(demux_id, filt, caid, provid, pid, n + 1, true);
1066 }
1067 }
1068 else
1069 {
1070 cs_log("ERROR: Could not start demux filter (api: %d errno=%d %s)", selected_api, errno, strerror(errno));
1071 }
1072 return ret;
1073}
1074
1075/*
1076 * Get number of available descramblers from box. On success, it stores result on
1077 * global variable "ca_descramblers_total". On failure, it uses a safe default value.
1078 */
1079static int32_t dvbapi_get_descrambler_info(void)
1080{
1081 // In enigma2 all ca devices are listed under adapter0. In addition we only
1082 // need to ask one ca device to get the total number of descramblers. In
1083 // PC installations, there are no ca devices, so we use a predefined value.
1084
1085 if(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
1086 {
1087 ca_descramblers_total = INDEX_MAX_NET;
1088 return 1; // nothing else to do for PCs
1089 }
1090
1091 int32_t fd = 0, ca_offset = 0;
1092 char device_path[128], device_path2[128];
1093 struct ca_descr_info descr_info;
1094 memset(&descr_info, 0, sizeof(descr_info));
1095
1096 // Use a safe default in case we fail to get the exact number
1097 ca_descramblers_total = INDEX_MAX_LOCAL;
1098
1099 if(cfg.dvbapi_boxtype == BOXTYPE_DUCKBOX ||
1100 cfg.dvbapi_boxtype == BOXTYPE_DBOX2 ||
1101 cfg.dvbapi_boxtype == BOXTYPE_UFS910)
1102 {
1103 ca_offset = 1;
1104 }
1105
1106 // Ask device for exact number of ca descramblers
1107 snprintf(device_path2, sizeof(device_path2), devices[selected_box].ca_device, ca_offset);
1108 snprintf(device_path, sizeof(device_path), devices[selected_box].path, 0);
1109 strncat(device_path, device_path2, sizeof(device_path) - strlen(device_path));
1110
1111 if((fd = open(device_path, O_RDWR | O_NONBLOCK)) < 0)
1112 {
1113 cs_log("ERROR: Can't open device %s (errno=%d %s)", device_path, errno, strerror(errno));
1114 return 0;
1115 }
1116
1117 if(dvbapi_ioctl(fd, CA_GET_DESCR_INFO, &descr_info) < 0)
1118 {
1119 cs_log("ERROR: ioctl(CA_GET_DESCR_INFO): %s", strerror(errno));
1120 }
1121
1122 if(close(fd) < 0)
1123 {
1124 cs_log("ERROR: Can't close device %s (errno=%d %s)", device_path, errno, strerror(errno));
1125 }
1126
1127 // We got a valid response from device (count the ECD type only)
1128 if(descr_info.num > 0 && (descr_info.type & 1))
1129 {
1130 ca_descramblers_total = descr_info.num;
1131 cs_log("Detected %s device, total available descramblers: %d", device_path, ca_descramblers_total);
1132 return 1;
1133 }
1134
1135 return 0;
1136}
1137
1138static int32_t dvbapi_detect_api(void)
1139{
1140#if defined WITH_COOLAPI || defined WITH_COOLAPI2
1141 selected_api = COOLAPI;
1142 selected_box = BOX_INDEX_COOLSTREAM;
1143 disable_pmt_files = 1;
1144 cfg.dvbapi_listenport = 0;
1145 cs_log("Detected Coolstream API");
1146 return 1;
1147#else
1148 if(cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX || cfg.dvbapi_boxtype == BOXTYPE_PC)
1149 {
1150 selected_api = DVBAPI_3;
1151 selected_box = BOX_INDEX_DREAMBOX_DVBAPI3;
1152 if(cfg.dvbapi_listenport)
1153 {
1154 cs_log("Using TCP listen socket, API forced to DVBAPIv3 (%d), userconfig boxtype: %d",
1155 selected_api, cfg.dvbapi_boxtype);
1156 }
1157 else
1158 {
1159 cs_log("Using %s listen socket, API forced to DVBAPIv3 (%d), userconfig boxtype: %d",
1160 devices[selected_box].cam_socket_path, selected_api, cfg.dvbapi_boxtype);
1161 }
1162 return 1;
1163 }
1164 else if(cfg.dvbapi_boxtype == BOXTYPE_SAMYGO)
1165 {
1166 selected_api = DVBAPI_3;
1167 selected_box = BOX_INDEX_QBOXHD;
1168 cfg.dvbapi_listenport = 0;
1169 disable_pmt_files = 1;
1170 cs_log("Using SamyGO dvbapi v0.1");
1171 return 1;
1172 }
1173 else
1174 {
1175 cfg.dvbapi_listenport = 0;
1176 }
1177
1178 int32_t i = 0, n = 0, devnum = -1, dmx_fd = 0, filtercount = 0;
1179 char device_path[128], device_path2[128];
1180 static LLIST *ll_max_fd;
1181 ll_max_fd = ll_create("ll_max_fd");
1182 LL_ITER itr;
1183
1184 struct s_open_fd
1185 {
1186 uint32_t fd;
1187 };
1188 struct s_open_fd *open_fd;
1189
1190 while(i < BOX_COUNT)
1191 {
1192 do
1193 {
1194 snprintf(device_path2, sizeof(device_path2), devices[i].demux_device, 0);
1195 snprintf(device_path, sizeof(device_path), devices[i].path, n);
1196 strncat(device_path, device_path2, sizeof(device_path) - strlen(device_path));
1197
1198 filtercount = 0;
1199 while((dmx_fd = open(device_path, O_RDWR | O_NONBLOCK)) > 0 && filtercount < MAX_FILTER)
1200 {
1201 filtercount++;
1202 if(!cs_malloc(&open_fd, sizeof(struct s_open_fd)))
1203 {
1204 close(dmx_fd);
1205 break;
1206 }
1207 open_fd->fd = dmx_fd;
1208 ll_append(ll_max_fd, open_fd);
1209 }
1210
1211 if(filtercount > 0)
1212 {
1213 itr = ll_iter_create(ll_max_fd);
1214 while((open_fd = ll_iter_next(&itr)))
1215 {
1216 dmx_fd = open_fd->fd;
1217 do
1218 {
1219 ;
1220 }
1221 while(close(dmx_fd) < 0);
1222 ll_iter_remove_data(&itr);
1223 }
1224 devnum = i;
1225 selected_api = devices[devnum].api;
1226 selected_box = devnum;
1227
1228 if(cfg.dvbapi_boxtype == BOXTYPE_NEUMO)
1229 {
1230 selected_api = DVBAPI_3; //DeepThought
1231 }
1232
1233#if defined(WITH_STAPI) || defined(WITH_STAPI5)
1234 if(selected_api == STAPI && stapi_open() == 0)
1235 {
1236 cs_log("ERROR: stapi: setting up stapi failed.");
1237 return 0;
1238 }
1239#endif
1240 maxfilter = filtercount;
1241 cs_log("Detected %s Api: %d, userconfig boxtype: %d maximum number of filters is %d (oscam limit is %d)",
1242 device_path, selected_api, cfg.dvbapi_boxtype, filtercount, MAX_FILTER);
1243 }
1244
1245 // try at least 8 adapters
1246 if((strchr(devices[i].path, '%') != NULL) && (n < 8))
1247 {
1248 n++;
1249 }
1250 else
1251 {
1252 n = 0; i++;
1253 }
1254
1255 } while(n != 0); // n is set to 0 again if 8 adapters are tried!
1256
1257 if(devnum != -1)
1258 {
1259 break; // check if box detected
1260 }
1261 }
1262
1263 ll_destroy(&ll_max_fd);
1264 if(devnum == -1)
1265 {
1266 return 0;
1267 }
1268#endif
1269
1270 return 1;
1271}
1272
1273static int32_t dvbapi_read_device(int32_t dmx_fd, uint8_t *buf, uint32_t length)
1274{
1275 int32_t readed;
1276 uint32_t count = 0;
1277 struct pollfd pfd[1];
1278
1279 pfd[0].fd = dmx_fd;
1280 pfd[0].events = (POLLIN | POLLPRI);
1281
1282 while(count < length)
1283 {
1284 if(poll(pfd, 1, 0)) // fd ready for reading?
1285 {
1286 if(pfd[0].revents & (POLLIN | POLLPRI)) // is there data to read?
1287 {
1288 readed = read(dmx_fd, &buf[count], length-count);
1289 if(readed < 0) // error occured while reading
1290 {
1291 if(errno == EINTR || errno == EAGAIN) // try again in case of interrupt
1292 {
1293 continue;
1294 }
1295
1296 cs_log("ERROR: Read error on fd %d (errno=%d %s)", dmx_fd, errno, strerror(errno));
1297 return (errno == EOVERFLOW ? 0 : -1);
1298 }
1299
1300 if(readed > 0) // succesfull read
1301 {
1302 count += readed;
1303 }
1304
1305 if(readed == 0 && count > 0) // nothing to read left
1306 {
1307 break;
1308 }
1309 }
1310 else
1311 {
1312 return -1; // other events than pollin/pri means bad news -> abort!
1313 }
1314 }
1315 else
1316 {
1317 break;
1318 }
1319 }
1320 cs_log_dump_dbg(D_TRACE, buf, count, "Received:");
1321 return count;
1322}
1323
1324int32_t dvbapi_open_device(int32_t type, int32_t num, int32_t adapter)
1325{
1326 int32_t dmx_fd, ret;
1327 int32_t ca_offset = 0;
1328 char device_path[128], device_path2[128];
1329
1330 if(cfg.dvbapi_listenport || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
1331 {
1332 return DUMMY_FD;
1333 }
1334
1335 if(type == 0)
1336 {
1337 snprintf(device_path2, sizeof(device_path2), devices[selected_box].demux_device, num);
1338 snprintf(device_path, sizeof(device_path), devices[selected_box].path, adapter);
1339 strncat(device_path, device_path2, sizeof(device_path) - strlen(device_path));
1340 }
1341 else
1342 {
1343 if(cfg.dvbapi_boxtype == BOXTYPE_DUCKBOX
1344 || cfg.dvbapi_boxtype == BOXTYPE_DBOX2
1345 || cfg.dvbapi_boxtype == BOXTYPE_UFS910)
1346 {
1347 ca_offset = 1;
1348 }
1349
1350 if(cfg.dvbapi_boxtype == BOXTYPE_QBOXHD
1351 || cfg.dvbapi_boxtype == BOXTYPE_PC
1352 || cfg.dvbapi_boxtype == BOXTYPE_SAMYGO)
1353 {
1354 num = 0;
1355 }
1356
1357 snprintf(device_path2, sizeof(device_path2), devices[selected_box].ca_device, num + ca_offset);
1358 snprintf(device_path, sizeof(device_path), devices[selected_box].path, adapter);
1359 strncat(device_path, device_path2, sizeof(device_path) - strlen(device_path));
1360 }
1361
1362 if(cfg.dvbapi_boxtype == BOXTYPE_SAMYGO)
1363 {
1364 if(type == 0)
1365 {
1366 struct sockaddr_un saddr;
1367 memset(&saddr, 0, sizeof(saddr));
1368 saddr.sun_family = AF_UNIX;
1369 cs_strncpy(saddr.sun_path, device_path, sizeof(saddr.sun_path));
1370 dmx_fd = socket(AF_UNIX, SOCK_STREAM, 0);
1371 ret = connect(dmx_fd, (struct sockaddr *)&saddr, sizeof(saddr));
1372 if(ret < 0)
1373 {
1374 close(dmx_fd);
1375 }
1376 }
1377 else if(type == 1)
1378 {
1379 int32_t udp_port = 9000;
1380 struct sockaddr_in saddr;
1381 memset(&saddr, 0, sizeof(saddr));
1382 saddr.sin_family = AF_INET;
1383 saddr.sin_port = htons(udp_port + adapter);
1384 saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
1385 dmx_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
1386 set_nonblock(dmx_fd, true);
1387 ret = connect(dmx_fd, (struct sockaddr *) &saddr, sizeof(saddr));
1388 if(ret < 0)
1389 {
1390 close(dmx_fd);
1391 }
1392 cs_log_dbg(D_DVBAPI, "NET DEVICE open (port = %d) fd %d", udp_port + adapter, dmx_fd);
1393 }
1394 else
1395 {
1396 ret = -1;
1397 }
1398 }
1399 else
1400 {
1401 dmx_fd = ret = open(device_path, O_RDWR | O_NONBLOCK);
1402 }
1403
1404 if(ret < 0)
1405 {
1406 cs_log("ERROR: Can't open device %s (errno=%d %s)", device_path, errno, strerror(errno));
1407 return -1;
1408 }
1409 cs_log_dbg(D_DVBAPI, "Open device %s (fd %d)", device_path, dmx_fd);
1410 return dmx_fd;
1411}
1412
1413uint16_t tunemm_caid_map(uint8_t direct, uint16_t caid, uint16_t srvid)
1414{
1415 int32_t i;
1416 struct s_client *cl = cur_client();
1417 TUNTAB *ttab = &cl->ttab;
1418
1419 if(!ttab->ttnum)
1420 {
1421 return caid;
1422 }
1423
1424 if(direct)
1425 {
1426 for(i = 0; i < ttab->ttnum; i++)
1427 {
1428 if(caid == ttab->ttdata[i].bt_caidto &&
1429 (srvid == ttab->ttdata[i].bt_srvid || ttab->ttdata[i].bt_srvid == 0xFFFF || !ttab->ttdata[i].bt_srvid))
1430 {
1431 return ttab->ttdata[i].bt_caidfrom;
1432 }
1433 }
1434 }
1435 else
1436 {
1437 for(i = 0; i < ttab->ttnum; i++)
1438 {
1439 if(caid == ttab->ttdata[i].bt_caidfrom &&
1440 (srvid == ttab->ttdata[i].bt_srvid || ttab->ttdata[i].bt_srvid == 0xFFFF || !ttab->ttdata[i].bt_srvid))
1441 {
1442 return ttab->ttdata[i].bt_caidto;
1443 }
1444 }
1445 }
1446 return caid;
1447}
1448
1449int32_t dvbapi_stop_filter(int32_t demux_id, int32_t type, uint32_t msgid)
1450{
1451#if defined(WITH_COOLAPI) || defined(WITH_COOLAPI2)
1452 // We prevented PAT and PMT from starting, so lets don't close them either.
1453 if(type != TYPE_ECM && type != TYPE_EMM && type != TYPE_SDT)
1454 {
1455 return 1;
1456 }
1457#endif
1458
1459 int32_t g, error = 0;
1460
1461 // just stop them all, we don't want to risk leaving
1462 // any stale filter running due to lowering of maxfilters
1463 for(g = 0; g < MAX_FILTER; g++)
1464 {
1465 if(demux[demux_id].demux_fd[g].type == type)
1466 {
1467 if(dvbapi_stop_filternum(demux_id, g, msgid) == -1)
1468 {
1469 error = 1;
1470 }
1471 }
1472 }
1473 return !error; // on error return 0, all ok 1
1474}
1475
1476int32_t dvbapi_stop_filternum(int32_t demux_id, int32_t num, uint32_t msgid)
1477{
1478 int32_t retfilter = -1, retfd = -1, fd = demux[demux_id].demux_fd[num].fd, try = 0;
1479
1480 if(USE_OPENXCAS)
1481 {
1482 demux[demux_id].demux_fd[num].type = 0;
1483 demux[demux_id].demux_fd[num].fd = 0;
1484 return 1; // all ok!
1485 }
1486
1487 if(fd > 0)
1488 {
1489 do
1490 {
1491 errno = 0;
1492 if(try)
1493 {
1494 cs_sleepms(50);
1495 }
1496 try++;
1497
1498 cs_log_dbg(D_DVBAPI, "Demuxer %d stop filter %d try %d (fd: %d api: %d, caid: %04X, provid: %06X, %spid: %04X)",
1499 demux_id,
1500 num + 1,
1501 try,
1502 fd,
1503 selected_api,
1504 demux[demux_id].demux_fd[num].caid,
1505 demux[demux_id].demux_fd[num].provid,
1506 demux[demux_id].demux_fd[num].type == TYPE_ECM ? "ecm" : "emm",
1507 demux[demux_id].demux_fd[num].pid);
1508
1509 switch(selected_api)
1510 {
1511 case DVBAPI_3:
1512 {
1513 if(cfg.dvbapi_listenport || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
1514 {
1515 retfilter = dvbapi_net_send(DVBAPI_DMX_STOP,
1516 demux[demux_id].socket_fd,
1517 msgid,
1518 demux_id,
1519 num,
1520 NULL,
1521 NULL,
1522 NULL,
1523 demux[demux_id].client_proto_version);
1524 }
1525 else
1526 {
1527 retfilter = dvbapi_ioctl(fd, DMX_STOP, NULL);
1528 }
1529 break;
1530 }
1531
1532 case DVBAPI_1:
1533 {
1534 retfilter = dvbapi_ioctl(fd, DMX_STOP, NULL);
1535 break;
1536 }
1537
1538#if defined(WITH_STAPI) || defined(WITH_STAPI5)
1539 case STAPI:
1540 {
1541 retfilter = stapi_remove_filter(demux_id, num, demux[demux_id].pmt_file);
1542 if(retfilter != 1) // stapi returns 0 for error, 1 for all ok
1543 {
1544 retfilter = -1;
1545 }
1546 break;
1547 }
1548#endif
1549#if defined WITH_COOLAPI || defined WITH_COOLAPI2
1550 case COOLAPI:
1551 {
1552 retfilter = coolapi_remove_filter(fd, num);
1553 if(retfilter >= 0)
1554 {
1555 retfd = coolapi_close_device(fd);
1556 }
1557 break;
1558 }
1559#endif
1560 default:
1561 break;
1562 }
1563
1564 if(errno == 9) // no error on bad file descriptor
1565 {
1566 retfilter = 0;
1567 }
1568 } while(retfilter < 0 && try < 10);
1569
1570#if !defined WITH_COOLAPI && !defined WITH_COOLAPI2 // no fd close for coolapi and stapi, all others do close fd!
1571 try = 0;
1572 do
1573 {
1574 if(try)
1575 {
1576 errno = 0;
1577 cs_sleepms(50);
1578 }
1579 try++;
1580
1581 // on bad filterfd dont try to close!
1582 if(!cfg.dvbapi_listenport && cfg.dvbapi_boxtype != BOXTYPE_PC_NODMX && errno != 9)
1583 {
1584 if(selected_api == STAPI)
1585 {
1586 retfd = 0; // stapi closes its own filter fd!
1587 }
1588 else
1589 {
1590 // flush filter input buffer in attempt to avoid overflow receivers internal buffer
1591 flush_read_fd(demux_id, num, fd);
1592 retfd = close(fd);
1593 if(errno == 9)
1594 {
1595 retfd = 0; // no error on bad file descriptor
1596 }
1597 }
1598 }
1599 else
1600 {
1601 retfd = 0;
1602 }
1603
1604 } while(retfd < 0 && try < 10);
1605#endif
1606 }
1607 else // fd <=0
1608 {
1609 return 1; // filter was already killed!
1610 }
1611
1612 if(retfilter < 0) // error on remove filter
1613 {
1614 cs_log("ERROR: Demuxer %d could not stop Filter %d (fd:%d api:%d errno=%d %s)",
1615 demux_id, num + 1, fd, selected_api, errno, strerror(errno));
1616 return retfilter;
1617 }
1618
1619 if(retfd < 0) // error on close filter fd
1620 {
1621 cs_log("ERROR: Demuxer %d could not close fd of Filter %d (fd=%d api:%d errno=%d %s)",
1622 demux_id, num + 1, fd, selected_api, errno, strerror(errno));
1623 return retfd;
1624 }
1625
1626 // code below runs only if nothing has gone wrong
1627 if(demux[demux_id].demux_fd[num].type == TYPE_ECM) // ecm filter stopped: reset index!
1628 {
1629 int32_t oldpid = demux[demux_id].demux_fd[num].pidindex;
1630 int32_t curpid = demux[demux_id].pidindex;
1631
1632 // workaround: below dont run on stapi since it handles it own pids...
1633 // stapi need to be better integrated in oscam dvbapi.
1634 if(selected_api != STAPI)
1635 {
1636 int32_t z;
1637 for(z = 0; z < MAX_STREAM_INDICES; z++)
1638 {
1639 uint32_t idx = demux[demux_id].ECMpids[oldpid].index[z];
1640 demux[demux_id].ECMpids[oldpid].index[z] = INDEX_INVALID;
1641
1642 if(idx != INDEX_INVALID) // if in use
1643 {
1644 int32_t i;
1645 for(i = 0; i < demux[demux_id].STREAMpidcount; i++)
1646 {
1647 int8_t match = 0;
1648
1649 // check streams of old disabled ecmpid
1650 if(!demux[demux_id].ECMpids[oldpid].streams
1651 || ((demux[demux_id].ECMpids[oldpid].streams & (1 << i)) == (uint) (1 << i)))
1652 {
1653 // check if new ecmpid is using same streams
1654 if(curpid != -1 && (!demux[demux_id].ECMpids[curpid].streams
1655 || ((demux[demux_id].ECMpids[curpid].streams & (1 << i)) == (uint) (1 << i))))
1656 {
1657 continue; // found same stream on old and new ecmpid -> skip! (and leave it enabled!)
1658 }
1659 int32_t pidtobestopped = demux[demux_id].STREAMpids[i];
1660 int32_t j, k, otherdemuxpid;
1661 uint32_t otherdemuxidx;
1662
1663 for(j = 0; j < MAX_DEMUX; j++) // check other demuxers for same streampid with same index
1664 {
1665 if(demux[j].program_number == 0 || demux_id == j || demux[j].ca_mask != demux[demux_id].ca_mask)
1666 {
1667 continue;
1668 // skip empty demuxers
1669 // skip same demuxer
1670 // skip streampid running on other ca device
1671 }
1672
1673 otherdemuxpid = demux[j].pidindex;
1674 if(otherdemuxpid == -1)
1675 {
1676 continue; // Other demuxer not descrambling yet
1677 }
1678
1679 int32_t y;
1680 for(y = 0; y < MAX_STREAM_INDICES; y++)
1681 {
1682 otherdemuxidx = demux[j].ECMpids[otherdemuxpid].index[y];
1683 if(otherdemuxidx == INDEX_INVALID || otherdemuxidx != idx)
1684 {
1685 continue; // Other demuxer has no index yet, or index is different
1686 }
1687
1688 for(k = 0; k < demux[j].STREAMpidcount; k++)
1689 {
1690 if(!demux[j].ECMpids[otherdemuxpid].streams
1691 || ((demux[j].ECMpids[otherdemuxpid].streams & (1 << k)) == (uint) (1 << k)))
1692 {
1693 if(demux[j].STREAMpids[k] == pidtobestopped)
1694 {
1695 continue; // found same streampid enabled with same index
1696 // on one or more other demuxers -> skip! (and leave it enabled!)
1697 }
1698 }
1699 match = 1; // matching stream found
1700 }
1701 }
1702 }
1703
1704 if(!match)
1705 {
1706 for(j = 0; j < CA_MAX; j++)
1707 {
1708 if(((demux[demux_id].ca_mask & (1 << j)) == (uint32_t) (1 << j)))
1709 {
1710 remove_streampid_from_list(j, pidtobestopped, idx);
1711 break;
1712 }
1713 }
1714 }
1715 }
1716 }
1717 }
1718 }
1719 }
1720 }
1721
1722 if(demux[demux_id].demux_fd[num].type == TYPE_EMM) // If emm type remove from emm filterlist
1723 {
1724 remove_emmfilter_from_list(demux_id,
1725 demux[demux_id].demux_fd[num].caid,
1726 demux[demux_id].demux_fd[num].provid,
1727 demux[demux_id].demux_fd[num].pid,
1728 num + 1);
1729 }
1730 demux[demux_id].demux_fd[num].type = 0;
1731 demux[demux_id].demux_fd[num].fd = 0;
1732 return 1; // all ok!
1733}
1734
1735void dvbapi_start_filter(int32_t demux_id, int32_t pidindex, uint16_t pid, uint16_t caid,
1736 uint32_t provid, uint8_t table, uint8_t mask, int32_t timeout, int32_t type)
1737{
1738 int32_t i;
1739 for(i = 0; i < maxfilter; i++) // check if filter is present
1740 {
1741 if(demux[demux_id].demux_fd[i].fd > 0 &&
1742 demux[demux_id].demux_fd[i].pid == pid &&
1743 demux[demux_id].demux_fd[i].type == type &&
1744 demux[demux_id].demux_fd[i].filter[0] == table &&
1745 demux[demux_id].demux_fd[i].mask[0] == mask)
1746 {
1747 return;
1748 }
1749 }
1750
1751 uint8_t filter[32];
1752 memset(filter, 0, 32);
1753 filter[0] = table;
1754 filter[16] = mask;
1755
1756 cs_log_dbg(D_DVBAPI, "Demuxer %d try to start new filter for caid: %04X, provid: %06X, pid: %04X",
1757 demux_id, caid, provid, pid);
1758
1759 dvbapi_set_filter(demux_id, selected_api, pid, caid, provid, filter, filter + 16, timeout, pidindex, type, 0);
1760}
1761
1762void dvbapi_start_sdt_filter(int32_t demux_id)
1763{
1764 dvbapi_start_filter(demux_id, demux[demux_id].pidindex, 0x11, 0x001, 0x01, 0x42, 0xFF, 0, TYPE_SDT);
1765 demux[demux_id].sdt_filter = 0;
1766}
1767
1768void dvbapi_start_pat_filter(int32_t demux_id)
1769{
1770#if defined(WITH_COOLAPI) || defined(WITH_COOLAPI2)
1771 // PAT-Filter breaks API and OSCAM for Coolstream.
1772 // Don't use it
1773 return;
1774#endif
1775 dvbapi_start_filter(demux_id, demux[demux_id].pidindex, 0x00, 0x001, 0x01, 0x00, 0xFF, 0, TYPE_PAT);
1776}
1777
1778void dvbapi_start_pmt_filter(int32_t demux_id)
1779{
1780#if defined(WITH_COOLAPI) || defined(WITH_COOLAPI2)
1781 // PMT-Filter breaks API and OSCAM for Coolstream.
1782 // Don't use it
1783 return;
1784#endif
1785 uint8_t filter[16], mask[16];
1786 memset(filter, 0, 16);
1787 memset(mask, 0, 16);
1788
1789 filter[0] = 0x02;
1790 i2b_buf(2, demux[demux_id].program_number, filter + 1); // add srvid to filter since the pid can deliver pmt for multiple srvid
1791 mask[0] = 0xFF;
1792 mask[1] = 0xFF;
1793 mask[2] = 0xFF;
1794
1795 dvbapi_set_filter(demux_id, selected_api, demux[demux_id].pmtpid, 0x001, 0x01, filter, mask, 0, 0, TYPE_PMT, 0);
1796}
1797
1798void dvbapi_start_emm_filter(int32_t demux_id)
1799{
1800 unsigned int j;
1801 if(!demux[demux_id].EMMpidcount)
1802 {
1803 return;
1804 }
1805
1806 struct s_csystem_emm_filter *dmx_filter = NULL;
1807 unsigned int filter_count = 0;
1808 uint16_t caid, ncaid;
1809 uint32_t provid;
1810 struct s_reader *rdr = NULL;
1811 struct s_client *cl = cur_client();
1812
1813 if(!cl || !cl->aureader_list)
1814 {
1815 return;
1816 }
1817
1818 LL_ITER itr = ll_iter_create(cl->aureader_list);
1819 while((rdr = ll_iter_next(&itr)))
1820 {
1821 if(!(rdr->grp & cl->grp))
1822 {
1823 continue;
1824 }
1825
1826 if(rdr->audisabled || !rdr->enable || (!is_network_reader(rdr) && rdr->card_status != CARD_INSERTED))
1827 {
1828 continue;
1829 }
1830
1831 const struct s_cardsystem *csystem;
1832 uint16_t c, match;
1833 cs_log_dbg(D_DVBAPI, "Demuxer %d matching reader %s against available emmpids -> START!", demux_id, rdr->label);
1834
1835 for(c = 0; c < demux[demux_id].EMMpidcount; c++)
1836 {
1837 caid = ncaid = demux[demux_id].EMMpids[c].CAID;
1838 if(!caid) continue;
1839
1840 if(chk_is_betatunnel_caid(caid) == 2)
1841 {
1842 ncaid = tunemm_caid_map(FROM_TO, caid, demux[demux_id].program_number);
1843 }
1844 provid = demux[demux_id].EMMpids[c].PROVID;
1845
1846 if(caid == ncaid)
1847 {
1848 match = emm_reader_match(rdr, caid, provid);
1849 }
1850 else
1851 {
1852 match = emm_reader_match(rdr, ncaid, provid);
1853 }
1854
1855 if(match)
1856 {
1857 if(rdr->typ == R_EMU)
1858 {
1859 csystem = rdr->csystem;
1860 }
1861 else
1862 {
1863 csystem = get_cardsystem_by_caid(caid);
1864 }
1865 if(csystem)
1866 {
1867 if(caid != ncaid)
1868 {
1869 csystem = get_cardsystem_by_caid(ncaid);
1870 if(csystem && csystem->get_tunemm_filter)
1871 {
1872 csystem->get_tunemm_filter(rdr, &dmx_filter, &filter_count);
1873 cs_log_dbg(D_DVBAPI, "Demuxer %d setting emm filter for betatunnel: %04X -> %04X",
1874 demux_id, ncaid, caid);
1875 }
1876 else
1877 {
1878 cs_log_dbg(D_DVBAPI, "Demuxer %d cardsystem for emm filter for caid %04X of reader %s not found",
1879 demux_id, ncaid, rdr->label);
1880 continue;
1881 }
1882 }
1883 else if(csystem->get_emm_filter)
1884 {
1885 if(rdr->typ == R_EMU)
1886 {
1887 csystem->get_emm_filter_adv(rdr, &dmx_filter, &filter_count, caid, provid, demux[demux_id].program_number,
1888 demux[demux_id].tsid, demux[demux_id].onid, demux[demux_id].ens);
1889 }
1890 else
1891 {
1892 csystem->get_emm_filter(rdr, &dmx_filter, &filter_count);
1893 }
1894 }
1895 }
1896 else
1897 {
1898 cs_log_dbg(D_DVBAPI, "Demuxer %d cardsystem for emm filter for caid %04X of reader %s not found",
1899 demux_id, caid, rdr->label);
1900 continue;
1901 }
1902
1903 for(j = 0; j < filter_count ; j++)
1904 {
1905 if(dmx_filter[j].enabled == 0)
1906 {
1907 continue;
1908 }
1909
1910 uint8_t filter[32];
1911 memset(filter, 0, sizeof(filter)); // reset filter
1912 uint32_t usefilterbytes = 16; // default use all filters
1913 memcpy(filter, dmx_filter[j].filter, usefilterbytes);
1914 memcpy(filter + 16, dmx_filter[j].mask, usefilterbytes);
1915 int32_t emmtype = dmx_filter[j].type;
1916
1917 if(filter[0] && (((1 << (filter[0] % 0x80)) & rdr->b_nano) && !((1 << (filter[0] % 0x80)) & rdr->s_nano)))
1918 {
1919 cs_log_dbg(D_DVBAPI, "Demuxer %d reader %s emmfilter %d/%d blocked by userconfig -> SKIP!",
1920 demux_id, rdr->label, j + 1, filter_count);
1921 continue;
1922 }
1923
1924 if((rdr->blockemm & emmtype) && !(((1 << (filter[0] % 0x80)) & rdr->s_nano) || (rdr->saveemm & emmtype)))
1925 {
1926 cs_log_dbg(D_DVBAPI, "Demuxer %d reader %s emmfilter %d/%d blocked by userconfig -> SKIP!",
1927 demux_id, rdr->label, j + 1, filter_count);
1928 continue;
1929 }
1930
1931 if(demux[demux_id].EMMpids[c].type & emmtype)
1932 {
1933 cs_log_dbg(D_DVBAPI, "Demuxer %d reader %s emmfilter %d/%d type match -> ENABLE!",
1934 demux_id, rdr->label, j + 1, filter_count);
1935 check_add_emmpid(demux_id, filter, c, emmtype);
1936 }
1937 else
1938 {
1939 cs_log_dbg(D_DVBAPI, "Demuxer %d reader %s emmfilter %d/%d type mismatch -> SKIP!",
1940 demux_id, rdr->label, j + 1, filter_count);
1941 }
1942 }
1943 // dmx_filter not use below this point;
1944 NULLFREE(dmx_filter);
1945 filter_count = 0;
1946 }
1947 }
1948 cs_log_dbg(D_DVBAPI, "Demuxer %d matching reader %s against available emmpids -> DONE!", demux_id, rdr->label);
1949 }
1950
1951 if(demux[demux_id].emm_filter == -1) // first run -1
1952 {
1953 demux[demux_id].emm_filter = 0;
1954 }
1955 cs_log_dbg(D_DVBAPI, "Demuxer %d handles %i emm filters", demux_id, demux[demux_id].emm_filter);
1956}
1957
1958void dvbapi_add_ecmpid_int(int32_t demux_id, uint16_t caid, uint16_t ecmpid, uint32_t provid, uint32_t cadata, char *txt)
1959{
1960 int32_t n, added = 0;
1961 int32_t stream = demux[demux_id].STREAMpidcount - 1;
1962
1963 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
1964 {
1965 if(demux[demux_id].ECMpids[n].CAID == caid && demux[demux_id].ECMpids[n].ECM_PID == ecmpid
1966 && (!provid || (provid && demux[demux_id].ECMpids[n].PROVID == provid)))
1967 {
1968 added = 1;
1969 if(stream > -1)
1970 {
1971 if(!demux[demux_id].ECMpids[n].streams)
1972 {
1973 // we already got this caid/ecmpid as global, no need to add the single stream
1974 cs_log_dbg(D_DVBAPI, "Demuxer %d skipped stream CAID: %04X ECM_PID: %04X PROVID: %06X (Same as ECMPID %d)",
1975 demux_id, caid, ecmpid, provid, n);
1976 continue;
1977 }
1978 demux[demux_id].ECMpids[n].streams |= (1 << stream);
1979 cs_log("Demuxer %d added stream to ecmpid %d CAID: %04X ECM_PID: %04X PROVID: %06X",
1980 demux_id, n, caid, ecmpid, provid);
1981 }
1982 }
1983 }
1984
1985 if(added == 1)
1986 {
1987 return;
1988 }
1989
1990 if(demux[demux_id].ECMpidcount >= MAX_ECM_PIDS)
1991 {
1992 cs_log("We reached maximum ECMpids: unable to add to demuxer %d ecmpid %d CAID: %04X ECM_PID: %04X PROVID: %06X %s",
1993 demux_id, demux[demux_id].ECMpidcount, caid, ecmpid, provid, txt);
1994 return;
1995 }
1996
1997 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].ECM_PID = ecmpid;
1998 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].CAID = caid;
1999 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].PROVID = provid;
2000 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].CHID = 0x10000; // reset CHID
2001 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].checked = 0;
2002 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].status = 0;
2003 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].tries = 0xFE;
2004 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].streams = 0; // reset streams!
2005 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].irdeto_curindex = 0xFE; // reset
2006 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].irdeto_maxindex = 0; // reset
2007 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].irdeto_cycle = 0xFE; // reset
2008 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].table = 0;
2009 demux[demux_id].ECMpids[demux[demux_id].ECMpidcount].cadata = cadata;
2010
2011 cs_log("Demuxer %d ecmpid %d CAID: %04X ECM_PID: %04X PROVID: %06X %s",
2012 demux_id, demux[demux_id].ECMpidcount, caid, ecmpid, provid, txt);
2013
2014 // marker to fetch emms early irdeto needs them!
2015 if(caid_is_irdeto(caid) || (caid_is_dre(caid) && (provid == 0x11 || provid == 0xFE)))
2016 {
2017 demux[demux_id].emmstart.time = 1;
2018 }
2019 demux[demux_id].ECMpidcount++;
2020}
2021
2022void dvbapi_add_ecmpid(int32_t demux_id, uint16_t caid, uint16_t ecmpid, uint32_t provid, uint32_t cadata, char *txt)
2023{
2024 dvbapi_add_ecmpid_int(demux_id, caid, ecmpid, provid, cadata, txt);
2025 struct s_dvbapi_priority *joinentry;
2026
2027 for(joinentry = dvbapi_priority; joinentry != NULL; joinentry = joinentry->next)
2028 {
2029 if((joinentry->type != 'j')
2030 || (joinentry->caid && joinentry->caid != caid)
2031 || (joinentry->provid && joinentry->provid != provid)
2032 || (joinentry->ecmpid && joinentry->ecmpid != ecmpid)
2033 || (joinentry->srvid && joinentry->srvid != demux[demux_id].program_number))
2034 {
2035 continue;
2036 }
2037
2038 cs_log_dbg(D_DVBAPI, "Join ecmpid %04X@%06X:%04X to %04X@%06X:%04X",
2039 caid, provid, ecmpid, joinentry->mapcaid, joinentry->mapprovid, joinentry->mapecmpid);
2040 dvbapi_add_ecmpid_int(demux_id, joinentry->mapcaid, joinentry->mapecmpid, joinentry->mapprovid, 0, txt);
2041 }
2042}
2043
2044void dvbapi_add_emmpid(int32_t demux_id, uint16_t caid, uint16_t emmpid, uint32_t provid, uint32_t cadata, uint8_t type)
2045{
2046 char typetext[40];
2047 char cadatatext[40];
2048 cs_strncpy(typetext, ":", sizeof(typetext));
2049
2050 if(type & 0x01) { strcat(typetext, "UNIQUE:"); }
2051 if(type & 0x02) { strcat(typetext, "SHARED:"); }
2052 if(type & 0x04) { strcat(typetext, "GLOBAL:"); }
2053 if(type & 0xF8) { strcat(typetext, "UNKNOWN:"); }
2054
2055 if(cadata > 0)
2056 {
2057 snprintf(cadatatext, 40, " CA DATA %X ", cadata);
2058 }
2059 else
2060 {
2061 cadatatext[0] = '\t'; cadatatext[1] = '\0';
2062 }
2063
2064 if(caid == 0x4AE1 && provid == 0x11 && cadata == 0)
2065 {
2066 return;
2067 }
2068
2069 uint16_t i;
2070 for(i = 0; i < demux[demux_id].EMMpidcount; i++)
2071 {
2072 if(demux[demux_id].EMMpids[i].PID == emmpid && demux[demux_id].EMMpids[i].CAID == caid &&
2073 demux[demux_id].EMMpids[i].PROVID == provid && demux[demux_id].EMMpids[i].cadata == cadata)
2074 {
2075 if(!(demux[demux_id].EMMpids[i].type & type))
2076 {
2077 demux[demux_id].EMMpids[i].type |= type; // register this emm kind to this emmpid
2078 cs_log_dbg(D_DVBAPI, "Added to existing emmpid %d additional emmtype %s",
2079 demux[demux_id].EMMpidcount - 1, typetext);
2080 }
2081 return;
2082 }
2083 }
2084
2085 if(i < MAX_EMM_PIDS)
2086 {
2087 demux[demux_id].EMMpids[demux[demux_id].EMMpidcount].PID = emmpid;
2088 demux[demux_id].EMMpids[demux[demux_id].EMMpidcount].CAID = caid;
2089 demux[demux_id].EMMpids[demux[demux_id].EMMpidcount].PROVID = provid;
2090 demux[demux_id].EMMpids[demux[demux_id].EMMpidcount].type = type;
2091 demux[demux_id].EMMpids[demux[demux_id].EMMpidcount++].cadata = cadata;
2092 cs_log_dbg(D_DVBAPI, "Added new emmpid %d CAID: %04X EMM_PID: %04X PROVID: %06X%sTYPE %s",
2093 demux[demux_id].EMMpidcount - 1, caid, emmpid, provid, cadatatext, typetext);
2094 }
2095 else
2096 {
2097 cs_log_dbg(D_DVBAPI, "We reached max emmpids: unable to add new emmpid %d CAID: %04X EMM_PID: %04X PROVID: %06X%sTYPE %s",
2098 demux[demux_id].EMMpidcount - 1, caid, emmpid, provid, cadatatext, typetext);
2099 }
2100}
2101
2102void dvbapi_parse_cat(int32_t demux_id, uint8_t *buf, int32_t len)
2103{
2104#if defined WITH_COOLAPI || defined WITH_COOLAPI2
2105 // driver sometimes reports error if too many emm filter
2106 // but adding more ecm filter is no problem
2107 // ... so ifdef here instead of limiting MAX_FILTER
2108 demux[demux_id].max_emm_filter = 14;
2109#else
2110 if(cfg.dvbapi_requestmode == 1)
2111 {
2112 uint16_t ecm_filter_needed = 0, n;
2113 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
2114 {
2115 if(demux[demux_id].ECMpids[n].status > -1)
2116 {
2117 ecm_filter_needed++;
2118 }
2119 }
2120
2121 if(maxfilter - ecm_filter_needed <= 0)
2122 {
2123 demux[demux_id].max_emm_filter = 0;
2124 }
2125 else
2126 {
2127 demux[demux_id].max_emm_filter = maxfilter - ecm_filter_needed;
2128 }
2129 }
2130 else
2131 {
2132 demux[demux_id].max_emm_filter = maxfilter - 1;
2133 }
2134#endif
2135
2136 uint16_t i, k;
2137 cs_log_dump_dbg(D_DVBAPI, buf, len, "cat:");
2138
2139 for(i = 8; i < (b2i(2, buf + 1) & 0xFFF) - 1; i += buf[i + 1] + 2)
2140 {
2141 if(buf[i] != 0x09)
2142 {
2143 continue;
2144 }
2145
2146 uint16_t caid = b2i(2, buf + i + 2);
2147 uint16_t emm_pid = b2i(2, buf + i +4) & 0x1FFF;
2148 uint32_t emm_provider = 0;
2149
2150 switch(caid >> 8)
2151 {
2152 case 0x01:
2153 dvbapi_add_emmpid(demux_id, caid, emm_pid, 0, 0, EMM_UNIQUE | EMM_GLOBAL);
2154 for(k = i + 7; k < i + buf[i + 1] + 2; k += 4)
2155 {
2156 emm_provider = b2i(2, buf + k + 2);
2157 emm_pid = b2i(2, buf + k) & 0xFFF;
2158 dvbapi_add_emmpid(demux_id, caid, emm_pid, emm_provider, 0, EMM_SHARED);
2159 }
2160 break;
2161
2162 case 0x05:
2163 for(k = i + 6; k < i + buf[i + 1] + 2; k += buf[k + 1] + 2)
2164 {
2165 if(buf[k] == 0x14)
2166 {
2167 emm_provider = (b2i(3, buf + k + 2) & 0xFFFFF0); // viaccess fixup last digit is a dont care!
2168 dvbapi_add_emmpid(demux_id, caid, emm_pid, emm_provider, 0, EMM_UNIQUE | EMM_SHARED | EMM_GLOBAL);
2169 }
2170 }
2171 break;
2172
2173 case 0x18:
2174 if(buf[i + 1] == 0x07 || buf[i + 1] == 0x0B)
2175 {
2176 for(k = i + 7; k < i + 7 + buf[i + 6]; k += 2)
2177 {
2178 emm_provider = b2i(2, buf + k);
2179 dvbapi_add_emmpid(demux_id, caid, emm_pid, emm_provider, 0, EMM_UNIQUE | EMM_SHARED | EMM_GLOBAL);
2180 }
2181 }
2182 else
2183 {
2184 dvbapi_add_emmpid(demux_id, caid, emm_pid, emm_provider, 0, EMM_UNIQUE | EMM_SHARED | EMM_GLOBAL);
2185 }
2186 break;
2187
2188 case 0x27:
2189 case 0x4A:
2190 if(caid_is_bulcrypt(caid))
2191 {
2192 dvbapi_add_emmpid(demux_id, caid, emm_pid, 0, 0, EMM_UNIQUE | EMM_SHARED | EMM_GLOBAL);
2193 break;
2194 }
2195 emm_provider = (uint32_t)buf[i + 6];
2196 if(buf[i + 6] == 0xFE)
2197 {
2198 dvbapi_add_emmpid(demux_id, caid, emm_pid, emm_provider, 0x102, EMM_GLOBAL);
2199 }
2200 else
2201 {
2202 uint32_t cadata = 0;
2203 if(buf[i + 1] == 0x0A)
2204 {
2205 cadata = (buf[i + 8] << 24) | (buf[i + 9] << 16) | (buf[i + 10] << 8) | buf[i + 11];
2206 }
2207 dvbapi_add_emmpid(demux_id, caid, emm_pid, emm_provider, cadata, EMM_UNIQUE | EMM_SHARED | EMM_GLOBAL);
2208 }
2209 break;
2210
2211 default:
2212 dvbapi_add_emmpid(demux_id, caid, emm_pid, 0, 0, EMM_UNIQUE | EMM_SHARED | EMM_GLOBAL);
2213 break;
2214 }
2215 }
2216 return;
2217}
2218
2219static pthread_mutex_t lockindex = PTHREAD_MUTEX_INITIALIZER;
2220
2221uint32_t dvbapi_get_desc_index(int32_t demux_id, int32_t pid, int32_t stream_id)
2222{
2223 int32_t i, j, k, fail = 1;
2224 uint32_t idx = 0;
2225
2226 if(cfg.dvbapi_boxtype == BOXTYPE_NEUMO)
2227 {
2228 sscanf(demux[demux_id].pmt_file, "pmt%3d.tmp", &idx);
2229 return idx;
2230 }
2231
2232 SAFE_MUTEX_LOCK(&lockindex); // to avoid race when readers become responsive!
2233 while(fail && idx <= INDEX_MAX)
2234 {
2235 fail = 0;
2236 for(i = 0; i < MAX_DEMUX && !fail && idx < INDEX_MAX; i++)
2237 {
2238 if(demux[i].program_number == 0)
2239 {
2240 continue; // skip empty demuxers
2241 }
2242
2243 if(demux[i].ca_mask != demux[demux_id].ca_mask
2244 && (!(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)))
2245 {
2246 continue; // skip demuxer using other ca device
2247 }
2248
2249 for(j = 0; j < demux[i].ECMpidcount && !fail; j++) // search for new unique index
2250 {
2251 for(k = 0; k < MAX_STREAM_INDICES; k++)
2252 {
2253 if(demux[i].ECMpids[j].index[k] == idx)
2254 {
2255 fail = 1;
2256 idx++;
2257 }
2258 }
2259 }
2260 }
2261 }
2262
2263 if(selected_api == DVBAPI_3 || selected_api == DVBAPI_1)
2264 {
2265 // make sure we haven't run out of descramblers
2266 if(ca_descramblers_used < ca_descramblers_total)
2267 {
2268 ca_descramblers_used++; // increase number of descramblers used
2269 }
2270 else
2271 {
2272 idx = INDEX_INVALID; // we don't have any descramblers left
2273 }
2274 }
2275 else // old style check for STAPI, COOLAPI, etc
2276 {
2277 if(idx > ca_descramblers_total)
2278 {
2279 idx = INDEX_INVALID; // we don't have any descramblers left
2280 }
2281 }
2282
2283 demux[demux_id].ECMpids[pid].index[stream_id] = idx;
2284 SAFE_MUTEX_UNLOCK(&lockindex); // and release it!
2285
2286 return idx;
2287}
2288
2289void dvbapi_set_pid(int32_t demux_id, int32_t num, uint32_t idx, bool enable, bool use_des, uint32_t msgid)
2290{
2291 int32_t i, currentfd;
2292 uint16_t streampid = demux[demux_id].STREAMpids[num];
2293 uint32_t newidx = 0, curidx;
2294 ca_pid_t ca_pid2;
2295
2296 if(demux[demux_id].pidindex == -1 && enable)
2297 {
2298 return; // no current pid on enable? --> exit
2299 }
2300
2301 switch(selected_api)
2302 {
2303#if defined(WITH_STAPI) || defined(WITH_STAPI5)
2304 case STAPI:
2305 if(!enable) idx = INDEX_INVALID;
2306 stapi_set_pid(demux_id, num, idx, streampid, demux[demux_id].pmt_file); // only used to disable pids!!!
2307 break;
2308#endif
2309
2310#if defined WITH_COOLAPI || defined WITH_COOLAPI2
2311 case COOLAPI:
2312 break;
2313#endif
2314
2315 default:
2316 for(i = 0; i < CA_MAX; i++)
2317 {
2318 newidx = INDEX_INVALID;
2319 curidx = idx;
2320
2321 if(((demux[demux_id].ca_mask & (1 << i)) == (uint32_t) (1 << i)))
2322 {
2323 uint32_t action = 0;
2324 if(enable)
2325 {
2326 action = update_streampid_list(i, streampid, curidx, use_des);
2327 }
2328
2329 if(!enable)
2330 {
2331 action = remove_streampid_from_list(i, streampid, curidx);
2332 }
2333
2334 if(action != NO_STREAMPID_LISTED && action != INVALID_STREAMPID_INDEX &&
2335 action != FOUND_STREAMPID_INDEX && action != ADDED_STREAMPID_INDEX &&
2336 action != REMOVED_STREAMPID_INDEX)
2337 {
2338 // removed last index of this streampid on ca? -> disable this pid with -1 on this ca
2339 if((action == REMOVED_STREAMPID_LASTINDEX || action == FIRST_STREAMPID_INDEX)
2340 && (is_ca_used(i, streampid) == INDEX_INVALID))
2341 {
2342 curidx = DVBAPI_INDEX_DISABLE;
2343 }
2344
2345 // removed index of streampid that is used to decode on ca -> get a fresh one
2346 if(action == REMOVED_DECODING_STREAMPID_INDEX || action == FIRST_STREAMPID_INDEX)
2347 {
2348 newidx = is_ca_used(i, streampid); // get an active index for this pid and enable it on ca device
2349 curidx = DVBAPI_INDEX_DISABLE;
2350 }
2351
2352 while(curidx != INDEX_INVALID || newidx != INDEX_INVALID)
2353 {
2354 memset(&ca_pid2, 0, sizeof(ca_pid2));
2355 ca_pid2.pid = streampid;
2356 if(curidx != INDEX_INVALID)
2357 {
2358 (curidx == DVBAPI_INDEX_DISABLE) ? (ca_pid2.index = -1) : (ca_pid2.index = curidx);
2359 cs_log_dbg(D_DVBAPI, "Demuxer %d %s stream %d pid=0x%04x index=%d on ca%d",
2360 demux_id,
2361 ((enable && curidx != DVBAPI_INDEX_DISABLE) ? "enable" : "disable"),
2362 num + 1,
2363 ca_pid2.pid,
2364 ca_pid2.index,
2365 i);
2366 curidx = INDEX_INVALID; // flag this index as handled
2367 }
2368 else if(newidx != INDEX_INVALID)
2369 {
2370 (newidx == DVBAPI_INDEX_DISABLE) ? (ca_pid2.index = -1) : (ca_pid2.index = newidx);
2371 cs_log_dbg(D_DVBAPI, "Demuxer %d %s stream %d pid=0x%04x by index=%d on ca%d",
2372 demux_id,
2373 ((enable && action == FIRST_STREAMPID_INDEX) ? "enable" : "takeover"),
2374 num + 1,
2375 ca_pid2.pid,
2376 ca_pid2.index,
2377 i);
2378 newidx = INDEX_INVALID; // flag this takeover / new index as handled
2379 }
2380
2381 if(use_des && cfg.dvbapi_extended_cw_api == 2 && ca_pid2.index != -1)
2382 {
2383 ca_pid2.index |= 0x100; // flag DES algo through pid index
2384 }
2385
2386 if(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
2387 {
2388 dvbapi_net_send(DVBAPI_CA_SET_PID, demux[demux_id].socket_fd,
2389 msgid,
2390 demux_id,
2391 -1 /*unused*/,
2392 (uint8_t *) &ca_pid2,
2393 NULL,
2394 NULL,
2395 demux[demux_id].client_proto_version);
2396 }
2397 else
2398 {
2399 currentfd = ca_fd[i];
2400 if(currentfd <= 0)
2401 {
2402 currentfd = dvbapi_open_device(1, i, demux[demux_id].adapter_index);
2403 ca_fd[i] = currentfd; // save fd of this ca
2404 }
2405
2406 if(currentfd > 0)
2407 {
2408 if(dvbapi_ioctl(currentfd, CA_SET_PID, &ca_pid2) == -1)
2409 {
2410 cs_log_dbg(D_TRACE | D_DVBAPI,"CA_SET_PID ioctl error (errno=%d %s)", errno, strerror(errno));
2411 remove_streampid_from_list(i, ca_pid2.pid, INDEX_DISABLE_ALL);
2412 }
2413
2414 uint32_t result = is_ca_used(i, 0); // check if in use by any pid
2415 if(result == INDEX_INVALID)
2416 {
2417 cs_log_dbg(D_DVBAPI, "Demuxer %d close now unused CA%d device", demux_id, i);
2418 int32_t ret = close(currentfd);
2419 if(ret < 0)
2420 {
2421 cs_log("ERROR: Could not close demuxer fd (errno=%d %s)", errno, strerror(errno));
2422 }
2423 currentfd = ca_fd[i] = 0;
2424 }
2425 }
2426 }
2427 }
2428 }
2429 }
2430 }
2431 break;
2432 }
2433 return;
2434}
2435
2436void dvbapi_stop_all_descrambling(uint32_t msgid)
2437{
2438 int32_t j;
2439 for(j = 0; j < MAX_DEMUX; j++)
2440 {
2441 if(demux[j].program_number == 0) { continue; }
2442 dvbapi_stop_descrambling(j, msgid);
2443 }
2444}
2445
2446void dvbapi_stop_all_emm_sdt_filtering(uint32_t msgid)
2447{
2448 int32_t j;
2449 for(j = 0; j < MAX_DEMUX; j++)
2450 {
2451 if(demux[j].program_number == 0) { continue; }
2452 dvbapi_stop_filter(j, TYPE_EMM, msgid);
2453 dvbapi_stop_filter(j, TYPE_SDT, msgid);
2454 demux[j].emm_filter = -1;
2455 }
2456}
2457
2458void dvbapi_stop_descrambling(int32_t demux_id, uint32_t msgid)
2459{
2460 int32_t i, j, z;
2461 if(demux[demux_id].program_number == 0) { return; }
2462 char channame[CS_SERVICENAME_SIZE];
2463
2464 i = demux[demux_id].pidindex;
2465 if(i < 0)
2466 {
2467 i = 0;
2468 }
2469
2470 demux[demux_id].pidindex = -1; // no ecmpid is to be descrambling since we start stop descrambling!
2471
2472 get_servicename(dvbapi_client, demux[demux_id].program_number,
2473 demux[demux_id].ECMpidcount > 0 ? demux[demux_id].ECMpids[i].PROVID : NO_PROVID_VALUE,
2474 demux[demux_id].ECMpidcount > 0 ? demux[demux_id].ECMpids[i].CAID : NO_CAID_VALUE,
2475 channame, sizeof(channame));
2476
2477 cs_log("Demuxer %d stopped descrambling for program %04X (%s)",
2478 demux_id, demux[demux_id].program_number, channame);
2479
2480 dvbapi_stop_filter(demux_id, TYPE_EMM, msgid);
2481 dvbapi_stop_filter(demux_id, TYPE_SDT, msgid);
2482 dvbapi_stop_filter(demux_id, TYPE_PAT, msgid);
2483 dvbapi_stop_filter(demux_id, TYPE_PMT, msgid);
2484
2485 for(i = 0; i < demux[demux_id].ECMpidcount && demux[demux_id].ECMpidcount > 0; i++)
2486 {
2487 for(j = 0; j < MAX_STREAM_INDICES; j++)
2488 {
2489 if(demux[demux_id].ECMpids[i].index[j] == INDEX_INVALID)
2490 {
2491 continue;
2492 }
2493
2494 // disable streams!
2495 for(z = 0; z < demux[demux_id].STREAMpidcount; z++)
2496 {
2497 dvbapi_set_pid(demux_id, z, demux[demux_id].ECMpids[i].index[j], false, false, msgid); // disable streampid
2498 }
2499 demux[demux_id].ECMpids[i].index[j] = INDEX_INVALID;
2500 }
2501 }
2502 dvbapi_stop_filter(demux_id, TYPE_ECM, msgid);
2503
2504 pthread_mutex_destroy(&demux[demux_id].answerlock);
2505 memset(&demux[demux_id], 0 , sizeof(DEMUXTYPE));
2506
2507 SAFE_MUTEX_INIT(&demux[demux_id].answerlock, NULL);
2508 for(i = 0; i < MAX_ECM_PIDS; i++)
2509 {
2510 for(j = 0; j < MAX_STREAM_INDICES; j++)
2511 {
2512 demux[demux_id].ECMpids[i].index[j] = INDEX_INVALID;
2513 }
2514 }
2515 demux[demux_id].pidindex = -1;
2516 demux[demux_id].curindex = -1;
2517
2518 if(!cfg.dvbapi_listenport && cfg.dvbapi_boxtype != BOXTYPE_PC_NODMX)
2519 {
2520 unlink(ECMINFO_FILE);
2521 }
2522 return;
2523}
2524
2525int32_t dvbapi_start_descrambling(int32_t demux_id, int32_t pid, int8_t checked, uint32_t msgid)
2526{
2527 int32_t started = 0; // in case ecmfilter started = 1
2528 int32_t fake_ecm = 0;
2529 ECM_REQUEST *er;
2530 struct s_reader *rdr;
2531
2532 if(!(er = get_ecmtask()))
2533 {
2534 return started;
2535 }
2536 demux[demux_id].ECMpids[pid].checked = checked + 1; // mark this pid as checked!
2537
2538 struct s_dvbapi_priority *p;
2539 for(p = dvbapi_priority; p != NULL ; p = p->next)
2540 {
2541 if((p->type != 'p')
2542 || (p->caid && p->caid != demux[demux_id].ECMpids[pid].CAID)
2543 || (p->provid && p->provid != demux[demux_id].ECMpids[pid].PROVID)
2544 || (p->ecmpid && p->ecmpid != demux[demux_id].ECMpids[pid].ECM_PID)
2545 || (p->srvid && p->srvid != demux[demux_id].program_number)
2546 || (p->pidx && p->pidx-1 != pid)
2547 || (p->cadata && p->cadata != demux[demux_id].ECMpids[pid].cadata))
2548 {
2549 continue;
2550 }
2551
2552 // if found chid and first run apply chid filter, on forced pids always apply!
2553 if(p->type == 'p' && p->chid < 0x10000 && (demux[demux_id].ECMpids[pid].checked == 1 || (p && p->force)))
2554 {
2555 if(demux[demux_id].ECMpids[pid].CHID < 0x10000) // channelcache delivered chid
2556 {
2557 er->chid = demux[demux_id].ECMpids[pid].CHID;
2558 }
2559 else
2560 {
2561 er->chid = p->chid; // no channelcache or no chid in use, so use prio chid
2562 demux[demux_id].ECMpids[pid].CHID = p->chid;
2563 }
2564 //cs_log("********* CHID %04X **************", demux[demux_id].ECMpids[pid].CHID);
2565 break; // we only accept one!
2566 }
2567 else
2568 {
2569 if(demux[demux_id].ECMpids[pid].CHID < 0x10000) // channelcache delivered chid
2570 {
2571 er->chid = demux[demux_id].ECMpids[pid].CHID;
2572 }
2573 else // no channelcache or no chid in use
2574 {
2575 er->chid = 0;
2576 demux[demux_id].ECMpids[pid].CHID = 0x10000;
2577 }
2578 }
2579 }
2580
2581 er->srvid = demux[demux_id].program_number;
2582 er->caid = demux[demux_id].ECMpids[pid].CAID;
2583 er->pid = demux[demux_id].ECMpids[pid].ECM_PID;
2584 er->prid = demux[demux_id].ECMpids[pid].PROVID;
2585 er->vpid = demux[demux_id].ECMpids[pid].VPID;
2586 er->pmtpid = demux[demux_id].pmtpid;
2587 er->onid = demux[demux_id].onid;
2588 er->msgid = msgid;
2589
2590#ifdef WITH_STAPI5
2591 cs_strncpy(er->dev_name, dev_list[demux[demux_id].dev_index].name, sizeof(dev_list[demux[demux_id].dev_index].name));
2592#endif
2593 struct timeb now;
2594 cs_ftime(&now);
2595
2596 for(rdr = first_active_reader; rdr != NULL ; rdr = rdr->next)
2597 {
2598 int8_t match = matching_reader(er, rdr); // check for matching reader
2599 int64_t gone = comp_timeb(&now, &rdr->emm_last);
2600 if(gone > 3600*1000 && rdr->needsemmfirst && caid_is_irdeto(er->caid))
2601 {
2602 cs_log("Warning reader %s received no emms for the last %d seconds -> skip, this reader needs emms first!",
2603 rdr->label, (int)(gone / 1000));
2604 continue; // skip this card needs to process emms first before it can be used for descramble
2605 }
2606
2607 if(p && p->force)
2608 {
2609 match = 1; // forced pid always started!
2610 }
2611
2612 if(!match) // if this reader does not match, check betatunnel for it
2613 {
2614 match = lb_check_auto_betatunnel(er, rdr);
2615 }
2616
2617 if(!match && chk_is_betatunnel_caid(er->caid)) // these caids might be tunneled invisible by peers
2618 {
2619 match = 1; // so make it a match to try it!
2620 }
2621
2622 // check if cache-ex is matching
2623 if(config_enabled(CS_CACHEEX) && (!match && (cacheex_is_match_alias(dvbapi_client, er))))
2624 {
2625 match = 1; // so make it a match to try it!
2626 }
2627
2628 // BISS1 and BISS2 mode 1/E or FAKE caid
2629 // ecm pid is fake, so send out one fake ecm request
2630 // special treatment: if we asked the cw first without starting a filter,
2631 // the cw request will be killed due to no ecmfilter started
2632 if(caid_is_fake(demux[demux_id].ECMpids[pid].CAID) || caid_is_biss_fixed(demux[demux_id].ECMpids[pid].CAID))
2633 {
2634 int32_t j, n;
2635 er->ecmlen = 5;
2636 er->ecm[0] = 0x80; // to pass the cache check it must be 0x80 or 0x81
2637 er->ecm[1] = 0x00;
2638 er->ecm[2] = 0x02;
2639 i2b_buf(2, er->srvid, er->ecm + 3);
2640
2641 for(j = 0, n = 5; j < demux[demux_id].STREAMpidcount; j++, n += 2)
2642 {
2643 i2b_buf(2, demux[demux_id].STREAMpids[j], er->ecm + n);
2644 er->ecm[2] += 2;
2645 er->ecmlen += 2;
2646 }
2647
2648 cs_log("Demuxer %d trying to descramble PID %d CAID %04X PROVID %06X ECMPID %04X ANY CHID PMTPID %04X VPID %04X",
2649 demux_id,
2650 pid,
2651 demux[demux_id].ECMpids[pid].CAID,
2652 demux[demux_id].ECMpids[pid].PROVID,
2653 demux[demux_id].ECMpids[pid].ECM_PID,
2654 demux[demux_id].pmtpid,
2655 demux[demux_id].ECMpids[pid].VPID);
2656
2657 demux[demux_id].curindex = pid; // set current pid to the fresh started one
2658 dvbapi_start_filter(demux_id,
2659 pid,
2660 demux[demux_id].ECMpids[pid].ECM_PID,
2661 demux[demux_id].ECMpids[pid].CAID,
2662 demux[demux_id].ECMpids[pid].PROVID,
2663 0x80,
2664 0xF0,
2665 3000,
2666 TYPE_ECM);
2667
2668 started = 1;
2669 request_cw(dvbapi_client, er, demux_id, 0); // do not register ecm since this try!
2670 fake_ecm = 1;
2671 break; // we started an ecmfilter so stop looking for next matching reader!
2672 }
2673
2674 if(match) // if matching reader found check for irdeto cas if local irdeto card check if it received emms in last 60 minutes
2675 {
2676 if(caid_is_irdeto(er->caid)) // irdeto cas init irdeto_curindex to wait for first index (00)
2677 {
2678 if(demux[demux_id].ECMpids[pid].irdeto_curindex == 0xFE)
2679 {
2680 demux[demux_id].ECMpids[pid].irdeto_curindex = 0x00;
2681 }
2682 }
2683
2684 if(p && p->chid < 0x10000) // do we prio a certain chid?
2685 {
2686 cs_log("Demuxer %d trying to descramble PID %d CAID %04X PROVID %06X ECMPID %04X CHID %04X PMTPID %04X VPID %04X",
2687 demux_id, pid,
2688 demux[demux_id].ECMpids[pid].CAID,
2689 demux[demux_id].ECMpids[pid].PROVID,
2690 demux[demux_id].ECMpids[pid].ECM_PID,
2691 demux[demux_id].ECMpids[pid].CHID,
2692 demux[demux_id].pmtpid,
2693 demux[demux_id].ECMpids[pid].VPID);
2694 }
2695 else
2696 {
2697 cs_log("Demuxer %d trying to descramble PID %d CAID %04X PROVID %06X ECMPID %04X ANY CHID PMTPID %04X VPID %04X",
2698 demux_id, pid,
2699 demux[demux_id].ECMpids[pid].CAID,
2700 demux[demux_id].ECMpids[pid].PROVID,
2701 demux[demux_id].ECMpids[pid].ECM_PID,
2702 demux[demux_id].pmtpid,
2703 demux[demux_id].ECMpids[pid].VPID);
2704 }
2705
2706 demux[demux_id].curindex = pid; // set current pid to the fresh started one
2707 dvbapi_start_filter(demux_id,
2708 pid,
2709 demux[demux_id].ECMpids[pid].ECM_PID,
2710 demux[demux_id].ECMpids[pid].CAID,
2711 demux[demux_id].ECMpids[pid].PROVID,
2712 0x80,
2713 0xF0,
2714 3000,
2715 TYPE_ECM);
2716
2717 started = 1;
2718 break; // we started an ecmfilter so stop looking for next matching reader!
2719 }
2720 }
2721
2722 if(demux[demux_id].curindex != pid)
2723 {
2724 cs_log("Demuxer %d impossible to descramble PID %d CAID %04X PROVID %06X ECMPID %04X PMTPID %04X (NO MATCHING READER)",
2725 demux_id, pid,
2726 demux[demux_id].ECMpids[pid].CAID,
2727 demux[demux_id].ECMpids[pid].PROVID,
2728 demux[demux_id].ECMpids[pid].ECM_PID,
2729 demux[demux_id].pmtpid);
2730
2731 demux[demux_id].ECMpids[pid].checked = 4; // flag this pid as checked
2732 demux[demux_id].ECMpids[pid].status = -1; // flag this pid as unusable
2733 dvbapi_edit_channel_cache(demux_id, pid, 0); // remove this pid from channelcache
2734 }
2735
2736 if(!fake_ecm)
2737 {
2738 NULLFREE(er);
2739 }
2740 return started;
2741}
2742
2743struct s_dvbapi_priority *dvbapi_check_prio_match_emmpid(int32_t demux_id, uint16_t caid, uint32_t provid, char type)
2744{
2745 struct s_dvbapi_priority *p;
2746 int32_t i;
2747 uint16_t ecm_pid = 0;
2748
2749 for(i = 0; i < demux[demux_id].ECMpidcount; i++)
2750 {
2751 if((demux[demux_id].ECMpids[i].CAID == caid) && (demux[demux_id].ECMpids[i].PROVID == provid))
2752 {
2753 ecm_pid = demux[demux_id].ECMpids[i].ECM_PID;
2754 break;
2755 }
2756 }
2757
2758 if(!ecm_pid)
2759 {
2760 return NULL;
2761 }
2762
2763 for(p = dvbapi_priority; p != NULL; p = p->next)
2764 {
2765 if(p->type != type
2766 || (p->caid && p->caid != caid)
2767 || (p->provid && p->provid != provid)
2768 || (p->ecmpid && p->ecmpid != ecm_pid)
2769 || (p->srvid && p->srvid != demux[demux_id].program_number)
2770 || (p->pidx && p->pidx-1 !=i)
2771 || (p->type == 'i' && (p->chid < 0x10000)))
2772 {
2773 continue;
2774 }
2775
2776 return p;
2777 }
2778 return NULL;
2779}
2780
2781struct s_dvbapi_priority *dvbapi_check_prio_match(int32_t demux_id, int32_t pidindex, char type)
2782{
2783 if(!dvbapi_priority)
2784 {
2785 return NULL;
2786 }
2787
2788 struct s_dvbapi_priority *p;
2789 struct s_ecmpid *ecmpid = &demux[demux_id].ECMpids[pidindex];
2790
2791 for(p = dvbapi_priority; p != NULL; p = p->next)
2792 {
2793 if(p->type != type
2794 || (p->caid && p->caid != ecmpid->CAID)
2795 || (p->provid && p->provid != ecmpid->PROVID)
2796 || (p->ecmpid && p->ecmpid != ecmpid->ECM_PID)
2797 || (p->srvid && p->srvid != demux[demux_id].program_number)
2798 || (p->pidx && p->pidx-1 != pidindex)
2799 || (p->chid < 0x10000 && p->chid != ecmpid->CHID))
2800 {
2801 continue;
2802 }
2803
2804 return p;
2805 }
2806 return NULL;
2807}
2808
2809void dvbapi_process_emm(int32_t demux_id, int32_t filter_num, uint8_t *buffer, uint32_t len)
2810{
2811 EMM_PACKET epg;
2812
2813 struct s_emm_filter *filter = get_emmfilter_by_filternum(demux_id, filter_num + 1); // 0 is used for pending emmfilters, so everything increase 1
2814 if(!filter)
2815 {
2816 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d no filter matches -> SKIP!", demux_id, filter_num + 1);
2817 return;
2818 }
2819
2820 uint32_t provider = filter->provid;
2821 uint16_t caid = filter->caid;
2822 struct s_dvbapi_priority *mapentry = dvbapi_check_prio_match_emmpid(filter->demux_id, filter->caid, filter->provid, 'm');
2823 if(mapentry)
2824 {
2825 cs_log_dbg(D_DVBAPI, "Demuxer %d mapping EMM from %04X@%06X to %04X@%06X",
2826 demux_id, caid, provider, mapentry->mapcaid, mapentry->mapprovid);
2827
2828 caid = mapentry->mapcaid;
2829 provider = mapentry->mapprovid;
2830 }
2831
2832 memset(&epg, 0, sizeof(epg));
2833 i2b_buf(2, caid, epg.caid);
2834 i2b_buf(4, provider, epg.provid);
2835 epg.emmlen = len > sizeof(epg.emm) ? sizeof(epg.emm) : len;
2836 memcpy(epg.emm, buffer, epg.emmlen);
2837
2838 if(config_enabled(READER_IRDETO) && chk_is_betatunnel_caid(caid) == 2)
2839 {
2840 uint16_t ncaid = tunemm_caid_map(FROM_TO, caid, demux[demux_id].program_number);
2841 if(caid != ncaid)
2842 {
2843 irdeto_add_emm_header(&epg);
2844 i2b_buf(2, ncaid, epg.caid);
2845 }
2846 }
2847 do_emm(dvbapi_client, &epg);
2848}
2849
2850void dvbapi_read_priority(void)
2851{
2852 FILE *fp;
2853 char token[128], str1[128];
2854 char type;
2855 int32_t i, ret, count = 0;
2856 const char *cs_prio = "oscam.dvbapi";
2857
2858 fp = fopen(get_config_filename(token, sizeof(token), cs_prio), "r");
2859 if(!fp)
2860 {
2861 cs_log_dbg(D_DVBAPI, "ERROR: Can't open priority file %s", token);
2862 return;
2863 }
2864
2865 if(dvbapi_priority)
2866 {
2867 cs_log_dbg(D_DVBAPI, "reread priority file %s", cs_prio);
2868 struct s_dvbapi_priority *o, *p;
2869 for(p = dvbapi_priority; p != NULL; p = o)
2870 {
2871 o = p->next;
2872 NULLFREE(p);
2873 }
2874 dvbapi_priority = NULL;
2875 }
2876
2877 while(fgets(token, sizeof(token), fp))
2878 {
2879 // Ignore comments and empty lines
2880 if(token[0] == '#' || token[0] == '/' || token[0] == '\n' || token[0] == '\r' || token[0] == '\0' || strlen(token) > 100)
2881 {
2882 continue;
2883 }
2884 memset(str1, 0, 128);
2885
2886 for(i = 0; i < (int)strlen(token) && token[i] == ' '; i++) { ; }
2887
2888 if(i == (int)strlen(token) - 1) // empty line or all spaces
2889 {
2890 continue;
2891 }
2892
2893 for(i = 0; i < (int)strlen(token); i++)
2894 {
2895 if(token[i] == '@')
2896 {
2897 token[i] = ':';
2898 }
2899 }
2900
2901 for(i = 0; i < (int)strlen(token); i++)
2902 {
2903 if((token[i] == ':' || token[i] == ' ') && token[i + 1] == ':') // if "::" or " :"
2904 {
2905 memmove(token + i + 2, token + i + 1, strlen(token) - i + 1); // insert extra position
2906 token[i + 1] = '0'; // and fill it with NULL
2907 }
2908
2909 if(token[i] == '#' || token[i] == '/')
2910 {
2911 token[i] = '\0';
2912 break;
2913 }
2914 }
2915
2916 type = 0;
2917#if defined(WITH_STAPI) || defined(WITH_STAPI5)
2918 uint32_t disablefilter = 0;
2919 ret = sscanf(trim(token), "%c: %63s %63s %d", &type, str1, str1 + 64, &disablefilter);
2920#else
2921 ret = sscanf(trim(token), "%c: %63s %63s", &type, str1, str1 + 64);
2922#endif
2923 type = tolower((uint8_t)type);
2924
2925 if(ret < 1 || (type != 'p' && type != 'i' && type != 'm' && type != 'd' &&
2926 type != 's' && type != 'l' && type != 'j' && type != 'a' && type != 'x'))
2927 {
2928 //fprintf(stderr, "Warning: line containing %s in %s not recognized, ignoring line\n", token, cs_prio);
2929 // fprintf would issue the warning to the command line, which is more consistent with other config warnings
2930 // however it takes OSCam a long time (>4 seconds) to reach this part of the program, so the warnings are
2931 // reaching tty rather late which leads to confusion. So send the warnings to log file instead
2932 cs_log_dbg(D_DVBAPI, "WARN: line containing %s in %s not recognized, ignoring...", token, cs_prio);
2933 continue;
2934 }
2935
2936 struct s_dvbapi_priority *entry;
2937 if(!cs_malloc(&entry, sizeof(struct s_dvbapi_priority)))
2938 {
2939 ret = fclose(fp);
2940 if(ret < 0)
2941 {
2942 cs_log("ERROR: Could not close oscam.dvbapi fd (errno=%d %s)", errno, strerror(errno));
2943 }
2944 return;
2945 }
2946
2947 entry->type = type;
2948 entry->next = NULL;
2949 count++;
2950
2951#if defined(WITH_STAPI) || defined(WITH_STAPI5)
2952 if(type == 's')
2953 {
2954 strncpy(entry->devname, str1, 29);
2955 strncpy(entry->pmtfile, str1 + 64, 29);
2956 entry->disablefilter = disablefilter;
2957 cs_log_dbg(D_DVBAPI, "stapi prio: ret=%d | %c: %s %s | disable %d",
2958 ret, type, entry->devname, entry->pmtfile, disablefilter);
2959
2960 if(!dvbapi_priority)
2961 {
2962 dvbapi_priority = entry;
2963 }
2964 else
2965 {
2966 struct s_dvbapi_priority *p;
2967 for(p = dvbapi_priority; p->next != NULL; p = p->next) { ; }
2968 p->next = entry;
2969 }
2970 continue;
2971 }
2972#endif
2973 char c_srvid[34];
2974 c_srvid[0] = '\0';
2975 uint32_t caid = 0, provid = 0, srvid = 0, ecmpid = 0, cadata = 0;;
2976 uint32_t chid = 0x10000; //chid=0 is a valid chid
2977
2978 ret = sscanf(str1, "%4x:%6x:%33[^:]:%4x:%4x:%8x"SCNx16, &caid, &provid, c_srvid, &ecmpid, &chid, &cadata);
2979 if(ret < 1)
2980 {
2981 cs_log("Error in oscam.dvbapi: ret=%d | %c: %04X %06X %s %04X %04X",
2982 ret, type, caid, provid, c_srvid, ecmpid, chid);
2983 continue; // skip this entry!
2984 }
2985 else
2986 {
2987 cs_log_dbg(D_DVBAPI, "Parsing rule: ret=%d | %c: %04X %06X %s %04X %04X %04X",
2988 ret, type, caid, provid, c_srvid, ecmpid, chid, cadata);
2989 }
2990
2991 entry->caid = caid;
2992 entry->provid = provid;
2993 entry->ecmpid = ecmpid;
2994 entry->chid = chid;
2995 entry->cadata = cadata;
2996 uint32_t delay = 0, force = 0, mapcaid = 0, mapprovid = 0, mapecmpid = 0, pidx = 0;
2997
2998 switch(type)
2999 {
3000 case 'i':
3001 ret = sscanf(str1 + 64, "%1d", &pidx);
3002 entry->pidx = pidx + 1;
3003 if(ret < 1) entry->pidx = 0;
3004 break;
3005
3006 case 'd':
3007 sscanf(str1 + 64, "%4d", &delay);
3008 entry->delay = delay;
3009 break;
3010
3011 case 'l':
3012 entry->delay = dyn_word_atob(str1 + 64);
3013 if(entry->delay == -1) { entry->delay = 0; }
3014 break;
3015
3016 case 'p':
3017 ret = sscanf(str1 + 64, "%1d:%1d", &force, &pidx);
3018 entry->force = force;
3019 entry->pidx = pidx + 1;
3020 if(ret < 2) entry->pidx = 0;
3021 break;
3022
3023 case 'm':
3024 sscanf(str1 + 64, "%4x:%6x", &mapcaid, &mapprovid);
3025 if(!mapcaid) { mapcaid = 0xFFFF; }
3026 entry->mapcaid = mapcaid;
3027 entry->mapprovid = mapprovid;
3028 break;
3029
3030 case 'a':
3031 case 'j':
3032 sscanf(str1 + 64, "%4x:%6x:%4x", &mapcaid, &mapprovid, &mapecmpid);
3033 if(!mapcaid) { mapcaid = 0xFFFF; }
3034 entry->mapcaid = mapcaid;
3035 entry->mapprovid = mapprovid;
3036 entry->mapecmpid = mapecmpid;
3037 break;
3038 }
3039
3040 if(c_srvid[0] == '=')
3041 {
3042 struct s_srvid *this;
3043 for(i = 0; i < 16; i++)
3044 {
3045 for(this = cfg.srvid[i]; this != NULL; this = this->next)
3046 {
3047 if(this->name && strcmp(this->name, c_srvid + 1) == 0)
3048 {
3049 struct s_dvbapi_priority *entry2;
3050 if(!cs_malloc(&entry2, sizeof(struct s_dvbapi_priority)))
3051 {
3052 continue;
3053 }
3054
3055 memcpy(entry2, entry, sizeof(struct s_dvbapi_priority));
3056 entry2->srvid = this->srvid;
3057 cs_log_dbg(D_DVBAPI, "prio srvid: ret=%d | %c: %04X %06X %04X %04X %04X -> map %04X %06X %04X | prio %d | delay %d",
3058 ret,
3059 entry2->type,
3060 entry2->caid,
3061 entry2->provid,
3062 entry2->srvid,
3063 entry2->ecmpid,
3064 entry2->chid,
3065 entry2->mapcaid,
3066 entry2->mapprovid,
3067 entry2->mapecmpid,
3068 entry2->force,
3069 entry2->delay);
3070
3071 if(!dvbapi_priority)
3072 {
3073 dvbapi_priority = entry2;
3074 }
3075 else
3076 {
3077 struct s_dvbapi_priority *p;
3078 for(p = dvbapi_priority; p->next != NULL; p = p->next) { ; }
3079 p->next = entry2;
3080 }
3081 }
3082 }
3083 }
3084 NULLFREE(entry);
3085 continue;
3086 }
3087 else
3088 {
3089 sscanf(c_srvid, "%4x", &srvid);
3090 entry->srvid = srvid;
3091 }
3092 cs_log_dbg(D_DVBAPI, "prio: ret=%d | %c: %04X %06X %04X %04X %04X -> map %04X %06X %04X | prio %d | delay %d",
3093 ret,
3094 entry->type,
3095 entry->caid,
3096 entry->provid,
3097 entry->srvid,
3098 entry->ecmpid,
3099 entry->chid,
3100 entry->mapcaid,
3101 entry->mapprovid,
3102 entry->mapecmpid,
3103 entry->force,
3104 entry->delay);
3105
3106 if(!dvbapi_priority)
3107 {
3108 dvbapi_priority = entry;
3109 }
3110 else
3111 {
3112 struct s_dvbapi_priority *p;
3113 for(p = dvbapi_priority; p->next != NULL; p = p->next) { ; }
3114 p->next = entry;
3115 }
3116 }
3117 cs_log_dbg(D_DVBAPI, "Read %d entries from %s", count, cs_prio);
3118
3119 ret = fclose(fp);
3120 if(ret < 0)
3121 {
3122 cs_log("ERROR: Could not close oscam.dvbapi fd (errno=%d %s)", errno, strerror(errno));
3123 }
3124 return;
3125}
3126
3127void dvbapi_resort_ecmpids(int32_t demux_id)
3128{
3129 int32_t n, cache = 0, matching_done = 0, found = -1, match_reader_count = 0, total_reader = 0;
3130 uint16_t btun_caid = 0;
3131 struct timeb start,end;
3132 cs_ftime(&start);
3133
3134 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3135 {
3136 demux[demux_id].ECMpids[n].status = 0;
3137 demux[demux_id].ECMpids[n].checked = 0;
3138 demux[demux_id].ECMpids[n].irdeto_curindex = 0xFE;
3139 demux[demux_id].ECMpids[n].irdeto_maxindex = 0;
3140 demux[demux_id].ECMpids[n].irdeto_cycle = 0xFE;
3141 demux[demux_id].ECMpids[n].tries = 0xFE;
3142 demux[demux_id].ECMpids[n].table = 0;
3143 }
3144
3145 demux[demux_id].max_status = 0;
3146 demux[demux_id].curindex = -1;
3147 demux[demux_id].pidindex = -1;
3148
3149 struct s_reader *rdr;
3150 int32_t p_order = demux[demux_id].ECMpidcount + 1;
3151 struct s_dvbapi_priority *prio;
3152
3153 // handle prio order in oscam.dvbapi + ignore all chids
3154 for(rdr = first_active_reader; rdr ; rdr = rdr->next)
3155 {
3156 total_reader++; // only need to calculate once!
3157 }
3158
3159 ECM_REQUEST *er;
3160 if(!cs_malloc(&er, sizeof(ECM_REQUEST)))
3161 {
3162 return;
3163 }
3164
3165 for(prio = dvbapi_priority; prio != NULL; prio = prio->next)
3166 {
3167 if(prio->type != 'p' && prio->type != 'i')
3168 {
3169 continue;
3170 }
3171
3172 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3173 {
3174 if(demux[demux_id].ECMpids[n].status == -1) continue; // skip ignores!
3175
3176 er->caid = er->ocaid = demux[demux_id].ECMpids[n].CAID;
3177 er->prid = demux[demux_id].ECMpids[n].PROVID;
3178 er->pid = demux[demux_id].ECMpids[n].ECM_PID;
3179 er->srvid = demux[demux_id].program_number;
3180 er->client = cur_client();
3181 btun_caid = chk_on_btun(SRVID_MASK, er->client, er);
3182
3183 if(prio->type == 'p' && btun_caid)
3184 {
3185 er->caid = btun_caid;
3186 }
3187
3188 if((prio->caid && (prio->caid != er->caid && prio->caid != er->ocaid))
3189 || (prio->provid && prio->provid != er->prid)
3190 || (prio->srvid && prio->srvid != er->srvid)
3191 || (prio->ecmpid && prio->ecmpid != er->pid)
3192 || (prio->pidx && prio->pidx - 1 != n))
3193 {
3194 continue;
3195 }
3196
3197 if(prio->type == 'p') // check for prio
3198 {
3199 if(prio->cadata != 0 && prio->cadata != demux[demux_id].ECMpids[n].cadata)
3200 {
3201 continue;
3202 }
3203
3204 if(prio->chid < 0x10000)
3205 {
3206 demux[demux_id].ECMpids[n].CHID = prio->chid;
3207 }
3208
3209 if(prio->force)
3210 {
3211 int32_t j;
3212 for(j = 0; j < demux[demux_id].ECMpidcount; j++)
3213 {
3214 demux[demux_id].ECMpids[j].status = -1;
3215 }
3216
3217 demux[demux_id].ECMpids[n].status = 1;
3218 demux[demux_id].ECMpids[n].checked = 0;
3219 demux[demux_id].max_status = 1;
3220 demux[demux_id].max_emm_filter = maxfilter - 1;
3221
3222 cs_log_dbg(D_DVBAPI, "Demuxer %d prio forced%s ecmpid %d %04X@%06X:%04X:%04X (file)",
3223 demux_id,
3224 ((prio->caid == er->caid && prio->caid != er->ocaid) ? " betatunneled" : ""),
3225 n,
3226 demux[demux_id].ECMpids[n].CAID,
3227 demux[demux_id].ECMpids[n].PROVID,
3228 demux[demux_id].ECMpids[n].ECM_PID,
3229 (uint16_t) prio->chid);
3230 NULLFREE(er);
3231 return; // go start descrambling since its forced by user!
3232 }
3233 else
3234 {
3235 if(!demux[demux_id].ECMpids[n].status) // only accept first matching prio from oscam.dvbapi
3236 {
3237 demux[demux_id].ECMpids[n].status = total_reader + p_order--;
3238 matching_done = 1;
3239 cs_log_dbg(D_DVBAPI, "Demuxer %d prio%s ecmpid %d %04X@%06X:%04X:%04X weight: %d (file)",
3240 demux_id,
3241 ((prio->caid == er->caid && prio->caid != er->ocaid) ? " betatunneled" : ""),
3242 n,
3243 demux[demux_id].ECMpids[n].CAID,
3244 demux[demux_id].ECMpids[n].PROVID,
3245 demux[demux_id].ECMpids[n].ECM_PID,
3246 (uint16_t) prio->chid,
3247 demux[demux_id].ECMpids[n].status);
3248 }
3249 continue; // evaluate next ecmpid
3250 }
3251 }
3252
3253 // check for ignore all chids
3254 if(prio->type == 'i' && prio->chid == 0x10000 && demux[demux_id].ECMpids[n].status == 0)
3255 {
3256 cs_log_dbg(D_DVBAPI, "Demuxer %d ignore ecmpid %d %04X@%06X:%04X all chids (file)",
3257 demux_id,
3258 n,
3259 demux[demux_id].ECMpids[n].CAID,
3260 demux[demux_id].ECMpids[n].PROVID,
3261 demux[demux_id].ECMpids[n].ECM_PID);
3262 demux[demux_id].ECMpids[n].status = -1;
3263 continue; // evaluate next ecmpid
3264 }
3265 }
3266 }
3267 p_order = demux[demux_id].ECMpidcount + 1;
3268
3269 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3270 {
3271 if(demux[demux_id].ECMpids[n].status == -1)
3272 {
3273 continue; // skip ignores!
3274 }
3275
3276 int32_t nr;
3277 SIDTAB *sidtab;
3278
3279 er->caid = er->ocaid = demux[demux_id].ECMpids[n].CAID;
3280 er->prid = demux[demux_id].ECMpids[n].PROVID;
3281 er->pid = demux[demux_id].ECMpids[n].ECM_PID;
3282 er->srvid = demux[demux_id].program_number;
3283 er->client = cur_client();
3284
3285 btun_caid = chk_on_btun(SRVID_MASK, er->client, er);
3286 if(btun_caid)
3287 {
3288 er->caid = btun_caid;
3289 }
3290
3291 match_reader_count = 0;
3292
3293 for(rdr = first_active_reader; rdr ; rdr = rdr->next)
3294 {
3295 if(matching_reader(er, rdr))
3296 {
3297 match_reader_count++;
3298 }
3299 }
3300
3301 if(match_reader_count == 0)
3302 {
3303 cs_log_dbg(D_DVBAPI, "Demuxer %d ignore ecmpid %d %04X@%06X:%04X:%04X (no matching reader)",
3304 demux_id,
3305 n,
3306 demux[demux_id].ECMpids[n].CAID,
3307 demux[demux_id].ECMpids[n].PROVID,
3308 demux[demux_id].ECMpids[n].ECM_PID,
3309 demux[demux_id].ECMpids[n].CHID);
3310 demux[demux_id].ECMpids[n].status = -1;
3311 continue; // evaluate next ecmpid
3312 }
3313 else // ecmpids with no matching readers are disabled and matching sidtabbits have now highest status
3314 {
3315 for(nr = 0, sidtab = cfg.sidtab; sidtab; sidtab = sidtab->next, nr++)
3316 {
3317 if(sidtab->num_caid | sidtab->num_provid | sidtab->num_srvid)
3318 {
3319 if((cfg.dvbapi_sidtabs.no & ((SIDTABBITS)1 << nr)) && (chk_srvid_match(er, sidtab)))
3320 {
3321 demux[demux_id].ECMpids[n].status = -1; //ignore
3322 cs_log_dbg(D_DVBAPI, "Demuxer %d ignore ecmpid %d %04X@%06X:%04X (service %s pos %d)",
3323 demux_id,
3324 n,
3325 demux[demux_id].ECMpids[n].CAID,
3326 demux[demux_id].ECMpids[n].PROVID,
3327 demux[demux_id].ECMpids[n].ECM_PID,
3328 sidtab->label,
3329 nr);
3330 continue; // evaluate next ecmpid
3331 }
3332 if((cfg.dvbapi_sidtabs.ok & ((SIDTABBITS) 1 << nr)) && (chk_srvid_match(er, sidtab)))
3333 {
3334 demux[demux_id].ECMpids[n].status++; // priority
3335 cs_log_dbg(D_DVBAPI, "Demuxer %d prio ecmpid %d %04X@%06X:%04X weight: %d (service %s pos %d)",
3336 demux_id,
3337 n,
3338 demux[demux_id].ECMpids[n].CAID,
3339 demux[demux_id].ECMpids[n].PROVID,
3340 demux[demux_id].ECMpids[n].ECM_PID,
3341 demux[demux_id].ECMpids[n].status,
3342 sidtab->label,
3343 nr);
3344 }
3345 }
3346 }
3347 }
3348 }
3349
3350 // ecmpid with highest prio from oscam.dvbapi has now highest status
3351 // check all ecmpids and get the highest amount cache-ex and local readers
3352 int32_t max_local_matching_reader = 0, max_cacheex_reader = 0;
3353
3354 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3355 {
3356 int32_t count_matching_cacheex_reader = 0, count_matching_local_reader = 0;
3357 if(demux[demux_id].ECMpids[n].status == -1)
3358 {
3359 continue; // skip ignores!
3360 }
3361
3362 er->caid = er->ocaid = demux[demux_id].ECMpids[n].CAID;
3363 er->prid = demux[demux_id].ECMpids[n].PROVID;
3364 er->pid = demux[demux_id].ECMpids[n].ECM_PID;
3365 er->srvid = demux[demux_id].program_number;
3366 er->client = cur_client();
3367
3368 btun_caid = chk_on_btun(SRVID_MASK, er->client, er);
3369 if(btun_caid)
3370 {
3371 er->caid = btun_caid;
3372 }
3373
3374 for(rdr = first_active_reader; rdr ; rdr = rdr->next)
3375 {
3376 if(matching_reader(er, rdr))
3377 {
3378 if(cacheex_reader(rdr))
3379 {
3380 count_matching_cacheex_reader++;
3381 }
3382 else if(is_localreader(rdr, er))
3383 {
3384 count_matching_local_reader++;
3385 }
3386 }
3387 }
3388
3389 if(max_local_matching_reader < count_matching_local_reader)
3390 {
3391 max_local_matching_reader = count_matching_local_reader;
3392 }
3393
3394 if(max_cacheex_reader < count_matching_cacheex_reader)
3395 {
3396 max_cacheex_reader = count_matching_cacheex_reader;
3397 }
3398 }
3399
3400 if(max_local_matching_reader != 0 || max_cacheex_reader != 0)
3401 {
3402 p_order = demux[demux_id].ECMpidcount * 2;
3403 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3404 {
3405 int32_t count_matching_cacheex_reader = 0, count_matching_local_reader = 0;
3406 int32_t localprio = 1, cacheexprio = 1;
3407
3408 if(demux[demux_id].ECMpids[n].status == -1)
3409 {
3410 continue; // skip ignores!
3411 }
3412
3413 if(cfg.preferlocalcards == 2) // ecmpids with local reader get highest prio
3414 {
3415 localprio = max_cacheex_reader + p_order + 1;
3416 }
3417 else if(cfg.preferlocalcards == 1) // ecmpids with cacheex reader get highest prio
3418 {
3419 cacheexprio = max_local_matching_reader + p_order + 1;
3420 }
3421
3422 er->caid = er->ocaid = demux[demux_id].ECMpids[n].CAID;
3423 er->prid = demux[demux_id].ECMpids[n].PROVID;
3424 er->pid = demux[demux_id].ECMpids[n].ECM_PID;
3425 er->srvid = demux[demux_id].program_number;
3426 er->client = cur_client();
3427
3428 btun_caid = chk_on_btun(SRVID_MASK, er->client, er);
3429 if(btun_caid)
3430 {
3431 er->caid = btun_caid;
3432 }
3433
3434 int32_t oldstatus = demux[demux_id].ECMpids[n].status;
3435 int32_t anyreader = 0;
3436
3437 for(rdr = first_active_reader; rdr; rdr = rdr->next)
3438 {
3439 if(matching_reader(er, rdr))
3440 {
3441 if(cfg.preferlocalcards == 0)
3442 {
3443 if(!matching_done)
3444 {
3445 demux[demux_id].ECMpids[n].status++;
3446 }
3447 anyreader++;
3448 continue;
3449 }
3450
3451 if(cacheex_reader(rdr))
3452 {
3453 demux[demux_id].ECMpids[n].status += cacheexprio;
3454 count_matching_cacheex_reader++;
3455 cacheexprio = 1;
3456 }
3457
3458 if(is_localreader(rdr, er))
3459 {
3460 demux[demux_id].ECMpids[n].status += localprio;
3461 count_matching_local_reader++;
3462 localprio = 1;
3463 }
3464 }
3465 }
3466
3467 if(oldstatus != demux[demux_id].ECMpids[n].status)
3468 {
3469 if(anyreader)
3470 {
3471 cs_log_dbg(D_DVBAPI, "Demuxer %d prio ecmpid %d %04X@%06X:%04X:%04X weight: %d (%d readers)",
3472 demux_id,
3473 n,
3474 demux[demux_id].ECMpids[n].CAID,
3475 demux[demux_id].ECMpids[n].PROVID,
3476 demux[demux_id].ECMpids[n].ECM_PID,
3477 demux[demux_id].ECMpids[n].CHID,
3478 demux[demux_id].ECMpids[n].status,
3479 anyreader);
3480 }
3481 else
3482 {
3483 cs_log_dbg(D_DVBAPI, "Demuxer %d prio ecmpid %d %04X@%06X:%04X:%04X weight: %d (%d local and %d cacheex readers)",
3484 demux_id,
3485 n,
3486 demux[demux_id].ECMpids[n].CAID,
3487 demux[demux_id].ECMpids[n].PROVID,
3488 demux[demux_id].ECMpids[n].ECM_PID,
3489 demux[demux_id].ECMpids[n].CHID,
3490 demux[demux_id].ECMpids[n].status,
3491 count_matching_local_reader,
3492 count_matching_cacheex_reader);
3493 }
3494 }
3495 }
3496 }
3497
3498 struct s_channel_cache *c = NULL;
3499
3500 for(n = 0; n < demux[demux_id].ECMpidcount && matching_done == 0; n++)
3501 {
3502 if(demux[demux_id].ECMpids[n].status == -1)
3503 {
3504 continue; // skip ignores!
3505 }
3506
3507 c = dvbapi_find_channel_cache(demux_id, n, 0); // find exact channel match
3508 if(c != NULL)
3509 {
3510 found = n;
3511 cache = 2; // found cache entry with higher priority
3512 demux[demux_id].ECMpids[n].status++; // prioritize CAIDs which already decoded same caid:provid:srvid
3513
3514 if(c->chid < 0x10000)
3515 {
3516 demux[demux_id].ECMpids[n].CHID = c->chid; // if chid registered in cache -> use it!
3517 }
3518 cs_log_dbg(D_DVBAPI, "Demuxer %d prio ecmpid %d %04X@%06X:%04X weight: %d (found caid/provid/srvid in cache)",
3519 demux_id,
3520 n,
3521 demux[demux_id].ECMpids[n].CAID,
3522 demux[demux_id].ECMpids[n].PROVID,
3523 demux[demux_id].ECMpids[n].ECM_PID,
3524 demux[demux_id].ECMpids[n].status);
3525 break;
3526 }
3527 }
3528
3529 if(found == -1)
3530 {
3531 // prioritize CAIDs which already decoded same caid:provid
3532 for(n = 0; n < demux[demux_id].ECMpidcount && matching_done == 0; n++)
3533 {
3534 if(demux[demux_id].ECMpids[n].status == -1) continue; // skip ignores!
3535
3536 c = dvbapi_find_channel_cache(demux_id, n, 1);
3537 if(c != NULL)
3538 {
3539 cache = 1; //found cache entry
3540 demux[demux_id].ECMpids[n].status++;
3541 cs_log_dbg(D_DVBAPI, "Demuxer %d prio ecmpid %d %04X@%06X:%04X weight: %d (found caid/provid in cache)",
3542 demux_id,
3543 n,
3544 demux[demux_id].ECMpids[n].CAID,
3545 demux[demux_id].ECMpids[n].PROVID,
3546 demux[demux_id].ECMpids[n].ECM_PID,
3547 demux[demux_id].ECMpids[n].status);
3548 }
3549 }
3550 }
3551
3552 int32_t max_status = 0;
3553 int32_t highest_priopid = -1;
3554
3555 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3556 {
3557 if(demux[demux_id].ECMpids[n].status == -1)
3558 {
3559 continue; // skip ignores!
3560 }
3561
3562 if(demux[demux_id].ECMpids[n].status > max_status) // find highest prio pid
3563 {
3564 max_status = demux[demux_id].ECMpids[n].status;
3565 highest_priopid = n;
3566 }
3567
3568 if(!USE_OPENXCAS) // openxcas doesnt use prio and non-prio run: all are equal!
3569 {
3570 if(demux[demux_id].ECMpids[n].status == 0)
3571 {
3572 demux[demux_id].ECMpids[n].checked = 2; // set pids with no status to no prio run
3573 }
3574 }
3575 }
3576
3577 demux[demux_id].max_status = max_status; // register maxstatus
3578
3579 // Found entry in channelcache that is valid and has exact match on srvid
3580 if(highest_priopid != -1 && found == highest_priopid && cache == 2)
3581 {
3582 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3583 {
3584 if(demux[demux_id].ECMpids[n].status == -1)
3585 {
3586 continue; // skip ignores!
3587 }
3588
3589 if(n != found)
3590 {
3591 // disable non matching pid
3592 demux[demux_id].ECMpids[n].status = -1;
3593 }
3594 else
3595 {
3596 demux[demux_id].ECMpids[n].status = 1;
3597 }
3598 }
3599 demux[demux_id].max_emm_filter = maxfilter - 1;
3600 demux[demux_id].max_status = 1;
3601 cs_log("Demuxer %d found channel in cache and matching prio -> start descrambling ecmpid %d ", demux_id, found);
3602 }
3603
3604 NULLFREE(er);
3605 cs_ftime(&end);
3606 int64_t gone = comp_timeb(&end, &start);
3607 cs_log_dbg(D_DVBAPI, "Demuxer %d sorting the ecmpids took %"PRId64" ms", demux_id, gone);
3608 return;
3609}
3610
3611static void dvbapi_priority_read_entry_add(int32_t demux_id, uint16_t video_pid)
3612{
3613 struct s_dvbapi_priority *add_entry;
3614
3615 for(add_entry = dvbapi_priority; add_entry != NULL; add_entry = add_entry->next)
3616 {
3617 // ECM pid is misused to hold PMT pid in case of 'A' rule.
3618 // Some receivers don't forward the PMT pid, so use the video pid instead
3619 if(add_entry->type != 'a' || add_entry->srvid != demux[demux_id].program_number
3620 || (add_entry->ecmpid && demux[demux_id].pmtpid && add_entry->ecmpid != demux[demux_id].pmtpid)
3621 || (add_entry->ecmpid && !demux[demux_id].pmtpid && add_entry->ecmpid != video_pid))
3622 {
3623 continue;
3624 }
3625
3626 dvbapi_add_ecmpid(demux_id, add_entry->mapcaid, add_entry->mapecmpid, add_entry->mapprovid, 0, "(fake ecm pid)");
3627
3628 cs_log_dbg(D_DVBAPI, "Demuxer %d added fake ecm pid %04X@%06X:%04X for program %04X", demux_id,
3629 add_entry->mapcaid, add_entry->mapprovid, add_entry->mapecmpid, demux[demux_id].program_number);
3630 break;
3631 }
3632}
3633
3634static void dvbapi_priority_read_entry_map(int32_t demux_id)
3635{
3636 int32_t j;
3637 struct s_dvbapi_priority *map_entry;
3638
3639 for(j = 0; j < demux[demux_id].ECMpidcount; j++)
3640 {
3641 map_entry = dvbapi_check_prio_match(demux_id, j, 'm');
3642 if(map_entry)
3643 {
3644 cs_log_dbg(D_DVBAPI, "Demuxer %d mapping ecm pid %d from %04X@%06X to %04X@%06X",
3645 demux_id, j, demux[demux_id].ECMpids[j].CAID, demux[demux_id].ECMpids[j].PROVID,
3646 map_entry->mapcaid, map_entry->mapprovid);
3647
3648 demux[demux_id].ECMpids[j].CAID = map_entry->mapcaid;
3649 demux[demux_id].ECMpids[j].PROVID = map_entry->mapprovid;
3650 }
3651 }
3652}
3653
3654static void dvbapi_priority_read_entry_extra(int32_t demux_id)
3655{
3656 struct s_dvbapi_priority *extra_entry;
3657 int32_t j, k, l, m, extra_demux_id;
3658
3659 for(extra_entry = dvbapi_priority; extra_entry != NULL; extra_entry = extra_entry->next)
3660 {
3661 if(extra_entry->type != 'x')
3662 {
3663 continue;
3664 }
3665
3666 for(j = 0; j <= demux[demux_id].ECMpidcount; ++j)
3667 {
3668 if((extra_entry->caid && extra_entry->caid != demux[demux_id].ECMpids[j].CAID)
3669 || (extra_entry->provid && extra_entry->provid != demux[demux_id].ECMpids[j].PROVID)
3670 || (extra_entry->ecmpid && extra_entry->ecmpid != demux[demux_id].ECMpids[j].ECM_PID)
3671 || (extra_entry->srvid && extra_entry->srvid != demux[demux_id].program_number))
3672 {
3673 continue;
3674 }
3675
3676 cs_log("Mapping ecm pid %04X@%06X:%04X:%04X to extra demuxer",
3677 extra_entry->caid, extra_entry->provid, extra_entry->ecmpid, extra_entry->srvid);
3678
3679 for(extra_demux_id = 0; extra_demux_id < MAX_DEMUX; extra_demux_id++)
3680 {
3681 if(demux[extra_demux_id].program_number != 0)
3682 {
3683 continue; // Skip occupied demuxers
3684 }
3685 }
3686
3687 if(extra_demux_id >= MAX_DEMUX)
3688 {
3689 cs_log("There is no free demuxer for extra streams");
3690 continue;
3691 }
3692
3693 demux[extra_demux_id].ECMpids[0] = demux[demux_id].ECMpids[j];
3694 demux[extra_demux_id].ECMpidcount = 1;
3695 demux[extra_demux_id].STREAMpidcount = 0;
3696 demux[extra_demux_id].program_number = demux[demux_id].program_number;
3697 demux[extra_demux_id].pmtpid = demux[demux_id].pmtpid;
3698 demux[extra_demux_id].demux_index = demux[demux_id].demux_index;
3699 demux[extra_demux_id].adapter_index = demux[demux_id].adapter_index;
3700 demux[extra_demux_id].ca_mask = demux[demux_id].ca_mask;
3701 demux[extra_demux_id].socket_fd = demux[demux_id].socket_fd;
3702 demux[extra_demux_id].stop_descrambling = false;
3703 demux[extra_demux_id].rdr = NULL;
3704 demux[extra_demux_id].curindex = -1;
3705
3706 // Add streams to extra demux
3707 for(k = 0; k < demux[demux_id].STREAMpidcount; ++k)
3708 {
3709 if(!demux[demux_id].ECMpids[j].streams || (demux[demux_id].ECMpids[j].streams & (1 << k)))
3710 {
3711 demux[extra_demux_id].ECMpids[0].streams |= (1 << demux[extra_demux_id].STREAMpidcount);
3712 demux[extra_demux_id].STREAMpids[demux[extra_demux_id].STREAMpidcount] = demux[demux_id].STREAMpids[k];
3713 demux[extra_demux_id].STREAMpidsType[demux[extra_demux_id].STREAMpidcount] = demux[demux_id].STREAMpidsType[k];
3714 ++demux[extra_demux_id].STREAMpidcount;
3715
3716 // Shift stream associations in normal demux because we will remove the stream entirely
3717 for(l = 0; l < demux[demux_id].ECMpidcount; ++l)
3718 {
3719 for(m = k; m < demux[demux_id].STREAMpidcount - 1; ++m)
3720 {
3721 if(demux[demux_id].ECMpids[l].streams & (1 << (m + 1)))
3722 {
3723 demux[demux_id].ECMpids[l].streams |= (1 << m);
3724 }
3725 else
3726 {
3727 demux[demux_id].ECMpids[l].streams &= ~(1 << m);
3728 }
3729 }
3730 }
3731
3732 // Remove stream association from normal demux device
3733 for(l = k; l < demux[demux_id].STREAMpidcount - 1; ++l)
3734 {
3735 demux[demux_id].STREAMpids[l] = demux[demux_id].STREAMpids[l + 1];
3736 demux[demux_id].STREAMpidsType[l] = demux[demux_id].STREAMpidsType[l + 1];
3737 }
3738
3739 --demux[demux_id].STREAMpidcount;
3740 --k;
3741 }
3742 }
3743
3744 // Remove ecm pid from normal demuxer
3745 for(k = j; k < demux[demux_id].ECMpidcount; ++k)
3746 {
3747 demux[demux_id].ECMpids[k] = demux[demux_id].ECMpids[k + 1];
3748 }
3749
3750 --demux[demux_id].ECMpidcount;
3751 --j;
3752
3753 if(demux[extra_demux_id].STREAMpidcount <= 0)
3754 {
3755 cs_log("Found no streams for extra demuxer. Not starting additional decoding on it.");
3756
3757 demux[extra_demux_id].program_number = 0;
3758 demux[extra_demux_id].stop_descrambling = true;
3759 }
3760
3761 if(demux[demux_id].STREAMpidcount < 1)
3762 {
3763 cs_log("Found no streams for normal demuxer. Not starting additional decoding on it.");
3764 }
3765 }
3766 }
3767}
3768
3769static void dvbapi_parse_ca_descriptor(int32_t demux_id, const uint8_t *buffer, uint8_t descriptor_length)
3770{
3771 uint16_t i, ca_system_id, ca_pid;
3772 uint32_t ca_provider = 0, ca_data = 0;
3773 char txt[40]; // room for PBM: 8 byte pbm and DATE: date
3774 memset(txt, 0x00, sizeof(txt));
3775
3776 if(descriptor_length < 4)
3777 {
3778 return; // CA descriptor has a minimum length of 4 bytes
3779 }
3780
3781 ca_system_id = b2i(2, buffer);
3782 ca_pid = b2i(2, buffer + 2) & 0x1FFF;
3783
3784 if(caid_is_seca(ca_system_id))
3785 {
3786 for(i = 2; i < descriptor_length; i += 15)
3787 {
3788 ca_pid = b2i(2, buffer + i) & 0x1FFF;
3789 ca_provider = b2i(2, buffer + i + 2);
3790
3791 int8_t year = buffer[i + 13] >> 1;
3792 int8_t month = (((buffer[i + 13] & 0x01) << 3) | (buffer[i + 14] >> 5));
3793 int8_t day = buffer[i + 14] & 0x1F;
3794
3795 snprintf(txt, sizeof(txt), "PBM: ");
3796 cs_hexdump(0, buffer + i + 5, 8, txt + 5, (2 * 8) + 1); // hexdump 8 byte pbm
3797 snprintf(txt + 20, sizeof(txt) - 20, " DATE: %d-%d-%d", day, month, year + 1990);
3798
3799 dvbapi_add_ecmpid(demux_id, ca_system_id, ca_pid, ca_provider, 0, txt);
3800 }
3801 }
3802 else
3803 {
3804 if(caid_is_viaccess(ca_system_id) && descriptor_length == 0x0F && buffer[10] == 0x14)
3805 {
3806 ca_provider = b2i(3, buffer + 12) & 0xFFFFF0;
3807 }
3808 else if(caid_is_nagra(ca_system_id) && descriptor_length == 0x07)
3809 {
3810 ca_provider = b2i(2, buffer + 5);
3811 }
3812 else if((ca_system_id >> 8 == 0x4A || ca_system_id == 0x2710) && descriptor_length > 0x04)
3813 {
3814 ca_provider = buffer[4];
3815
3816 if(caid_is_dre(ca_system_id) && descriptor_length == 0x0A)
3817 {
3818 ca_data = b2i(4, buffer + 6);
3819 snprintf(txt, 40, "CA DATA: %X", ca_data);
3820 }
3821 }
3822
3823 dvbapi_add_ecmpid(demux_id, ca_system_id, ca_pid, ca_provider, ca_data, txt);
3824 }
3825}
3826
3827static void dvbapi_parse_pmt_descriptors(int32_t demux_id, const uint8_t *buffer, uint16_t length, uint8_t *type)
3828{
3829 uint16_t i, j;
3830 uint8_t descriptor_tag, descriptor_length;
3831
3832 for(i = 0; i + 1 < length; i += 2 + descriptor_length)
3833 {
3834 descriptor_tag = buffer[i];
3835 descriptor_length = buffer[i + 1];
3836
3837 cs_log_dbg(D_DVBAPI, "Demuxer %d found %s descriptor (tag: %02X length: %02X)",
3838 demux_id, get_descriptor_tag_txt(descriptor_tag), descriptor_tag, descriptor_length);
3839
3840 switch(descriptor_tag)
3841 {
3842 case 0x05: // Registration descriptor
3843 {
3844 // "HDMV" format identifier is removed
3845 // OSCam does not need to know about Blu-ray
3846 const char format_identifiers_audio[10][5] =
3847 {
3848 "AC-3", "BSSD", "dmat", "DRA1", "DTS1",
3849 "DTS2", "DTS3", "EAC3", "mlpa", "Opus",
3850 };
3851
3852 for(j = 0; j < 10; j++)
3853 {
3854 if(memcmp(buffer + i + 2, format_identifiers_audio[j], 4) == 0)
3855 {
3856 *type = STREAM_AUDIO;
3857 break;
3858 }
3859 }
3860 break;
3861 }
3862
3863 case 0x09: // CA descriptor
3864 {
3865 dvbapi_parse_ca_descriptor(demux_id, buffer + i + 2, descriptor_length);
3866 break;
3867 }
3868
3869 case 0x59: // Subtitling descriptor (DVB)
3870 {
3871 *type = STREAM_SUBTITLE;
3872 break;
3873 }
3874
3875 case 0x6A: // AC-3 descriptor (DVB)
3876 case 0x7A: // Enhanced AC-3 descriptor (DVB)
3877 case 0x7B: // DTS descriptor (DVB)
3878 case 0x7C: // AAC descriptor (DVB)
3879 {
3880 *type = STREAM_AUDIO;
3881 break;
3882 }
3883
3884 case 0x7F: // Extension descriptor (DVB)
3885 {
3886 uint8_t extension_descriptor_tag = buffer[i + 2];
3887
3888 cs_log_dbg(D_DVBAPI, "Demuxer %d found %s descriptor (extension tag: %02X)",
3889 demux_id, get_extension_descriptor_txt(extension_descriptor_tag), extension_descriptor_tag);
3890
3891 switch(extension_descriptor_tag)
3892 {
3893 case 0x0E: // DTS-HD descriptor (DVB)
3894 case 0x0F: // DTS Neural descriptor (DVB)
3895 case 0x15: // AC-4 descriptor (DVB)
3896 *type = STREAM_AUDIO;
3897 break;
3898
3899 default:
3900 *type = STREAM_UNDEFINED;
3901 break;
3902 }
3903 break;
3904 }
3905
3906 case 0x81: // AC-3 descriptor (ATSC)
3907 {
3908 *type = STREAM_AUDIO;
3909 cs_log_dbg(D_DVBAPI, "Demuxer %d assuming AC-3 descriptor (ATSC)", demux_id);
3910 break;
3911 }
3912
3913 default:
3914 break;
3915 }
3916 }
3917}
3918
3919void request_cw(struct s_client *client, ECM_REQUEST *er, int32_t demux_id, uint8_t delayed_ecm_check)
3920{
3921 if(!er) { return; }
3922
3923 int32_t filternum = dvbapi_set_section_filter(demux_id, er, -1); // set ecm filter to odd -> even and visaversa
3924 if(filternum < 0)
3925 {
3926 cs_log_dbg(D_DVBAPI, "Demuxer %d not requesting cw -> ecm filter was killed!", demux_id);
3927 NULLFREE(er);
3928 return;
3929 }
3930
3931 if(!delayed_ecm_check) // no delayed ecm check for this filter
3932 {
3933 memset(demux[demux_id].demux_fd[filternum].lastecmd5, 0, CS_ECMSTORESIZE); // no ecm delay check: zero it!
3934 }
3935 else
3936 {
3937 uint8_t md5tmp[MD5_DIGEST_LENGTH];
3938 MD5(er->ecm, er->ecmlen, md5tmp);
3939
3940 if(!memcmp(demux[demux_id].demux_fd[filternum].prevecmd5, md5tmp, CS_ECMSTORESIZE))
3941 {
3942 if(demux[demux_id].demux_fd[filternum].prevresult < E_NOTFOUND)
3943 {
3944 cs_log_dbg(D_DVBAPI, "Demuxer %d not requesting same ecm again! -> SKIP!", demux_id);
3945 NULLFREE(er);
3946 return;
3947 }
3948 else
3949 {
3950 cs_log_dbg(D_DVBAPI, "Demuxer %d requesting same ecm again (previous result was not found!)", demux_id);
3951 }
3952 }
3953 else if(!memcmp(demux[demux_id].demux_fd[filternum].lastecmd5, md5tmp, CS_ECMSTORESIZE))
3954 {
3955 if(demux[demux_id].demux_fd[filternum].lastresult < E_NOTFOUND)
3956 {
3957 cs_log_dbg(D_DVBAPI, "Demuxer %d not requesting same ecm again! -> SKIP!", demux_id);
3958 NULLFREE(er);
3959 return;
3960 }
3961 else
3962 {
3963 cs_log_dbg(D_DVBAPI, "Demuxer %d requesting same ecm again (previous result was not found!)", demux_id);
3964 }
3965 }
3966
3967 memcpy(demux[demux_id].demux_fd[filternum].prevecmd5, demux[demux_id].demux_fd[filternum].lastecmd5, CS_ECMSTORESIZE);
3968 demux[demux_id].demux_fd[filternum].prevresult = demux[demux_id].demux_fd[filternum].lastresult;
3969 memcpy(demux[demux_id].demux_fd[filternum].lastecmd5, md5tmp, CS_ECMSTORESIZE);
3970 demux[demux_id].demux_fd[filternum].lastresult = 0xFF;
3971 }
3972
3973 er->adapter_index = demux[demux_id].adapter_index;
3974 cs_log_dbg(D_DVBAPI, "Demuxer %d get controlword!", demux_id);
3975 get_cw(client, er);
3976
3977#ifdef WITH_DEBUG
3978 char buf[ECM_FMT_LEN];
3979 format_ecm(er, buf, ECM_FMT_LEN);
3980 cs_log_dbg(D_DVBAPI, "Demuxer %d request controlword for ecm %s", demux_id, buf);
3981#endif
3982}
3983
3984void dvbapi_try_next_caid(int32_t demux_id, int8_t checked, uint32_t msgid)
3985{
3986 int32_t n, j, found = -1, started = 0;
3987 int32_t status = demux[demux_id].max_status;
3988
3989 for(j = status; j >= 0; j--) // largest status first!
3990 {
3991 for(n = 0; n < demux[demux_id].ECMpidcount; n++)
3992 {
3993 //cs_log_dbg(D_DVBAPI,"Demuxer %d PID %d checked = %d status = %d (searching for pid with status = %d)",
3994 // demux_id, n, demux[demux_id].ECMpids[n].checked, demux[demux_id].ECMpids[n].status, j);
3995
3996 if(demux[demux_id].ECMpids[n].checked == checked && demux[demux_id].ECMpids[n].status == j)
3997 {
3998 found = n;
3999 openxcas_set_provid(demux[demux_id].ECMpids[found].PROVID);
4000 openxcas_set_caid(demux[demux_id].ECMpids[found].CAID);
4001 openxcas_set_ecm_pid(demux[demux_id].ECMpids[found].ECM_PID);
4002
4003 // fixup for cas that need emm first!
4004 if(caid_is_irdeto(demux[demux_id].ECMpids[found].CAID) || (caid_is_dre(demux[demux_id].ECMpids[found].CAID)
4005 && ((demux[demux_id].ECMpids[found].PROVID == 0x11 || demux[demux_id].ECMpids[found].PROVID == 0xFE))))
4006 {
4007 demux[demux_id].emmstart.time = 0;
4008 }
4009
4010 started = dvbapi_start_descrambling(demux_id, found, checked, msgid);
4011 if(cfg.dvbapi_requestmode == 0 && started == 1)
4012 {
4013 return; // in requestmode 0 we only start 1 ecm request at the time
4014 }
4015 }
4016 }
4017 }
4018
4019 if(found == -1 && demux[demux_id].pidindex == -1)
4020 {
4021 cs_log("Demuxer %d no suitable readers found that can be used for decoding!", demux_id);
4022 return;
4023 }
4024}
4025
4026static void dvbapi_parse_pmt_program_info(int32_t demux_id, const uint8_t *buffer, uint16_t length, uint8_t *ca_pmt_cmd_id)
4027{
4028 uint16_t i, offset = 0;
4029 uint8_t descriptor_tag, descriptor_length;
4030
4031 if(ca_pmt_cmd_id != NULL) // We are on CA PMT parsing
4032 {
4033 *ca_pmt_cmd_id = buffer[0];
4034 offset = 1;
4035 }
4036
4037 for(i = offset; i + 1 < length; i += 2 + descriptor_length)
4038 {
4039 descriptor_tag = buffer[i];
4040 descriptor_length = buffer[i + 1];
4041
4042 if(descriptor_tag == 0x09) // We only care about CA descriptors at program level
4043 {
4044 dvbapi_parse_ca_descriptor(demux_id, buffer + i + 2, descriptor_length);
4045 }
4046 }
4047}
4048
4049static void dvbapi_parse_pmt_es_info(int32_t demux_id, const uint8_t *buffer, uint16_t length, uint8_t *ca_pmt_cmd_id, uint16_t *video_pid)
4050{
4051 uint16_t i, elementary_pid, es_info_length, offset = 0;
4052 uint8_t stream_type, type;
4053
4054 for(i = 0; i + 4 < length; i += 5 + es_info_length)
4055 {
4056 if(demux[demux_id].STREAMpidcount >= MAX_STREAM_PIDS)
4057 {
4058 cs_log("Demuxer %d reached maximum number of elementary streams", demux_id);
4059 break;
4060 }
4061
4062 type = STREAM_UNDEFINED;
4063 stream_type = buffer[i];
4064 elementary_pid = b2i(2, buffer + i + 1) & 0x1FFF;
4065 es_info_length = b2i(2, buffer + i + 3) & 0x0FFF;
4066
4067 cs_log_dbg(D_DVBAPI,"Demuxer %d found %s stream (type: %02X pid: %04X)",
4068 demux_id, get_stream_type_txt(stream_type), stream_type, elementary_pid);
4069
4070 if(es_info_length != 0 && es_info_length < length)
4071 {
4072 if(ca_pmt_cmd_id != NULL) // We are on CA PMT parsing
4073 {
4074 // Only enigma2, Spark and VDR follow the CA PMT specification ("ca_pmt_cmd_id"
4075 // shall be present in the ES info loop). For the first two, checking for boxtype
4076 // "dreambox" is sufficient, but for VDR this is not enough, because it shares
4077 // the same boxtype with tvheadend. So, for every other box (including VDR and
4078 // tvheadend), we stick to the old style check based on the value (descriptors
4079 // with tag 0x00 or 0x01 are not allowed, so this works), while for enigma2 we
4080 // do a proper check, because the "ca_pmt_cmd_id" can also take greater values.
4081 if(cfg.dvbapi_boxtype == BOXTYPE_DREAMBOX)
4082 {
4083 *ca_pmt_cmd_id = buffer[i + 5]; // It should be identical for all ES and the same as in program info
4084 offset = 1;
4085 }
4086 else
4087 {
4088 offset = (buffer[i + 5] <= 0x01) ? 1 : 0;
4089 }
4090 }
4091
4092 // Parse descriptors at ES level
4093 dvbapi_parse_pmt_descriptors(demux_id, buffer + i + 5 + offset, es_info_length, &type);
4094 }
4095
4096 // Get basic stream type (video, audio, subtitle) for each ES pid
4097 switch(stream_type)
4098 {
4099 case 0x01:
4100 case 0x02:
4101 case 0x10:
4102 case 0x1B:
4103 case 0x20:
4104 case 0x24:
4105 case 0x25:
4106 case 0x42:
4107 case 0xD1:
4108 case 0xEA:
4109 if(*video_pid == 0)
4110 {
4111 *video_pid = elementary_pid;
4112 }
4113 demux[demux_id].STREAMpidsType[demux[demux_id].STREAMpidcount] = STREAM_VIDEO;
4114 break;
4115
4116 case 0x03:
4117 case 0x04:
4118 case 0x0F:
4119 case 0x11:
4120 case 0x1C:
4121 case 0x2D:
4122 case 0x2E:
4123 demux[demux_id].STREAMpidsType[demux[demux_id].STREAMpidcount] = STREAM_AUDIO;
4124 break;
4125
4126 case 0x06:
4127 case 0x81:
4128 case 0x87:
4129 // Set the type based on the descriptors for these stream types
4130 demux[demux_id].STREAMpidsType[demux[demux_id].STREAMpidcount] = type;
4131 break;
4132
4133 default:
4134 demux[demux_id].STREAMpidsType[demux[demux_id].STREAMpidcount] = STREAM_UNDEFINED;
4135 break;
4136 }
4137
4138 demux[demux_id].STREAMpids[demux[demux_id].STREAMpidcount] = elementary_pid;
4139 demux[demux_id].STREAMpidcount++;
4140 }
4141}
4142
4143static void dvbapi_parse_pmt_info(int32_t demux_id, const uint8_t *buffer, uint16_t length, uint8_t *ca_pmt_cmd_id)
4144{
4145 uint16_t i, program_info_length, video_pid = 0;
4146
4147 // Cleanout demuxer from possible stale info
4148 // (reset ECM pids and streams)
4149 if(demux[demux_id].running == false)
4150 {
4151 demux[demux_id].ECMpidcount = 0;
4152 }
4153
4154 for(i = 0; i < demux[demux_id].ECMpidcount; i++)
4155 {
4156 demux[demux_id].ECMpids[i].streams = 0;
4157 }
4158
4159 demux[demux_id].STREAMpidcount = 0;
4160
4161 // Parse program info
4162 // In case of CA PMT, read the ca_pmt_cmd_id as well
4163 program_info_length = b2i(2, buffer) & 0x0FFF;
4164 if(program_info_length != 0 && program_info_length < length)
4165 {
4166 dvbapi_parse_pmt_program_info(demux_id, buffer + 2, program_info_length, ca_pmt_cmd_id);
4167 }
4168
4169 // Parse elementary stream info
4170 // In case of CA PMT, read the ca_pmt_cmd_id for each stream as well
4171 dvbapi_parse_pmt_es_info(demux_id, buffer + 2 + program_info_length, length - 2 - program_info_length, ca_pmt_cmd_id, &video_pid);
4172
4173 cs_log("Demuxer %d found %d ECM pids and %d STREAM pids in %sPMT", demux_id,
4174 demux[demux_id].ECMpidcount, demux[demux_id].STREAMpidcount, ca_pmt_cmd_id != NULL ? "CA " : "");
4175
4176 // Various retarded boxes misuse the "ca_pmt_cmd_id" value,
4177 // usually by setting it to zero. If we are on CA PMT parsing,
4178 // make sure we pass a value we can work with later on.
4179 if(ca_pmt_cmd_id != NULL)
4180 {
4181 *ca_pmt_cmd_id = (*ca_pmt_cmd_id < CA_PMT_CMD_OK_DESCRAMBLING) ? CA_PMT_CMD_OK_DESCRAMBLING : *ca_pmt_cmd_id;
4182 }
4183
4184 // If no elementary streams are available, set the PMT pid as the
4185 // first stream (PMT cannot be encrypted, like it was mentioned
4186 // in the old comment, so not sure why this is needed...)
4187 if(demux[demux_id].STREAMpidcount == 0)
4188 {
4189 demux[demux_id].STREAMpids[0] = demux[demux_id].pmtpid;
4190 demux[demux_id].STREAMpidsType[0] = STREAM_VIDEO;
4191 demux[demux_id].STREAMpidcount++;
4192 video_pid = demux[demux_id].pmtpid;
4193 }
4194
4195 // Register found video pid on all ECM pids of this demuxer
4196 for(i = 0; i < demux[demux_id].ECMpidcount; i++)
4197 {
4198 demux[demux_id].ECMpids[i].VPID = video_pid;
4199 }
4200
4201 // Search for dvbapi priority entries for this program
4202 if(dvbapi_priority != NULL)
4203 {
4204 dvbapi_priority_read_entry_add(demux_id, video_pid);
4205 dvbapi_priority_read_entry_map(demux_id);
4206 dvbapi_priority_read_entry_extra(demux_id);
4207 }
4208}
4209
4210typedef struct demux_parameters
4211{
4212 uint8_t demux_index;
4213 uint8_t adapter_index;
4214 uint32_t ca_mask;
4215 uint16_t program_number;
4216 uint16_t pmtpid;
4217 uint16_t onid;
4218 uint16_t tsid;
4219 uint32_t ens;
4220} demux_parameters_t;
4221
4222static void get_demux_parameters(const uint8_t *buffer, demux_parameters_t *parameters)
4223{
4224 parameters->ca_mask = 1;
4225 parameters->demux_index = 0;
4226 parameters->adapter_index = 0;
4227 parameters->pmtpid = 0;
4228 parameters->program_number = b2i(2, buffer + 1);
4229
4230 uint16_t program_info_length = b2i(2, buffer + 4) & 0x0FFF;
4231 uint16_t pos = 7; // 4 + 2 (program_info_length) + 1 (ca_pmt_cmd_id)
4232
4233 while(pos + 1 < 5 + program_info_length)
4234 {
4235 uint8_t descriptor_tag = buffer[pos];
4236 uint8_t descriptor_length = buffer[pos + 1];
4237
4238 switch(descriptor_tag)
4239 {
4240 case 0x09: // We parse ca_descriptor() later
4241 break;
4242
4243 case 0x81: // enigma_namespace_descriptor()
4244 {
4245 if(descriptor_length == 0x08)
4246 {
4247 parameters->ens = b2i(4, buffer + pos + 2);
4248 parameters->tsid = b2i(2, buffer + pos + 6);
4249 parameters->onid = b2i(2, buffer + pos + 8);
4250 }
4251 break;
4252 }
4253
4254 case 0x82: // demux, ca_mask, adapter (deprecated - applications should use descriptors 0x83, 0x86 and 0x87 instead)
4255 {
4256 if(descriptor_length == 0x02 && (cfg.dvbapi_boxtype == BOXTYPE_PC ||
4257 cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX || cfg.dvbapi_boxtype == BOXTYPE_SAMYGO))
4258 {
4259 parameters->demux_index = buffer[pos + 2]; // Usually 0, but not always
4260 parameters->adapter_index = buffer[pos + 3]; // Can be 0, 1, 2, ...
4261 parameters->ca_mask = (1 << parameters->adapter_index); // use adapter_index as ca_mask
4262 }
4263 else if(descriptor_length == 0x03 && cfg.dvbapi_boxtype == BOXTYPE_QBOXHD)
4264 {
4265 // ca_mask = buffer[pos + 2]; // with STONE 1.0.4 always 0x01
4266 parameters->demux_index = buffer[pos + 3]; // with STONE 1.0.4 always 0x00
4267 parameters->adapter_index = buffer[pos + 4]; // with STONE 1.0.4 adapter index can be 0, 1, 2
4268 parameters->ca_mask = (1 << parameters->adapter_index); // use adapter_index as ca_mask
4269 }
4270 else if(descriptor_length == 0x02) // enigma2
4271 {
4272 parameters->ca_mask = buffer[pos + 2];
4273 uint8_t demux_tmp = buffer[pos + 3];
4274
4275 if(demux_tmp >= 8 && parameters->ca_mask == 0) // openpli based images
4276 {
4277 parameters->ca_mask = 1 << demux_tmp;
4278 }
4279
4280 if(demux_tmp == 0xFF) // tryfix prismcube (0xFF -> "demux-1" = error!)
4281 {
4282 demux_tmp = 0;
4283 }
4284 parameters->demux_index = demux_tmp;
4285 }
4286 break;
4287 }
4288
4289 case 0x83: // adapter_device_descriptor()
4290 {
4291 if(descriptor_length == 0x01)
4292 {
4293 parameters->adapter_index = buffer[pos + 2];
4294 }
4295 break;
4296 }
4297
4298 case 0x84: // pmt_pid_descriptor()
4299 {
4300 if(descriptor_length == 0x02)
4301 {
4302 parameters->pmtpid = b2i(2, buffer + pos + 2);
4303 }
4304 break;
4305 }
4306
4307 case 0x85: // service_type_mask_descriptor() (not used by OSCam)
4308 break;
4309
4310 case 0x86: // demux_device_descriptor()
4311 {
4312 if(descriptor_length == 0x01)
4313 {
4314 parameters->demux_index = buffer[pos + 2];
4315 parameters->ca_mask = 1 << parameters->demux_index;
4316 }
4317 break;
4318 }
4319
4320 case 0x87: // ca_device_descriptor()
4321 {
4322 if(descriptor_length == 0x01)
4323 {
4324 parameters->ca_mask = 1 << buffer[pos + 2];
4325 }
4326 break;
4327 }
4328
4329 default:
4330 {
4331 cs_log_dbg(D_DVBAPI, "Skipped unsupported or CA PMT irrelevant descriptor (tag: %02X length: %02X)",
4332 descriptor_tag, descriptor_length);
4333 break;
4334 }
4335 }
4336
4337 pos += 2 + descriptor_length;
4338 }
4339}
4340
4341static void dvbapi_capmt_notify(struct demux_s *dmx)
4342{
4343 struct s_client *cl;
4344 for(cl = first_client->next; cl; cl = cl->next)
4345 {
4346 if((cl->typ == 'p' || cl->typ == 'r') && cl->reader && cl->reader->ph.c_capmt)
4347 {
4348 struct demux_s *curdemux;
4349 if(cs_malloc(&curdemux, sizeof(struct demux_s)))
4350 {
4351 memcpy(curdemux, dmx, sizeof(struct demux_s));
4352 add_job(cl, ACTION_READER_CAPMT_NOTIFY, curdemux, sizeof(struct demux_s));
4353 }
4354 }
4355 }
4356}
4357
4358static void dvbapi_prepare_descrambling(int32_t demux_id, uint32_t msgid)
4359{
4360 bool is_powervu = false, start_emm = true;
4361
4362 // The CA PMT should have given us enough info to determine if descrambling
4363 // is possible. Parsing the (real) PMT is not necessary, unless we have a
4364 // PowerVu encrypted channel or (for some weird reason) no stream pids at all.
4365 // Actually, when no streams are available, we set the PMT pid as the 1st
4366 // stream pid, so we have to check against that. Finally, if the PMT pid is
4367 // not included in the CA PMT, we start the PAT filter instead.
4368
4369#ifdef WITH_EXTENDED_CW
4370 uint8_t i;
4371 for(i = 0; i < demux[demux_id].ECMpidcount; i++)
4372 {
4373 if(caid_is_powervu(demux[demux_id].ECMpids[i].CAID))
4374 {
4375 is_powervu = true;
4376 break;
4377 }
4378 }
4379#endif
4380
4381 if(demux[demux_id].pmtpid == 0)
4382 {
4383 dvbapi_start_pat_filter(demux_id);
4384 }
4385 else if(demux[demux_id].STREAMpids[0] == demux[demux_id].pmtpid || is_powervu)
4386 {
4387 dvbapi_start_pmt_filter(demux_id);
4388 }
4389
4390 if(demux[demux_id].running)
4391 {
4392 disable_unused_streampids(demux_id); // disable all streampids not in use anymore
4393 }
4394
4395 if(!demux[demux_id].running && demux[demux_id].ECMpidcount != 0) // only start demuxer if it wasn't running
4396 {
4397 // remove all non important filtering
4398 // (there are images with limited amount of filters available!)
4399 dvbapi_stop_all_emm_sdt_filtering(msgid);
4400
4401 cs_log_dbg(D_DVBAPI, "Demuxer %d started descrambling for program %04X (fd: %d)",
4402 demux_id, demux[demux_id].program_number, demux[demux_id].socket_fd);
4403
4404 demux[demux_id].running = true; // mark channel as running
4405 openxcas_set_sid(demux[demux_id].program_number);
4406 demux[demux_id].decodingtries = -1;
4407 dvbapi_resort_ecmpids(demux_id);
4408 dvbapi_try_next_caid(demux_id, 0, msgid);
4409 cs_sleepms(1);
4410 }
4411 else if(demux[demux_id].ECMpidcount == 0) // FTA: do logging and part of ecm handler
4412 {
4413 cs_log_dbg(D_DVBAPI, "Demuxer %d no descrambling needed for FTA program %04X (fd: %d)",
4414 demux_id, demux[demux_id].program_number, demux[demux_id].socket_fd);
4415
4416 demux[demux_id].running = false; // reset running flag
4417 demux[demux_id].pidindex = -1; // reset ecmpid used for descrambling
4418 dvbapi_stop_filter(demux_id, TYPE_ECM, msgid);
4419
4420 if(cfg.usrfileflag) // add to user log previous channel + time on channel
4421 {
4422 cs_statistics(dvbapi_client);
4423 }
4424
4425 dvbapi_client->last_srvid = demux[demux_id].program_number; // set new channel srvid
4426 dvbapi_client->last_caid = NO_CAID_VALUE; // FTA channels have no caid!
4427 dvbapi_client->last_provid = NO_PROVID_VALUE; // FTA channels have no provid!
4428 dvbapi_client->lastswitch = dvbapi_client->last = time((time_t *)0); // reset idle-Time & last switch
4429 }
4430
4431#if defined(WITH_COOLAPI) || defined(WITH_COOLAPI2)
4432 // Don't start and Stop EMM Filters over and over again if we are on FTA
4433 if(dvbapi_client->last_caid == NO_CAID_VALUE)
4434 {
4435 start_emm = false;
4436 }
4437#endif
4438
4439 // only do emm setup if au enabled and not running!
4440 if(cfg.dvbapi_au > 0 && demux[demux_id].EMMpidcount == 0 && start_emm == true)
4441 {
4442 demux[demux_id].emm_filter = -1; // to register first run emmfilter start
4443
4444 if(demux[demux_id].emmstart.time == 1) // irdeto fetch emm cat direct!
4445 {
4446 // trick to let emm fetching start after 30 seconds to speed up zapping
4447 cs_ftime(&demux[demux_id].emmstart);
4448
4449 dvbapi_start_filter(demux_id, demux[demux_id].pidindex, 0x001, 0x001, 0x01, 0x01, 0xFF, 0, TYPE_EMM); // CAT
4450 }
4451 else
4452 {
4453 cs_ftime(&demux[demux_id].emmstart); // for all other caids delayed start!
4454 }
4455 }
4456}
4457
4458int32_t dvbapi_parse_capmt(const uint8_t *buffer, uint32_t length, int32_t connfd, char *pmtfile, uint16_t client_proto_version, uint32_t msgid)
4459{
4460 int32_t i, demux_id = -1;
4461 uint8_t ca_pmt_list_management, ca_pmt_cmd_id;
4462 bool is_update = false;
4463 demux_parameters_t parameters;
4464 memset(&parameters, 0, sizeof(parameters));
4465
4466#if defined WITH_COOLAPI || defined WITH_COOLAPI2
4467 ca_pmt_list_management = CA_PMT_LIST_ONLY;
4468#else
4469 ca_pmt_list_management = buffer[0];
4470#endif
4471
4472 // We received a new list of CA PMT objects.
4473 // Mark all demuxers to stop descrambling, but do not actually stop any of them,
4474 // until we verify the new list does not contain any previously selected program.
4475 if(ca_pmt_list_management == CA_PMT_LIST_FIRST || ca_pmt_list_management == CA_PMT_LIST_ONLY)
4476 {
4477 for(i = 0; i < MAX_DEMUX; i++)
4478 {
4479 // Skip empty demuxers, demuxers belonging to different
4480 // CA PMT connections or handled by different PMT files.
4481 if(demux[i].program_number == 0 || demux[i].socket_fd != connfd ||
4482 (demux[i].socket_fd == -1 && pmtfile && strcmp(demux[i].pmt_file, pmtfile) != 0))
4483 {
4484 continue;
4485 }
4486
4487 demux[i].stop_descrambling = true; // Mark for deletion if not used again by following CA PMT objects
4488
4489 cs_log_dbg(D_DVBAPI, "Demuxer %d marked to stop descrambling for program %04X (fd: %d)",
4490 i, demux[i].program_number, connfd);
4491 }
4492 }
4493
4494 // Read private descriptors inside the CA PMT message
4495 // in order to get adapter, demux, ca, pmt pid and more.
4496 get_demux_parameters(buffer, &parameters);
4497
4498 cs_log_dbg(D_DVBAPI, "Received CA PMT list management %d for program %04X (pmt pid: %04X adapter: %d demux: %d camask: %d)",
4499 ca_pmt_list_management, parameters.program_number, parameters.pmtpid, parameters.adapter_index,
4500 parameters.demux_index, parameters.ca_mask);
4501
4502 // Search current demuxers for having the same program
4503 // as the one we received in this CA PMT object.
4504 for(i = 0; i < MAX_DEMUX; i++)
4505 {
4506 if(demux[i].program_number == 0)
4507 {
4508 continue;
4509 }
4510
4511 if(cfg.dvbapi_boxtype == BOXTYPE_IPBOX_PMT)
4512 {
4513 parameters.demux_index = i; // fixup for ipbox
4514 }
4515
4516 bool full_check = true, matched = false;
4517
4518 if(config_enabled(WITH_COOLAPI) || config_enabled(WITH_COOLAPI2) || cfg.dvbapi_boxtype == BOXTYPE_SAMYGO)
4519 {
4520 full_check = false;
4521 }
4522
4523 if(full_check)
4524 {
4525 matched = (connfd > 0 && demux[i].socket_fd == connfd) && demux[i].program_number == parameters.program_number;
4526 }
4527 else
4528 {
4529 matched = connfd > 0 && demux[i].program_number == parameters.program_number;
4530 }
4531
4532 if(matched)
4533 {
4534 if(full_check)
4535 {
4536 // In PMT mode 6, when zapping between channels with the same program number and PMT pid
4537 // (sometimes the case with satellite feeds), as all hardware parameters being the same
4538 // (adapter, demux, ca_mask, connfd), the new program is considered an existing one (matched).
4539 // The only reliable way to determine whether we actually have a new program is to compare
4540 // the enigma namespace, tsid and onid as well.
4541 if(demux[i].demux_index != parameters.demux_index || demux[i].ca_mask != parameters.ca_mask ||
4542 demux[i].adapter_index != parameters.adapter_index || demux[i].pmtpid != parameters.pmtpid ||
4543 demux[i].ens != parameters.ens || demux[i].tsid != parameters.tsid || demux[i].onid != parameters.onid)
4544 {
4545 continue;
4546 }
4547 }
4548
4549 // A program update is normally signaled by either a list management:
4550 // 1. UPDATE for an existing program
4551 // 2. ADD for an existing program (which according to the specifications should be treated as an UPDATE)
4552 // 3. ONLY for an existing program (with broken clients, in pmt modes other than 6)
4553 if(ca_pmt_list_management == CA_PMT_LIST_UPDATE || ca_pmt_list_management == CA_PMT_LIST_ADD
4554 || (cfg.dvbapi_pmtmode != 6 && ca_pmt_list_management == CA_PMT_LIST_ONLY))
4555 {
4556 is_update = true;
4557 cs_log("Demuxer %d received updated CA PMT for program %04X", i, parameters.program_number);
4558 }
4559
4560 cs_log("Demuxer %d continues descrambling for program %04X", i, demux[i].program_number);
4561 openxcas_set_sid(parameters.program_number);
4562 demux[i].stop_descrambling = false; // don't stop current demuxer!
4563 demux_id = i;
4564 break; // no need to explore other demuxers since we have a match!
4565 }
4566 }
4567
4568 // We are currently processing the last object of the CA PMT list.
4569 // We should now stop descrambling all programs not included in this list.
4570 if(ca_pmt_list_management != CA_PMT_LIST_FIRST && ca_pmt_list_management != CA_PMT_LIST_MORE)
4571 {
4572 for(i = 0; i < MAX_DEMUX; i++)
4573 {
4574 if(demux[i].program_number == 0)
4575 {
4576 continue;
4577 }
4578
4579 if(demux[i].stop_descrambling)
4580 {
4581 dvbapi_stop_descrambling(i, msgid);
4582 }
4583 }
4584 }
4585
4586 // We continue reading the CA PMT object only when we get
4587 // a new program (demux_id == -1) or an updated program.
4588 if(!(demux_id == -1 || is_update))
4589 {
4590 return demux_id;
4591 }
4592
4593 // We received a CA PMT object for a new program.
4594 // Let's find an empty demuxer for it.
4595 if(demux_id == -1)
4596 {
4597 if(ca_pmt_list_management == CA_PMT_LIST_UPDATE)
4598 {
4599 cs_log("ERROR: Received CA PMT list update for unknown program");
4600 return -1;
4601 }
4602
4603 for(demux_id = 0; demux_id < MAX_DEMUX; demux_id++)
4604 {
4605 if(demux[demux_id].program_number != 0)
4606 {
4607 continue; // Skip occupied demuxers
4608 }
4609
4610 // Probably this box doesn't send any private descriptor in the
4611 // CA PMT, so we have to improvise before saving to the demuxer.
4612 if(cfg.dvbapi_boxtype == BOXTYPE_IPBOX_PMT)
4613 {
4614 parameters.ca_mask = demux_id + 1;
4615 parameters.demux_index = demux_id;
4616 }
4617
4618 demux[demux_id].demux_index = parameters.demux_index;
4619 demux[demux_id].adapter_index = parameters.adapter_index;
4620 demux[demux_id].ca_mask = parameters.ca_mask;
4621 demux[demux_id].socket_fd = connfd;
4622 demux[demux_id].client_proto_version = client_proto_version;
4623 demux[demux_id].program_number = parameters.program_number;
4624 demux[demux_id].pmtpid = parameters.pmtpid;
4625 demux[demux_id].ens = parameters.ens;
4626 demux[demux_id].tsid = parameters.tsid;
4627 demux[demux_id].onid = parameters.onid;
4628 demux[demux_id].stop_descrambling = false;
4629 demux[demux_id].running = false;
4630 demux[demux_id].sdt_filter = -1;
4631 demux[demux_id].rdr = NULL;
4632
4633 if(pmtfile)
4634 {
4635 cs_strncpy(demux[demux_id].pmt_file, pmtfile, sizeof(demux[demux_id].pmt_file));
4636 }
4637
4638 break;
4639 }
4640
4641 if(demux_id >= MAX_DEMUX)
4642 {
4643 cs_log("There is no free demuxer for the new program! Aborting...");
4644 return -1;
4645 }
4646 }
4647
4648 // We continue parsing the CA PMT info for new or updated programs.
4649 // For updated programs, we just delete all previous stream pids and
4650 // ECM pids and start parsing the fresh data.
4651 dvbapi_parse_pmt_info(demux_id, buffer + 4, length - 4, &ca_pmt_cmd_id);
4652
4653 // Finally, evaluate what response the host requires from OSCam.
4654 // This allows multiple CA applications to run at the host simultaneously.
4655 // "OK query" will be implemented at a later stage, when support is first
4656 // added in enigma2.
4657 switch(ca_pmt_cmd_id)
4658 {
4659 case CA_PMT_CMD_OK_DESCRAMBLING:
4660 {
4661 // remove from unassoc_fd when necessary
4662 for(i = 0; i < MAX_DEMUX; i++)
4663 {
4664 if(unassoc_fd[i] == connfd)
4665 {
4666 unassoc_fd[i] = 0;
4667 }
4668 }
4669
4670 dvbapi_capmt_notify(&demux[demux_id]);
4671 dvbapi_prepare_descrambling(demux_id, msgid);
4672 return demux_id;
4673 }
4674
4675 case CA_PMT_CMD_QUERY:
4676 {
4677 cs_log("Received unsupported CA PMT command ID 'query' for program %04X", demux[demux_id].program_number);
4678 dvbapi_stop_descrambling(demux_id, msgid); // Clear all data from this demuxer
4679 return -1;
4680 }
4681
4682 case CA_PMT_CMD_NOT_SELETED:
4683 {
4684 cs_log("Program %04X is not selected for descrambling", demux[demux_id].program_number);
4685 dvbapi_stop_descrambling(demux_id, msgid); // Clear all data from this demuxer
4686 return -1;
4687 }
4688
4689 default:
4690 {
4691 cs_log("Received unknown or unsupported CA PMT command ID %02X from host", ca_pmt_cmd_id);
4692 dvbapi_stop_descrambling(demux_id, msgid);
4693 return -1;
4694 }
4695 }
4696}
4697
4698static void dvbapi_parse_pmt(int32_t demux_id, const uint8_t *buffer, uint32_t length, uint32_t msgid)
4699{
4700 uint16_t program_number = b2i(2, buffer + 3);
4701 if(program_number != demux[demux_id].program_number)
4702 {
4703 cs_log("Demuxer %d received PMT for undefined program %04X", demux_id, program_number);
4704 return;
4705 }
4706
4707 dvbapi_stop_filter(demux_id, TYPE_PMT, msgid);
4708 dvbapi_parse_pmt_info(demux_id, buffer + 10, length - 10 - 4, NULL); // last 4 bytes are the CRC-32
4709}
4710
4711static uint32_t dvbapi_extract_sdt_string(char *buf, uint32_t buflen, uint8_t *source, uint32_t sourcelen)
4712{
4713 uint32_t i, j, offset = 0;
4714 int8_t iso_mode = -1;
4715 char *tmpbuf;
4716 const uint8_t *ptr_in;
4717 uint8_t *ptr_out;
4718 size_t in_bytes, out_bytes;
4719
4720 if(sourcelen == 0)
4721 {
4722 buf[0] = '\0';
4723 return 1;
4724 }
4725
4726 if(!cs_malloc(&tmpbuf, buflen))
4727 {
4728 return 0;
4729 }
4730
4731 if((sourcelen + 1) > buflen)
4732 {
4733 sourcelen = buflen - 1;
4734 }
4735
4736 if(sourcelen > 0 && source[0] < 0x20)
4737 {
4738 //ISO-8859
4739 if(source[0] >= 0x01 && source[0] <= 0x0B && source[0] != 0x08)
4740 {
4741 offset = 1;
4742 iso_mode = 4 + source[0];
4743 }
4744 //ISO-8859
4745 else if(source[0] == 0x10 && source[1] == 0x00 && source[2] >= 0x01 && source[2] <= 0x0F && source[2] != 0x0C)
4746 {
4747 offset = 3; iso_mode = source[2];
4748 }
4749 //Unicode
4750 else if(source[0] == 0x11)
4751 {
4752 offset = 1;
4753 iso_mode = -2;
4754 }
4755 //missing: 0x12 Korean Character Set KSC5601-1987
4756 //missing: 0x13 Simplified Chinese Character Set GB-2312-1980
4757 //missing: 0x14 Big5 subset of ISO/IEC 10646-1 (Traditional Chinese)
4758 //Unicode as UTF-8
4759 else if(source[0] == 0x15)
4760 {
4761 offset = 1;
4762 iso_mode = -3;
4763 }
4764 //missing: 0x1F Described by encoding_type_id *standard not finished yet*
4765 //Reserved for future use
4766 else
4767 {
4768 NULLFREE(tmpbuf); return 0;
4769 }
4770 }
4771
4772 if(offset >= sourcelen)
4773 {
4774 NULLFREE(tmpbuf); return 0;
4775 }
4776
4777 if(iso_mode >= -1)
4778 {
4779 for(i = 0, j = 0; i < (sourcelen - offset); i++)
4780 {
4781 if(((uint8_t)source[offset + i]) >= 0x80 && ((uint8_t)source[offset + i]) <= 0x9F)
4782 {
4783 continue;
4784 }
4785 tmpbuf[j] = source[offset + i];
4786 j++;
4787 }
4788 tmpbuf[j] = '\0';
4789 }
4790
4791 ptr_in = (const uint8_t *)tmpbuf;
4792 in_bytes = strlen(tmpbuf);
4793 ptr_out = (uint8_t *)buf;
4794 out_bytes = buflen;
4795
4796#ifdef READ_SDT_CHARSETS
4797 if(iso_mode >= -1)
4798 {
4799 memset(buf, 0, buflen);
4800 cs_log_dbg(D_DVBAPI, "sdt-info dbg: iso_mode: %d offset: %u", iso_mode, offset);
4801 cs_log_dump_dbg(D_DVBAPI, (uint8_t *)tmpbuf, in_bytes, "sdt-info dbg: raw string: ");
4802
4803 if(iso_mode == -1)
4804 {
4805 if(ISO6937toUTF8(&ptr_in, &in_bytes, &ptr_out, &out_bytes) == (size_t)(-1))
4806 {
4807 cs_log_dbg(D_DVBAPI, "sdt-info error: ISO6937toUTF8 failed");
4808 NULLFREE(tmpbuf);
4809 return 0;
4810 }
4811 }
4812 else
4813 {
4814 if(ISO8859toUTF8(iso_mode, &ptr_in, &in_bytes, &ptr_out, &out_bytes) == (size_t)(-1))
4815 {
4816 cs_log_dbg(D_DVBAPI, "sdt-info error: ISO8859toUTF8 failed");
4817 NULLFREE(tmpbuf);
4818 return 0;
4819 }
4820 }
4821 }
4822#else
4823 if(iso_mode >= -1)
4824 {
4825 cs_strncpy(buf, tmpbuf, buflen);
4826 cs_log_dbg(D_DVBAPI, "sdt-info warning: your build of oscam does not support iso-to-utf8 conversion, special chars may be corrupted!");
4827 }
4828#endif
4829 else if(iso_mode == -2)
4830 {
4831 memset(buf, 0, buflen);
4832 cs_log_dbg(D_DVBAPI, "sdt-info dbg: iso_mode: %d offset: %u", iso_mode, offset);
4833
4834 if(UnicodetoUTF8(&ptr_in, &in_bytes, &ptr_out, &out_bytes) == (size_t)(-1))
4835 {
4836 cs_log_dbg(D_DVBAPI, "sdt-info error: UnicodetoUTF8 failed");
4837 NULLFREE(tmpbuf);
4838 return 0;
4839 }
4840 }
4841 else if(iso_mode == -3)
4842 {
4843 memcpy(buf, source + offset, sourcelen - offset);
4844 buf[sourcelen - offset] = '\0';
4845 cs_log_dbg(D_DVBAPI, "sdt-info dbg: iso_mode: -3 offset: %u", offset);
4846 }
4847 cs_log_dump_dbg(D_DVBAPI, (uint8_t*)buf, strlen(buf), "sdt-info dbg: encoded string: ");
4848 NULLFREE(tmpbuf);
4849 return 1;
4850}
4851
4852static void dvbapi_create_srvid_line(int32_t demux_id, char *buffer, uint32_t buflen)
4853{
4854 int32_t i, j;
4855 uint16_t caid_done[32], cur_caid;
4856 uint8_t caid_done_count = 0, skip_caid;
4857 int32_t pos = 0;
4858
4859 if(demux[demux_id].ECMpidcount == 0)
4860 {
4861 snprintf(buffer, buflen, "%04X@%06X", NO_CAID_VALUE, NO_PROVID_VALUE);
4862 return;
4863 }
4864
4865 for(i = 0; i < demux[demux_id].ECMpidcount && i < 32; i++)
4866 {
4867 skip_caid = 0;
4868 for(j = 0; j < caid_done_count; j++)
4869 {
4870 if(caid_done[j] == demux[demux_id].ECMpids[i].CAID)
4871 {
4872 skip_caid = 1;
4873 break;
4874 }
4875 }
4876
4877 if(skip_caid)
4878 {
4879 continue;
4880 }
4881
4882 cur_caid = demux[demux_id].ECMpids[i].CAID;
4883 pos += snprintf(buffer + pos, buflen - pos, "%s%04X", caid_done_count > 0 ? "," : "", cur_caid == 0 ? NO_CAID_VALUE : cur_caid);
4884
4885 for(j = i; j < demux[demux_id].ECMpidcount; j++)
4886 {
4887 if(demux[demux_id].ECMpids[j].PROVID == 0)
4888 {
4889 continue;
4890 }
4891
4892 if(cur_caid == demux[demux_id].ECMpids[j].CAID)
4893 {
4894 pos += snprintf(buffer + pos, buflen - pos, "@%06X", demux[demux_id].ECMpids[j].PROVID);
4895 }
4896 }
4897 caid_done[caid_done_count] = demux[demux_id].ECMpids[i].CAID;
4898 caid_done_count++;
4899 }
4900}
4901
4902static const char *dvbapi_get_service_type(uint8_t service_type_id)
4903{
4904 switch(service_type_id)
4905 {
4906 case 0x01:
4907 case 0x11:
4908 return "TV";
4909
4910 case 0x02:
4911 case 0x07:
4912 case 0x0A:
4913 return "Radio";
4914
4915 case 0x03:
4916 return "Teletext";
4917
4918 case 0x0C:
4919 return "Data";
4920
4921 default:
4922 return "TV";
4923 }
4924}
4925
4926static void dvbapi_parse_sdt(int32_t demux_id, uint8_t *buffer, uint32_t length, uint32_t msgid)
4927{
4928 uint8_t tag, data_length = 0, provider_name_length, service_name_length, service_type;
4929 uint16_t service_id, descriptor_length, dpos;
4930 uint32_t section_length, pos;
4931 int8_t did_save_srvid = 0;
4932 int32_t provid, caid, pidindex;
4933 char provider_name[64], service_name[64], tmp[256], srvid_line[1024];
4934 const char *type;
4935 FILE *fpsave = NULL;
4936
4937 cs_log_dump_dbg(D_DVBAPI, buffer, length, "sdt-info dbg: sdt data: ");
4938
4939 if(length < 3)
4940 {
4941 return;
4942 }
4943
4944 if(buffer[0] != 0x42)
4945 {
4946 return;
4947 }
4948
4949 section_length = b2i(2, buffer + 1) & 0xFFF;
4950 if(section_length + 3 != length)
4951 {
4952 return;
4953 }
4954
4955 for(pos = 11; pos + 5 < length; pos += descriptor_length)
4956 {
4957 service_id = b2i(2, buffer + pos);
4958 descriptor_length = b2i(2, buffer + pos + 3) & 0xFFF;
4959
4960 if((pos + 5 + descriptor_length) >= length)
4961 {
4962 return;
4963 }
4964 pos += 5;
4965
4966 if(service_id != demux[demux_id].program_number)
4967 {
4968 continue;
4969 }
4970
4971 for(dpos = 0; dpos + 1 < descriptor_length; dpos += (2 + data_length))
4972 {
4973 tag = buffer[pos + dpos];
4974 data_length = buffer[pos + dpos + 1];
4975
4976 if(dpos + 1 + data_length >= descriptor_length)
4977 {
4978 break;
4979 }
4980
4981 if(tag != 0x48)
4982 {
4983 continue;
4984 }
4985
4986 if(dpos + 3 >= descriptor_length)
4987 {
4988 break;
4989 }
4990
4991 service_type = buffer[pos + dpos + 2];
4992 provider_name_length = buffer[pos + dpos + 3];
4993
4994 if((dpos + 4 + provider_name_length + 1) > descriptor_length)
4995 {
4996 break;
4997 }
4998
4999 service_name_length = buffer[pos + dpos + 4 + provider_name_length];
5000 if((dpos + 4 + provider_name_length + 1 + service_name_length) > descriptor_length)
5001 {
5002 break;
5003 }
5004
5005 pidindex = demux[demux_id].pidindex;
5006 if(pidindex !=-1)
5007 {
5008 provid = demux[demux_id].ECMpids[pidindex].PROVID;
5009 caid = demux[demux_id].ECMpids[pidindex].CAID;
5010 }
5011 else
5012 {
5013 if(demux[demux_id].ECMpidcount == 0 || demux[demux_id].ECMpids[0].CAID == 0)
5014 {
5015 caid = NO_CAID_VALUE;
5016 provid = NO_PROVID_VALUE;
5017 }
5018 else
5019 {
5020 caid = demux[demux_id].ECMpids[0].CAID;
5021 provid = demux[demux_id].ECMpids[0].PROVID;
5022 }
5023 }
5024
5025 if(!dvbapi_extract_sdt_string(provider_name, sizeof(provider_name), buffer + pos + dpos + 4, provider_name_length))
5026 {
5027 break;
5028 }
5029
5030 if(!dvbapi_extract_sdt_string(service_name, sizeof(service_name), buffer + pos + dpos + 4 + provider_name_length + 1, service_name_length))
5031 {
5032 break;
5033 }
5034
5035 cs_log_dbg(D_DVBAPI,"sdt-info (provider: %s - channel: %s)", provider_name, service_name);
5036 dvbapi_stop_filter(demux_id, TYPE_SDT, msgid);
5037
5038 if(strlen(provider_name) && caid != NO_CAID_VALUE)
5039 {
5040 get_providername_or_null(provid, caid, tmp, sizeof(tmp));
5041 if(tmp[0] == '\0')
5042 {
5043 get_config_filename(tmp, sizeof(tmp), "oscam.provid");
5044 if((fpsave = fopen(tmp, "a")))
5045 {
5046 fprintf(fpsave, "\n%04X@%06X|%s|", caid, provid, provider_name);
5047 fclose(fpsave);
5048 init_provid();
5049 }
5050 }
5051 }
5052
5053 if(strlen(service_name))
5054 {
5055 get_servicename_or_null(cur_client(), service_id, provid, caid, tmp, sizeof(tmp));
5056
5057 if(tmp[0] == '\0')
5058 {
5059 type = dvbapi_get_service_type(service_type);
5060 get_config_filename(tmp, sizeof(tmp), "oscam.srvid2");
5061
5062 if(!access(tmp, F_OK) && (fpsave = fopen(tmp, "a")))
5063 {
5064 if((caid != NO_CAID_VALUE) || (cfg.dvbapi_read_sdt > 1))
5065 {
5066 dvbapi_create_srvid_line(demux_id, srvid_line, sizeof(srvid_line));
5067
5068 if(cfg.dvbapi_write_sdt_prov)
5069 {
5070 fprintf(fpsave, "\n%04X:%s|%s|%s||%s", service_id, srvid_line, service_name, type, provider_name);
5071 }
5072 else
5073 {
5074 fprintf(fpsave, "\n%04X:%s|%s|%s", service_id, srvid_line, service_name, type);
5075 }
5076 did_save_srvid = 1;
5077 }
5078 }
5079 else
5080 {
5081 get_config_filename(tmp, sizeof(tmp), "oscam.srvid");
5082
5083 if((fpsave = fopen(tmp, "a")))
5084 {
5085 if((caid != NO_CAID_VALUE) || (cfg.dvbapi_read_sdt > 1))
5086 {
5087 dvbapi_create_srvid_line(demux_id, srvid_line, sizeof(srvid_line));
5088
5089 if(cfg.dvbapi_write_sdt_prov)
5090 {
5091 fprintf(fpsave, "\n%s:%04X|%s|%s|%s", srvid_line, service_id, provider_name, service_name, type);
5092 }
5093 else
5094 {
5095 fprintf(fpsave, "\n%s:%04X||%s|%s", srvid_line, service_id, service_name, type);
5096 }
5097 did_save_srvid = 1;
5098 }
5099 }
5100 }
5101
5102 if(fpsave)
5103 {
5104 fclose(fpsave);
5105 }
5106
5107 if(did_save_srvid)
5108 {
5109 init_srvid();
5110 }
5111 }
5112 }
5113 return;
5114 }
5115 }
5116}
5117
5118static void dvbapi_parse_pat(int32_t demux_id, uint8_t *buffer, uint32_t length, uint32_t msgid)
5119{
5120 uint16_t srvid;
5121 uint32_t i;
5122
5123 dvbapi_stop_filter(demux_id, TYPE_PAT, msgid);
5124
5125 for(i = 8; i + 7 < length; i += 4)
5126 {
5127 srvid = b2i(2, buffer + i);
5128 if(srvid == 0)
5129 {
5130 continue;
5131 }
5132
5133 if(demux[demux_id].program_number == srvid)
5134 {
5135 demux[demux_id].pmtpid = b2i(2, buffer + i + 2) & 0x1FFF;
5136 dvbapi_start_pmt_filter(demux_id);
5137 break;
5138 }
5139 }
5140}
5141
5142int32_t dvbapi_init_listenfd(void)
5143{
5144 int32_t clilen, listenfd;
5145 struct sockaddr_un servaddr;
5146
5147 memset(&servaddr, 0, sizeof(struct sockaddr_un));
5148 servaddr.sun_family = AF_UNIX;
5149 cs_strncpy(servaddr.sun_path, devices[selected_box].cam_socket_path, sizeof(servaddr.sun_path));
5150 clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
5151
5152 if(((unlink(devices[selected_box].cam_socket_path) < 0) && (errno != ENOENT))
5153 || ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
5154 || (bind(listenfd, (struct sockaddr *)&servaddr, clilen) < 0)
5155 || (listen(listenfd, 5) < 0))
5156 {
5157 return 0;
5158 }
5159
5160 // change the access right on the camd.socket
5161 // this will allow oscam to run as root if needed
5162 // and still allow non root client to connect to the socket
5163 chmod(devices[selected_box].cam_socket_path, S_IRWXU | S_IRWXG | S_IRWXO);
5164 return listenfd;
5165}
5166
5167int32_t dvbapi_net_init_listenfd(void)
5168{
5169 int32_t listenfd;
5170 struct SOCKADDR servaddr;
5171
5172 memset(&servaddr, 0, sizeof(servaddr));
5173 SIN_GET_FAMILY(servaddr) = DEFAULT_AF;
5174 SIN_GET_ADDR(servaddr) = ADDR_ANY;
5175 SIN_GET_PORT(servaddr) = htons((uint16_t)cfg.dvbapi_listenport);
5176
5177 if((listenfd = socket(DEFAULT_AF, SOCK_STREAM, 0)) < 0)
5178 {
5179 return 0;
5180 }
5181 int32_t opt = 0;
5182
5183#ifdef IPV6SUPPORT
5184// azbox toolchain do not have this define
5185#ifndef IPV6_V6ONLY
5186#define IPV6_V6ONLY 26
5187#endif
5188 // set the server socket option to listen on IPv4 and IPv6 simultaneously
5189 setsockopt(listenfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&opt, sizeof(opt));
5190#endif
5191
5192 opt = 1;
5193 setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&opt, sizeof(opt));
5194 set_so_reuseport(listenfd);
5195
5196 if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
5197 {
5198 return 0;
5199 }
5200
5201 if(listen(listenfd, 5) < 0)
5202 {
5203 return 0;
5204 }
5205 return listenfd;
5206}
5207
5208static pthread_mutex_t event_handler_lock = PTHREAD_MUTEX_INITIALIZER;
5209
5210void event_handler(int32_t UNUSED(signal))
5211{
5212 struct stat pmt_info;
5213 char dest[1024];
5214 DIR *dirp;
5215 struct dirent entry, *dp = NULL;
5216 int32_t i, pmt_fd;
5217 uint8_t mbuf[2048]; // dirty fix: larger buffer needed for CA PMT mode 6 with many parallel channels to decode
5218
5219 if(dvbapi_client != cur_client())
5220 {
5221 return;
5222 }
5223
5224 SAFE_MUTEX_LOCK(&event_handler_lock);
5225 if(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX || cfg.dvbapi_boxtype == BOXTYPE_SAMYGO)
5226 {
5227 pausecam = 0;
5228 }
5229 else
5230 {
5231 int32_t standby_fd = open(STANDBY_FILE, O_RDONLY);
5232 pausecam = (standby_fd > 0) ? 1 : 0;
5233 if(standby_fd > 0)
5234 {
5235 int32_t ret = close(standby_fd);
5236 if(ret < 0)
5237 {
5238 cs_log("ERROR: Could not close standby fd (errno=%d %s)", errno, strerror(errno));
5239 }
5240 }
5241 }
5242
5243 if(cfg.dvbapi_boxtype == BOXTYPE_IPBOX || cfg.dvbapi_pmtmode == 1)
5244 {
5245 SAFE_MUTEX_UNLOCK(&event_handler_lock);
5246 return;
5247 }
5248
5249 for(i = 0; i < MAX_DEMUX; i++)
5250 {
5251 if(demux[i].pmt_file[0] != 0)
5252 {
5253 snprintf(dest, sizeof(dest), "%s%s", TMPDIR, demux[i].pmt_file);
5254 pmt_fd = open(dest, O_RDONLY);
5255 if(pmt_fd > 0)
5256 {
5257 if(fstat(pmt_fd, &pmt_info) != 0)
5258 {
5259 int32_t ret = close(pmt_fd);
5260 if(ret < 0)
5261 {
5262 cs_log("ERROR: Could not close PMT fd (errno=%d %s)", errno, strerror(errno));
5263 }
5264 continue;
5265 }
5266
5267 if((time_t)pmt_info.st_mtime != demux[i].pmt_time)
5268 {
5269 dvbapi_stop_descrambling(i, 0);
5270 }
5271
5272 int32_t ret = close(pmt_fd);
5273 if(ret < 0)
5274 {
5275 cs_log("ERROR: Could not close PMT fd (errno=%d %s)", errno, strerror(errno));
5276 }
5277 continue;
5278 }
5279 else
5280 {
5281 cs_log("Demuxer %d Unable to open PMT file %s -> stop descrambling!", i, dest);
5282 dvbapi_stop_descrambling(i, 0);
5283 }
5284 }
5285 }
5286
5287 if(disable_pmt_files)
5288 {
5289 SAFE_MUTEX_UNLOCK(&event_handler_lock);
5290 return;
5291 }
5292
5293 dirp = opendir(TMPDIR);
5294 if(!dirp)
5295 {
5296 cs_log_dbg(D_DVBAPI, "opendir failed (errno=%d %s)", errno, strerror(errno));
5297 SAFE_MUTEX_UNLOCK(&event_handler_lock);
5298 return;
5299 }
5300
5301 while(!cs_readdir_r(dirp, &entry, &dp))
5302 {
5303 if(!dp)
5304 {
5305 break;
5306 }
5307
5308 if(strlen(dp->d_name) < 7)
5309 {
5310 continue;
5311 }
5312
5313 if(strncmp(dp->d_name, "pmt", 3) != 0 || strncmp(dp->d_name + strlen(dp->d_name) - 4, ".tmp", 4) != 0)
5314 {
5315 continue;
5316 }
5317
5318#if defined(WITH_STAPI) || defined(WITH_STAPI5)
5319 struct s_dvbapi_priority *p;
5320 for(p = dvbapi_priority; p != NULL; p = p->next) // stapi: check if there is a device connected to this pmt file!
5321 {
5322 if(p->type != 's') { continue; } // stapi rule?
5323 if(strcmp(dp->d_name, p->pmtfile) != 0) { continue; } // same file?
5324 break; // found match!
5325 }
5326
5327 if(p == NULL)
5328 {
5329 cs_log_dbg(D_DVBAPI, "No matching S: line in oscam.dvbapi for pmtfile %s -> skip!", dp->d_name);
5330 continue;
5331 }
5332#endif
5333 snprintf(dest, sizeof(dest), "%s%s", TMPDIR, dp->d_name);
5334 pmt_fd = open(dest, O_RDONLY);
5335 if(pmt_fd < 0)
5336 {
5337 continue;
5338 }
5339
5340 if(fstat(pmt_fd, &pmt_info) != 0)
5341 {
5342 int32_t ret = close(pmt_fd);
5343 if(ret < 0)
5344 {
5345 cs_log("ERROR: Could not close PMT fd (errno=%d %s)", errno, strerror(errno));
5346 }
5347 continue;
5348 }
5349
5350 int32_t found = 0;
5351
5352 for(i = 0; i < MAX_DEMUX; i++)
5353 {
5354 if(strcmp(demux[i].pmt_file, dp->d_name) == 0)
5355 {
5356 if((time_t)pmt_info.st_mtime == demux[i].pmt_time)
5357 {
5358 found = 1;
5359 break;
5360 }
5361 }
5362 }
5363
5364 if(found)
5365 {
5366 int32_t ret = close(pmt_fd);
5367 if(ret < 0)
5368 {
5369 cs_log("ERROR: Could not close PMT fd (errno=%d %s)", errno, strerror(errno));
5370 }
5371 continue;
5372 }
5373 cs_log_dbg(D_DVBAPI, "found pmt file %s", dest);
5374 cs_sleepms(100);
5375
5376 uint32_t len = read(pmt_fd, mbuf, sizeof(mbuf));
5377 int32_t ret = close(pmt_fd);
5378
5379 if(ret < 0)
5380 {
5381 cs_log("ERROR: Could not close PMT fd (errno=%d %s)", errno, strerror(errno));
5382 }
5383
5384 if(len < 1)
5385 {
5386 cs_log_dbg(D_DVBAPI, "pmt file %s have invalid len!", dest);
5387 continue;
5388 }
5389
5390 int32_t demux_id;
5391#ifdef QBOXHD
5392 uint32_t j1, j2;
5393
5394 // QboxHD pmt.tmp is the full capmt written as a string of hex values
5395 // pmt.tmp must be longer than 3 bytes (6 hex chars) and even length
5396 if((len < 6) || ((len % 2) != 0) || ((len / 2) > sizeof(dest)))
5397 {
5398 cs_log_dbg(D_DVBAPI, "error parsing QboxHD pmt.tmp, incorrect length");
5399 continue;
5400 }
5401
5402 for(j2 = 0, j1 = 0; j2 < len; j2 += 2, j1++)
5403 {
5404 unsigned int tmp;
5405 if(sscanf((char *)mbuf + j2, "%02X", &tmp) != 1)
5406 {
5407 cs_log_dbg(D_DVBAPI, "error parsing QboxHD pmt.tmp, data not valid in position %d", j2);
5408 SAFE_MUTEX_UNLOCK(&event_handler_lock);
5409 return;
5410 }
5411 else
5412 {
5413 memcpy(dest + j1, &tmp, 4);
5414 }
5415 }
5416
5417 cs_log_dump_dbg(D_DVBAPI, (uint8_t *)dest, len / 2, "QboxHD pmt.tmp:");
5418 demux_id = dvbapi_parse_capmt((uint8_t *)dest + 4, (len / 2) - 4, -1, dp->d_name, 0, 0);
5419#else
5420 if(len > sizeof(dest))
5421 {
5422 cs_log_dbg(D_DVBAPI, "event_handler() dest buffer is to small for pmt data!");
5423 continue;
5424 }
5425
5426 if(len < 16)
5427 {
5428 cs_log_dbg(D_DVBAPI, "event_handler() received pmt is too small! (%d < 16 bytes!)", len);
5429 continue;
5430 }
5431
5432 cs_log_dump_dbg(D_DVBAPI, mbuf, len, "PMT file:"); // Original PMT file
5433
5434 // Do some tidying on the PMT file to make it compatible with the CA PMT parser
5435 dest[0] = CA_PMT_LIST_ONLY;
5436 memcpy(dest + 1, mbuf + 3, 2); // program_number
5437 uint16_t pmt_program_info_length = b2i(2, mbuf + 10) & 0x0FFF;
5438 i2b_buf(2, pmt_program_info_length + 1, (uint8_t *)dest + 4);
5439 dest[6] = CA_PMT_CMD_OK_DESCRAMBLING;
5440 memcpy(dest + 7, mbuf + 12, len - 12 - 4);
5441
5442 cs_log_dump_dbg(D_DVBAPI, (uint8_t *)dest, 7 + len - 12 - 4, "CA PMT:"); // Actual CA PMT message
5443 demux_id = dvbapi_parse_capmt((uint8_t *)dest, 7 + len - 12 - 4, -1, dp->d_name, 0, 0);
5444#endif
5445
5446 if(demux_id >= 0)
5447 {
5448 cs_strncpy(demux[demux_id].pmt_file, dp->d_name, sizeof(demux[demux_id].pmt_file));
5449 demux[demux_id].pmt_time = (time_t)pmt_info.st_mtime;
5450 }
5451
5452 if(cfg.dvbapi_pmtmode == 3)
5453 {
5454 disable_pmt_files = 1;
5455 break;
5456 }
5457 }
5458 closedir(dirp);
5459 SAFE_MUTEX_UNLOCK(&event_handler_lock);
5460}
5461
5462void *dvbapi_event_thread(void *cli)
5463{
5464 struct s_client *client = (struct s_client *) cli;
5465 SAFE_SETSPECIFIC(getclient, client);
5466 set_thread_name(__func__);
5467
5468 while(!exit_oscam)
5469 {
5470 cs_sleepms(750);
5471 event_handler(0);
5472 }
5473 return NULL;
5474}
5475
5476void dvbapi_process_input(int32_t demux_id, int32_t filter_num, uint8_t *buffer, int32_t len, uint32_t msgid)
5477{
5478 struct s_ecmpid *curpid = NULL;
5479 int32_t pid = demux[demux_id].demux_fd[filter_num].pidindex;
5480 uint16_t filtertype = demux[demux_id].demux_fd[filter_num].type;
5481 uint32_t sctlen = SCT_LEN(buffer);
5482
5483 if((uint32_t) len < sctlen) // invalid CAT length
5484 {
5485 cs_log_dbg(D_DVBAPI, "Received filterdata with total length 0x%03X but section length is 0x%03X -> invalid length!", len, sctlen);
5486 return;
5487 }
5488
5489 if(demux_id < 0 || demux_id >= MAX_DEMUX)
5490 {
5491 cs_log("dvbapi_process_input(): error - received invalid demux_id (%d)", demux_id);
5492 return;
5493 }
5494
5495 if(filter_num < 0 || filter_num >= MAX_FILTER)
5496 {
5497 cs_log("dvbapi_process_input(): error - received invalid filter_num (%d)", filter_num);
5498 return;
5499 }
5500
5501 if(pid != -1 && filtertype == TYPE_ECM)
5502 {
5503 curpid = &demux[demux_id].ECMpids[pid];
5504 }
5505
5506 int32_t filt_match = filtermatch(buffer, filter_num, demux_id, sctlen); // acts on all filters (sdt/emm/ecm)
5507 if(!filt_match)
5508 {
5509 cs_log_dbg(D_DVBAPI,"Demuxer %d receiver returned data not matching the filter -> delivered filter data discarded!", demux_id);
5510 return;
5511 }
5512
5513 if(curpid && curpid->tries <= 0xF0 && filtertype == TYPE_ECM)
5514 {
5515 curpid->irdeto_maxindex = 0;
5516 curpid->irdeto_curindex = 0xFE;
5517 curpid->tries = 0xFE; // reset timeout retry flag
5518 curpid->irdeto_cycle = 0xFE; // reset irdetocycle
5519 curpid->table = 0;
5520 curpid->checked = 4; // flag ecmpid as checked
5521 curpid->status = -1; // flag ecmpid as unusable
5522
5523 if(pid == demux[demux_id].pidindex)
5524 {
5525 // current pid delivered problems so this pid isn't
5526 // being used to descramble any longer -> clear pidindex
5527 demux[demux_id].pidindex = -1;
5528
5529 // remove this pid from channel cache since we had no founds on any ecmpid!
5530 dvbapi_edit_channel_cache(demux_id, pid, 0);
5531 }
5532
5533 dvbapi_stop_filternum(demux_id, filter_num, msgid); // stop this ecm filter!
5534 return;
5535 }
5536
5537 if(filtertype == TYPE_ECM)
5538 {
5539 uint32_t chid = 0x10000;
5540 int8_t pvu_skip = 0;
5541 ECM_REQUEST *er;
5542
5543 if(len != 0) // len = 0 receiver encountered an internal bufferoverflow!
5544 {
5545 cs_log_dump_dbg(D_DVBAPI, buffer, sctlen, "Demuxer %d Filter %d fetched ECM data (ecmlength = 0x%03X):",
5546 demux_id, filter_num + 1, sctlen);
5547
5548 if(sctlen > MAX_ECM_SIZE) // ecm too long to handle!
5549 {
5550 cs_log_dbg(D_DVBAPI, "Received data with total length 0x%03X but max supported ECM length is 0x%03X -> Please report!",
5551 sctlen, MAX_ECM_SIZE);
5552
5553 if(curpid)
5554 {
5555 curpid->tries -= 0x0E;
5556 }
5557 return;
5558 }
5559
5560 if(!(buffer[0] == 0x80 || buffer[0] == 0x81))
5561 {
5562 cs_log_dbg(D_DVBAPI, "Received an ECM with invalid ecmtable ID %02X -> ignoring!", buffer[0]);
5563 if(curpid)
5564 {
5565 curpid->tries--;
5566 }
5567 return;
5568 }
5569
5570#ifdef WITH_EMU
5571 if(caid_is_powervu(curpid->CAID)) // ecm counter for powervu
5572 {
5573 pvu_skip = 1;
5574
5575 if(sctlen - 11 > buffer[9])
5576 {
5577 if(buffer[11 + buffer[9]] > curpid->pvu_counter
5578 || (curpid->pvu_counter == 255 && buffer[11 + buffer[9]] == 0)
5579 || ((curpid->pvu_counter - buffer[11 + buffer[9]]) > 5))
5580 {
5581 curpid->pvu_counter = buffer[11 + buffer[9]];
5582 pvu_skip = 0;
5583 }
5584 }
5585 }
5586#endif
5587 // wait for odd / even ecm change (only not for irdeto!)
5588 if((curpid->table == buffer[0] && !caid_is_irdeto(curpid->CAID)) || pvu_skip)
5589 {
5590 if(!(er = get_ecmtask()))
5591 {
5592 return;
5593 }
5594 er->srvid = demux[demux_id].program_number;
5595
5596#ifdef WITH_STAPI5
5597 cs_strncpy(er->dev_name, dev_list[demux[demux_id].dev_index].name, sizeof(dev_list[demux[demux_id].dev_index].name));
5598#endif
5599 er->tsid = demux[demux_id].tsid;
5600 er->onid = demux[demux_id].onid;
5601 er->pmtpid = demux[demux_id].pmtpid;
5602 er->ens = demux[demux_id].ens;
5603 er->caid = curpid->CAID;
5604 er->pid = curpid->ECM_PID;
5605 er->prid = curpid->PROVID;
5606 er->vpid = curpid->VPID;
5607 er->ecmlen = sctlen;
5608 memcpy(er->ecm, buffer, er->ecmlen);
5609 chid = get_subid(er); // fetch chid or fake chid
5610 er->chid = chid;
5611 er->msgid = msgid;
5612 dvbapi_set_section_filter(demux_id, er, filter_num);
5613 NULLFREE(er);
5614 return;
5615 }
5616
5617 if(caid_is_irdeto(curpid->CAID))
5618 {
5619 // 80 70 39 53 04 05 00 88
5620 // 81 70 41 41 01 06 00 13 00 06 80 38 1F 52 93 D2
5621 //if(buffer[5]>20) return;
5622 if(curpid->irdeto_maxindex != buffer[5]) // 6, register max irdeto index
5623 {
5624 cs_log_dbg(D_DVBAPI, "Found %d IRDETO ECM CHIDs", buffer[5] + 1);
5625 curpid->irdeto_maxindex = buffer[5]; // numchids = 7 (0..6)
5626 }
5627 }
5628 }
5629
5630 if(!(er = get_ecmtask()))
5631 {
5632 return;
5633 }
5634 er->srvid = demux[demux_id].program_number;
5635
5636#ifdef WITH_STAPI5
5637 cs_strncpy(er->dev_name, dev_list[demux[demux_id].dev_index].name, sizeof(dev_list[demux[demux_id].dev_index].name));
5638#endif
5639
5640 er->tsid = demux[demux_id].tsid;
5641 er->onid = demux[demux_id].onid;
5642 er->pmtpid = demux[demux_id].pmtpid;
5643 er->ens = demux[demux_id].ens;
5644 er->caid = curpid->CAID;
5645 er->pid = curpid->ECM_PID;
5646 er->prid = curpid->PROVID;
5647 er->vpid = curpid->VPID;
5648 er->ecmlen = sctlen;
5649 memcpy(er->ecm, buffer, er->ecmlen);
5650 er->msgid = msgid;
5651 chid = get_subid(er); // fetch chid or fake chid
5652 uint32_t fixedprovid = chk_provid(er->ecm, er->caid);
5653
5654 if(fixedprovid && fixedprovid != er->prid)
5655 {
5656 cs_log_dbg(D_DVBAPI, "Fixing provid ecmpid %d from %06X -> %06X", pid, curpid->PROVID, fixedprovid);
5657 curpid->PROVID = fixedprovid;
5658
5659 if(!USE_OPENXCAS)
5660 {
5661 cs_log_dbg(D_DVBAPI, "Fixing provid filter %d from %06X -> %06X",
5662 filter_num + 1, demux[demux_id].demux_fd[filter_num].provid, fixedprovid);
5663
5664 demux[demux_id].demux_fd[filter_num].provid = fixedprovid;
5665 }
5666 cs_log_dbg(D_DVBAPI, "Fixing provid ecmrequest from %06X -> %06X", er->prid, fixedprovid);
5667 er->prid = fixedprovid;
5668 }
5669 er->chid = chid;
5670
5671 // only used on receiver internal buffer overflow
5672 // to get quickly fresh ecm filterdata otherwise freezing!
5673 if(len == 0)
5674 {
5675 curpid->table = 0;
5676 dvbapi_set_section_filter(demux_id, er, filter_num);
5677 NULLFREE(er);
5678 return;
5679 }
5680
5681 if(caid_is_irdeto(curpid->CAID))
5682 {
5683 if(curpid->irdeto_curindex != buffer[4]) // old style wrong irdeto index
5684 {
5685 if(curpid->irdeto_curindex == 0xFE) // check if this ecmfilter just started up
5686 {
5687 // on startup set the current index to the irdeto index of the ecm
5688 curpid->irdeto_curindex = buffer[4];
5689 }
5690 else // we are already running and not interested in this ecm
5691 {
5692 if(curpid->table != buffer[0]) // fix for receivers not supporting section filtering
5693 {
5694 curpid->table = 0;
5695 }
5696
5697 // set ecm filter to odd + even since
5698 // this ecm doesn't match with current irdeto index
5699 dvbapi_set_section_filter(demux_id, er, filter_num);
5700
5701 NULLFREE(er);
5702 return;
5703 }
5704 }
5705 else // fix for receivers not supporting section filtering
5706 {
5707 if(curpid->table == buffer[0])
5708 {
5709 NULLFREE(er);
5710 return;
5711 }
5712 }
5713 cs_log_dbg(D_DVBAPI, "Demuxer %d ECMTYPE %02X CAID %04X PROVID %06X ECMPID %04X IRDETO INDEX %02X MAX INDEX %02X CHID %04X CYCLE %02X VPID %04X",
5714 demux_id, er->ecm[0], er->caid, er->prid, er->pid, er->ecm[4], er->ecm[5], er->chid, curpid->irdeto_cycle, er->vpid);
5715 }
5716 else
5717 {
5718 cs_log_dbg(D_DVBAPI, "Demuxer %d ECMTYPE %02X CAID %04X PROVID %06X ECMPID %04X FAKECHID %04X (unique part in ecm)",
5719 demux_id, er->ecm[0], er->caid, er->prid, er->pid, er->chid);
5720 }
5721
5722 // check for matching chid (unique ecm part in case of non-irdeto cas)
5723 // plus added fix for seca2 monthly changing fakechid
5724 if((curpid->CHID < 0x10000) && !((chid == curpid->CHID) || ((curpid->CAID >> 8 == 0x01) && (chid & 0xF0FF) == (curpid->CHID & 0xF0FF))))
5725 {
5726 if(caid_is_irdeto(curpid->CAID))
5727 {
5728 // if same: we cycled all indexes but no luck!
5729 if((curpid->irdeto_cycle < 0xFE) && (curpid->irdeto_cycle == curpid->irdeto_curindex))
5730 {
5731 struct s_dvbapi_priority *forceentry = dvbapi_check_prio_match(demux_id, pid, 'p');
5732
5733 // forced pid? keep trying the forced ecmpid, no force kill ecm filter
5734 if(!forceentry || !forceentry->force)
5735 {
5736 if(curpid->checked == 2)
5737 {
5738 curpid->checked = 4;
5739 }
5740
5741 if(curpid->checked == 1)
5742 {
5743 curpid->checked = 2;
5744 curpid->CHID = 0x10000;
5745 }
5746
5747 dvbapi_stop_filternum(demux_id, filter_num, msgid); // stop this ecm filter!
5748 NULLFREE(er);
5749 return;
5750 }
5751 }
5752 curpid->irdeto_curindex++; // set check on next index
5753
5754 if(curpid->irdeto_cycle == 0xFE)
5755 {
5756 curpid->irdeto_cycle = buffer[4]; // on startup set to current irdeto index
5757 }
5758
5759 if(curpid->irdeto_curindex > curpid->irdeto_maxindex)
5760 {
5761 curpid->irdeto_curindex = 0; // check if we reached max irdeto index, if so reset to 0
5762 }
5763 curpid->table = 0;
5764
5765 // set ecm filter to odd + even since
5766 // this ecm doesn't match with current irdeto index
5767 dvbapi_set_section_filter(demux_id, er, filter_num);
5768
5769 NULLFREE(er);
5770 return;
5771 }
5772 else // all non irdeto cas systems
5773 {
5774 struct s_dvbapi_priority *forceentry = dvbapi_check_prio_match(demux_id, pid, 'p');
5775 curpid->table = 0;
5776
5777 // set ecm filter to odd + even since
5778 // this ecm doesn't match with current irdeto index
5779 dvbapi_set_section_filter(demux_id, er, filter_num);
5780
5781 if(forceentry && forceentry->force)
5782 {
5783 NULLFREE(er);
5784 return; // forced pid? keep trying the forced ecmpid!
5785 }
5786
5787 if(curpid->checked == 2)
5788 {
5789 curpid->checked = 4;
5790 }
5791
5792 if(curpid->checked == 1)
5793 {
5794 curpid->checked = 2;
5795 curpid->CHID = 0x10000;
5796 }
5797
5798 dvbapi_stop_filternum(demux_id, filter_num, msgid); // stop this ecm filter!
5799 NULLFREE(er);
5800 return;
5801 }
5802 }
5803
5804 struct s_dvbapi_priority *p;
5805 for(p = dvbapi_priority; p != NULL; p = p->next)
5806 {
5807 if(p->type != 'l'
5808 || (p->caid && p->caid != curpid->CAID)
5809 || (p->provid && p->provid != curpid->PROVID)
5810 || (p->ecmpid && p->ecmpid != curpid->ECM_PID)
5811 || (p->srvid && p->srvid != demux[demux_id].program_number))
5812 {
5813 continue;
5814 }
5815
5816 if((uint)p->delay == sctlen && p->force < 6)
5817 {
5818 p->force++;
5819 NULLFREE(er);
5820 return;
5821 }
5822
5823 if(p->force >= 6)
5824 {
5825 p->force = 0;
5826 }
5827 }
5828
5829 if(!curpid->PROVID)
5830 {
5831 curpid->PROVID = chk_provid(buffer, curpid->CAID);
5832 }
5833
5834 if(caid_is_irdeto(curpid->CAID)) // irdeto: wait for the correct index
5835 {
5836 if(buffer[4] != curpid->irdeto_curindex)
5837 {
5838 curpid->table = 0;
5839
5840 // set ecm filter to odd + even since
5841 // this ecm doesn't match with current irdeto index
5842 dvbapi_set_section_filter(demux_id, er, filter_num);
5843
5844 NULLFREE(er);
5845 return;
5846 }
5847 }
5848
5849 // we have an ecm with the correct irdeto index (or fakechid)
5850 for(p = dvbapi_priority; p != NULL ; p = p->next) // check for ignore!
5851 {
5852 if((p->type != 'i')
5853 || (p->caid && p->caid != curpid->CAID)
5854 || (p->provid && p->provid != curpid->PROVID)
5855 || (p->ecmpid && p->ecmpid != curpid->ECM_PID)
5856 || (p->pidx && p->pidx - 1 != pid)
5857 || (p->srvid && p->srvid != demux[demux_id].program_number))
5858 {
5859 continue;
5860 }
5861
5862 // found an ignore chid match with current ecm -> ignoring this irdeto index
5863 if(p->type == 'i' && (p->chid < 0x10000 && p->chid == chid))
5864 {
5865 curpid->irdeto_curindex++;
5866 if(curpid->irdeto_cycle == 0xFE)
5867 {
5868 curpid->irdeto_cycle = buffer[4]; // on startup set to current irdeto index
5869 }
5870
5871 if(curpid->irdeto_curindex > curpid->irdeto_maxindex) // check if curindex is over the max
5872 {
5873 curpid->irdeto_curindex = 0;
5874 }
5875 curpid->table = 0;
5876
5877 // irdeto: wait for the correct index + check if we cycled all
5878 if(caid_is_irdeto(curpid->CAID) && (curpid->irdeto_cycle != curpid->irdeto_curindex))
5879 {
5880 // set ecm filter to odd + even since this chid has to be ignored!
5881 dvbapi_set_section_filter(demux_id, er, filter_num);
5882 }
5883 else // this fakechid has to be ignored, kill this filter!
5884 {
5885 if(curpid->checked == 2)
5886 {
5887 curpid->checked = 4;
5888 }
5889
5890 if(curpid->checked == 1)
5891 {
5892 curpid->checked = 2;
5893 curpid->CHID = 0x10000;
5894 }
5895
5896 dvbapi_stop_filternum(demux_id, filter_num, msgid); // stop this ecm filter!
5897 }
5898 NULLFREE(er);
5899 return;
5900 }
5901 }
5902
5903 if(er)
5904 {
5905 curpid->table = er->ecm[0];
5906 }
5907
5908 request_cw(dvbapi_client, er, demux_id, 1); // register this ecm for delayed ecm response check
5909 return; // end of ecm filterhandling!
5910 }
5911
5912 if(filtertype == TYPE_EMM)
5913 {
5914 if(len != 0) // len = 0 receiver encountered an internal buffer overflow!
5915 {
5916 cs_log_dump_dbg(D_DVBAPI, buffer, sctlen, "Demuxer %d Filter %d fetched EMM data (emmlength = 0x%03X):",
5917 demux_id, filter_num + 1, sctlen);
5918
5919 if(sctlen > MAX_EMM_SIZE) // emm too long to handle!
5920 {
5921 cs_log_dbg(D_DVBAPI, "Received data with total length 0x%03X but max supported EMM length is 0x%03X -> Please report!",
5922 sctlen, MAX_EMM_SIZE);
5923
5924 return;
5925 }
5926 }
5927 else
5928 {
5929 return; // just skip on internal buffer overflow
5930 }
5931
5932 if(demux[demux_id].demux_fd[filter_num].pid == 0x01) // CAT
5933 {
5934 cs_log_dbg(D_DVBAPI, "receiving cat");
5935 dvbapi_parse_cat(demux_id, buffer, sctlen);
5936 dvbapi_stop_filternum(demux_id, filter_num, msgid);
5937 return;
5938 }
5939
5940#ifdef WITH_EMU
5941 if(caid_is_director(demux[demux_id].demux_fd[filter_num].caid))
5942 {
5943 uint32_t i;
5944 uint32_t emmhash;
5945
5946 if(sctlen < 4)
5947 {
5948 return;
5949 }
5950
5951 for(i = 0; i + 2 < sctlen; i++)
5952 {
5953 if(buffer[i] == 0xF0 && (buffer[i + 2] == 0xE1 || buffer[i + 2] == 0xE4))
5954 {
5955 emmhash = (buffer[3] << 8) | buffer[sctlen - 2];
5956 if(demux[demux_id].demux_fd[filter_num].cadata == emmhash)
5957 {
5958 return;
5959 }
5960
5961 demux[demux_id].demux_fd[filter_num].cadata = emmhash;
5962 dvbapi_process_emm(demux_id, filter_num, buffer, sctlen);
5963 return;
5964 }
5965 }
5966 return;
5967 }
5968#endif
5969 // fix to handle more than one irdeto emm packet
5970 uint8_t *pbuf = buffer;
5971 int32_t done = 0;
5972 int32_t unhandled = len;
5973
5974 while(len > done)
5975 {
5976 pbuf += done;
5977 sctlen = SCT_LEN(pbuf);
5978
5979 if(unhandled < 4 || (int32_t)sctlen > unhandled || sctlen > MAX_EMM_SIZE)
5980 {
5981 break;
5982 }
5983
5984 dvbapi_process_emm(demux_id, filter_num, pbuf, sctlen);
5985 done += sctlen;
5986 unhandled -= sctlen;
5987 }
5988 }
5989
5990 if(filtertype == TYPE_SDT)
5991 {
5992 cs_log_dump_dbg(D_DVBAPI, buffer, sctlen, "Demuxer %d Filter %d fetched SDT data (length = 0x%03X):",
5993 demux_id, filter_num + 1, sctlen);
5994
5995 dvbapi_parse_sdt(demux_id, buffer, sctlen, msgid);
5996 }
5997
5998 if(filtertype == TYPE_PAT)
5999 {
6000 cs_log_dump_dbg(D_DVBAPI, buffer, sctlen, "Demuxer %d Filter %d fetched PAT data (length = 0x%03X):",
6001 demux_id, filter_num + 1, sctlen);
6002
6003 dvbapi_parse_pat(demux_id, buffer, sctlen, msgid);
6004 }
6005
6006 if(filtertype == TYPE_PMT)
6007 {
6008 cs_log_dump_dbg(D_DVBAPI, buffer, sctlen, "Demuxer %d Filter %d fetched PMT data (length = 0x%03X):",
6009 demux_id, filter_num + 1, sctlen);
6010
6011 dvbapi_parse_pmt(demux_id, buffer, sctlen, msgid);
6012 }
6013}
6014
6015static int32_t dvbapi_recv(int32_t connfd, uint8_t *mbuf, size_t rlen)
6016{
6017 ssize_t len = cs_recv(connfd, mbuf, rlen, MSG_DONTWAIT);
6018
6019 if((len == -1 && (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) || (len == 0))
6020 {
6021 return -1;
6022 }
6023
6024 if(len == -1)
6025 {
6026 return 0;
6027 }
6028
6029 return len;
6030}
6031
6032static uint16_t dvbapi_get_nbof_missing_header_bytes(uint8_t *mbuf, uint16_t mbuf_len)
6033{
6034 if(mbuf_len < 4)
6035 {
6036 return 4 - mbuf_len;
6037 }
6038 uint32_t opcode = b2i(4, mbuf); //get the client opcode (4 bytes)
6039
6040 // detect the opcode, its size (chunksize) and its internal data size (data_len)
6041 if((opcode & 0xFFFFF000) == DVBAPI_AOT_CA) // min 4+size bytes
6042 {
6043 if(mbuf[3] & 0x80)
6044 {
6045 uint32_t size = mbuf[3] & 0x7F;
6046 if(mbuf_len < (4 + size))
6047 {
6048 return (4 + size) - mbuf_len;
6049 }
6050 }
6051 return 0;
6052 }
6053 else
6054 {
6055 switch (opcode)
6056 {
6057 case DVBAPI_FILTER_DATA: // min 9 bytes
6058 if(mbuf_len < 9)
6059 {
6060 return 9 - mbuf_len;
6061 }
6062 return 0;
6063
6064 case DVBAPI_CLIENT_INFO: // min 7 bytes
6065 if(mbuf_len < 7)
6066 {
6067 return 7 - mbuf_len;
6068 }
6069 return 0;
6070
6071 default:
6072 return 0;
6073 }
6074 }
6075}
6076
6077static void dvbapi_get_packet_size(uint8_t *mbuf, uint16_t mbuf_len, uint16_t *chunksize, uint16_t *data_len, uint16_t client_proto_version)
6078{
6079 //chunksize: size of complete chunk in the buffer (an opcode with the data)
6080 //data_len: variable for internal data length (eg. for the filter data size, PMT len)
6081 uint32_t msgid_size = 0;
6082 (*chunksize) = 0;
6083 (*data_len) = 0;
6084
6085 if(client_proto_version >= 3)
6086 {
6087 msgid_size = 5;
6088 }
6089
6090 if(mbuf_len < 4 + msgid_size)
6091 {
6092 cs_log("dvbapi_get_packet_size(): error - buffer length (%" PRIu16 ") too short", mbuf_len);
6093 (*chunksize) = 1;
6094 (*data_len) = 1;
6095 return;
6096 }
6097
6098 mbuf += msgid_size;
6099 uint32_t opcode = b2i(4, mbuf); //get the client opcode (4 bytes)
6100
6101 //detect the opcode, its size (chunksize) and its internal data size (data_len)
6102 if((opcode & 0xFFFFF000) == DVBAPI_AOT_CA) // min 4+size bytes
6103 {
6104 // parse packet size (ASN.1)
6105 uint32_t size = 0;
6106 if(mbuf[3] & 0x80)
6107 {
6108 uint32_t tmp_data_len = 0;
6109 size = mbuf[3] & 0x7F;
6110 if(3 + size < mbuf_len)
6111 {
6112 uint32_t k;
6113 for(k = 0; k < size; k++)
6114 {
6115 tmp_data_len = (tmp_data_len << 8) | mbuf[4 + k];
6116 }
6117 }
6118 else
6119 {
6120 cs_log("dvbapi_get_packet_size(): error - buffer length (%" PRIu16 ") too short for opcode %08X", mbuf_len, opcode);
6121 (*chunksize) = 1;
6122 (*data_len) = 1;
6123 return;
6124 }
6125
6126 if(tmp_data_len > 0xFFFF)
6127 {
6128 cs_log("Socket command too big: %d bytes", tmp_data_len);
6129 (*data_len) = 0xFFFF - 4 - size;
6130 }
6131 else
6132 {
6133 (*data_len) = tmp_data_len;
6134 }
6135 }
6136 else
6137 {
6138 (*data_len) = mbuf[3] & 0x7F;
6139 }
6140
6141 (*chunksize) = 4 + size + (*data_len);
6142 cs_log_dbg(D_DVBAPI, "Got packet with opcode %08X and size %" PRIu16, opcode, (*chunksize));
6143 }
6144 else
6145 {
6146 switch (opcode)
6147 {
6148 case DVBAPI_FILTER_DATA: // min 9 bytes
6149 {
6150 if(mbuf_len < 9)
6151 {
6152 cs_log("dvbapi_get_packet_size(): error - buffer length (%" PRIu16 ") too short for DVBAPI_FILTER_DATA", mbuf_len);
6153 (*chunksize) = 1;
6154 (*data_len) = 1;
6155 return;
6156 }
6157 (*data_len) = b2i(2, mbuf + 7) & 0x0FFF;
6158 (*chunksize) = 6 + 3 + (*data_len);
6159 cs_log_dbg(D_DVBAPI, "Got DVBAPI_FILTER_DATA packet with size %" PRIu16, (*chunksize));
6160 break;
6161 }
6162
6163 case DVBAPI_CLIENT_INFO: // min 7 bytes
6164 {
6165 if(mbuf_len < 7)
6166 {
6167 cs_log("dvbapi_get_packet_size(): error - buffer length (%" PRIu16 ") too short for DVBAPI_CLIENT_INFO", mbuf_len);
6168 (*chunksize) = 1;
6169 (*data_len) = 1;
6170 return;
6171 }
6172 (*data_len) = mbuf[6];
6173 (*chunksize) = 6 + 1 + (*data_len);
6174 cs_log_dbg(D_DVBAPI, "Got DVBAPI_CLIENT_INFO packet with size %" PRIu16, (*chunksize));
6175 break;
6176 }
6177
6178 default:
6179 {
6180 cs_log("Unknown socket command received: 0x%08X", opcode);
6181 (*chunksize) = 1;
6182 (*data_len) = 1;
6183 break;
6184 }
6185 }
6186 }
6187
6188 if((*chunksize) < 1)
6189 {
6190 (*chunksize) = 1;
6191 (*data_len) = 1;
6192 }
6193
6194 if((*chunksize) > 1)
6195 {
6196 (*chunksize) += msgid_size;
6197 }
6198}
6199
6200static void dvbapi_handlesockmsg(uint8_t *mbuf, uint16_t chunksize, uint16_t data_len, uint8_t *add_to_poll, int32_t connfd, uint16_t *client_proto_version)
6201{
6202 uint32_t msgid = 0;
6203 if(*client_proto_version >= 3)
6204 {
6205 if(mbuf[0] != 0xa5)
6206 {
6207 cs_log("Error: network packet malformed! (no start)");
6208 return;
6209 }
6210 msgid = b2i(4, mbuf + 1);
6211 mbuf += 5;
6212 }
6213
6214 uint32_t opcode = b2i(4, mbuf); //get the client opcode (4 bytes)
6215 if((opcode & 0xFFFFF000) == DVBAPI_AOT_CA)
6216 {
6217 cs_log_dump_dbg(D_DVBAPI, mbuf, chunksize, "Received CA PMT object on socket %d:", connfd);
6218
6219 switch(opcode & 0xFFFFFF00)
6220 {
6221 case DVBAPI_AOT_CA_PMT:
6222 {
6223 if(data_len < 5)
6224 {
6225 cs_log("Error: packet DVBAPI_AOT_CA_PMT is too short!");
6226 break;
6227 }
6228
6229 dvbapi_parse_capmt(mbuf + (chunksize - data_len), data_len, connfd, NULL, *client_proto_version, msgid);
6230 break;
6231 }
6232
6233 case (DVBAPI_AOT_CA_STOP & 0xFFFFFF00):
6234 {
6235 // 9F 80 3f 04 83 02 00 <demux index>
6236 if(opcode != DVBAPI_AOT_CA_STOP)
6237 {
6238 cs_log_dbg(D_DVBAPI, "dvbapi_handlesockmsg(): DVBAPI_AOT_CA opcode unknown: %08X", opcode);
6239 break;
6240 }
6241
6242 int32_t i;
6243
6244 if(data_len < 4)
6245 {
6246 cs_log("Error: packet DVBAPI_AOT_CA_STOP is too short!");
6247 break;
6248 }
6249
6250 // ipbox fix
6251 if(cfg.dvbapi_boxtype == BOXTYPE_IPBOX || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX || cfg.dvbapi_listenport)
6252 {
6253 int32_t demux_index = mbuf[7];
6254 for(i = 0; i < MAX_DEMUX; i++)
6255 {
6256 // 0xff demux_index is a wildcard => close all related demuxers
6257 if(demux_index == 0xff)
6258 {
6259 if(demux[i].socket_fd == connfd)
6260 {
6261 dvbapi_stop_descrambling(i, msgid);
6262 }
6263 }
6264 else if(demux[i].demux_index == demux_index)
6265 {
6266 dvbapi_stop_descrambling(i, msgid);
6267 break;
6268 }
6269 }
6270
6271 if(cfg.dvbapi_boxtype == BOXTYPE_IPBOX)
6272 {
6273 // check do we have any demux running on this fd
6274 int16_t execlose = 1;
6275 for(i = 0; i < MAX_DEMUX; i++)
6276 {
6277 if(demux[i].socket_fd == connfd)
6278 {
6279 execlose = 0;
6280 break;
6281 }
6282 }
6283
6284 if(execlose)
6285 {
6286 int32_t ret = close(connfd);
6287 if(ret < 0)
6288 {
6289 cs_log("ERROR: Could not close PMT fd (errno=%d %s)", errno, strerror(errno));
6290 }
6291 }
6292 }
6293 }
6294 else
6295 {
6296 if(cfg.dvbapi_pmtmode != 6)
6297 {
6298 int32_t ret = close(connfd);
6299 if(ret < 0)
6300 {
6301 cs_log("ERROR: Could not close PMT fd (errno=%d %s)", errno, strerror(errno));
6302 }
6303 }
6304 }
6305 break;
6306 }
6307
6308 default:
6309 {
6310 cs_log_dbg(D_DVBAPI, "dvbapi_handlesockmsg(): DVBAPI_AOT_CA opcode unknown: %08X", opcode);
6311 break;
6312 }
6313 }
6314
6315 if(cfg.dvbapi_listenport && opcode == DVBAPI_AOT_CA_STOP)
6316 {
6317 (*add_to_poll) = 1;
6318 }
6319 else
6320 {
6321 (*add_to_poll) = 0;
6322 }
6323 }
6324 else
6325 {
6326 switch(opcode)
6327 {
6328 case DVBAPI_FILTER_DATA:
6329 {
6330 if(data_len < 1)
6331 {
6332 cs_log("Error: packet DVBAPI_FILTER_DATA is too short!");
6333 break;
6334 }
6335
6336 int32_t demux_id = mbuf[4];
6337 int32_t filter_num = mbuf[5];
6338
6339 if(demux_id < 0 || demux_id >= MAX_DEMUX)
6340 {
6341 cs_log("dvbapi_handlesockmsg(): error - received invalid demux_id (%d)", demux_id);
6342 break;
6343 }
6344
6345 if(filter_num < 0 || filter_num >= MAX_FILTER)
6346 {
6347 cs_log("dvbapi_handlesockmsg(): error - received invalid filter_num (%d)", filter_num);
6348 break;
6349 }
6350 dvbapi_process_input(demux_id, filter_num, mbuf + 6, data_len + 3, msgid);
6351 break;
6352 }
6353
6354 case DVBAPI_CLIENT_INFO:
6355 {
6356 uint16_t client_proto = b2i(2, mbuf + 4);
6357 NULLFREE(last_client_name);
6358
6359 if(cs_malloc(&last_client_name, data_len + 1))
6360 {
6361 memcpy(last_client_name, &mbuf[7], data_len);
6362 last_client_name[data_len] = 0;
6363 cs_log("Client connected: '%s' (protocol version = %" PRIu16 ")", last_client_name, client_proto);
6364 }
6365
6366 (*client_proto_version) = client_proto; // setting the global var according to the client
6367 last_client_proto_version = client_proto;
6368
6369 // as a response we are sending our info to the client:
6370 dvbapi_net_send(DVBAPI_SERVER_INFO, connfd, msgid, -1, -1, NULL, NULL, NULL, client_proto);
6371 break;
6372 }
6373
6374 default:
6375 {
6376 cs_log_dbg(D_DVBAPI, "dvbapi_handlesockmsg(): opcode unknown: %08X", opcode);
6377 cs_log_dump(mbuf, chunksize, "Unknown command:");
6378 break;
6379 }
6380 }
6381 }
6382}
6383
6384static bool dvbapi_handlesockdata(int32_t connfd, uint8_t *mbuf, uint16_t mbuf_size, uint16_t unhandled_len,
6385 uint8_t *add_to_poll, uint16_t *new_unhandled_len, uint16_t *client_proto_version)
6386{
6387 int32_t recv_result;
6388 uint16_t chunksize = 1, data_len = 1;
6389 uint8_t packet_count = 0;
6390 uint16_t missing_header_bytes = dvbapi_get_nbof_missing_header_bytes(mbuf, unhandled_len);
6391
6392 if(missing_header_bytes)
6393 {
6394 // read first few bytes so we know packet type and length
6395 cs_log_dbg(D_TRACE, "%s reading %" PRIu16 " bytes from connection fd %d",
6396 (unhandled_len == 0) ? "Try" : "Continue", missing_header_bytes, connfd);
6397
6398 recv_result = dvbapi_recv(connfd, mbuf + unhandled_len, mbuf_size - unhandled_len);
6399 if(recv_result < 1)
6400 {
6401 (*new_unhandled_len) = unhandled_len;
6402 return (recv_result != -1);
6403 }
6404 else
6405 {
6406 unhandled_len += recv_result;
6407 if(unhandled_len < dvbapi_get_nbof_missing_header_bytes(mbuf, unhandled_len))
6408 {
6409 (*new_unhandled_len) = unhandled_len;
6410 return true;
6411 }
6412 }
6413 }
6414
6415 do
6416 {
6417 // we got at least the first few bytes, detect packet type and length, then read the missing bytes
6418 dvbapi_get_packet_size(mbuf, unhandled_len, &chunksize, &data_len, *client_proto_version);
6419 if(chunksize > mbuf_size)
6420 {
6421 cs_log("***** WARNING: SOCKET DATA BUFFER OVERFLOW (%" PRIu16 " bytes), PLEASE REPORT! ****** ", chunksize);
6422 (*new_unhandled_len) = 0;
6423 return true;
6424 }
6425
6426 if(unhandled_len < chunksize) // we are missing some bytes, try to read them
6427 {
6428 cs_log_dbg(D_TRACE, "Continue to read %d bytes from connection fd %d", chunksize - unhandled_len, connfd);
6429 recv_result = dvbapi_recv(connfd, mbuf + unhandled_len, mbuf_size - unhandled_len);
6430 if(recv_result < 1)
6431 {
6432 (*new_unhandled_len) = unhandled_len;
6433 return (recv_result != -1);
6434 }
6435 else
6436 {
6437 unhandled_len += recv_result;
6438 if(unhandled_len < chunksize)
6439 {
6440 (*new_unhandled_len) = unhandled_len;
6441 return true;
6442 }
6443 }
6444 }
6445
6446 // we got at least one full packet, handle it, then return
6447 dvbapi_handlesockmsg(mbuf, chunksize, data_len, add_to_poll, connfd, client_proto_version);
6448
6449 unhandled_len -= chunksize;
6450 if(unhandled_len > 0)
6451 {
6452 memmove(mbuf, mbuf + chunksize, unhandled_len);
6453 }
6454 packet_count++;
6455 } while(dvbapi_get_nbof_missing_header_bytes(mbuf, unhandled_len) == 0 && packet_count < 7);
6456
6457 (*new_unhandled_len) = unhandled_len;
6458 return true;
6459}
6460
6461static void *dvbapi_main_local(void *cli)
6462{
6463 int32_t i, j, l;
6464 struct s_client *client = (struct s_client *)cli;
6465 client->thread = pthread_self();
6466 SAFE_SETSPECIFIC(getclient, cli);
6467 dvbapi_client = cli;
6468 int32_t maxpfdsize = (MAX_DEMUX * maxfilter) + MAX_DEMUX + 2;
6469 struct pollfd pfd2[maxpfdsize];
6470 struct timeb start, end; // start time poll, end time poll
6471#define PMT_SERVER_SOCKET "/tmp/.listen.camd.socket"
6472 struct sockaddr_un saddr;
6473 saddr.sun_family = AF_UNIX;
6474 cs_strncpy(saddr.sun_path, PMT_SERVER_SOCKET, sizeof(saddr.sun_path));
6475 int32_t rc, pfdcount, g, connfd, clilen;
6476 int32_t ids[maxpfdsize], fdn[maxpfdsize], type[maxpfdsize];
6477 struct SOCKADDR servaddr;
6478 ssize_t len = 0;
6479 static const uint16_t mbuf_size = 2048;
6480 uint8_t *mbuf;
6481 uint16_t unhandled_buf_len[maxpfdsize], unhandled_buf_used[maxpfdsize];
6482 uint8_t *unhandled_buf[maxpfdsize];
6483 struct s_auth *account;
6484 int32_t ok = 0;
6485 uint16_t client_proto_version[maxpfdsize];
6486
6487 if(!cs_malloc(&mbuf, sizeof(uint8_t) * mbuf_size))
6488 {
6489 return NULL;
6490 }
6491
6492 for(i = 0; i < maxpfdsize; i++)
6493 {
6494 unhandled_buf[i] = NULL;
6495 unhandled_buf_len[i] = 0;
6496 unhandled_buf_used[i] = 0;
6497 client_proto_version[i] = 0;
6498 }
6499
6500 for(account = cfg.account; account != NULL; account = account->next)
6501 {
6502 if((ok = is_dvbapi_usr(account->usr)))
6503 {
6504 break;
6505 }
6506 }
6507
6508 cs_auth_client(client, ok ? account : (struct s_auth *)(-1), "dvbapi");
6509 memset(demux, 0, sizeof(demux));
6510
6511 for(i = 0; i < MAX_DEMUX; i++)
6512 {
6513 SAFE_MUTEX_INIT(&demux[i].answerlock, NULL);
6514 for(j = 0; j < MAX_ECM_PIDS; j++)
6515 {
6516 for(l = 0; l < MAX_STREAM_INDICES; l++)
6517 {
6518 demux[i].ECMpids[j].index[l] = INDEX_INVALID;
6519 }
6520 }
6521 demux[i].pidindex = -1;
6522 demux[i].curindex = -1;
6523 }
6524
6525 memset(ca_fd, 0, sizeof(ca_fd));
6526 memset(unassoc_fd, 0, sizeof(unassoc_fd));
6527 dvbapi_read_priority();
6528 dvbapi_load_channel_cache();
6529 dvbapi_detect_api();
6530
6531 if(selected_box == -1 || selected_api == -1)
6532 {
6533 cs_log("ERROR: Could not detect DVBAPI version.");
6534 free(mbuf);
6535 return NULL;
6536 }
6537
6538 // detect box type first and then get descrambler info
6539 dvbapi_get_descrambler_info();
6540
6541 if(cfg.dvbapi_pmtmode == 1)
6542 {
6543 disable_pmt_files = 1;
6544 }
6545
6546 int32_t listenfd = -1;
6547 if(cfg.dvbapi_boxtype != BOXTYPE_IPBOX_PMT &&
6548 cfg.dvbapi_pmtmode != 2 && cfg.dvbapi_pmtmode != 5 && cfg.dvbapi_pmtmode != 6)
6549 {
6550 if(!cfg.dvbapi_listenport)
6551 {
6552 listenfd = dvbapi_init_listenfd();
6553 }
6554 else
6555 {
6556 listenfd = dvbapi_net_init_listenfd();
6557 }
6558
6559 if(listenfd < 1)
6560 {
6561 cs_log("ERROR: Could not init socket: (errno=%d: %s)", errno, strerror(errno));
6562 free(mbuf);
6563 return NULL;
6564 }
6565 }
6566
6567 for(i = 0; i < MAX_DEMUX; i++) // init all demuxers!
6568 {
6569 demux[i].pidindex = -1;
6570 demux[i].curindex = -1;
6571 }
6572
6573 if(cfg.dvbapi_pmtmode != 4 && cfg.dvbapi_pmtmode != 5 && cfg.dvbapi_pmtmode != 6)
6574 {
6575 struct sigaction signal_action;
6576 signal_action.sa_handler = event_handler;
6577 sigemptyset(&signal_action.sa_mask);
6578 signal_action.sa_flags = SA_RESTART;
6579 sigaction(SIGRTMIN + 1, &signal_action, NULL);
6580
6581 dir_fd = open(TMPDIR, O_RDONLY);
6582 if(dir_fd >= 0)
6583 {
6584 fcntl(dir_fd, F_SETSIG, SIGRTMIN + 1);
6585 fcntl(dir_fd, F_NOTIFY, DN_MODIFY | DN_CREATE | DN_DELETE | DN_MULTISHOT);
6586 event_handler(SIGRTMIN + 1);
6587 }
6588 }
6589 else
6590 {
6591 int32_t ret = start_thread("dvbapi event", dvbapi_event_thread, (void *) dvbapi_client, NULL, 1, 0);
6592 if(ret)
6593 {
6594 free(mbuf);
6595 return NULL;
6596 }
6597 }
6598
6599 if(listenfd != -1)
6600 {
6601 pfd2[0].fd = listenfd;
6602 pfd2[0].events = (POLLIN | POLLPRI);
6603 type[0] = 1;
6604 }
6605
6606#if defined WITH_COOLAPI || defined WITH_COOLAPI2 || defined WITH_NEUTRINO
6607 system("pzapit -rz");
6608#endif
6609 cs_ftime(&start); // register start time
6610
6611 while(!exit_oscam)
6612 {
6613 if(pausecam) // for dbox2, STAPI or PC in standby mode don't parse any ecm/emm or try to start next filter
6614 {
6615 continue;
6616 }
6617
6618 if(cfg.dvbapi_pmtmode == 6)
6619 {
6620 if(listenfd < 0)
6621 {
6622 cs_log("PMT mode 6: Connecting to enigma CA PMT listen socket...");
6623
6624 // socket init
6625 if((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
6626 {
6627 cs_log("socket error (errno=%d %s)", errno, strerror(errno));
6628 listenfd = -1;
6629 }
6630 else if(connect(listenfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
6631 {
6632 cs_log("socket connect error (errno=%d %s)", errno, strerror(errno));
6633 close(listenfd);
6634 listenfd = -1;
6635 }
6636 else
6637 {
6638 pfd2[0].fd = listenfd;
6639 pfd2[0].events = (POLLIN | POLLPRI);
6640 type[0] = 1;
6641 cs_log("PMT mode 6: Successfully connected to CA PMT server (fd %d)", listenfd);
6642 }
6643 }
6644
6645 if(listenfd == -1) // not connected!
6646 {
6647 cs_sleepms(1000);
6648 continue; // start fresh connect attempt!
6649 }
6650 }
6651
6652 pfdcount = (listenfd > -1) ? 1 : 0;
6653 for(i = 0; i < MAX_DEMUX; i++)
6654 {
6655 // add client fd's which are not yet associated
6656 // with the demux but needs to be polled for data
6657 if(unassoc_fd[i])
6658 {
6659 pfd2[pfdcount].fd = unassoc_fd[i];
6660 pfd2[pfdcount].events = (POLLIN | POLLPRI);
6661 client_proto_version[pfdcount] = last_client_proto_version;
6662 type[pfdcount++] = 1;
6663 }
6664
6665 if(demux[i].program_number == 0)
6666 {
6667 continue; // only evalutate demuxers that have channels assigned
6668 }
6669
6670 uint32_t ecmcounter = 0, emmcounter = 0;
6671 for(g = 0; g < maxfilter; g++)
6672 {
6673 if(demux[i].demux_fd[g].fd <= 0)
6674 {
6675 continue; // deny obvious invalid fd!
6676 }
6677
6678 if(!cfg.dvbapi_listenport && cfg.dvbapi_boxtype != BOXTYPE_PC_NODMX
6679 && selected_api != STAPI && selected_api != COOLAPI)
6680 {
6681 pfd2[pfdcount].fd = demux[i].demux_fd[g].fd;
6682 pfd2[pfdcount].events = (POLLIN | POLLPRI);
6683 ids[pfdcount] = i;
6684 fdn[pfdcount] = g;
6685 type[pfdcount++] = 0;
6686 }
6687
6688 // count ecm filters to see if demuxing is possible anyway
6689 if(demux[i].demux_fd[g].type == TYPE_ECM)
6690 {
6691 ecmcounter++;
6692 }
6693
6694 // count emm filters also
6695 if(demux[i].demux_fd[g].type == TYPE_EMM)
6696 {
6697 emmcounter++;
6698 }
6699 }
6700
6701 // only produce log if something changed
6702 if(ecmcounter != demux[i].old_ecmfiltercount || emmcounter != demux[i].old_emmfiltercount)
6703 {
6704 cs_log_dbg(D_DVBAPI, "Demuxer %d has %d ecmpids, %d streampids, %d ecmfilters and %d of max %d emmfilters",
6705 i, demux[i].ECMpidcount, demux[i].STREAMpidcount, ecmcounter, emmcounter, demux[i].max_emm_filter);
6706
6707 demux[i].old_ecmfiltercount = ecmcounter; // save new amount of ecm filters
6708 demux[i].old_emmfiltercount = emmcounter; // save new amount of emm filters
6709 }
6710
6711 // delayed emm start for non irdeto caids,
6712 // start emm cat if not already done for this demuxer!
6713 struct timeb now;
6714 cs_ftime(&now);
6715 int64_t gone;
6716 int8_t do_emm_start = (cfg.dvbapi_au > 0 && demux[i].emm_filter == -1 && demux[i].EMMpidcount == 0 && emmcounter == 0);
6717 int8_t do_sdt_start = (cfg.dvbapi_read_sdt && demux[i].sdt_filter == -1 && cfg.dvbapi_boxtype != BOXTYPE_SAMYGO);
6718
6719 if(do_emm_start || do_sdt_start)
6720 {
6721 gone = comp_timeb(&now, &demux[i].emmstart);
6722 if(gone > 20 * 1000)
6723 {
6724 if(do_emm_start)
6725 {
6726 cs_ftime(&demux[i].emmstart); // trick to let emm fetching start after 30 seconds to speed up zapping
6727 dvbapi_start_filter(i, demux[i].pidindex, 0x001, 0x001, 0x01, 0x01, 0xFF, 0, TYPE_EMM); //CAT
6728 }
6729 }
6730
6731 if(gone > 5 * 1000)
6732 {
6733 if(do_sdt_start)
6734 {
6735 dvbapi_start_sdt_filter(i);
6736 }
6737 }
6738 }
6739
6740 // early start for irdeto since they need emm before ecm
6741 // (pmt emmstart = 1 if detected caid 0x06)
6742 int32_t emmstarted = demux[i].emm_filter;
6743
6744 // check every time since share readers might
6745 // give us new filters due to hexserial change
6746 if(cfg.dvbapi_au && demux[i].EMMpidcount > 0)
6747 {
6748 if(!emmcounter && emmstarted == -1)
6749 {
6750 demux[i].emmstart = now;
6751 dvbapi_start_emm_filter(i); // start emm filtering if emm pids are found
6752 }
6753 else
6754 {
6755 gone = comp_timeb(&now, &demux[i].emmstart);
6756 if(gone > 30 * 1000)
6757 {
6758 demux[i].emmstart = now;
6759 dvbapi_start_emm_filter(i); // start emm filtering delayed if filters already were running
6760 rotate_emmfilter(i); // rotate active emm filters
6761 }
6762 }
6763 }
6764
6765 // Restart decoding all caids we have ecmpids but no ecm filters!
6766 if(ecmcounter == 0 && demux[i].ECMpidcount > 0)
6767 {
6768 int32_t started = 0;
6769
6770 // avoid race: not all pids are asked and checked out yet!
6771 for(g = 0; g < demux[i].ECMpidcount; g++)
6772 {
6773 // check if prio run is done
6774 if(demux[i].ECMpids[g].checked == 0 && demux[i].ECMpids[g].status >= 0)
6775 {
6776 dvbapi_try_next_caid(i, 0, 0); // not done, so start next prio pid
6777 started = 1;
6778 break;
6779 }
6780 }
6781
6782 if(started)
6783 {
6784 continue; // if started a filter proceed with next demuxer
6785 }
6786
6787 // all usable pids (with prio) are tried, lets start over again without prio!
6788 if(g == demux[i].ECMpidcount)
6789 {
6790 // avoid race: not all pids are asked and checked out yet!
6791 for(g = 0; g < demux[i].ECMpidcount; g++)
6792 {
6793 // check if noprio run is done
6794 if(demux[i].ECMpids[g].checked == 2 && demux[i].ECMpids[g].status >= 0)
6795 {
6796 demux[i].ECMpids[g].irdeto_curindex = 0xFE;
6797 demux[i].ECMpids[g].irdeto_maxindex = 0;
6798 demux[i].ECMpids[g].irdeto_cycle = 0xFE;
6799 demux[i].ECMpids[g].tries = 0xFE;
6800 demux[i].ECMpids[g].table = 0;
6801 demux[i].ECMpids[g].CHID = 0x10000; // remove chid prio
6802
6803 dvbapi_try_next_caid(i, 2, 0); // not done, so start next no prio pid
6804 started = 1;
6805 break;
6806 }
6807 }
6808 }
6809
6810 if(started)
6811 {
6812 continue; // if started a filter proceed with next demuxer
6813 }
6814
6815 if(g == demux[i].ECMpidcount) // all usable pids are tried, lets start over again!
6816 {
6817 if(demux[i].decodingtries == -1) // first redecoding attempt?
6818 {
6819 cs_ftime(&demux[i].decstart);
6820
6821 // re-init some used things from second run (without prio)
6822 for(g = 0; g < demux[i].ECMpidcount; g++)
6823 {
6824 demux[i].ECMpids[g].checked = 0;
6825 demux[i].ECMpids[g].irdeto_curindex = 0xFE;
6826 demux[i].ECMpids[g].irdeto_maxindex = 0;
6827 demux[i].ECMpids[g].irdeto_cycle = 0xFE;
6828 demux[i].ECMpids[g].table = 0;
6829 demux[i].decodingtries = 0;
6830
6831 // remove this pid from channel cache since we had no founds on any ecmpid!
6832 dvbapi_edit_channel_cache(i, g, 0);
6833 }
6834 }
6835
6836 uint8_t number_of_enabled_pids = 0;
6837 demux[i].decodingtries++;
6838 dvbapi_resort_ecmpids(i);
6839
6840 for(g = 0; g < demux[i].ECMpidcount; g++) // count number of enabled pids!
6841 {
6842 if(demux[i].ECMpids[g].status >= 0) number_of_enabled_pids++;
6843 }
6844
6845 if(!number_of_enabled_pids)
6846 {
6847 if(demux[i].decodingtries == 10)
6848 {
6849 demux[i].decodingtries = 0;
6850 cs_log("Demuxer %d no enabled matching ecmpids -> decoding is waiting for matching readers!",i);
6851 }
6852 }
6853 else
6854 {
6855 cs_ftime(&demux[i].decend);
6856 demux[i].decodingtries = -1; // reset to first run again!
6857 gone = comp_timeb(&demux[i].decend, &demux[i].decstart);
6858
6859 cs_log("Demuxer %d restarting decoding requests after %"PRId64" ms with %d enabled and %d disabled ecmpids!",
6860 i, gone, number_of_enabled_pids, (demux[i].ECMpidcount-number_of_enabled_pids));
6861
6862 dvbapi_try_next_caid(i, 0, 0);
6863 }
6864 }
6865 }
6866
6867 if(demux[i].socket_fd > 0 && cfg.dvbapi_pmtmode != 6)
6868 {
6869 rc = 0;
6870 for(j = 0; j < pfdcount; j++)
6871 {
6872 if(pfd2[j].fd == demux[i].socket_fd)
6873 {
6874 rc = 1;
6875 break;
6876 }
6877 }
6878
6879 if(rc == 1)
6880 {
6881 continue;
6882 }
6883
6884 pfd2[pfdcount].fd = demux[i].socket_fd;
6885 pfd2[pfdcount].events = (POLLIN | POLLPRI);
6886 ids[pfdcount] = i;
6887 type[pfdcount++] = 1;
6888 }
6889 }
6890
6891 rc = 0;
6892 while(!(listenfd == -1 && cfg.dvbapi_pmtmode == 6))
6893 {
6894 rc = poll(pfd2, pfdcount, 500);
6895 if(rc < 0) // error occured while polling for fd's with fresh data
6896 {
6897 if(errno == EINTR || errno == EAGAIN) // try again in case of interrupt
6898 {
6899 continue;
6900 }
6901 cs_log("ERROR: error on poll of %d fd's (errno=%d %s)", pfdcount, errno, strerror(errno));
6902 break;
6903 }
6904 else
6905 {
6906 break;
6907 }
6908 }
6909
6910 if(rc > 0)
6911 {
6912 cs_ftime(&end); // register end time
6913 int64_t timeout = comp_timeb(&end, &start);
6914 if(timeout < 0)
6915 {
6916 cs_log("*** WARNING: BAD TIME AFFECTING WHOLE OSCAM ECM HANDLING ****");
6917 }
6918 cs_log_dbg(D_TRACE, "New events occurred on %d of %d handlers after %"PRId64" ms inactivity", rc, pfdcount, timeout);
6919 cs_ftime(&start); // register new start time for next poll
6920 }
6921
6922 for(i = 0; i < pfdcount && rc > 0; i++)
6923 {
6924 if(pfd2[i].revents == 0) { continue; } // skip sockets with no changes
6925 rc--; //event handled!
6926 cs_log_dbg(D_TRACE, "Now handling fd %d that reported event %d", pfd2[i].fd, pfd2[i].revents);
6927
6928 if(pfd2[i].revents & (POLLHUP | POLLNVAL | POLLERR))
6929 {
6930 if(type[i] == 1)
6931 {
6932 for(j = 0; j < MAX_DEMUX; j++)
6933 {
6934 // if listenfd closes stop all assigned decoding!
6935 if(demux[j].socket_fd == pfd2[i].fd)
6936 {
6937 dvbapi_stop_descrambling(j, 0);
6938 }
6939
6940 // remove from unassoc_fd when necessary
6941 if(unassoc_fd[j] == pfd2[i].fd)
6942 {
6943 unassoc_fd[j] = 0;
6944 }
6945 }
6946
6947 int32_t ret = close(pfd2[i].fd);
6948 if(ret < 0 && errno != 9)
6949 {
6950 cs_log("ERROR: Could not close demuxer socket fd (errno=%d %s)", errno, strerror(errno));
6951 }
6952
6953 if(pfd2[i].fd == listenfd && cfg.dvbapi_pmtmode == 6)
6954 {
6955 listenfd = -1;
6956 }
6957 cs_log_dbg(D_DVBAPI, "Socket %d reported hard connection close", pfd2[i].fd);
6958 }
6959 else // type = 0
6960 {
6961 int32_t demux_id = ids[i];
6962 int32_t n = fdn[i];
6963
6964 if(cfg.dvbapi_boxtype != BOXTYPE_SAMYGO)
6965 {
6966 // stop filter since its giving errors and wont return anything good
6967 dvbapi_stop_filternum(demux_id, n, 0);
6968 }
6969 else
6970 {
6971 int32_t ret, pid;
6972 uint8_t filter[32];
6973 struct dmx_sct_filter_params sFP;
6974 cs_log_dbg(D_DVBAPI, "re-opening connection to demux socket");
6975 close(demux[demux_id].demux_fd[n].fd);
6976 demux[demux_id].demux_fd[n].fd = -1;
6977
6978 ret = dvbapi_open_device(0, demux[demux_id].demux_index, demux[demux_id].adapter_index);
6979 if(ret != -1)
6980 {
6981 demux[demux_id].demux_fd[n].fd = ret;
6982 pid = demux[demux_id].curindex;
6983 memset(filter, 0, 32);
6984 memset(&sFP, 0, sizeof(sFP));
6985 filter[0] = 0x80;
6986 filter[16] = 0xF0;
6987 sFP.pid = demux[demux_id].ECMpids[pid].ECM_PID;
6988 sFP.timeout = 3000;
6989 sFP.flags = DMX_IMMEDIATE_START;
6990 memcpy(sFP.filter.filter, filter, 16);
6991 memcpy(sFP.filter.mask, filter + 16, 16);
6992 ret = dvbapi_ioctl(demux[demux_id].demux_fd[n].fd, DMX_SET_FILTER, &sFP);
6993 }
6994
6995 if(ret == -1)
6996 {
6997 // stop filter since it's giving errors and wont return anything good
6998 dvbapi_stop_filternum(demux_id, n, 0);
6999 }
7000 }
7001 }
7002 continue; // continue with other events
7003 }
7004
7005 if(pfd2[i].revents & (POLLIN | POLLPRI))
7006 {
7007 if(type[i] == 1)
7008 {
7009 connfd = -1; // initially no socket to read from
7010 uint8_t add_to_poll = 0; // we may need to additionally poll this socket when no PMT data comes in
7011
7012 if(pfd2[i].fd == listenfd)
7013 {
7014 if(cfg.dvbapi_pmtmode == 6)
7015 {
7016 connfd = listenfd;
7017 disable_pmt_files = 1;
7018 }
7019 else
7020 {
7021 clilen = sizeof(servaddr);
7022 connfd = accept(listenfd, (struct sockaddr *)&servaddr, (socklen_t *)&clilen);
7023 cs_log_dbg(D_DVBAPI, "new socket connection fd: %d", connfd);
7024
7025 if(cfg.dvbapi_listenport)
7026 {
7027 // update webif data
7028 client->ip = SIN_GET_ADDR(servaddr);
7029 client->port = ntohs(SIN_GET_PORT(servaddr));
7030 }
7031 add_to_poll = 1;
7032
7033 if(cfg.dvbapi_pmtmode == 3 || cfg.dvbapi_pmtmode == 0)
7034 {
7035 disable_pmt_files = 1;
7036 }
7037
7038 if(connfd <= 0)
7039 {
7040 cs_log_dbg(D_DVBAPI, "accept() returns error on fd event %d (errno=%d %s)",
7041 pfd2[i].revents, errno, strerror(errno));
7042 }
7043 }
7044 }
7045 else
7046 {
7047 connfd = pfd2[i].fd;
7048 }
7049
7050 //reading and completing data from socket
7051 if(connfd > 0)
7052 {
7053 if(unhandled_buf_used[i])
7054 {
7055 memcpy(mbuf, unhandled_buf[i], unhandled_buf_used[i]);
7056 }
7057
7058 if(!dvbapi_handlesockdata(connfd, mbuf, mbuf_size, unhandled_buf_used[i], &add_to_poll, &unhandled_buf_used[i], &client_proto_version[i]))
7059 {
7060 unhandled_buf_used[i] = 0;
7061 // client disconnects, stop all assigned decoding
7062 cs_log_dbg(D_DVBAPI, "Socket %d reported connection close", connfd);
7063 int active_conn = 0; // other active connections counter
7064 add_to_poll = 0;
7065
7066 for(j = 0; j < MAX_DEMUX; j++)
7067 {
7068 if(demux[j].socket_fd == connfd)
7069 {
7070 dvbapi_stop_descrambling(j, 0);
7071 }
7072 else if(demux[j].socket_fd)
7073 {
7074 active_conn++;
7075 }
7076
7077 // remove from unassoc_fd when necessary
7078 if(unassoc_fd[j] == connfd)
7079 {
7080 unassoc_fd[j] = 0;
7081 }
7082 }
7083 close(connfd);
7084 connfd = -1;
7085
7086 // last connection closed
7087 if(!active_conn && (cfg.dvbapi_listenport || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX))
7088 {
7089 if(cfg.dvbapi_listenport)
7090 {
7091 // update webif data
7092 client->ip = get_null_ip();
7093 client->port = 0;
7094 }
7095 }
7096 continue;
7097 }
7098
7099 if(unhandled_buf_used[i])
7100 {
7101 if(unhandled_buf_used[i] > unhandled_buf_len[i])
7102 {
7103 NULLFREE(unhandled_buf[i]);
7104 unhandled_buf_len[i] = unhandled_buf_used[i] < 128 ? 128 : unhandled_buf_used[i];
7105 if(!cs_malloc(&unhandled_buf[i], sizeof(uint8_t) * unhandled_buf_len[i]))
7106 {
7107 unhandled_buf_len[i] = 0;
7108 unhandled_buf_used[i] = 0;
7109 continue;
7110 }
7111 }
7112 memcpy(unhandled_buf[i], mbuf, unhandled_buf_used[i]);
7113 }
7114
7115 // if the connection is new and we read no PMT data, then add it to the poll,
7116 // otherwise this socket will not be checked with poll when data arives
7117 // because fd it is not yet assigned with the demux
7118 if(add_to_poll)
7119 {
7120 for(j = 0; j < MAX_DEMUX; j++)
7121 {
7122 if(!unassoc_fd[j])
7123 {
7124 unassoc_fd[j] = connfd;
7125 break;
7126 }
7127 }
7128 }
7129 }
7130 }
7131 else // type == 0
7132 {
7133 int32_t demux_id = ids[i];
7134 int32_t n = fdn[i];
7135
7136 if((int)demux[demux_id].demux_fd[n].fd != pfd2[i].fd)
7137 {
7138 continue; // filter already killed, no need to process this data!
7139 }
7140
7141 len = dvbapi_read_device(pfd2[i].fd, mbuf, mbuf_size);
7142 if(len < 0) // serious filterdata read error
7143 {
7144 // stop filter since it's giving errors and won't return anything good
7145 dvbapi_stop_filternum(demux_id, n, 0);
7146
7147 maxfilter--; // lower maxfilters to avoid this with new filter setups!
7148 continue;
7149 }
7150
7151 if(!len) // receiver internal filter buffer overflow
7152 {
7153 memset(mbuf, 0, mbuf_size);
7154 }
7155 dvbapi_process_input(demux_id, n, mbuf, len, 0);
7156 }
7157 continue; // continue with other events!
7158 }
7159 }
7160 }
7161
7162 for(j = 0; j < maxpfdsize; j++)
7163 {
7164 NULLFREE(unhandled_buf[j]);
7165 }
7166 free(mbuf);
7167
7168 return NULL;
7169}
7170
7171void dvbapi_write_cw(int32_t demux_id, int32_t pid, int32_t stream_id, uint8_t *cw, uint8_t cw_length, uint8_t *iv,
7172 uint8_t iv_length, enum ca_descr_algo algo, enum ca_descr_cipher_mode cipher_mode, uint32_t msgid)
7173{
7174 int8_t n, cw_empty = 0;
7175 uint8_t null_cw[cw_length];
7176 ca_descr_t ca_descr;
7177 ca_descr_mode_t ca_descr_mode;
7178 ca_descr_data_t ca_descr_data;
7179
7180 memset(null_cw, 0, cw_length);
7181 memset(&ca_descr, 0, sizeof(ca_descr));
7182 memset(&ca_descr_mode, 0, sizeof(ca_descr_mode));
7183 memset(&ca_descr_data, 0, sizeof(ca_descr_data));
7184
7185 if(memcmp(demux[demux_id].last_cw[stream_id][0], null_cw, cw_length) == 0
7186 && memcmp(demux[demux_id].last_cw[stream_id][1], null_cw, cw_length) == 0)
7187 {
7188 cw_empty = 1; // to make sure that both cws get written on constantcw
7189 }
7190
7191 for(n = 0; n < 2; n++)
7192 {
7193 // Check if cw has changed and if new cw is empty (all zeros)
7194 // Skip check for BISS1 - cw could be indeed zero
7195 // Skip check for BISS2 - we use the extended cw, so the "simple" cw is always zero
7196 if((memcmp(cw + (n * cw_length), demux[demux_id].last_cw[stream_id][n], cw_length) != 0 || cw_empty)
7197 && (memcmp(cw + (n * cw_length), null_cw, cw_length) != 0 || caid_is_biss(demux[demux_id].ECMpids[pid].CAID)))
7198 {
7199 // prepare ca device
7200 uint32_t idx = dvbapi_ca_set_pid(demux_id, pid, stream_id, (algo == CA_ALGO_DES), msgid);
7201 if(idx == INDEX_INVALID)
7202 {
7203 return; // return on no index!
7204 }
7205
7206#if defined WITH_COOLAPI || defined WITH_COOLAPI2
7207 ca_descr.index = idx;
7208 ca_descr.parity = n;
7209
7210 // just to make the compiler happy (-Wunused-parameter)
7211 // (better move the coolapi code to a separate function)
7212 ca_descr_mode.cipher_mode = cipher_mode;
7213 ca_descr_data.data = iv;
7214 ca_descr_data.length = iv_length;
7215
7216 memcpy(demux[demux_id].last_cw[stream_id][n], cw + (n * 8), 8);
7217 memcpy(ca_descr.cw, cw + (n * 8), 8);
7218
7219 cs_log_dbg(D_DVBAPI, "Demuxer %d write cw%d index: %d (ca_mask %d)",
7220 demux_id, n, ca_descr.index, demux[demux_id].ca_mask);
7221
7222 coolapi_write_cw(demux[demux_id].ca_mask, demux[demux_id].STREAMpids, demux[demux_id].STREAMpidcount, &ca_descr);
7223#else
7224 int32_t i, j, write_cw = 0;
7225 uint32_t usedidx, lastidx;
7226
7227 char lastcw[2 * cw_length + 1];
7228 char newcw[2 * cw_length + 1];
7229 cs_hexdump(0, demux[demux_id].last_cw[stream_id][n], cw_length, lastcw, sizeof(lastcw));
7230 cs_hexdump(0, cw + (n * cw_length), cw_length, newcw, sizeof(newcw));
7231
7232 for(i = 0; i < CA_MAX; i++)
7233 {
7234 if(!(demux[demux_id].ca_mask & (1 << i)))
7235 {
7236 continue; // ca not in use by this demuxer!
7237 }
7238 lastidx = INDEX_INVALID;
7239
7240 for(j = 0; j < demux[demux_id].STREAMpidcount; j++)
7241 {
7242 write_cw = 0;
7243 if(!demux[demux_id].ECMpids[pid].streams || ((demux[demux_id].ECMpids[pid].streams & (1 << j)) == (uint) (1 << j)))
7244 {
7245 usedidx = is_ca_used(i, demux[demux_id].STREAMpids[j]);
7246 if(usedidx != INDEX_INVALID)
7247 {
7248 if(idx != usedidx)
7249 {
7250 cs_log_dbg(D_DVBAPI,"Demuxer %d ca%d is using index %d for streampid %04X -> skip!",
7251 demux_id, i, usedidx, demux[demux_id].STREAMpids[j]);
7252 continue; // if not used for descrambling -> skip!
7253 }
7254 else
7255 {
7256 if(usedidx == lastidx)
7257 {
7258 cs_log_dbg(D_DVBAPI,"Demuxer %d ca%d is using index %d for streampid %04X -> skip, %s part of cw already written!",
7259 demux_id, i, usedidx, demux[demux_id].STREAMpids[j], (n == 1 ? "even" : "odd"));
7260 continue;
7261 }
7262
7263 cs_log_dbg(D_DVBAPI,"Demuxer %d ca%d is using index %d for streampid %04X -> write %s part of cw!",
7264 demux_id, i, usedidx, demux[demux_id].STREAMpids[j], (n == 1 ? "even" : "odd"));
7265
7266 write_cw = 1;
7267 }
7268 }
7269 }
7270
7271 if(!write_cw)
7272 {
7273 continue; // no need to write the cw since this ca isnt using it!
7274 }
7275
7276 lastidx = usedidx;
7277 ca_descr.index = usedidx;
7278 ca_descr.parity = n;
7279
7280 memcpy(demux[demux_id].last_cw[stream_id][n], cw + (n * cw_length), cw_length);
7281 memcpy(ca_descr.cw, cw + (n * 8), 8); // ca_descr is only used for 8 byte CWs
7282
7283 cs_log_dbg(D_DVBAPI, "Demuxer %d writing %s part (%s) of controlword, replacing expired (%s)",
7284 demux_id, (n == 1 ? "even" : "odd"), newcw, lastcw);
7285
7286 cs_log_dbg(D_DVBAPI, "Demuxer %d write cw%d index: %d (ca%d)", demux_id, n, ca_descr.index, i);
7287
7288 if(cfg.dvbapi_extended_cw_api == 1) // Set descrambler algorithm and mode
7289 {
7290 ca_descr_mode.index = usedidx;
7291 ca_descr_mode.algo = algo;
7292 ca_descr_mode.cipher_mode = cipher_mode;
7293
7294 if(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
7295 {
7296 dvbapi_net_send(DVBAPI_CA_SET_DESCR_MODE, demux[demux_id].socket_fd, msgid, demux_id, -1 /*unused*/,
7297 (uint8_t *) &ca_descr_mode, NULL, NULL, demux[demux_id].client_proto_version);
7298 }
7299 else
7300 {
7301 if(ca_fd[i] <= 0)
7302 {
7303 ca_fd[i] = dvbapi_open_device(1, i, demux[demux_id].adapter_index);
7304 if(ca_fd[i] <= 0) { continue; }
7305 }
7306
7307 if(dvbapi_ioctl(ca_fd[i], CA_SET_DESCR_MODE, &ca_descr_mode) < 0)
7308 {
7309 cs_log("ERROR: ioctl(CA_SET_DESCR_MODE): %s", strerror(errno));
7310 }
7311 }
7312 }
7313
7314 // Send 16 byte CW and IV for AES128, DVB-CISSA
7315 if(cfg.dvbapi_extended_cw_api == 1 && algo == CA_ALGO_AES128)
7316 {
7317 // First send IV
7318 ca_descr_data.index = usedidx;
7319 ca_descr_data.data_type = CA_DATA_IV;
7320 ca_descr_data.data = iv;
7321 ca_descr_data.length = iv_length;
7322
7323 if(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
7324 {
7325 dvbapi_net_send(DVBAPI_CA_SET_DESCR_DATA, demux[demux_id].socket_fd, msgid, demux_id, -1 /*unused*/,
7326 (uint8_t *) &ca_descr_data, NULL, NULL, demux[demux_id].client_proto_version);
7327 }
7328 else
7329 {
7330 if(dvbapi_ioctl(ca_fd[i], CA_SET_DESCR_DATA, &ca_descr_data) < 0)
7331 {
7332 cs_log("ERROR: ioctl(CA_SET_DESCR_DATA): %s", strerror(errno));
7333 }
7334 }
7335
7336 // Then send CW
7337 ca_descr_data.index = usedidx;
7338 ca_descr_data.data_type = CA_DATA_KEY;
7339 ca_descr_data.data = cw + (n * cw_length);
7340 ca_descr_data.length = cw_length;
7341 ca_descr_data.parity = n;
7342
7343 if(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
7344 {
7345 dvbapi_net_send(DVBAPI_CA_SET_DESCR_DATA, demux[demux_id].socket_fd, msgid, demux_id, -1 /*unused*/,
7346 (uint8_t *) &ca_descr_data, NULL, NULL, demux[demux_id].client_proto_version);
7347 }
7348 else
7349 {
7350 if(dvbapi_ioctl(ca_fd[i], CA_SET_DESCR_DATA, &ca_descr_data) < 0)
7351 {
7352 cs_log("ERROR: ioctl(CA_SET_DESCR_DATA): %s", strerror(errno));
7353 }
7354 }
7355 }
7356 else // Send 8 byte CW for DVB-CSA or DES
7357 {
7358 if(cfg.dvbapi_boxtype == BOXTYPE_PC || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
7359 {
7360 dvbapi_net_send(DVBAPI_CA_SET_DESCR, demux[demux_id].socket_fd, msgid, demux_id, -1 /*unused*/,
7361 (uint8_t *) &ca_descr, NULL, NULL, demux[demux_id].client_proto_version);
7362 }
7363 else
7364 {
7365 if(ca_fd[i] <= 0)
7366 {
7367 ca_fd[i] = dvbapi_open_device(1, i, demux[demux_id].adapter_index);
7368 if(ca_fd[i] <= 0)
7369 {
7370 continue;
7371 }
7372 }
7373
7374 if(dvbapi_ioctl(ca_fd[i], CA_SET_DESCR, &ca_descr) < 0)
7375 {
7376 cs_log("ERROR: ioctl(CA_SET_DESCR): %s", strerror(errno));
7377 }
7378 }
7379 }
7380 }
7381 }
7382#endif
7383 }
7384 }
7385 cs_log_dbg(D_DVBAPI, "Using %d of %d total descramblers", ca_descramblers_used, ca_descramblers_total);
7386}
7387
7388void delayer(ECM_REQUEST *er, uint32_t delay)
7389{
7390 if(delay <= 0) { return; }
7391
7392 struct timeb tpe;
7393 cs_ftime(&tpe);
7394 int64_t gone = comp_timeb(&tpe, &er->tps);
7395
7396 if(gone < delay)
7397 {
7398 cs_log_dbg(D_DVBAPI, "delayer: gone=%"PRId64" ms, cfg=%d ms -> delay=%"PRId64" ms", gone, delay, delay - gone);
7399 cs_sleepms(delay - gone);
7400 }
7401}
7402
7403void dvbapi_send_dcw(struct s_client *client, ECM_REQUEST *er)
7404{
7405 int32_t i, j, k, handled = 0;
7406 for(i = 0; i < MAX_DEMUX; i++)
7407 {
7408 uint32_t nocw_write = 0; // 0 = write cw, 1 = dont write cw to hardware demuxer
7409
7410 // ignore empty demuxers, skip ecm response for other
7411 // srvid and ecm recponse for different adapter
7412 if(demux[i].program_number == 0
7413 || demux[i].program_number != er->srvid
7414 || demux[i].adapter_index != er->adapter_index)
7415 {
7416 continue;
7417 }
7418
7419#ifdef WITH_STAPI5
7420 if(strcmp(dev_list[demux[i].dev_index].name, er->dev_name) != 0)
7421 {
7422 continue; // skip request if PTI device doesn't match request
7423 }
7424#endif
7425
7426 demux[i].rdr = er->selected_reader;
7427
7428 for(j = 0; j < demux[i].ECMpidcount; j++) // check for matching ecmpid
7429 {
7430 if((demux[i].ECMpids[j].CAID == er->caid || demux[i].ECMpids[j].CAID == er->ocaid)
7431 && demux[i].ECMpids[j].ECM_PID == er->pid && demux[i].ECMpids[j].PROVID == er->prid
7432 && demux[i].ECMpids[j].VPID == er->vpid)
7433 {
7434 break;
7435 }
7436 }
7437
7438 if(j == demux[i].ECMpidcount)
7439 {
7440 continue; // ecm response srvid ok but no matching ecmpid, perhaps this for other demuxer
7441 }
7442
7443 cs_log_dbg(D_DVBAPI, "Demuxer %d %scontrol word received for PID %d CAID %04X PROVID %06X ECMPID %04X CHID %04X VPID %04X",
7444 i, (er->rc >= E_NOTFOUND ? "no " : ""), j, er->caid, er->prid, er->pid, er->chid, er->vpid);
7445
7446 uint32_t status = dvbapi_check_ecm_delayed_delivery(i, er);
7447 uint32_t comparecw0 = 0, comparecw1 = 0;
7448 char ecmd5[17 * 3];
7449 cs_hexdump(0, er->ecmd5, 16, ecmd5, sizeof(ecmd5));
7450
7451 if(status == 1 && er->rc) // wrong ecmhash
7452 {
7453 cs_log_dbg(D_DVBAPI, "Demuxer %d not interested in response ecmhash %s (requested different one)", i, ecmd5);
7454 continue;
7455 }
7456
7457 if(status == 2) // no filter
7458 {
7459 cs_log_dbg(D_DVBAPI, "Demuxer %d not interested in response ecmhash %s (filter already killed)", i, ecmd5);
7460 continue;
7461 }
7462
7463 if(status == 5) // empty cw
7464 {
7465 cs_log_dbg(D_DVBAPI, "Demuxer %d not interested in response ecmhash %s (delivered cw is empty!)", i, ecmd5);
7466 nocw_write = 1;
7467
7468 if(er->rc < E_NOTFOUND)
7469 {
7470 er->rc = E_NOTFOUND;
7471 }
7472 }
7473
7474 // 0=matching ecm hash, 2=no filter, 3=table reset, 4=cache-ex response
7475 // Check only against last_cw[0] (index 0) - No need to check the rest
7476 // Skip check for BISS1 - cw could be indeed zero
7477 // Skip check for BISS2 - we use the extended cw, so the "simple" cw is always zero
7478 if((status == 0 || status == 3 || status == 4) && er->rc < E_NOTFOUND && !caid_is_biss(er->caid))
7479 {
7480 // check for matching control word
7481 if(memcmp(er->cw, demux[i].last_cw[0][0], 8) == 0 &&
7482 memcmp(er->cw + 8, demux[i].last_cw[0][1], 8) == 0)
7483 {
7484 comparecw0 = 1;
7485 }
7486 else if(memcmp(er->cw, demux[i].last_cw[0][1], 8) == 0 &&
7487 memcmp(er->cw + 8, demux[i].last_cw[0][0], 8) == 0)
7488 {
7489 comparecw1 = 1;
7490 }
7491
7492 if(comparecw0 == 1 || comparecw1 == 1)
7493 {
7494 cs_log_dbg(D_DVBAPI, "Demuxer %d duplicate controlword ecm response hash %s (duplicate controlword!)", i, ecmd5);
7495 nocw_write = 1;
7496 }
7497 }
7498
7499 if(status == 3) // table reset
7500 {
7501 cs_log_dbg(D_DVBAPI, "Demuxer %d luckyshot new controlword ecm response hash %s (ecm table reset)", i, ecmd5);
7502 }
7503
7504 if(status == 4) // no check on cache-ex responses!
7505 {
7506 cs_log_dbg(D_DVBAPI, "Demuxer %d new controlword from cache-ex reader (no ecmhash check possible)", i);
7507 }
7508
7509 handled = 1; // mark this ecm response as handled
7510 if(er->rc < E_NOTFOUND && cfg.dvbapi_requestmode == 0 && (demux[i].pidindex == -1) && er->caid != 0)
7511 {
7512 demux[i].ECMpids[j].tries = 0xFE; // reset timeout retry flag
7513 demux[i].ECMpids[j].irdeto_cycle = 0xFE; // reset irdetocycle
7514 demux[i].pidindex = j; // set current index as *the* pid to descramble
7515 demux[i].ECMpids[j].checked = 4;
7516
7517 cs_log_dbg(D_DVBAPI, "Demuxer %d descrambling PID %d CAID %04X PROVID %06X ECMPID %04X CHID %02X VPID %04X",
7518 i, demux[i].pidindex, er->caid, er->prid, er->pid, er->chid, er->vpid);
7519 }
7520
7521 if(er->rc < E_NOTFOUND && cfg.dvbapi_requestmode == 1 && er->caid != 0) // FOUND
7522 {
7523 SAFE_MUTEX_LOCK(&demux[i].answerlock); // only process one ecm answer
7524 if(demux[i].ECMpids[j].checked != 4)
7525 {
7526 int32_t t, o, ecmcounter = 0;
7527 int32_t oldpidindex = demux[i].pidindex;
7528 demux[i].pidindex = j; // set current ecmpid as the new pid to descramble
7529
7530 if(oldpidindex != -1)
7531 {
7532 for(k = 0; k < MAX_STREAM_INDICES; k++)
7533 {
7534 demux[i].ECMpids[j].index[k] = demux[i].ECMpids[oldpidindex].index[k]; // swap index with lower status pid that was descrambling
7535 demux[i].ECMpids[j].useMultipleIndices = demux[i].ECMpids[oldpidindex].useMultipleIndices;
7536 }
7537 }
7538
7539 // check this pid with control word FOUND for higher status
7540 for(t = 0; t < demux[i].ECMpidcount; t++)
7541 {
7542 if(t != j && demux[i].ECMpids[j].status >= demux[i].ECMpids[t].status)
7543 {
7544 // check if ecm filter is in use and
7545 // stop all ecm filters of lower status pids
7546 for(o = 0; o < maxfilter; o++)
7547 {
7548 if(demux[i].demux_fd[o].fd > 0 && demux[i].demux_fd[o].type == TYPE_ECM
7549 && demux[i].demux_fd[o].pidindex == t)
7550 {
7551 // ecm filter belongs to lower status pid -> kill!
7552 dvbapi_stop_filternum(i, o, er->msgid);
7553 }
7554 }
7555 dvbapi_edit_channel_cache(i, t, 0); // remove lower status pid from channel cache
7556 demux[i].ECMpids[t].checked = 4; // mark index t as low status
7557 }
7558 }
7559
7560 for(o = 0; o < maxfilter; o++)
7561 {
7562 if(demux[i].demux_fd[o].type == TYPE_ECM)
7563 {
7564 ecmcounter++; // count all ecm filters
7565 }
7566 }
7567
7568 demux[i].ECMpids[j].tries = 0xFE; // reset timeout retry flag
7569 demux[i].ECMpids[j].irdeto_cycle = 0xFE; // reset irdeto cycle
7570
7571 if(ecmcounter == 1) // if total found running ecmfilters is 1 -> we found the "best" pid
7572 {
7573 dvbapi_edit_channel_cache(i, j, 1);
7574 demux[i].ECMpids[j].checked = 4; // mark best pid last ;)
7575 }
7576 cs_log_dbg(D_DVBAPI, "Demuxer %d descrambling PID %d CAID %04X PROVID %06X ECMPID %04X CHID %02X VPID %04X",
7577 i, demux[i].pidindex, er->caid, er->prid, er->pid, er->chid, er->vpid);
7578 }
7579 SAFE_MUTEX_UNLOCK(&demux[i].answerlock); // and release it!
7580 }
7581
7582 if(er->rc >= E_NOTFOUND) // not found on requestmode 0 + 1
7583 {
7584 if(er->rc == E_SLEEPING)
7585 {
7586 dvbapi_stop_descrambling(i, er->msgid);
7587 return;
7588 }
7589
7590 struct s_dvbapi_priority *forceentry = dvbapi_check_prio_match(i, j, 'p');
7591 if(forceentry && forceentry->force) // forced pid? keep trying the forced ecmpid!
7592 {
7593 // all cas or irdeto cas with forced prio chid
7594 if(!caid_is_irdeto(er->caid) || forceentry->chid < 0x10000)
7595 {
7596 demux[i].ECMpids[j].table = 0;
7597 dvbapi_set_section_filter(i, er, -1);
7598 continue;
7599 }
7600 else // irdeto cas without chid prio forced
7601 {
7602 // init irdeto current index to first one
7603 if(demux[i].ECMpids[j].irdeto_curindex == 0xFE)
7604 {
7605 demux[i].ECMpids[j].irdeto_curindex = 0x00;
7606 }
7607
7608 // check for last / max chid
7609 if(!(demux[i].ECMpids[j].irdeto_curindex + 1 > demux[i].ECMpids[j].irdeto_maxindex))
7610 {
7611 cs_log_dbg(D_DVBAPI, "Demuxer %d trying next irdeto chid of FORCED PID %d CAID %04X PROVID %06X ECMPID %04X",
7612 i, j, er->caid, er->prid, er->pid);
7613
7614 demux[i].ECMpids[j].irdeto_curindex++; // irdeto index one up
7615 demux[i].ECMpids[j].table = 0;
7616 dvbapi_set_section_filter(i, er, -1);
7617 continue;
7618 }
7619 }
7620 }
7621
7622 // in case of timeout or fatal LB event give
7623 // this pid another try but no more than 1 try
7624 if((er->rc == E_TIMEOUT || (er->rcEx && er->rcEx <= E2_CCCAM_NOCARD))
7625 && demux[i].ECMpids[j].tries == 0xFE)
7626 {
7627 demux[i].ECMpids[j].tries -= 0x07;
7628 demux[i].ECMpids[j].table = 0;
7629 dvbapi_set_section_filter(i, er, -1);
7630 continue;
7631 }
7632 else // all not found responses exception: first timeout response and first fatal loadbalancer response
7633 {
7634 demux[i].ECMpids[j].CHID = 0x10000; // get rid of this prio chid since it failed!
7635 demux[i].ECMpids[j].tries = 0xFE; // reset timeout retry
7636 }
7637
7638 if(caid_is_irdeto(er->caid))
7639 {
7640 // init irdeto current index to first one
7641 if(demux[i].ECMpids[j].irdeto_curindex == 0xFE)
7642 {
7643 demux[i].ECMpids[j].irdeto_curindex = 0x00;
7644 }
7645
7646 // check for last / max chid
7647 if(!(demux[i].ECMpids[j].irdeto_curindex + 1 > demux[i].ECMpids[j].irdeto_maxindex))
7648 {
7649 cs_log_dbg(D_DVBAPI, "Demuxer %d trying next irdeto chid of PID %d CAID %04X PROVID %06X ECMPID %04X VPID %04X",
7650 i, j, er->caid, er->prid, er->pid, er->vpid);
7651
7652 demux[i].ECMpids[j].irdeto_curindex++; // irdeto index one up
7653 demux[i].ECMpids[j].table = 0;
7654 dvbapi_set_section_filter(i, er, -1);
7655 continue;
7656 }
7657 }
7658
7659 dvbapi_edit_channel_cache(i, j, 0); // remove this pid from channelcache
7660
7661 if(demux[i].pidindex == j)
7662 {
7663 // current pid delivered a notfound so this pid isn't
7664 // being used to descramble any longer -> clear pidindex
7665 demux[i].pidindex = -1;
7666 }
7667
7668 demux[i].ECMpids[j].irdeto_maxindex = 0;
7669 demux[i].ECMpids[j].irdeto_curindex = 0xFE;
7670 demux[i].ECMpids[j].tries = 0xFE; // reset timeout retry flag
7671 demux[i].ECMpids[j].irdeto_cycle = 0xFE; // reset irdetocycle
7672 demux[i].ECMpids[j].table = 0;
7673 demux[i].ECMpids[j].checked = 4; // flag ecmpid as checked
7674 demux[i].ECMpids[j].status = -1; // flag ecmpid as unusable
7675
7676 int32_t found = 1; // setup for first run
7677 int32_t filternum = -1;
7678
7679 while(found > 0) // disable all ecm + emm filters for this notfound
7680 {
7681 found = 0;
7682
7683 filternum = dvbapi_get_filternum(i, er, TYPE_ECM); // get ecm filternumber
7684 if(filternum > -1) // in case valid filter found
7685 {
7686 int32_t fd = demux[i].demux_fd[filternum].fd;
7687 if(fd > 0) // in case valid fd
7688 {
7689 dvbapi_stop_filternum(i, filternum, er->msgid); // stop ecmfilter
7690 found = 1;
7691 }
7692 }
7693
7694 if(caid_is_irdeto(er->caid)) // in case irdeto cas stop old emm filters
7695 {
7696 filternum = dvbapi_get_filternum(i, er, TYPE_EMM); // get emm filternumber
7697 if(filternum > -1) // in case valid filter found
7698 {
7699 int32_t fd = demux[i].demux_fd[filternum].fd;
7700 if(fd > 0) // in case valid fd
7701 {
7702 dvbapi_stop_filternum(i, filternum, er->msgid); // stop emmfilter
7703 found = 1;
7704 }
7705 }
7706 }
7707 }
7708 continue;
7709 }
7710
7711 // below this should be only run in case of ecm answer is found
7712 uint32_t chid = get_subid(er); // derive current chid in case of irdeto, or a unique part of ecm on other cas systems
7713 demux[i].ECMpids[j].CHID = (chid != 0 ? chid : 0x10000); // if not zero apply, otherwise use no chid value 0x10000
7714 dvbapi_edit_channel_cache(i, j, 1); // do it here to here after the right CHID is registered
7715
7716 //dvbapi_set_section_filter(i, er); is not needed anymore (unsure)
7717 demux[i].ECMpids[j].tries = 0xFE; // reset timeout retry flag
7718 demux[i].ECMpids[j].irdeto_cycle = 0xFE; // reset irdeto cycle
7719
7720 // cw was already written by another filter or current pid
7721 // isn't pid used to descramble so it ends here!
7722 if(nocw_write || demux[i].pidindex != j)
7723 {
7724 continue;
7725 }
7726
7727 struct s_dvbapi_priority *delayentry = dvbapi_check_prio_match(i, demux[i].pidindex, 'd');
7728 uint32_t delay = 0;
7729
7730 if(delayentry)
7731 {
7732 if(delayentry->delay < 1000)
7733 {
7734 delay = delayentry->delay;
7735 cs_log_dbg(D_DVBAPI, "specific delay: write cw %d ms after ecmrequest", delay);
7736 }
7737 }
7738 else if(cfg.dvbapi_delayer > 0)
7739 {
7740 delay = cfg.dvbapi_delayer;
7741 cs_log_dbg(D_DVBAPI, "generic delay: write cw %d ms after ecmrequest", delay);
7742 }
7743
7744 delayer(er, delay);
7745
7746#ifdef WITH_EMU
7747 if(!chk_ctab_ex(er->caid, &cfg.emu_stream_relay_ctab) || !cfg.emu_stream_relay_enabled)
7748#endif
7749 switch(selected_api)
7750 {
7751#if defined(WITH_STAPI) || defined(WITH_STAPI5)
7752 case STAPI:
7753 stapi_write_cw(i, er->cw, demux[i].STREAMpids, demux[i].STREAMpidcount, demux[i].pmt_file);
7754 break;
7755#endif
7756 default:
7757 {
7758#ifdef WITH_EXTENDED_CW
7759 if(er->cw_ex.mode != demux[i].ECMpids[j].useMultipleIndices)
7760 {
7761 uint32_t idx;
7762
7763 for(k = 0; k < demux[i].STREAMpidcount; k++)
7764 {
7765 if(demux[i].ECMpids[j].useMultipleIndices)
7766 {
7767 idx = demux[i].ECMpids[j].index[k];
7768 }
7769 else
7770 {
7771 idx = demux[i].ECMpids[j].index[0];
7772 }
7773 dvbapi_set_pid(i, k, idx, false, false, er->msgid); // disable streampid
7774 }
7775
7776 for(k = 0; k < MAX_STREAM_INDICES; k++)
7777 {
7778 demux[i].ECMpids[j].index[k] = INDEX_INVALID;
7779 }
7780 }
7781
7782 if(er->cw_ex.mode == CW_MODE_MULTIPLE_CW)
7783 {
7784 int32_t key_pos_a = 0;
7785 demux[i].ECMpids[j].useMultipleIndices = 1;
7786
7787 for(k = 0; k < demux[i].STREAMpidcount; k++)
7788 {
7789 if(demux[i].STREAMpidsType[k] == STREAM_VIDEO)
7790 {
7791 dvbapi_write_cw(i, j, k, er->cw, 8, NULL, 0, er->cw_ex.algo, er->cw_ex.algo_mode, er->msgid);
7792 }
7793 else if(demux[i].STREAMpidsType[k] == STREAM_AUDIO)
7794 {
7795 if(key_pos_a < 4)
7796 {
7797 dvbapi_write_cw(i, j, k, er->cw_ex.audio[key_pos_a], 8, NULL, 0, er->cw_ex.algo, er->cw_ex.algo_mode, er->msgid);
7798 key_pos_a++;
7799 }
7800 }
7801 // Every channel that uses the extended cw has unencrypted subtitle streams,
7802 // so disable CW writing to save indices for audio streams and recordings.
7803 //else // Data
7804 //{
7805 // dvbapi_write_cw(i, j, k, er->cw_ex.data, 8, NULL, 0, er->cw_ex.algo, er->cw_ex.algo_mode, er->msgid);
7806 //}
7807 }
7808 }
7809 else
7810 {
7811 demux[i].ECMpids[j].useMultipleIndices = 0;
7812
7813 if(er->cw_ex.algo == CW_ALGO_AES128)
7814 {
7815 dvbapi_write_cw(i, j, 0, er->cw_ex.session_word, 16, er->cw_ex.data, 16, er->cw_ex.algo, er->cw_ex.algo_mode, er->msgid);
7816 }
7817 else
7818 {
7819 dvbapi_write_cw(i, j, 0, er->cw, 8, NULL, 0, er->cw_ex.algo, er->cw_ex.algo_mode, er->msgid);
7820 }
7821 }
7822#else
7823 cfg.dvbapi_extended_cw_api = 0; // in CSA mode extended_cw_api should be always 0 regardless what user selected!
7824 dvbapi_write_cw(i, j, 0, er->cw, 8, NULL, 0, CA_ALGO_DVBCSA, CA_MODE_CBC, er->msgid);
7825#endif
7826 break;
7827 }
7828 }
7829
7830 // reset idle-Time
7831 client->last = time((time_t *)0); // ********* TO BE FIXED LATER ON ******
7832
7833 if((cfg.dvbapi_listenport || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX) && demux[i].client_proto_version >= 2)
7834 {
7835 dvbapi_net_send(DVBAPI_ECM_INFO, demux[i].socket_fd, 0, i, 0, NULL, client, er, demux[i].client_proto_version);
7836 }
7837#ifndef __CYGWIN__
7838 else if(!cfg.dvbapi_listenport && cfg.dvbapi_boxtype != BOXTYPE_PC_NODMX)
7839#endif
7840 if(cfg.dvbapi_boxtype != BOXTYPE_SAMYGO)
7841 {
7842#ifdef WITH_EXTENDED_CW
7843 // Only print CWs for index 0 in ecm.info file
7844 if(er->cw_ex.algo == CA_ALGO_AES128)
7845 {
7846 dvbapi_write_ecminfo_file(client, er, demux[i].last_cw[0][0], demux[i].last_cw[0][1], 16);
7847 }
7848 else
7849 {
7850 dvbapi_write_ecminfo_file(client, er, demux[i].last_cw[0][0], demux[i].last_cw[0][1], 8);
7851 }
7852#else
7853 dvbapi_write_ecminfo_file(client, er, demux[i].last_cw[0][0], demux[i].last_cw[0][1], 8);
7854#endif
7855 }
7856 }
7857
7858 if(handled == 0)
7859 {
7860 cs_log_dbg(D_DVBAPI, "Unhandled ECM response received for CAID %04X PROVID %06X ECMPID %04X CHID %04X VPID %04X",
7861 er->caid, er->prid, er->pid, er->chid, er->vpid);
7862 }
7863}
7864
7865static int8_t isValidCW(uint8_t *cw)
7866{
7867 uint8_t i;
7868 for(i = 0; i < 16; i += 4)
7869 {
7870 if(((cw[i] + cw[i + 1] + cw[i + 2]) & 0xff) != cw[i + 3])
7871 {
7872 return 0;
7873 }
7874 }
7875 return 1;
7876}
7877
7878void dvbapi_write_ecminfo_file(struct s_client *client, ECM_REQUEST *er, uint8_t *lastcw0, uint8_t *lastcw1, uint8_t cw_length)
7879{
7880#define ECMINFO_TYPE_OSCAM 0
7881#define ECMINFO_TYPE_OSCAM_MS 1
7882#define ECMINFO_TYPE_WICARDD 2
7883#define ECMINFO_TYPE_MGCAMD 3
7884#define ECMINFO_TYPE_CCCAM 4
7885#define ECMINFO_TYPE_CAMD3 5
7886
7887 FILE *ecmtxt = fopen(ECMINFO_FILE, "w");
7888 if(ecmtxt != NULL && er->rc < E_NOTFOUND)
7889 {
7890 char tmp[49]; // holds 16 byte cw - (2 hex digits + 1 space) * 16 byte + string termination)
7891 const char *reader_name = NULL, *from_name = NULL, *proto_name = NULL;
7892 int8_t hops = 0;
7893 int32_t from_port = 0;
7894 char system_name[64];
7895 const char *const_system_name = get_cardsystem_desc_by_caid(er->caid);
7896
7897 cs_strncpy(system_name, const_system_name, sizeof(system_name));
7898 system_name[0] = (char)toupper((int)system_name[0]);
7899
7900 if(cfg.dvbapi_ecminfo_type <= ECMINFO_TYPE_WICARDD)
7901 {
7902 if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_WICARDD)
7903 {
7904 fprintf(ecmtxt, "system: %s\n", system_name);
7905 }
7906
7907 fprintf(ecmtxt, "caid: 0x%04X\npid: 0x%04X\n", er->caid, er->pid);
7908
7909 if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_WICARDD)
7910 {
7911 fprintf(ecmtxt, "prov: %06X\n", (uint) er->prid);
7912 }
7913 else
7914 {
7915 fprintf(ecmtxt, "prov: 0x%06X\n", (uint) er->prid);
7916 }
7917
7918 fprintf(ecmtxt, "chid: 0x%04X\n", er->chid);
7919 }
7920 else if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_MGCAMD)
7921 {
7922 fprintf(ecmtxt, "===== %s ECM on CaID 0x%04X, pid 0x%04X =====\nprov: %06X\n",
7923 system_name, er->caid, er->pid, (uint) er->prid);
7924 }
7925 else if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_CCCAM)
7926 {
7927 char provider_name[128];
7928 get_providername(er->prid, er->caid, provider_name, sizeof(provider_name));
7929
7930 if(provider_name[0])
7931 {
7932 fprintf(ecmtxt, "system: %s\ncaid: 0x%04X\nprovider: %s\nprovid: 0x%06X\npid: 0x%04X\n",
7933 system_name, er->caid, provider_name, (uint) er->prid, er->pid);
7934 }
7935 else
7936 {
7937 fprintf(ecmtxt, "system: %s\ncaid: 0x%04X\nprovid: 0x%06X\npid: 0x%04X\n",
7938 system_name, er->caid, (uint) er->prid, er->pid);
7939 }
7940 }
7941 else if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_CAMD3)
7942 {
7943 fprintf(ecmtxt, "CAID 0x%04X, PID 0x%04X, PROVIDER 0x%06X\n",
7944 er->caid, er->pid, (uint) er->prid);
7945 }
7946
7947 switch(er->rc)
7948 {
7949 case E_FOUND:
7950 if(er->selected_reader)
7951 {
7952 reader_name = er->selected_reader->label;
7953 if(is_network_reader(er->selected_reader))
7954 {
7955 from_name = er->selected_reader->device;
7956 }
7957 else
7958 {
7959 from_name = "local";
7960 }
7961 from_port = er->selected_reader->r_port;
7962 proto_name = reader_get_type_desc(er->selected_reader, 1);
7963 hops = er->selected_reader->currenthops;
7964 }
7965 else
7966 {
7967 reader_name = "none";
7968 from_name = "local";
7969 proto_name = "none";
7970 }
7971 break;
7972
7973 case E_CACHE1:
7974 reader_name = "Cache";
7975 from_name = "cache1";
7976 proto_name = "none";
7977 break;
7978
7979 case E_CACHE2:
7980 reader_name = "Cache";
7981 from_name = "cache2";
7982 proto_name = "none";
7983 break;
7984
7985 case E_CACHEEX:
7986 reader_name = "Cache";
7987 from_name = "cache3";
7988 proto_name = "none";
7989 break;
7990 }
7991
7992 if(cfg.dvbapi_ecminfo_type <= ECMINFO_TYPE_OSCAM_MS)
7993 {
7994 switch(er->rc)
7995 {
7996 case E_FOUND:
7997 if(er->selected_reader)
7998 {
7999 fprintf(ecmtxt, "reader: %s\nfrom: %s:%d\nprotocol: %s\nhops: %d\n",
8000 reader_name, from_name, from_port, proto_name, hops);
8001 }
8002 break;
8003
8004 case E_CACHE1:
8005 case E_CACHE2:
8006 case E_CACHEEX:
8007 fprintf(ecmtxt, "reader: %s\nfrom: %s:%d\nprotocol: %s\n",
8008 reader_name, from_name, from_port, proto_name);
8009 break;
8010 }
8011
8012 if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_OSCAM)
8013 {
8014 fprintf(ecmtxt, "ecm time: %.3f\n", (float) client->cwlastresptime / 1000);
8015 }
8016 else
8017 {
8018 fprintf(ecmtxt, "ecm time: %d\n", client->cwlastresptime);
8019 }
8020 }
8021
8022 if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_CAMD3)
8023 {
8024 fprintf(ecmtxt, "FROM: %s\n", reader_name);
8025 fprintf(ecmtxt, "CW0: %s\n", cs_hexdump(1, lastcw0, cw_length, tmp, sizeof(tmp)));
8026 fprintf(ecmtxt, "CW1: %s\n", cs_hexdump(1, lastcw1, cw_length, tmp, sizeof(tmp)));
8027 }
8028 else
8029 {
8030 fprintf(ecmtxt, "cw0: %s\n", cs_hexdump(1, lastcw0, cw_length, tmp, sizeof(tmp)));
8031 fprintf(ecmtxt, "cw1: %s\n", cs_hexdump(1, lastcw1, cw_length, tmp, sizeof(tmp)));
8032 }
8033
8034 if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_WICARDD || cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_MGCAMD)
8035 {
8036 time_t walltime;
8037 struct tm lt;
8038 char timebuf[32];
8039
8040 if(cw_length == 8) // only check checksum for 8 byte CWs
8041 {
8042 fprintf(ecmtxt, "Signature %s\n", (isValidCW(lastcw0) || isValidCW(lastcw1)) ? "OK" : "NOK");
8043 }
8044 else
8045 {
8046 fprintf(ecmtxt, "Signature %s\n", "OK");
8047 }
8048
8049 if(reader_name != NULL)
8050 {
8051 fprintf(ecmtxt, "source: %s (%s at %s:%d)\n", reader_name, proto_name, from_name, from_port);
8052 }
8053
8054 walltime = cs_time();
8055 localtime_r(&walltime, &lt);
8056
8057 if(strftime(timebuf, 32, "%a %b %d %H:%M:%S %Y", &lt) != 0)
8058 {
8059 fprintf(ecmtxt, "%d msec -- %s\n", client->cwlastresptime, timebuf);
8060 }
8061 }
8062
8063 if(cfg.dvbapi_ecminfo_type == ECMINFO_TYPE_CCCAM)
8064 {
8065 if(reader_name != NULL)
8066 {
8067 fprintf(ecmtxt, "using: %s\naddress: %s:%d\nhops: %d\n",
8068 proto_name, from_name, from_port, hops);
8069 }
8070 fprintf(ecmtxt, "ecm time: %d\n", client->cwlastresptime);
8071 }
8072 }
8073
8074 if(ecmtxt)
8075 {
8076 int32_t ret = fclose(ecmtxt);
8077 if(ret < 0)
8078 {
8079 cs_log("ERROR: Could not close ecmtxt fd (errno=%d %s)", errno, strerror(errno));
8080 }
8081 ecmtxt = NULL;
8082 }
8083}
8084
8085
8086void *dvbapi_start_handler(struct s_client *cl, uint8_t *UNUSED(mbuf), int32_t module_idx, void *(*_main_func)(void *))
8087{
8088 // cs_log("dvbapi loaded fd=%d", idx);
8089 if(cfg.dvbapi_enabled == 1)
8090 {
8091 cl = create_client(get_null_ip());
8092 cl->module_idx = module_idx;
8093 cl->typ = 'c';
8094
8095 int32_t ret = start_thread("dvbapi handler", _main_func, (void *)cl, &cl->thread, 1, 0);
8096 if(ret)
8097 {
8098 return NULL;
8099 }
8100 }
8101 return NULL;
8102}
8103
8104void *dvbapi_handler(struct s_client *cl, uint8_t *mbuf, int32_t module_idx)
8105{
8106 return dvbapi_start_handler(cl, mbuf, module_idx, dvbapi_main_local);
8107}
8108
8109int32_t dvbapi_set_section_filter(int32_t demux_id, ECM_REQUEST *er, int32_t n)
8110{
8111 if(!er) { return -1; }
8112
8113 if(USE_OPENXCAS || (selected_api != DVBAPI_3 && selected_api != DVBAPI_1 && selected_api != STAPI) // only valid for dvbapi3, dvbapi1 and STAPI
8114 || (cfg.dvbapi_boxtype == BOXTYPE_IPBOX || cfg.dvbapi_boxtype == BOXTYPE_IPBOX_PMT)) // reported buggy using sectionfiltering after 1~4 hours -> for now disabled!
8115 {
8116 return 0;
8117 }
8118
8119 if(n == -1)
8120 {
8121 n = dvbapi_get_filternum(demux_id, er, TYPE_ECM);
8122 }
8123
8124 if(n < 0) // in case no valid filter found;
8125 {
8126 return -1;
8127 }
8128
8129 int32_t fd = demux[demux_id].demux_fd[n].fd;
8130 if(fd < 1) // in case no valid fd
8131 {
8132 return -1;
8133 }
8134
8135 uint8_t filter[16];
8136 uint8_t mask[16];
8137 memset(filter, 0, 16);
8138 memset(mask, 0, 16);
8139 struct s_ecmpid *curpid = NULL;
8140
8141 int32_t pid = demux[demux_id].demux_fd[n].pidindex;
8142 if(pid != -1)
8143 {
8144 curpid = &demux[demux_id].ECMpids[pid];
8145 }
8146
8147 if(curpid->table != er->ecm[0] && curpid->table != 0)
8148 {
8149 return -1; // if current ecmtype differs from latest requested ecmtype do not apply section filtering!
8150 }
8151
8152 uint8_t ecmfilter = 0;
8153
8154 if(er->ecm[0] == 0x80)
8155 {
8156 ecmfilter = 0x81; // current processed ecm is even, next will be filtered for odd
8157 }
8158 else
8159 {
8160 ecmfilter = 0x80; // current processed ecm is odd, next will be filtered for even
8161 }
8162
8163 if(curpid->table != 0) // cycle ecmtype from odd to even or even to odd
8164 {
8165 filter[0] = ecmfilter; // only accept new ecms (if previous odd, filter for even and vice versa)
8166 mask[0] = 0xFF;
8167 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d set ecmtable to %s (CAID %04X PROVID %06X FD %d)",
8168 demux_id, n + 1, (ecmfilter == 0x80 ? "EVEN" : "ODD"), curpid->CAID, curpid->PROVID, fd);
8169 }
8170 else // not decoding right now so we are interessted in all ecm types!
8171 {
8172 filter[0] = 0x80; // set filter to wait for any ecms
8173 mask[0] = 0xF0;
8174 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d set ecmtable to ODD+EVEN (CAID %04X PROVID %06X FD %d)",
8175 demux_id, n + 1, curpid->CAID, curpid->PROVID, fd);
8176 }
8177
8178 uint32_t offset = 0, extramask = 0xFF;
8179 struct s_dvbapi_priority *forceentry = dvbapi_check_prio_match(demux_id, pid, 'p');
8180 //cs_log("**** curpid->CHID %04X, checked = %d, er->chid = %04X *****", curpid->CHID, curpid->checked, er->chid);
8181 // checked 4 to make sure we dont set chid filter and no such ecm in dvbstream except for forced pids!
8182
8183 if(curpid->CHID < 0x10000 && (curpid->checked == 4 || (forceentry && forceentry->force)))
8184 {
8185 switch(er->caid >> 8)
8186 {
8187 case 0x01: // seca
8188 offset = 7;
8189 extramask = 0xF0;
8190 break;
8191
8192 case 0x05: // viaccess
8193 offset = 8;
8194 break;
8195
8196 case 0x06: // irdeto
8197 offset = 6;
8198 break;
8199
8200 case 0x09: // videoguard
8201 offset = 11;
8202 break;
8203
8204 case 0x4A: // DRE-Crypt, Bulcrypt, Tongang and others?
8205 if(!caid_is_bulcrypt(er->caid))
8206 {
8207 offset = 6;
8208 }
8209 break;
8210 }
8211 }
8212
8213 int32_t irdetomatch = 1; // check if wanted irdeto index is the one the delivers current chid!
8214 if(caid_is_irdeto(curpid->CAID))
8215 {
8216 if(curpid->irdeto_curindex == er->ecm[4]) { irdetomatch = 1; } // ok apply chid filtering
8217 else { irdetomatch = 0; } // skip chid filtering but apply irdeto index filtering
8218 }
8219
8220 if(offset && irdetomatch) // we have a cas with chid or unique part in checked ecm
8221 {
8222 i2b_buf(2, curpid->CHID, filter + (offset - 2));
8223 mask[(offset - 2)] = 0xFF & extramask; // additional mask seca2 chid can be FC10 or FD10 varies each month so only apply F?10
8224 mask[(offset - 1)] = 0xFF;
8225 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d set chid to %04X on fd %d", demux_id, n + 1, curpid->CHID, fd);
8226 }
8227 else
8228 {
8229 // on irdeto we can always apply irdeto index filtering!
8230 if(caid_is_irdeto(curpid->CAID) && (curpid->irdeto_curindex < 0xFE))
8231 {
8232 filter[2] = curpid->irdeto_curindex;
8233 mask[2] = 0xFF;
8234 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d set irdetoindex to %d on fd %d",
8235 demux_id, n + 1, curpid->irdeto_curindex, fd);
8236 }
8237 else // all other cas systems also cas systems without chid or unique ecm part
8238 {
8239 cs_log_dbg(D_DVBAPI, "Demuxer %d Filter %d set chid to ANY CHID on fd %d", demux_id, n + 1, fd);
8240 }
8241 }
8242
8243 int32_t ret = dvbapi_activate_section_filter(demux_id, n, fd, curpid->ECM_PID, filter, mask, er->msgid);
8244 if(ret < 0) // something went wrong setting filter!
8245 {
8246 cs_log("Demuxer %d Filter %d (fd %d) error setting section filtering -> stop filter!", demux_id, n + 1, fd);
8247
8248 ret = dvbapi_stop_filternum(demux_id, n, er->msgid);
8249 if(ret == -1)
8250 {
8251 cs_log("Demuxer %d Filter %d (fd %d) stopping filter failed -> kill all filters of this demuxer!", demux_id, n + 1, fd);
8252 dvbapi_stop_filter(demux_id, TYPE_EMM, er->msgid);
8253 dvbapi_stop_filter(demux_id, TYPE_ECM, er->msgid);
8254 }
8255 return -1;
8256 }
8257 return n;
8258}
8259
8260int32_t dvbapi_activate_section_filter(int32_t demux_id, int32_t num, int32_t fd, int32_t pid, uint8_t *filter, uint8_t *mask, uint32_t msgid)
8261{
8262 int32_t ret = -1;
8263
8264 switch(selected_api)
8265 {
8266 case DVBAPI_3:
8267 {
8268 struct dmx_sct_filter_params sFP2;
8269 memset(&sFP2, 0, sizeof(sFP2));
8270 sFP2.pid = pid;
8271 sFP2.timeout = 0;
8272 sFP2.flags = DMX_IMMEDIATE_START;
8273
8274 if(cfg.dvbapi_boxtype == BOXTYPE_NEUMO)
8275 {
8276 //DeepThought: on dgs/cubestation and neumo images, perhaps others
8277 //the following code is needed to descramble
8278 sFP2.filter.filter[0] = filter[0];
8279 sFP2.filter.mask[0] = mask[0];
8280 sFP2.filter.filter[1] = 0;
8281 sFP2.filter.mask[1] = 0;
8282 sFP2.filter.filter[2] = 0;
8283 sFP2.filter.mask[2] = 0;
8284 memcpy(sFP2.filter.filter + 3, filter + 1, 16 - 3);
8285 memcpy(sFP2.filter.mask + 3, mask + 1, 16 - 3);
8286
8287 //DeepThought: in the drivers of the dgs/cubestation and neumo images,
8288 //dvbapi 1 and 3 are somehow mixed. In the kernel drivers, the DMX_SET_FILTER
8289 //ioctl expects to receive a dmx_sct_filter_params structure (DVBAPI 3) but
8290 //due to a bug its sets the "positive mask" wrongly (they should be all 0).
8291 //On the other hand, the DMX_SET_FILTER1 ioctl also uses the dmx_sct_filter_params
8292 //structure, which is incorrect (it should be dmxSctFilterParams).
8293 //The only way to get it right is to call DMX_SET_FILTER1 with the argument
8294 //expected by DMX_SET_FILTER. Otherwise, the timeout parameter is not passed correctly.
8295
8296 ret = dvbapi_ioctl(fd, DMX_SET_FILTER1, &sFP2);
8297 }
8298 else
8299 {
8300 memcpy(sFP2.filter.filter, filter, 16);
8301 memcpy(sFP2.filter.mask, mask, 16);
8302
8303 if(cfg.dvbapi_listenport || cfg.dvbapi_boxtype == BOXTYPE_PC_NODMX)
8304 {
8305 ret = dvbapi_net_send(DVBAPI_DMX_SET_FILTER,
8306 demux[demux_id].socket_fd,
8307 msgid,
8308 demux_id,
8309 num,
8310 (uint8_t *) &sFP2,
8311 NULL,
8312 NULL,
8313 demux[demux_id].client_proto_version);
8314 }
8315 else
8316 {
8317 ret = dvbapi_ioctl(fd, DMX_SET_FILTER, &sFP2);
8318 }
8319 }
8320 break;
8321 }
8322
8323 case DVBAPI_1:
8324 {
8325 struct dmxSctFilterParams sFP1;
8326 memset(&sFP1, 0, sizeof(sFP1));
8327 sFP1.pid = pid;
8328 sFP1.timeout = 0;
8329 sFP1.flags = DMX_IMMEDIATE_START;
8330 memcpy(sFP1.filter.filter, filter, 16);
8331 memcpy(sFP1.filter.mask, mask, 16);
8332 ret = dvbapi_ioctl(fd, DMX_SET_FILTER1, &sFP1);
8333 break;
8334 }
8335
8336#if defined(WITH_STAPI) || defined(WITH_STAPI5)
8337 case STAPI:
8338 {
8339 ret = stapi_activate_section_filter(fd, filter, mask);
8340 break;
8341 }
8342#endif
8343 // Isn't implemented in COOLAPI-1 (legacy)
8344#if defined WITH_COOLAPI2
8345 case COOLAPI:
8346 {
8347 int32_t n = coolapi_get_filter_num(fd);
8348 if(n < 0)
8349 {
8350 return n;
8351 }
8352 coolapi_set_filter(fd, n, pid, filter, mask, TYPE_ECM);
8353 break;
8354 }
8355#endif
8356
8357 default:
8358 break;
8359 }
8360
8361 if(ret != -1) // only change filter/mask for comparing if box returned no errors!
8362 {
8363 // copy filter and mask to check later on if receiver delivered accordingly
8364 memcpy(demux[demux_id].demux_fd[num].filter, filter, 16);
8365 memcpy(demux[demux_id].demux_fd[num].mask, mask, 16);
8366 }
8367 return ret;
8368}
8369
8370int32_t dvbapi_check_ecm_delayed_delivery(int32_t demux_id, ECM_REQUEST *er)
8371{
8372 int32_t ret = 0;
8373 int32_t filternum = dvbapi_get_filternum(demux_id, er, TYPE_ECM);
8374 char nullcw[CS_ECMSTORESIZE];
8375 memset(nullcw, 0, CS_ECMSTORESIZE);
8376
8377 if(filternum < 0) // if no matching filter act like ecm response is delayed
8378 {
8379 return 2;
8380 }
8381
8382 if(memcmp(demux[demux_id].demux_fd[filternum].lastecmd5, nullcw, CS_ECMSTORESIZE))
8383 {
8384 demux[demux_id].demux_fd[filternum].lastresult = er->rc; // save last result
8385 char ecmd5[17 * 3];
8386 cs_hexdump(0, er->ecmd5, 16, ecmd5, sizeof(ecmd5));
8387
8388 cs_log_dbg(D_DVBAPI, "Demuxer %d requested controlword for ecm %s on fd %d",
8389 demux_id, ecmd5, demux[demux_id].demux_fd[filternum].fd);
8390
8391 uint8_t md5tmp[MD5_DIGEST_LENGTH];
8392 MD5(er->ecm, er->ecmlen, md5tmp);
8393
8394 // 1 = no response on the ecm we request last for this fd!
8395 ret = (memcmp(demux[demux_id].demux_fd[filternum].lastecmd5, md5tmp, CS_ECMSTORESIZE) != 0 ? 1 : 0);
8396 }
8397
8398 // Check for null cw
8399 // Skip check for BISS1 - cw could be indeed zero
8400 // Skip check for BISS2 - we use the extended cw, so the "simple" cw is always zero
8401 if(memcmp(er->cw, nullcw, 8) == 0 && memcmp(er->cw + 8, nullcw, 8) == 0 && !caid_is_biss(er->caid))
8402 {
8403 return 5;
8404 }
8405
8406 struct s_ecmpid *curpid = NULL;
8407 int32_t pid = demux[demux_id].demux_fd[filternum].pidindex;
8408
8409 if(pid !=-1)
8410 {
8411 curpid = &demux[demux_id].ECMpids[pid];
8412 if(curpid->table == 0) // on change table act like ecm response is found
8413 {
8414 return 3;
8415 }
8416 }
8417
8418 if(er->rc == E_CACHEEX) // on cache-ex response act like ecm response is found
8419 {
8420 return 4;
8421 }
8422
8423 return ret;
8424}
8425
8426int32_t dvbapi_get_filternum(int32_t demux_id, ECM_REQUEST *er, int32_t type)
8427{
8428 if(!er) { return -1; }
8429
8430 int32_t n;
8431 int32_t fd = -1;
8432
8433 for(n = 0; n < maxfilter; n++) // determine fd
8434 {
8435 // check for valid and right type (ecm or emm)
8436 if(demux[demux_id].demux_fd[n].fd > 0 && demux[demux_id].demux_fd[n].type == type)
8437 {
8438 if(type == TYPE_ECM && er->srvid != demux[demux_id].program_number)
8439 {
8440 continue;
8441 }
8442
8443 if((demux[demux_id].demux_fd[n].pid == er->pid) && ((demux[demux_id].demux_fd[n].provid == er->prid)
8444 || demux[demux_id].demux_fd[n].provid == 0 || er->prid == 0) && ((demux[demux_id].demux_fd[n].caid == er->caid)
8445 || (demux[demux_id].demux_fd[n].caid == er->ocaid))) // current ecm pid?
8446 {
8447 fd = demux[demux_id].demux_fd[n].fd; // found!
8448 if(demux[demux_id].demux_fd[n].caid == er->ocaid)
8449 {
8450 // clear ecmd5 hash since betatunneled ecms hash different!
8451 memset(demux[demux_id].demux_fd[n].lastecmd5, 0, CS_ECMSTORESIZE);
8452 }
8453 break;
8454 }
8455 }
8456 }
8457
8458 if(fd > 0 && demux[demux_id].demux_fd[n].provid == 0)
8459 {
8460 demux[demux_id].demux_fd[n].provid = er->prid; // hack to fill in provid into demuxer
8461 }
8462 return (fd > 0 ? n : fd); // return -1(fd) on not found, on found return filternumber(n)
8463}
8464
8465uint32_t dvbapi_ca_set_pid(int32_t demux_id, int32_t pid, int32_t stream_id, bool use_des, uint32_t msgid)
8466{
8467 uint32_t idx;
8468 int32_t n;
8469
8470 if(pid == -1 || pid > demux[demux_id].ECMpidcount)
8471 {
8472 return INDEX_INVALID;
8473 }
8474
8475 if(demux[demux_id].ECMpids[pid].useMultipleIndices)
8476 {
8477 n = stream_id;
8478 idx = demux[demux_id].ECMpids[pid].index[n];
8479
8480 if(idx == INDEX_INVALID) // if we have no index for this pid, get one!
8481 {
8482 idx = dvbapi_get_desc_index(demux_id, pid, n);
8483 if(idx == INDEX_INVALID)
8484 {
8485 cs_log_dbg(D_DVBAPI, "Demuxer %d PID: %d CAID: %04X ECMPID: %04X has no free index",
8486 demux_id, pid, demux[demux_id].ECMpids[pid].CAID, demux[demux_id].ECMpids[pid].ECM_PID);
8487
8488 return INDEX_INVALID;
8489 }
8490
8491 cs_log_dbg(D_DVBAPI, "Demuxer %d PID: %d CAID: %04X ECMPID: %04X is using index %d for stream %d",
8492 demux_id, pid, demux[demux_id].ECMpids[pid].CAID, demux[demux_id].ECMpids[pid].ECM_PID, idx, n);
8493 }
8494
8495 if(!demux[demux_id].ECMpids[pid].streams || ((demux[demux_id].ECMpids[pid].streams & (1 << n)) == (uint) (1 << n)))
8496 {
8497 dvbapi_set_pid(demux_id, n, idx, true, use_des, msgid); // enable stream pid
8498 }
8499 else
8500 {
8501 dvbapi_set_pid(demux_id, n, idx, false, false, msgid); // disable stream pid
8502 }
8503 }
8504 else
8505 {
8506 idx = demux[demux_id].ECMpids[pid].index[0];
8507
8508 if(idx == INDEX_INVALID) // if we have no index for this pid, get one!
8509 {
8510 idx = dvbapi_get_desc_index(demux_id, pid, 0);
8511 if(idx == INDEX_INVALID)
8512 {
8513 cs_log_dbg(D_DVBAPI, "Demuxer %d PID: %d CAID: %04X ECMPID: %04X has no free index",
8514 demux_id, pid, demux[demux_id].ECMpids[pid].CAID, demux[demux_id].ECMpids[pid].ECM_PID);
8515
8516 return INDEX_INVALID;
8517 }
8518
8519 cs_log_dbg(D_DVBAPI, "Demuxer %d PID: %d CAID: %04X ECMPID: %04X is using index %d",
8520 demux_id, pid, demux[demux_id].ECMpids[pid].CAID, demux[demux_id].ECMpids[pid].ECM_PID, idx);
8521 }
8522
8523 for(n = 0; n < demux[demux_id].STREAMpidcount; n++)
8524 {
8525 if(!demux[demux_id].ECMpids[pid].streams || ((demux[demux_id].ECMpids[pid].streams & (1 << n)) == (uint) (1 << n)))
8526 {
8527 dvbapi_set_pid(demux_id, n, idx, true, use_des, 0); // enable stream pid
8528 }
8529 else
8530 {
8531 dvbapi_set_pid(demux_id, n, idx, false, false, 0); // disable stream pid
8532 }
8533 }
8534 }
8535 return idx; // return ca index
8536}
8537
8538int8_t update_streampid_list(uint8_t cadevice, uint16_t pid, uint32_t idx, bool use_des)
8539{
8540 struct s_streampid *listitem, *newlistitem;
8541 LL_ITER itr;
8542 if(!ll_activestreampids)
8543 {
8544 ll_activestreampids = ll_create("ll_activestreampids");
8545 }
8546
8547 if(idx >= INDEX_MAX)
8548 {
8549 return INVALID_STREAMPID_INDEX;
8550 }
8551
8552 if(ll_count(ll_activestreampids) > 0)
8553 {
8554 itr = ll_iter_create(ll_activestreampids);
8555 while((listitem = ll_iter_next(&itr)))
8556 {
8557 if(cadevice == listitem->cadevice && pid == listitem->streampid)
8558 {
8559 if((listitem->activeindexers & (1 << idx)) == (uint64_t) (1 << idx))
8560 {
8561 if(cfg.dvbapi_extended_cw_api == 2 && use_des != listitem->use_des)
8562 {
8563 listitem->use_des = use_des;
8564 return FIRST_STREAMPID_INDEX;
8565 }
8566 return FOUND_STREAMPID_INDEX; // match found
8567 }
8568 else
8569 {
8570 listitem->activeindexers |= (1 << idx); // ca + pid found but not this index -> add this index
8571 cs_log_dbg(D_DVBAPI, "Added existing streampid %04X with new index %d to ca%d", pid, idx, cadevice);
8572
8573 if(cfg.dvbapi_extended_cw_api == 2 && use_des != listitem->use_des)
8574 {
8575 listitem->use_des = use_des;
8576 return FIRST_STREAMPID_INDEX;
8577 }
8578 return ADDED_STREAMPID_INDEX;
8579 }
8580 }
8581 }
8582 }
8583
8584 if(!cs_malloc(&newlistitem, sizeof(struct s_streampid)))
8585 {
8586 return FIRST_STREAMPID_INDEX; // not sure if this is correct
8587 }
8588
8589 newlistitem->cadevice = cadevice;
8590 newlistitem->streampid = pid;
8591 newlistitem->activeindexers = (1 << idx);
8592 newlistitem->caindex = idx; // set this index as used to decode on ca device
8593 newlistitem->use_des = use_des;
8594
8595 ll_append(ll_activestreampids, newlistitem);
8596 cs_log_dbg(D_DVBAPI, "Added new streampid %04X with index %d to ca%d", pid, idx, cadevice);
8597
8598 return FIRST_STREAMPID_INDEX;
8599}
8600
8601int8_t remove_streampid_from_list(uint8_t cadevice, uint16_t pid, uint32_t idx)
8602{
8603 struct s_streampid *listitem;
8604 int8_t removed = 0;
8605 LL_ITER itr;
8606
8607 if(!ll_activestreampids)
8608 {
8609 return NO_STREAMPID_LISTED;
8610 }
8611
8612 if(idx >= INDEX_MAX)
8613 {
8614 return INVALID_STREAMPID_INDEX;
8615 }
8616
8617 if(ll_count(ll_activestreampids) > 0)
8618 {
8619 itr = ll_iter_create(ll_activestreampids);
8620 while((listitem = ll_iter_next(&itr)))
8621 {
8622 if(cadevice == listitem->cadevice && pid == listitem->streampid)
8623 {
8624 if(idx == INDEX_DISABLE_ALL)
8625 {
8626 listitem->activeindexers = 0;
8627 removed = 1;
8628 }
8629 else if((listitem->activeindexers & (1 << idx)) == (uint64_t) (1 << idx))
8630 {
8631 listitem->activeindexers &= ~(1 << idx); // flag it as disabled for this index
8632 removed = 1;
8633 }
8634
8635 if(removed)
8636 {
8637 if(ca_descramblers_used > 0) // it should never go below 0, but you never know
8638 {
8639 ca_descramblers_used--; // decrease number of used descramblers
8640 }
8641 cs_log_dbg(D_DVBAPI, "Remove streampid %04X using indexer %d from ca%d", pid, idx, cadevice);
8642 }
8643
8644 if(listitem->activeindexers == 0 && removed == 1) // all indexers disabled? -> remove pid from list!
8645 {
8646 ll_iter_remove_data(&itr);
8647 cs_log_dbg(D_DVBAPI, "Removed last indexer of streampid %04X from ca%d", pid, cadevice);
8648 return REMOVED_STREAMPID_LASTINDEX;
8649 }
8650 else if(removed == 1)
8651 {
8652 if(idx != INDEX_DISABLE_ALL && idx != listitem->caindex)
8653 {
8654 return REMOVED_STREAMPID_INDEX;
8655 }
8656 else
8657 {
8658 listitem->caindex = INDEX_INVALID;
8659 cs_log_dbg(D_DVBAPI, "Streampid %04X index %d was used for decoding on ca%d", pid, idx, cadevice);
8660 return REMOVED_DECODING_STREAMPID_INDEX;
8661 }
8662 }
8663 return INVALID_STREAMPID_INDEX;
8664 }
8665 }
8666 }
8667 return NO_STREAMPID_LISTED;
8668}
8669
8670void disable_unused_streampids(int16_t demux_id)
8671{
8672 int32_t ecmpid = demux[demux_id].pidindex;
8673
8674 if(ecmpid == -1 // no active ecmpid!
8675 || !ll_activestreampids
8676 || selected_api == STAPI // stapi handles pids itself!
8677 || ll_count(ll_activestreampids) == 0) // no items in list?
8678 {
8679 return;
8680 }
8681
8682 int32_t j;
8683 if(demux[demux_id].ECMpids[ecmpid].useMultipleIndices == 0)
8684 {
8685 uint32_t idx = demux[demux_id].ECMpids[ecmpid].index[0];
8686 int32_t i, n;
8687 struct s_streampid *listitem;
8688
8689 // search for old enabled streampids on
8690 // all ca devices that have to be disabled
8691 for(i = 0; i < CA_MAX && idx != INDEX_INVALID; i++)
8692 {
8693 if(!((demux[demux_id].ca_mask & (1 << i)) == (uint32_t) (1 << i)))
8694 {
8695 continue; // ca is not used by this demuxer
8696 }
8697
8698 LL_ITER itr;
8699 itr = ll_iter_create(ll_activestreampids);
8700
8701 while((listitem = ll_iter_next(&itr)))
8702 {
8703 if(i != listitem->cadevice)
8704 {
8705 continue; // ca doesn't match
8706 }
8707
8708 if(!((listitem->activeindexers & (1 << (idx))) == (uint64_t) (1 << (idx))))
8709 {
8710 continue; // index doesn't match
8711 }
8712
8713 for(n = 0; n < demux[demux_id].STREAMpidcount; n++)
8714 {
8715 if(demux[demux_id].ECMpidcount == 0) // FTA? -> disable stream!
8716 {
8717 n = demux[demux_id].STREAMpidcount;
8718 break;
8719 }
8720
8721 // check if pid matches with current stream pid on demuxer
8722 if(listitem->streampid == demux[demux_id].STREAMpids[n])
8723 {
8724 break;
8725 }
8726 }
8727
8728 if(n == demux[demux_id].STREAMpidcount) // no match found
8729 {
8730 demux[demux_id].STREAMpids[n] = listitem->streampid; // put it here temporarily!
8731 dvbapi_set_pid(demux_id, n, idx, false, false, 0); // disable this unused streampid
8732 demux[demux_id].STREAMpids[n] = 0; // remove it from temp position!
8733 }
8734 }
8735
8736 // ECMpidcount != 0 -> skip enabling on fta
8737 for(n = 0; n < demux[demux_id].STREAMpidcount && demux[demux_id].ECMpidcount != 0; n++)
8738 {
8739 ll_iter_reset(&itr);
8740 if(!demux[demux_id].ECMpids[ecmpid].streams || ((demux[demux_id].ECMpids[ecmpid].streams & (1 << n)) == (uint) (1 << n)))
8741 {
8742 while((listitem = ll_iter_next(&itr)))
8743 {
8744 if(i != listitem->cadevice) // ca doesn't match
8745 {
8746 continue;
8747 }
8748
8749 if(!((listitem->activeindexers & (1 << (idx))) == (uint64_t) (1 << (idx)))) // index doesn't match
8750 {
8751 continue;
8752 }
8753
8754 // check if pid matches with current streampid on demuxer
8755 if(listitem->streampid == demux[demux_id].STREAMpids[n])
8756 {
8757 break;
8758 }
8759 }
8760
8761 if(!listitem) // if streampid not listed -> enable it!
8762 {
8763 dvbapi_set_pid(demux_id, n, idx, true, false, 0); // enable streampid
8764 }
8765 }
8766 }
8767 }
8768 }
8769 else
8770 {
8771 uint32_t idx = INDEX_INVALID;
8772 int32_t i, n;
8773 uint8_t skip;
8774 struct s_streampid *listitem;
8775
8776 // search for old enabled streampids
8777 // on all ca devices that have to be disabled
8778 for(i = 0; i < CA_MAX && idx != INDEX_INVALID; i++)
8779 {
8780 if(!((demux[demux_id].ca_mask & (1 << i)) == (uint32_t) (1 << i)))
8781 {
8782 continue; // continue if ca is unused by this demuxer
8783 }
8784
8785 LL_ITER itr;
8786 itr = ll_iter_create(ll_activestreampids);
8787
8788 while((listitem = ll_iter_next(&itr)))
8789 {
8790 if(i != listitem->cadevice)
8791 {
8792 continue; // ca doesn't match
8793 }
8794
8795 for(skip = 1, j = 0; j < MAX_STREAM_INDICES; j++)
8796 {
8797 idx = demux[demux_id].ECMpids[ecmpid].index[j];
8798 if(idx == INDEX_INVALID)
8799 {
8800 continue;
8801 }
8802
8803 // index match
8804 if((listitem->activeindexers & (1 << (idx))) == (uint64_t) (1 << (idx)))
8805 {
8806 skip = 0;
8807 break;
8808 }
8809 }
8810
8811 if(skip)
8812 {
8813 continue;
8814 }
8815
8816 for(n = 0; n < demux[demux_id].STREAMpidcount; n++)
8817 {
8818 if(demux[demux_id].ECMpidcount == 0) // FTA? -> disable stream!
8819 {
8820 n = demux[demux_id].STREAMpidcount;
8821 break;
8822 }
8823
8824 // check if pid matches with current streampid on demuxer
8825 if(listitem->streampid == demux[demux_id].STREAMpids[n])
8826 {
8827 break;
8828 }
8829 }
8830
8831 if(n == demux[demux_id].STREAMpidcount)
8832 {
8833 demux[demux_id].STREAMpids[n] = listitem->streampid; // put it temp here!
8834 dvbapi_set_pid(demux_id, n, idx, false, false, 0); // no match found so disable this now unused streampid
8835 demux[demux_id].STREAMpids[n] = 0; // remove temp!
8836 }
8837 }
8838
8839 // ECMpidcount != 0 -> skip enabling on fta
8840 for(n = 0; n < demux[demux_id].STREAMpidcount && demux[demux_id].ECMpidcount != 0; n++)
8841 {
8842 ll_iter_reset(&itr);
8843 if(!demux[demux_id].ECMpids[ecmpid].streams || ((demux[demux_id].ECMpids[ecmpid].streams & (1 << n)) == (uint) (1 << n)))
8844 {
8845 while((listitem = ll_iter_next(&itr)))
8846 {
8847 if(i != listitem->cadevice) // ca doesn't match
8848 {
8849 continue;
8850 }
8851
8852 for(skip = 1, j = 0; j < MAX_STREAM_INDICES; j++)
8853 {
8854 idx = demux[demux_id].ECMpids[ecmpid].index[j];
8855 if(idx == INDEX_INVALID)
8856 {
8857 continue;
8858 }
8859
8860 if((listitem->activeindexers & (1 << (idx))) == (uint64_t) (1 << (idx)))
8861 {
8862 skip = 0; // index match
8863 break;
8864 }
8865 }
8866
8867 if(skip)
8868 {
8869 continue;
8870 }
8871
8872 // check if pid matches with current streampid on demuxer
8873 if(listitem->streampid == demux[demux_id].STREAMpids[n])
8874 {
8875 break;
8876 }
8877 }
8878
8879 if(!listitem) // if streampid not listed -> enable it!
8880 {
8881 dvbapi_set_pid(demux_id, n, idx, true, false, 0); // enable streampid
8882 }
8883 }
8884 }
8885 }
8886 }
8887}
8888
8889uint32_t is_ca_used(uint8_t cadevice, int32_t pid)
8890{
8891 struct s_streampid *listitem;
8892 LL_ITER itr;
8893 if(!ll_activestreampids)
8894 {
8895 return INDEX_INVALID;
8896 }
8897
8898 if(ll_count(ll_activestreampids) > 0)
8899 {
8900 itr = ll_iter_create(ll_activestreampids);
8901 while((listitem = ll_iter_next(&itr)))
8902 {
8903 // if pid is 0, we match ca device only
8904 if(listitem->cadevice != cadevice || (pid && listitem->streampid != pid))
8905 {
8906 continue;
8907 }
8908
8909 uint32_t i = 0;
8910 while(listitem->caindex == INDEX_INVALID && i < INDEX_MAX)
8911 {
8912 if((listitem->activeindexers & (1 << i)) == (uint64_t) (1 << i))
8913 {
8914 listitem->caindex = i; // set fresh one
8915 cs_log_dbg(D_DVBAPI, "Streampid %04X is now using index %d for decoding on ca%d", pid, i, cadevice);
8916 break;
8917 }
8918 i++;
8919 }
8920
8921 if(listitem->caindex == INDEX_INVALID)
8922 {
8923 ll_iter_remove_data(&itr);
8924 return INDEX_INVALID;
8925 }
8926 return listitem->caindex;
8927 }
8928 }
8929 return INDEX_INVALID; // no indexer found for this pid!
8930}
8931
8932uint16_t dvbapi_get_client_proto_version(void)
8933{
8934 return last_client_proto_version;
8935}
8936
8937const char *dvbapi_get_client_name(void)
8938{
8939 return last_client_name ? last_client_name : "";
8940}
8941
8942void check_add_emmpid(int32_t demux_id, uint8_t *filter, int32_t l, int32_t emmtype)
8943{
8944 if(l < 0) { return; }
8945
8946 uint32_t typtext_idx = 0;
8947 int32_t ret = -1;
8948 const char *typtext[] = { "UNIQUE", "SHARED", "GLOBAL", "UNKNOWN" };
8949
8950 while(((emmtype >> typtext_idx) & 0x01) == 0 && typtext_idx < sizeof(typtext) / sizeof(const char *))
8951 {
8952 ++typtext_idx;
8953 }
8954
8955 // filter already in list?
8956 if(is_emmfilter_in_list(filter, demux[demux_id].EMMpids[l].PID, demux[demux_id].EMMpids[l].PROVID, demux[demux_id].EMMpids[l].CAID))
8957 {
8958 cs_log_dbg(D_DVBAPI, "Demuxer %d duplicate emm filter type %s, emmpid: 0x%04X, emmcaid: %04X, emmprovid: %06X -> SKIPPED!",
8959 demux_id,
8960 typtext[typtext_idx],
8961 demux[demux_id].EMMpids[l].PID,
8962 demux[demux_id].EMMpids[l].CAID,
8963 demux[demux_id].EMMpids[l].PROVID);
8964 return;
8965 }
8966
8967 if(demux[demux_id].emm_filter < demux[demux_id].max_emm_filter) // can this filter be started?
8968 {
8969 // try to activate this emmfilter
8970 ret = dvbapi_set_filter(demux_id,
8971 selected_api,
8972 demux[demux_id].EMMpids[l].PID,
8973 demux[demux_id].EMMpids[l].CAID,
8974 demux[demux_id].EMMpids[l].PROVID,
8975 filter,
8976 filter + 16,
8977 0,
8978 demux[demux_id].pidindex,
8979 TYPE_EMM, 1);
8980 }
8981
8982 if(ret != -1) // -1 if maxfilter reached or filter start error!
8983 {
8984 if(demux[demux_id].emm_filter == -1) // -1: first run of emm filtering on this demuxer
8985 {
8986 demux[demux_id].emm_filter = 0;
8987 }
8988 demux[demux_id].emm_filter++; // increase total active filters
8989
8990 cs_log_dump_dbg(D_DVBAPI, filter, 32, "Demuxer %d started emm filter type %s, pid: 0x%04X",
8991 demux_id, typtext[typtext_idx], demux[demux_id].EMMpids[l].PID);
8992 return;
8993 }
8994 else // not set successful, so add it to the list for try again later on!
8995 {
8996 add_emmfilter_to_list(demux_id, filter, demux[demux_id].EMMpids[l].CAID, demux[demux_id].EMMpids[l].PROVID, demux[demux_id].EMMpids[l].PID, 0, false);
8997 cs_log_dump_dbg(D_DVBAPI, filter, 32, "Demuxer %d added inactive emm filter type %s, pid: 0x%04X",
8998 demux_id, typtext[typtext_idx], demux[demux_id].EMMpids[l].PID);
8999 }
9000 return;
9001}
9002
9003void rotate_emmfilter(int32_t demux_id)
9004{
9005 // emm filter iteration
9006 if(!ll_emm_active_filter)
9007 {
9008 ll_emm_active_filter = ll_create("ll_emm_active_filter");
9009 }
9010
9011 if(!ll_emm_inactive_filter)
9012 {
9013 ll_emm_inactive_filter = ll_create("ll_emm_inactive_filter");
9014 }
9015
9016 if(!ll_emm_pending_filter)
9017 {
9018 ll_emm_pending_filter = ll_create("ll_emm_pending_filter");
9019 }
9020
9021 uint32_t filter_count = ll_count(ll_emm_active_filter) + ll_count(ll_emm_inactive_filter);
9022 if(demux[demux_id].max_emm_filter > 0 && ll_count(ll_emm_inactive_filter) > 0 && filter_count > demux[demux_id].max_emm_filter)
9023 {
9024 int32_t filter_queue = ll_count(ll_emm_inactive_filter);
9025 int32_t stopped = 0, started = 0;
9026 struct timeb now;
9027 cs_ftime(&now);
9028 struct s_emm_filter *filter_item;
9029 LL_ITER itr;
9030 itr = ll_iter_create(ll_emm_active_filter);
9031
9032 while((filter_item = ll_iter_next(&itr)) != NULL)
9033 {
9034 if(!ll_count(ll_emm_inactive_filter) || started == filter_queue)
9035 {
9036 break;
9037 }
9038
9039 int64_t gone = comp_timeb(&now, &filter_item->time_started);
9040 if(gone > 45 * 1000)
9041 {
9042 struct s_dvbapi_priority *forceentry = dvbapi_check_prio_match_emmpid(filter_item->demux_id, filter_item->caid, filter_item->provid, 'p');
9043 if(!forceentry || (forceentry && !forceentry->force))
9044 {
9045 // stop active filter and add to pending list
9046 dvbapi_stop_filternum(filter_item->demux_id, filter_item->num - 1, 0);
9047 ll_iter_remove_data(&itr);
9048 add_emmfilter_to_list(filter_item->demux_id, filter_item->filter, filter_item->caid, filter_item->provid, filter_item->pid, -1, false);
9049 stopped++;
9050 }
9051 }
9052
9053 int32_t ret;
9054 if(stopped > started) // we have room for new filters, try to start an inactive emmfilter!
9055 {
9056 struct s_emm_filter *filter_item2;
9057 LL_ITER itr2 = ll_iter_create(ll_emm_inactive_filter);
9058 while((filter_item2 = ll_iter_next(&itr2)))
9059 {
9060 ret = dvbapi_set_filter(filter_item2->demux_id,
9061 selected_api,
9062 filter_item2->pid,
9063 filter_item2->caid,
9064 filter_item2->provid,
9065 filter_item2->filter,
9066 filter_item2->filter + 16,
9067 0,
9068 demux[filter_item2->demux_id].pidindex,
9069 TYPE_EMM, 1);
9070 if(ret != -1)
9071 {
9072 ll_iter_remove_data(&itr2);
9073 started++;
9074 break;
9075 }
9076 }
9077 }
9078 }
9079
9080 itr = ll_iter_create(ll_emm_pending_filter);
9081 while((filter_item = ll_iter_next(&itr)) != NULL) // move pending filters to inactive
9082 {
9083 add_emmfilter_to_list(filter_item->demux_id, filter_item->filter, filter_item->caid, filter_item->provid, filter_item->pid, 0, false);
9084 ll_iter_remove_data(&itr);
9085 }
9086 }
9087}
9088
9089int32_t filtermatch(uint8_t *buffer, int32_t filter_num, int32_t demux_id, int32_t len)
9090{
9091 int32_t i, k, match;
9092 uint8_t flt, mask;
9093
9094 match = 1;
9095 for(i = 0, k = 0; i < 16 && match; i++, k++)
9096 {
9097 mask = demux[demux_id].demux_fd[filter_num].mask[i];
9098 if(k == 1) // skip len bytes
9099 {
9100 k += 2;
9101 }
9102
9103 if(!mask)
9104 {
9105 continue;
9106 }
9107
9108 flt = (demux[demux_id].demux_fd[filter_num].filter[i]&mask);
9109 cs_log_dbg(D_DVBAPI,"Demuxer %d filter%d[%d] = %02X, filter mask[%d] = %02X, flt&mask = %02X , buffer[%d] = %02X, buffer[%d] & mask = %02X",
9110 demux_id, filter_num + 1, i, demux[demux_id].demux_fd[filter_num].filter[i], i, mask, flt&mask, k, buffer[k], k, buffer[k] & mask);
9111
9112 if(k <= len)
9113 {
9114 match = (flt == (buffer[k] & mask));
9115 }
9116 else
9117 {
9118 match = 0;
9119 }
9120 }
9121 return (match && i == 16); // 0 = delivered data does not match with filter, 1 = delivered data matches with filter
9122}
9123
9124/*
9125 * protocol structure
9126 */
9127void module_dvbapi(struct s_module *ph)
9128{
9129 ph->desc = "dvbapi";
9130 ph->type = MOD_CONN_SERIAL;
9131 ph->listenertype = LIS_DVBAPI;
9132#if defined(WITH_AZBOX)
9133 ph->s_handler = azbox_handler;
9134 ph->send_dcw = azbox_send_dcw;
9135#elif defined(WITH_MCA)
9136 ph->s_handler = mca_handler;
9137 ph->send_dcw = mca_send_dcw;
9138 selected_box = selected_api = 0; // HACK: This fixes incorrect warning about out of bounds array access in functionas that are not even called when WITH_MCA is defined
9139#else
9140 ph->s_handler = dvbapi_handler;
9141 ph->send_dcw = dvbapi_send_dcw;
9142#endif
9143}
9144#endif // HAVE_DVBAPI
Note: See TracBrowser for help on using the repository browser.