source: trunk/oscam.c@ 1760

Last change on this file since 1760 was 1760, checked in by landlord, 10 years ago

Fix compiling error: CS_HW_DRAGON

File size: 69.4 KB
Line 
1#define CS_CORE
2#include "globals.h"
3#ifdef CS_WITH_GBOX
4# include "csgbox/gbox.h"
5# define CS_VERSION_X CS_VERSION "-gbx-" GBXVERSION
6#else
7# define CS_VERSION_X CS_VERSION
8#endif
9/*****************************************************************************
10 Globals
11*****************************************************************************/
12int pfd=0; // Primary FD, must be closed on exit
13int mfdr=0; // Master FD (read)
14int fd_m2c=0; // FD Master -> Client (for clients / read )
15int fd_c2m=0; // FD Client -> Master (for clients / write )
16int fd_c2l=0; // FD Client -> Logger (for clients / write )
17int cs_dblevel=0; // Debug Level (TODO !!)
18int cs_idx=0; // client index (0=master, ...)
19int cs_ptyp=0; // process-type
20struct s_module ph[CS_MAX_MOD]; // Protocols
21int maxph=0; // Protocols used
22int cs_hw=0; // hardware autodetect
23int is_server=0; // used in modules to specify function
24pid_t master_pid=0; // master pid OUTSIDE shm
25ushort len4caid[256]; // table for guessing caid (by len)
26char cs_confdir[128]=CS_CONFDIR;
27uchar mbuf[1024]; // global buffer
28ECM_REQUEST *ecmtask;
29EMM_PACKET epg;
30#ifdef CS_ANTICASC
31struct s_acasc ac_stat[CS_MAXPID];
32#endif
33
34/*****************************************************************************
35 Shared Memory
36*****************************************************************************/
37int *ecmidx; // Shared Memory
38int *logidx; // Shared Memory
39int *oscam_sem; // sem (multicam.o)
40int *c_start; // idx of 1st client
41int *log_fd; // log-process is running
42struct s_ecm *ecmcache; // Shared Memory
43struct s_client *client; // Shared Memory
44struct s_reader *reader; // Shared Memory
45
46struct card_struct *Cards; // Shared Memory
47struct idstore_struct *idstore; // Shared Memory
48unsigned long *IgnoreList; // Shared Memory
49
50struct s_config *cfg; // Shared Memory
51#ifdef CS_ANTICASC
52struct s_acasc_shm *acasc; // anti-cascading table indexed by account.ac_idx
53#endif
54#ifdef CS_LOGHISTORY
55int *loghistidx; // ptr to current entry
56char *loghist; // ptr of log-history
57#endif
58int *mcl=0; // Master close log?
59
60static int shmsize = CS_ECMCACHESIZE*(sizeof(struct s_ecm)) +
61 CS_MAXPID*(sizeof(struct s_client)) +
62 CS_MAXREADER*(sizeof(struct s_reader)) +
63#ifdef CS_WITH_GBOX
64 CS_MAXCARDS*(sizeof(struct card_struct))+
65 CS_MAXIGNORE*(sizeof(long))+
66 CS_MAXPID*(sizeof(struct idstore_struct))+
67#endif
68#ifdef CS_ANTICASC
69 CS_MAXPID*(sizeof(struct s_acasc_shm)) +
70#endif
71#ifdef CS_LOGHISTORY
72 CS_MAXLOGHIST*CS_LOGHISTSIZE + sizeof(int) +
73#endif
74 sizeof(struct s_config)+(6*sizeof(int));
75
76#ifdef CS_NOSHM
77char cs_memfile[128]=CS_MMAPFILE;
78#endif
79
80/*****************************************************************************
81 Statics
82*****************************************************************************/
83static char mloc[128]={0};
84static int shmid=0; // Shared Memory ID
85static int cs_last_idx=0; // client index of last fork (master only)
86static char *logo = " ___ ____ ___ \n / _ \\/ ___| / __|__ _ _ __ ___ \n| | | \\___ \\| | / _` | '_ ` _ \\ \n| |_| |___) | |_| (_| | | | | | |\n \\___/|____/ \\___\\__,_|_| |_| |_|\n";
87
88static void cs_set_mloc(int ato, char *txt)
89{
90 if (ato>=0)
91 alarm(ato);
92 if (txt)
93 strcpy(mloc, txt);
94}
95
96char *cs_platform(char *buf)
97{
98 static char *hw=NULL;
99 if (!hw)
100 {
101#ifdef TUXBOX
102 struct stat st;
103 cs_hw=CS_HW_DBOX2; // dbox2, default for now
104 if (!stat("/dev/sci0", &st)) cs_hw=CS_HW_DREAM; // dreambox
105#ifdef TRIPLEDRAGON
106 if (!stat("/dev/stb/tdsc0", &st)) cs_hw=CS_HW_DRAGON; // tripledragon
107#endif
108 switch(cs_hw)
109 {
110#ifdef PPC
111 case CS_HW_DBOX2: hw="dbox2" ; break;
112#endif
113 case CS_HW_DREAM: hw="dreambox"; break;
114 case CS_HW_DRAGON: hw="tripledragon"; break;
115 }
116#endif
117 if (!hw) hw=CS_OS_HW;
118 }
119 sprintf(buf, "%s-%s-%s", CS_OS_CPU, hw, CS_OS_SYS);
120 return(buf);
121}
122
123static void usage()
124{
125 fprintf(stderr, "%s\n\n", logo);
126 fprintf(stderr, "OSCam cardserver v%s, build #%s (%s) - (w) 2009-2010 streamboard SVN\n", CS_VERSION_X, CS_SVN_VERSION, CS_OSTYPE);
127 fprintf(stderr, "\tsee http://streamboard.gmc.to:8001/wiki/ for more details\n");
128 fprintf(stderr, "\tbased on OSCam 0.99.x, (w) 2010 streamboard SVN\n");
129 fprintf(stderr, "\tbased on streamboard mp-cardserver v0.9d - (w) 2004-2007 by dukat\n");
130 fprintf(stderr, "\tinbuilt modules: ");
131#ifdef HAVE_DVBAPI
132 fprintf(stderr, "dvbapi ");
133#endif
134#ifdef WEBIF
135 fprintf(stderr, "webinterface ");
136#endif
137#ifdef CS_ANTICASC
138 fprintf(stderr, "anticascading ");
139#endif
140#ifdef LIBUSB
141 fprintf(stderr, "smartreader ");
142#endif
143#ifdef HAVE_PCSC
144 fprintf(stderr, "pcsc ");
145#endif
146#ifdef CS_WITH_GBOX
147 fprintf(stderr, "gbox ");
148#endif
149#ifdef IRDETO_GUESSING
150 fprintf(stderr, "irdeto-guessing ");
151#endif
152 fprintf(stderr, "\n\n");
153 fprintf(stderr, "oscam [-b] [-c config-dir] [-d]");
154#ifdef CS_NOSHM
155 fprintf(stderr, " [-m memory-file]");
156#endif
157 fprintf(stderr, "\n\n\t-b : start in background\n");
158 fprintf(stderr, "\t-c <dir> : read configuration from <dir>\n");
159 fprintf(stderr, "\t default = %s\n", CS_CONFDIR);
160 fprintf(stderr, "\t-d <level> : debug level mask\n");
161 fprintf(stderr, "\t 0 = no debugging (default)\n");
162 fprintf(stderr, "\t 1 = detailed error messages\n");
163 fprintf(stderr, "\t 2 = ATR parsing info, ECM, EMM and CW dumps\n");
164 fprintf(stderr, "\t 4 = traffic from/to the reader\n");
165 fprintf(stderr, "\t 8 = traffic from/to the clients\n");
166 fprintf(stderr, "\t 16 = traffic to the reader-device on IFD layer\n");
167 fprintf(stderr, "\t 32 = traffic to the reader-device on I/O layer\n");
168 fprintf(stderr, "\t 64 = EMM logging\n");
169 fprintf(stderr, "\t 255 = debug all\n");
170#ifdef CS_NOSHM
171 fprintf(stderr, "\t-m <file> : use <file> as mmaped memory file\n");
172 fprintf(stderr, "\t default = %s\n", CS_MMAPFILE);
173#endif
174 fprintf(stderr, "\n");
175 exit(1);
176}
177
178#ifdef NEED_DAEMON
179#ifdef OS_MACOSX
180// this is done because daemon is being deprecated starting with 10.5 and -Werror will always trigger an error
181static int daemon_compat(int nochdir, int noclose)
182#else
183static int daemon(int nochdir, int noclose)
184#endif
185{
186 int fd;
187
188 switch (fork())
189 {
190 case -1: return (-1);
191 case 0: break;
192 default: _exit(0);
193 }
194
195 if (setsid()==(-1))
196 return(-1);
197
198 if (!nochdir)
199 (void)chdir("/");
200
201 if (!noclose && (fd=open("/dev/null", O_RDWR, 0)) != -1)
202 {
203 (void)dup2(fd, STDIN_FILENO);
204 (void)dup2(fd, STDOUT_FILENO);
205 (void)dup2(fd, STDERR_FILENO);
206 if (fd>2)
207 (void)close(fd);
208 }
209 return(0);
210}
211#endif
212
213int recv_from_udpipe(uchar *buf)
214{
215 unsigned short n;
216 if (!pfd) return(-9);
217 if (!read(pfd, buf, 3)) cs_exit(1);
218 if (buf[0]!='U')
219 {
220 cs_log("INTERNAL PIPE-ERROR");
221 cs_exit(1);
222 }
223 memcpy(&n, buf+1, 2);
224 return(read(pfd, buf, n));
225}
226
227char *username(int idx)
228{
229 if (client[idx].usr[0])
230 return(client[idx].usr);
231 else
232 return("anonymous");
233}
234
235static int idx_from_ip(in_addr_t ip, in_port_t port)
236{
237 int i, idx;
238 for (i=idx=0; (i<CS_MAXPID) && (!idx); i++)
239 if ((client[i].ip==ip) && (client[i].port==port) &&
240 ((client[i].typ=='c') || (client[i].typ=='m')))
241 idx=i;
242 return(idx);
243}
244
245int idx_from_pid(pid_t pid)
246{
247 int i, idx;
248 for (i=0, idx=(-1); (i<CS_MAXPID) && (idx<0); i++)
249 if (client[i].pid==pid)
250 idx=i;
251 return(idx);
252}
253
254static long chk_caid(ushort caid, CAIDTAB *ctab)
255{
256 int n;
257 long rc;
258 for (rc=(-1), n=0; (n<CS_MAXCAIDTAB) && (rc<0); n++)
259 if ((caid & ctab->mask[n]) == ctab->caid[n])
260 rc=ctab->cmap[n] ? ctab->cmap[n] : caid;
261 return(rc);
262}
263
264int chk_bcaid(ECM_REQUEST *er, CAIDTAB *ctab)
265{
266 long caid;
267 if ((caid=chk_caid(er->caid, ctab))<0)
268 return(0);
269 er->caid=caid;
270 return(1);
271}
272
273/*
274 * void set_signal_handler(int sig, int flags, void (*sighandler)(int))
275 * flags: 1 = restart, 2 = don't modify if SIG_IGN, may be combined
276 */
277void set_signal_handler(int sig, int flags, void (*sighandler)(int))
278{
279#ifdef CS_SIGBSD
280 if ((signal(sig, sighandler)==SIG_IGN) && (flags & 2))
281 {
282 signal(sig, SIG_IGN);
283 siginterrupt(sig, 0);
284 }
285 else
286 siginterrupt(sig, (flags & 1) ? 0 : 1);
287#else
288 struct sigaction sa;
289 sigaction(sig, (struct sigaction *) 0, &sa);
290 if (!((flags & 2) && (sa.sa_handler==SIG_IGN)))
291 {
292 sigemptyset(&sa.sa_mask);
293 sa.sa_flags=(flags & 1) ? SA_RESTART : 0;
294 sa.sa_handler=sighandler;
295 sigaction(sig, &sa, (struct sigaction *) 0);
296 }
297#endif
298}
299
300static void cs_alarm()
301{
302 cs_debug("Got alarm signal");
303 cs_log("disconnect from %s (deadlock!)", cs_inet_ntoa(client[cs_idx].ip));
304 cs_exit(0);
305}
306
307static void cs_master_alarm()
308{
309 cs_log("PANIC: master deadlock! last location: %s", mloc);
310 fprintf(stderr, "PANIC: master deadlock! last location: %s", mloc);
311 fflush(stderr);
312 cs_exit(0);
313}
314
315static void cs_sigpipe()
316{
317 if ((cs_idx) && (master_pid!=getppid()))
318 cs_exit(0);
319 cs_log("Got sigpipe signal -> captured");
320}
321
322void cs_exit(int sig)
323{
324 int i;
325
326 set_signal_handler(SIGCHLD, 1, SIG_IGN);
327 set_signal_handler(SIGHUP , 1, SIG_IGN);
328 if (sig && (sig!=SIGQUIT))
329 cs_log("exit with signal %d", sig);
330 switch(client[cs_idx].typ)
331 {
332 case 'c': cs_statistics(cs_idx);
333 case 'm': break;
334 case 'n': *log_fd=0;
335 break;
336 case 's': *log_fd=0;
337 for (i=1; i<CS_MAXPID; i++)
338 if (client[i].pid)
339 kill(client[i].pid, SIGQUIT);
340 cs_log("cardserver down");
341#ifndef CS_NOSHM
342 if (ecmcache) shmdt((void *)ecmcache);
343#endif
344 break;
345 }
346 if (pfd) close(pfd);
347#ifdef CS_NOSHM
348 munmap((void *)ecmcache, (size_t)shmsize);
349 if (shmid) close(shmid);
350 unlink(CS_MMAPFILE); // ignore errors, last process must succeed
351#endif
352 exit(sig);
353}
354
355void cs_reinit_clients()
356{
357 int i;
358 struct s_auth *account;
359
360 for( i = 1; i < CS_MAXPID; i++ )
361 if( client[i].pid && client[i].typ == 'c' && client[i].usr[0] ) {
362 for (account = cfg->account; (account) ; account = account->next)
363 if (!strcmp(client[i].usr, account->usr))
364 break;
365
366 if (account && client[i].pcrc == crc32(0L, MD5((uchar *)account->pwd, strlen(account->pwd), NULL), 16)) {
367 client[i].grp = account->grp;
368 client[i].au = account->au;
369 client[i].autoau = account->autoau;
370 client[i].expirationdate = account->expirationdate;
371 client[i].ncd_keepalive = account->ncd_keepalive;
372 client[i].c35_suppresscmd08 = account->c35_suppresscmd08;
373 client[i].tosleep = (60*account->tosleep);
374 client[i].monlvl = account->monlvl;
375 client[i].disabled = account->disabled;
376 client[i].fchid = account->fchid; // CHID filters
377 client[i].cltab = account->cltab; // Class
378
379 // newcamd module dosent like ident reloading
380 if(!client[i].ncd_server)
381 client[i].ftab = account->ftab; // Ident
382
383 client[i].sidtabok = account->sidtabok; // services
384 client[i].sidtabno = account->sidtabno; // services
385
386 memcpy(&client[i].ctab, &account->ctab, sizeof(client[i].ctab));
387 memcpy(&client[i].ttab, &account->ttab, sizeof(client[i].ttab));
388
389#ifdef CS_ANTICASC
390 client[i].ac_idx = account->ac_idx;
391 client[i].ac_penalty= account->ac_penalty;
392 client[i].ac_limit = (account->ac_users * 100 + 80) * cfg->ac_stime;
393#endif
394 } else {
395 if (ph[client[i].ctyp].type & MOD_CONN_NET) {
396 cs_debug("client '%s', pid=%d not found in db (or password changed)", client[i].usr, client[i].pid);
397 kill(client[i].pid, SIGQUIT);
398 }
399 }
400 }
401}
402
403static void cs_sighup()
404{
405 uchar dummy[1]={0x00};
406 write_to_pipe(fd_c2m, PIP_ID_HUP, dummy, 1);
407}
408
409static void cs_accounts_chk()
410{
411 int i;
412 init_userdb();
413 cs_reinit_clients();
414#ifdef CS_ANTICASC
415 for (i=0; i<CS_MAXPID; i++)
416 if (client[i].typ=='a')
417 {
418 kill(client[i].pid, SIGHUP);
419 break;
420 }
421#endif
422}
423
424static void cs_debug_level()
425{
426 int i;
427
428 //switch debuglevel forward one step if not set from outside
429 if(cfg->debuglvl == cs_dblevel) {
430 switch (cs_dblevel) {
431 case 0:
432 cs_dblevel = 1;
433 break;
434 case 64:
435 cs_dblevel = 255;
436 break;
437 case 255:
438 cs_dblevel = 0;
439 break;
440 default:
441 cs_dblevel <<= 1;
442 }
443 } else {
444 cs_dblevel = cfg->debuglvl;
445 }
446
447 cfg->debuglvl = cs_dblevel;
448
449 if (master_pid == getpid())
450 for (i=0; i<CS_MAXPID && client[i].pid; i++)
451 client[i].dbglvl = cs_dblevel;
452 else
453 client[cs_idx].dbglvl = cs_dblevel;
454 cs_log("%sdebug_level=%d", (master_pid == getpid())?"all ":"", cs_dblevel);
455}
456
457static void cs_card_info(int i)
458{
459 uchar dummy[1]={0x00};
460
461 for( i=1; i<CS_MAXPID; i++ )
462 if( client[i].pid && client[i].typ=='r' && client[i].fd_m2c ){
463 write_to_pipe(client[i].fd_m2c, PIP_ID_CIN, dummy, 1);
464 }
465
466 //kill(client[i].pid, SIGUSR2);
467}
468
469static void cs_child_chk(int i)
470{
471 while (waitpid(0, NULL, WNOHANG)>0);
472 for (i=1; i<CS_MAXPID; i++)
473 if (client[i].pid)
474 if (kill(client[i].pid, 0)) {
475 if ((client[i].typ!='c') && (client[i].typ!='m'))
476 {
477 char *txt="";
478 *log_fd=0;
479 switch(client[i].typ)
480 {
481#ifdef CS_ANTICASC
482 case 'a': txt="anticascader"; break;
483#endif
484 case 'l': txt="logger"; break;
485 case 'p': txt="proxy"; break;
486 case 'r': txt="reader"; break;
487 case 'n': txt="resolver"; break;
488#ifdef WEBIF
489 case 'h': txt="http"; break;
490#endif
491 }
492 cs_log("PANIC: %s lost !! (pid=%d)", txt, client[i].pid);
493 cs_exit(1);
494 }
495 else
496 {
497#ifdef CS_ANTICASC
498 char usr[32];
499 ushort ac_idx=0;
500 ushort ac_limit=0;
501 uchar ac_penalty=0;
502 if( cfg->ac_enabled )
503 {
504 cs_strncpy(usr, client[i].usr, sizeof(usr));
505 ac_idx = client[i].ac_idx;
506 ac_limit = client[i].ac_limit;
507 ac_penalty = client[i].ac_penalty;
508 }
509#endif
510 if (client[i].fd_m2c) close(client[i].fd_m2c);
511 if (client[i].ufd) close(client[i].ufd);
512 memset(&client[i], 0, sizeof(struct s_client));
513#ifdef CS_ANTICASC
514 if( cfg->ac_enabled )
515 {
516 client[i].ac_idx = ac_idx;
517 client[i].ac_limit = ac_limit;
518 client[i].ac_penalty = ac_penalty;
519 strcpy(client[i].usr, usr);
520 }
521#endif
522 client[i].au=(-1);
523 }
524 }
525 return;
526}
527
528int cs_fork(in_addr_t ip, in_port_t port)
529{
530 int i;
531 pid_t pid;
532 for (i=1; (i<CS_MAXPID) && (client[i].pid); i++);
533 if (i<CS_MAXPID)
534 {
535 int fdp[2];
536 memset(&client[i], 0, sizeof(struct s_client));
537 client[i].au=(-1);
538 if (pipe(fdp))
539 {
540 cs_log("Cannot create pipe (errno=%d)", errno);
541 cs_exit(1);
542 }
543 switch(pid=fork())
544 {
545 case -1:
546 cs_log("PANIC: Cannot fork() (errno=%d)", errno);
547 cs_exit(1);
548 case 0: // HERE is client
549 alarm(0);
550 set_signal_handler(SIGALRM, 0, cs_alarm);
551 set_signal_handler(SIGCHLD, 1, SIG_IGN);
552 set_signal_handler(SIGHUP , 1, SIG_IGN);
553 set_signal_handler(SIGINT , 1, SIG_IGN);
554 set_signal_handler(SIGUSR1, 1, cs_debug_level);
555 is_server=((ip) || (port<90)) ? 1 : 0;
556 fd_m2c=fdp[0];
557 close(fdp[1]);
558 close(mfdr);
559 if( port!=97 ) cs_close_log();
560 mfdr=0;
561 cs_ptyp=D_CLIENT;
562 cs_idx=i;
563#ifndef CS_NOSHM
564 shmid=0;
565#endif
566 break;
567 default: // HERE is master
568 client[i].fd_m2c=fdp[1];
569 client[i].dbglvl=cs_dblevel;
570 close(fdp[0]);
571 if (ip)
572 {
573 client[i].typ='c'; // dynamic client
574 client[i].ip=ip;
575 client[i].port=port;
576 cs_log("client(%d) connect from %s (pid=%d, pipfd=%d)",
577 i-cdiff, cs_inet_ntoa(ip), pid, client[i].fd_m2c);
578 }
579 else
580 {
581 client[i].stat=1;
582 switch(port)
583 {
584 case 99: client[i].typ='r'; // reader
585 client[i].sidtabok=reader[ridx].sidtabok;
586 client[i].sidtabno=reader[ridx].sidtabno;
587 reader[ridx].fd=client[i].fd_m2c;
588 reader[ridx].cs_idx=i;
589 reader[ridx].pid=pid;
590 if (reader[ridx].r_port)
591 cs_log("proxy started (pid=%d, server=%s)",
592 pid, reader[ridx].device);
593 else
594 {
595 if (reader[ridx].typ==R_MOUSE || reader[ridx].typ==R_SMART)
596 cs_log("reader started (pid=%d, device=%s, detect=%s%s, mhz=%d, cardmhz=%d)",
597 pid, reader[ridx].device,
598 reader[ridx].detect&0x80 ? "!" : "",
599 RDR_CD_TXT[reader[ridx].detect&0x7f],
600 reader[ridx].mhz,
601 reader[ridx].cardmhz);
602 else
603 cs_log("reader started (pid=%d, device=%s)",
604 pid, reader[ridx].device);
605 client[i].ip=client[0].ip;
606 strcpy(client[i].usr, client[0].usr);
607 }
608 cdiff=i;
609 break;
610 case 98: client[i].typ='n'; // resolver
611 client[i].ip=client[0].ip;
612 strcpy(client[i].usr, client[0].usr);
613 cs_log("resolver started (pid=%d, delay=%d sec)",
614 pid, cfg->resolvedelay);
615 cdiff=i;
616 break;
617 case 97: client[i].typ='l'; // logger
618 client[i].ip=client[0].ip;
619 strcpy(client[i].usr, client[0].usr);
620 cs_log("logger started (pid=%d)", pid);
621 cdiff=i;
622 break;
623#ifdef CS_ANTICASC
624 case 96: client[i].typ='a';
625 client[i].ip=client[0].ip;
626 strcpy(client[i].usr, client[0].usr);
627 cs_log("anticascader started (pid=%d, delay=%d min)",
628 pid, cfg->ac_stime);
629 cdiff=i;
630 break;
631#endif
632
633#ifdef WEBIF
634 case 95: client[i].typ='h'; // http
635 client[i].ip=client[0].ip;
636 strcpy(client[i].usr, client[0].usr);
637 cs_log("http started (pid=%d)",pid);
638 cdiff=i;
639 break;
640#endif
641
642 default: client[i].typ='c'; // static client
643 client[i].ip=client[0].ip;
644 client[i].ctyp=port;
645 cs_log("%s: initialized (pid=%d%s)", ph[port].desc,
646 pid, ph[port].logtxt ? ph[port].logtxt : "");
647 break;
648 }
649 }
650 client[i].login=client[i].last=time((time_t *)0);
651 client[i].pid=pid; // MUST be last -> wait4master()
652 cs_last_idx=i;
653 i=0;
654 }
655 }
656 else
657 {
658 cs_log("max connections reached -> reject client %s", cs_inet_ntoa(ip));
659 i=(-1);
660 }
661 return(i);
662}
663
664static void init_signal()
665{
666 int i;
667 for (i=1; i<NSIG; i++)
668 set_signal_handler(i, 3, cs_exit);
669 set_signal_handler(SIGWINCH, 1, SIG_IGN);
670 // set_signal_handler(SIGPIPE , 0, SIG_IGN);
671 set_signal_handler(SIGPIPE , 0, cs_sigpipe);
672 // set_signal_handler(SIGALRM , 0, cs_alarm);
673 set_signal_handler(SIGALRM , 0, cs_master_alarm);
674 set_signal_handler(SIGCHLD , 1, cs_child_chk);
675 // set_signal_handler(SIGHUP , 1, cs_accounts_chk);
676 set_signal_handler(SIGHUP , 1, cs_sighup);
677 set_signal_handler(SIGUSR1, 1, cs_debug_level);
678 set_signal_handler(SIGUSR2, 1, cs_card_info);
679 set_signal_handler(SIGCONT, 1, SIG_IGN);
680 cs_log("signal handling initialized (type=%s)",
681#ifdef CS_SIGBSD
682 "bsd"
683#else
684 "sysv"
685#endif
686 );
687 return;
688}
689
690static void init_shm()
691{
692#ifdef CS_NOSHM
693 //int i, fd;
694 char *buf;
695 if ((shmid=open(cs_memfile, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR))<0)
696 {
697 fprintf(stderr, "Cannot create mmaped file (errno=%d)", errno);
698 cs_exit(1);
699 }
700
701 buf=(char *)malloc(shmsize);
702 memset(buf, 0, shmsize);
703 if (!write(shmid, buf, shmsize)) cs_exit(1);
704 free(buf);
705
706 ecmcache=(struct s_ecm *)mmap((void *)0, (size_t) shmsize,
707 PROT_READ|PROT_WRITE, MAP_SHARED, shmid, 0);
708#else
709 struct shmid_ds sd;
710 char *shmerr_txt="Cannot %s shared memory (errno=%d)\n";
711 if ((shmid=shmget(IPC_PRIVATE, shmsize, IPC_CREAT | 0600))<0)
712 {
713 fprintf(stderr, shmerr_txt, "create", errno);
714 shmid=0;
715 cs_exit(1);
716 }
717 if ((ecmcache=(struct s_ecm *)shmat(shmid, 0, 0))==(void *)(-1))
718 {
719 fprintf(stderr, shmerr_txt, "attach", errno);
720 cs_exit(1);
721 }
722 memset(ecmcache, 0, shmsize);
723 shmctl(shmid, IPC_RMID, &sd);
724#endif
725#ifdef CS_ANTICASC
726 acasc=(struct s_acasc_shm *)&ecmcache[CS_ECMCACHESIZE];
727 ecmidx=(int *)&acasc[CS_MAXPID];
728#else
729 ecmidx=(int *)&ecmcache[CS_ECMCACHESIZE];
730#endif
731 mcl=(int *)((void *)ecmidx+sizeof(int));
732 logidx=(int *)((void *)mcl+sizeof(int));
733 c_start=(int *)((void *)logidx+sizeof(int));
734 log_fd=(int *)((void *)c_start+sizeof(int));
735 oscam_sem=(int *)((void *)log_fd+sizeof(int));
736 client=(struct s_client *)((void *)oscam_sem+sizeof(int));
737 reader=(struct s_reader *)&client[CS_MAXPID];
738#ifdef CS_WITH_GBOX
739 Cards=(struct card_struct*)&reader[CS_MAXREADER];
740 IgnoreList=(unsigned long*)&Cards[CS_MAXCARDS];
741 idstore=(struct idstore_struct*)&IgnoreList[CS_MAXIGNORE];
742 cfg=(struct s_config *)&idstore[CS_MAXPID];
743#else
744 cfg=(struct s_config *)&reader[CS_MAXREADER];
745#endif
746#ifdef CS_LOGHISTORY
747 loghistidx=(int *)((void *)cfg+sizeof(struct s_config));
748 loghist=(char *)((void *)loghistidx+sizeof(int));
749#endif
750
751#ifdef DEBUG_SHM_POINTER
752 printf("SHM ALLOC: %x\n", shmsize);
753 printf("SHM START: %p\n", (void *) ecmcache);
754 printf("SHM ST1: %p %x (%x)\n", (void *) ecmidx, ((void *) ecmidx) - ((void *) ecmcache), CS_ECMCACHESIZE*(sizeof(struct s_ecm)));
755 printf("SHM ST2: %p %x (%x)\n", (void *) oscam_sem, ((void *) oscam_sem) - ((void *) ecmidx), sizeof(int));
756 printf("SHM ST3: %p %x (%x)\n", (void *) client, ((void *) client) - ((void *) oscam_sem), sizeof(int));
757 printf("SHM ST4: %p %x (%x)\n", (void *) reader, ((void *) reader) - ((void *) client), CS_MAXPID*(sizeof(struct s_client)));
758 printf("SHM ST5: %p %x (%x)\n", (void *) cfg, ((void *) cfg) - ((void *) reader), CS_MAXREADER*(sizeof(struct s_reader)));
759 printf("SHM ST6: %p %x (%x)\n", ((void *) cfg)+sizeof(struct s_config), sizeof(struct s_config), sizeof(struct s_config));
760 printf("SHM ENDE: %p\n", ((void *) cfg)+sizeof(struct s_config));
761 printf("SHM SIZE: %x\n", ((void *) cfg)-((void *) ecmcache) + sizeof(struct s_config));
762 fflush(stdout);
763#endif
764
765 *ecmidx=0;
766 *logidx=0;
767 *oscam_sem=0;
768 client[0].pid=getpid();
769 client[0].login=time((time_t *)0);
770 client[0].ip=cs_inet_addr("127.0.0.1");
771 client[0].typ='s';
772 client[0].au=(-1);
773 client[0].dbglvl=cs_dblevel;
774 strcpy(client[0].usr, "root");
775#ifdef CS_LOGHISTORY
776 *loghistidx=0;
777 memset(loghist, 0, CS_MAXLOGHIST*CS_LOGHISTSIZE);
778#endif
779}
780
781static int start_listener(struct s_module *ph, int port_idx)
782{
783 int ov=1, timeout, is_udp, i;
784 char ptxt[2][32];
785 //struct hostent *ptrh; /* pointer to a host table entry */
786 struct protoent *ptrp; /* pointer to a protocol table entry */
787 struct sockaddr_in sad; /* structure to hold server's address */
788
789 ptxt[0][0]=ptxt[1][0]='\0';
790 if (!ph->ptab->ports[port_idx].s_port)
791 {
792 cs_log("%s: disabled", ph->desc);
793 return(0);
794 }
795 is_udp=(ph->type==MOD_CONN_UDP);
796
797 memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
798 sad.sin_family = AF_INET; /* set family to Internet */
799 if (!ph->s_ip)
800 ph->s_ip=cfg->srvip;
801 if (ph->s_ip)
802 {
803 sad.sin_addr.s_addr=ph->s_ip;
804 sprintf(ptxt[0], ", ip=%s", inet_ntoa(sad.sin_addr));
805 }
806 else
807 sad.sin_addr.s_addr=INADDR_ANY;
808 timeout=cfg->bindwait;
809 //ph->fd=0;
810 ph->ptab->ports[port_idx].fd = 0;
811
812 if (ph->ptab->ports[port_idx].s_port > 0) /* test for illegal value */
813 sad.sin_port = htons((u_short)ph->ptab->ports[port_idx].s_port);
814 else
815 {
816 cs_log("%s: Bad port %d", ph->desc, ph->ptab->ports[port_idx].s_port);
817 return(0);
818 }
819
820 /* Map transport protocol name to protocol number */
821
822 if( (ptrp=getprotobyname(is_udp ? "udp" : "tcp")) )
823 ov=ptrp->p_proto;
824 else
825 ov=(is_udp) ? 17 : 6; // use defaults on error
826
827 if ((ph->ptab->ports[port_idx].fd=socket(PF_INET,is_udp ? SOCK_DGRAM : SOCK_STREAM, ov))<0)
828 {
829 cs_log("%s: Cannot create socket (errno=%d)", ph->desc, errno);
830 return(0);
831 }
832
833 ov=1;
834 if (setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_REUSEADDR, (void *)&ov, sizeof(ov))<0)
835 {
836 cs_log("%s: setsockopt failed (errno=%d)", ph->desc, errno);
837 close(ph->ptab->ports[port_idx].fd);
838 return(ph->ptab->ports[port_idx].fd=0);
839 }
840
841#ifdef SO_REUSEPORT
842 setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_REUSEPORT, (void *)&ov, sizeof(ov));
843#endif
844
845#ifdef SO_PRIORITY
846 if (cfg->netprio)
847 if (!setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_PRIORITY, (void *)&cfg->netprio, sizeof(ulong)))
848 sprintf(ptxt[1], ", prio=%ld", cfg->netprio);
849#endif
850
851 if( !is_udp )
852 {
853 ulong keep_alive = 1;
854 setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_KEEPALIVE,
855 (void *)&keep_alive, sizeof(ulong));
856 }
857
858 while (timeout--)
859 {
860 if (bind(ph->ptab->ports[port_idx].fd, (struct sockaddr *)&sad, sizeof (sad))<0)
861 {
862 if (timeout)
863 {
864 cs_log("%s: Bind request failed, waiting another %d seconds",
865 ph->desc, timeout);
866 cs_sleepms(1000);
867 }
868 else
869 {
870 cs_log("%s: Bind request failed, giving up", ph->desc);
871 close(ph->ptab->ports[port_idx].fd);
872 return(ph->ptab->ports[port_idx].fd=0);
873 }
874 }
875 else timeout=0;
876 }
877
878 if (!is_udp)
879 if (listen(ph->ptab->ports[port_idx].fd, CS_QLEN)<0)
880 {
881 cs_log("%s: Cannot start listen mode (errno=%d)", ph->desc, errno);
882 close(ph->ptab->ports[port_idx].fd);
883 return(ph->ptab->ports[port_idx].fd=0);
884 }
885
886 cs_log("%s: initialized (fd=%d, port=%d%s%s%s)",
887 ph->desc, ph->ptab->ports[port_idx].fd,
888 ph->ptab->ports[port_idx].s_port,
889 ptxt[0], ptxt[1], ph->logtxt ? ph->logtxt : "");
890
891 for( i=0; i<ph->ptab->ports[port_idx].ftab.nfilts; i++ ) {
892 int j;
893 cs_log("CAID: %04X", ph->ptab->ports[port_idx].ftab.filts[i].caid );
894 for( j=0; j<ph->ptab->ports[port_idx].ftab.filts[i].nprids; j++ )
895 cs_log("provid #%d: %06X", j, ph->ptab->ports[port_idx].ftab.filts[i].prids[j]);
896 }
897 return(ph->ptab->ports[port_idx].fd);
898}
899
900static void cs_client_resolve()
901{
902 while (1)
903 {
904 struct hostent *rht;
905 struct s_auth *account;
906 struct sockaddr_in udp_sa;
907
908 for (account=cfg->account; account; account=account->next)
909 if (account->dyndns[0])
910 {
911 rht=gethostbyname((const char *)account->dyndns);
912 if (rht)
913 {
914 memcpy(&udp_sa.sin_addr, rht->h_addr, sizeof(udp_sa.sin_addr));
915 account->dynip=cs_inet_order(udp_sa.sin_addr.s_addr);
916 }
917 else
918 cs_log("can't resolve hostname %s (user: %s)", account->dyndns, account->usr);
919 client[cs_idx].last=time((time_t)0);
920 }
921 sleep(cfg->resolvedelay);
922 }
923}
924
925static void start_client_resolver()
926{
927 int i;
928 pthread_t tid;
929
930 i=pthread_create(&tid, (pthread_attr_t *)0, (void *)&cs_client_resolve, (void *) 0);
931 if (i)
932 cs_log("ERROR: can't create resolver-thread (err=%d)", i);
933 else
934 {
935 cs_log("resolver thread started");
936 pthread_detach(tid);
937 }
938}
939
940void cs_resolve()
941{
942 int i, idx;
943 struct hostent *rht;
944 struct s_auth;
945 for (i=0; i<CS_MAXREADER; i++)
946 if ((idx=reader[i].cs_idx) && (reader[i].typ & R_IS_NETWORK))
947 {
948 client[cs_idx].last=time((time_t)0);
949 rht=gethostbyname(reader[i].device);
950 if (rht)
951 {
952 memcpy(&client[idx].udp_sa.sin_addr, rht->h_addr,
953 sizeof(client[idx].udp_sa.sin_addr));
954 client[idx].ip=cs_inet_order(client[idx].udp_sa.sin_addr.s_addr);
955 }
956 else
957 cs_log("can't resolve %s", reader[i].device);
958 client[cs_idx].last=time((time_t)0);
959 }
960}
961
962static void cs_logger(void)
963{
964 *log_fd=client[cs_idx].fd_m2c;
965 while(1)
966 {
967 uchar *ptr;
968 //struct timeval tv;
969 fd_set fds;
970
971 FD_ZERO(&fds);
972 FD_SET(fd_m2c, &fds);
973 select(fd_m2c+1, &fds, 0, 0, 0);
974
975 if (master_pid!=getppid())
976 cs_exit(0);
977
978 if (FD_ISSET(fd_m2c, &fds))
979 {
980 int n;
981// switch(n=read_from_pipe(fd_m2c, &ptr, 1))
982 n=read_from_pipe(fd_m2c, &ptr, 1);
983//if (n!=PIP_ID_NUL) printf("received %d bytes\n", n); fflush(stdout);
984 switch(n)
985 {
986 case PIP_ID_LOG:
987 cs_write_log((char *)ptr);
988 break;
989 }
990 }
991 }
992}
993
994static void start_resolver()
995{
996 int i;
997
998 cs_sleepms(1000); // wait for reader
999 while(1)
1000 {
1001 if (master_pid!=getppid())
1002 cs_exit(0);
1003 cs_resolve();
1004 for (i=0; i<cfg->resolvedelay; i++)
1005 if (master_pid!=getppid())
1006 cs_exit(0);
1007 else
1008 cs_sleepms(1000);
1009// sleep(cfg->resolvedelay);
1010 }
1011}
1012
1013#ifdef CS_ANTICASC
1014static void start_anticascader()
1015{
1016 int i;
1017
1018 use_ac_log=1;
1019 set_signal_handler(SIGHUP, 1, ac_init_stat);
1020
1021 ac_init_stat();
1022 while(1)
1023 {
1024 for( i=0; i<cfg->ac_stime*60; i++ )
1025 if( master_pid!=getppid() )
1026 cs_exit(0);
1027 else
1028 cs_sleepms(1000);
1029
1030 if (master_pid!=getppid())
1031 cs_exit(0);
1032
1033 ac_do_stat();
1034 }
1035}
1036#endif
1037
1038#ifdef WEBIF
1039static void cs_http()
1040{
1041 http_srv();
1042}
1043#endif
1044
1045static void init_cardreader()
1046{
1047 for (ridx=0; ridx<CS_MAXREADER; ridx++)
1048 if ((reader[ridx].device[0]) && (reader[ridx].enable == 1))
1049 switch(cs_fork(0, 99)) {
1050 case -1:
1051 cs_exit(1);
1052 case 0:
1053 break;
1054 default:
1055
1056 wait4master();
1057 start_cardreader();
1058 }
1059}
1060
1061static void init_service(int srv)
1062{
1063 switch(cs_fork(0, srv))
1064 {
1065 case -1:
1066 cs_exit(1);
1067 case 0:
1068 break;
1069 default:
1070 wait4master();
1071 switch(srv)
1072 {
1073#ifdef CS_ANTICASC
1074 case 96: start_anticascader();
1075#endif
1076 case 97: cs_logger();
1077 case 98: start_resolver();
1078#ifdef WEBIF
1079 case 95: cs_http();
1080#endif
1081 }
1082 }
1083}
1084
1085void wait4master()
1086{
1087 int i;
1088 for (i=0; (i<1000) && (client[cs_idx].pid!=getpid()); i++)
1089 cs_sleepms(1);
1090 if (client[cs_idx].pid!=getpid())
1091 {
1092 cs_log("PANIC: client not found in shared memory");
1093 cs_exit(1);
1094 }
1095 cs_debug("starting client %d with ip %s",
1096 cs_idx-cdiff, cs_inet_ntoa(client[cs_idx].ip));
1097}
1098
1099static void cs_fake_client(char *usr, int uniq, in_addr_t ip)
1100{
1101 /* Uniq = 1: only one connection per user
1102 *
1103 * Uniq = 2: set (new connected) user only to fake if source
1104 * ip is different (e.g. for newcamd clients with
1105 * different CAID's -> Ports)
1106 *
1107 * Uniq = 3: only one connection per user, but only the last
1108 * login will survive (old mpcs behavior)
1109 *
1110 * Uniq = 4: set user only to fake if source ip is
1111 * different, but only the last login will survive
1112 */
1113
1114 int i;
1115 for (i=cdiff+1; i<CS_MAXPID; i++)
1116 {
1117 if (client[i].pid && (client[i].typ == 'c') && !client[i].dup && !strcmp(client[i].usr, usr)
1118 && (uniq < 5) && ((uniq % 2) || (client[i].ip != ip)))
1119 {
1120 if (uniq == 3 || uniq == 4)
1121 {
1122 client[i].dup = 1;
1123 client[i].au = -1;
1124 cs_log("client(%d) duplicate user '%s' from %s set to fake (uniq=%d)", i-cdiff, usr, cs_inet_ntoa(ip), uniq);
1125 }
1126 else
1127 {
1128 client[cs_idx].dup = 1;
1129 client[cs_idx].au = -1;
1130 cs_log("client(%d) duplicate user '%s' from %s set to fake (uniq=%d)", cs_idx-cdiff, usr, cs_inet_ntoa(ip), uniq);
1131 break;
1132 }
1133
1134 }
1135 }
1136
1137}
1138
1139int cs_auth_client(struct s_auth *account, char *e_txt)
1140{
1141 int rc=0;
1142 char buf[32];
1143 char *t_crypt="encrypted";
1144 char *t_plain="plain";
1145 char *t_grant=" granted";
1146 char *t_reject=" rejected";
1147 char *t_msg[]= { buf, "invalid access", "invalid ip", "unknown reason" };
1148 client[cs_idx].grp=0xffffffff;
1149 client[cs_idx].au=(-1);
1150 switch((long)account)
1151 {
1152 case -2: // gbx-dummy
1153 client[cs_idx].dup=0;
1154 break;
1155 case 0: // reject access
1156 rc=1;
1157 cs_log("%s %s-client %s%s (%s)",
1158 client[cs_idx].crypted ? t_crypt : t_plain,
1159 ph[client[cs_idx].ctyp].desc,
1160 client[cs_idx].ip ? cs_inet_ntoa(client[cs_idx].ip) : "",
1161 client[cs_idx].ip ? t_reject : t_reject+1,
1162 e_txt ? e_txt : t_msg[rc]);
1163 break;
1164 default: // grant/check access
1165 if (client[cs_idx].ip && account->dyndns[0])
1166 if (client[cs_idx].ip != account->dynip)
1167 rc=2;
1168 if (!rc)
1169 {
1170 client[cs_idx].dup=0;
1171 if (client[cs_idx].typ=='c')
1172 {
1173 client[cs_idx].expirationdate=account->expirationdate;
1174 client[cs_idx].disabled=account->disabled;
1175 client[cs_idx].c35_suppresscmd08 = account->c35_suppresscmd08;
1176 client[cs_idx].ncd_keepalive = account->ncd_keepalive;
1177 client[cs_idx].grp=account->grp;
1178 client[cs_idx].au=account->au;
1179 client[cs_idx].autoau=account->autoau;
1180 client[cs_idx].tosleep=(60*account->tosleep);
1181 memcpy(&client[cs_idx].ctab, &account->ctab, sizeof(client[cs_idx].ctab));
1182 if (account->uniq)
1183 cs_fake_client(account->usr, account->uniq, client[cs_idx].ip);
1184 client[cs_idx].ftab = account->ftab; // IDENT filter
1185 client[cs_idx].cltab = account->cltab; // CLASS filter
1186 client[cs_idx].fchid = account->fchid; // CHID filter
1187 client[cs_idx].sidtabok= account->sidtabok; // services
1188 client[cs_idx].sidtabno= account->sidtabno; // services
1189 client[cs_idx].pcrc = crc32(0L, MD5((uchar *)account->pwd, strlen(account->pwd), NULL), 16);
1190 memcpy(&client[cs_idx].ttab, &account->ttab, sizeof(client[cs_idx].ttab));
1191#ifdef CS_ANTICASC
1192 ac_init_client(account);
1193#endif
1194 }
1195 }
1196 client[cs_idx].monlvl=account->monlvl;
1197 strcpy(client[cs_idx].usr, account->usr);
1198 case -1: // anonymous grant access
1199 if (rc)
1200 t_grant=t_reject;
1201 else
1202 {
1203 if (client[cs_idx].typ=='m')
1204 sprintf(t_msg[0], "lvl=%d", client[cs_idx].monlvl);
1205 else
1206 {
1207 if(client[cs_idx].autoau)
1208 {
1209 if(client[cs_idx].ncd_server)
1210 {
1211 int r=0;
1212 for(r=0;r<CS_MAXREADER;r++)
1213 {
1214 if(reader[r].caid[0]==cfg->ncd_ptab.ports[client[cs_idx].port_idx].ftab.filts[0].caid)
1215 {
1216 client[cs_idx].au=r;
1217 break;
1218 }
1219 }
1220 if(client[cs_idx].au<0) sprintf(t_msg[0], "au(auto)=%d", client[cs_idx].au+1);
1221 else sprintf(t_msg[0], "au(auto)=%s", reader[client[cs_idx].au].label);
1222 }
1223 else
1224 {
1225 sprintf(t_msg[0], "au=auto");
1226 }
1227 }
1228 else
1229 {
1230 if(client[cs_idx].au<0) sprintf(t_msg[0], "au=%d", client[cs_idx].au+1);
1231 else sprintf(t_msg[0], "au=%s", reader[client[cs_idx].au].label);
1232 }
1233 }
1234 }
1235 if(client[cs_idx].ncd_server)
1236 {
1237 cs_log("%s %s:%d-client %s%s (%s, %s)",
1238 client[cs_idx].crypted ? t_crypt : t_plain,
1239 e_txt ? e_txt : ph[client[cs_idx].ctyp].desc,
1240 cfg->ncd_ptab.ports[client[cs_idx].port_idx].s_port,
1241 client[cs_idx].ip ? cs_inet_ntoa(client[cs_idx].ip) : "",
1242 client[cs_idx].ip ? t_grant : t_grant+1,
1243 username(cs_idx), t_msg[rc]);
1244 }
1245 else
1246 {
1247 cs_log("%s %s-client %s%s (%s, %s)",
1248 client[cs_idx].crypted ? t_crypt : t_plain,
1249 e_txt ? e_txt : ph[client[cs_idx].ctyp].desc,
1250 client[cs_idx].ip ? cs_inet_ntoa(client[cs_idx].ip) : "",
1251 client[cs_idx].ip ? t_grant : t_grant+1,
1252 username(cs_idx), t_msg[rc]);
1253 }
1254
1255 break;
1256 }
1257 return(rc);
1258}
1259
1260void cs_disconnect_client(void)
1261{
1262 char buf[32]={0};
1263 if (client[cs_idx].ip)
1264 sprintf(buf, " from %s", cs_inet_ntoa(client[cs_idx].ip));
1265 cs_log("%s disconnected%s", username(cs_idx), buf);
1266 cs_exit(0);
1267}
1268
1269int check_ecmcache(ECM_REQUEST *er, ulong grp)
1270{
1271 int i;
1272// cs_ddump(ecmd5, CS_ECMSTORESIZE, "ECM search");
1273//cs_log("cache CHECK: grp=%lX", grp);
1274 for(i=0; i<CS_ECMCACHESIZE; i++)
1275 if ((grp & ecmcache[i].grp) &&
1276 ecmcache[i].caid==er->caid &&
1277 (!memcmp(ecmcache[i].ecmd5, er->ecmd5, CS_ECMSTORESIZE)))
1278 {
1279//cs_log("cache found: grp=%lX cgrp=%lX", grp, ecmcache[i].grp);
1280 memcpy(er->cw, ecmcache[i].cw, 16);
1281 return(1);
1282 }
1283 return(0);
1284}
1285
1286static void store_ecm(ECM_REQUEST *er)
1287{
1288 int rc;
1289 rc=*ecmidx;
1290 *ecmidx=(*ecmidx+1) % CS_ECMCACHESIZE;
1291 //cs_log("store ecm from reader %d", er->reader[0]);
1292 memcpy(ecmcache[rc].ecmd5, er->ecmd5, CS_ECMSTORESIZE);
1293 memcpy(ecmcache[rc].cw, er->cw, 16);
1294 ecmcache[rc].caid=er->caid;
1295 ecmcache[rc].grp=reader[er->reader[0]].grp;
1296 //cs_ddump(ecmcache[*ecmidx].ecmd5, CS_ECMSTORESIZE, "ECM stored (idx=%d)", *ecmidx);
1297}
1298
1299void store_logentry(char *txt)
1300{
1301#ifdef CS_LOGHISTORY
1302 char *ptr;
1303 ptr=(char *)(loghist+(*loghistidx*CS_LOGHISTSIZE));
1304 ptr[0]='\1'; // make username unusable
1305 ptr[1]='\0';
1306 if ((client[cs_idx].typ=='c') || (client[cs_idx].typ=='m'))
1307 cs_strncpy(ptr, client[cs_idx].usr, 31);
1308 cs_strncpy(ptr+32, txt, CS_LOGHISTSIZE-33);
1309 *loghistidx=(*loghistidx+1) % CS_MAXLOGHIST;
1310#endif
1311}
1312
1313/*
1314 * write_to_pipe():
1315 * write all kind of data to pipe specified by fd
1316 */
1317int write_to_pipe(int fd, int id, uchar *data, int n)
1318{
1319 uchar buf[1024+3+sizeof(int)];
1320
1321//printf("WRITE_START pid=%d", getpid()); fflush(stdout);
1322 if ((id<0) || (id>PIP_ID_MAX))
1323 return(PIP_ID_ERR);
1324 memcpy(buf, PIP_ID_TXT[id], 3);
1325 memcpy(buf+3, &n, sizeof(int));
1326 memcpy(buf+3+sizeof(int), data, n);
1327 n+=3+sizeof(int);
1328//n=write(fd, buf, n);
1329//printf("WRITE_END pid=%d", getpid()); fflush(stdout);
1330//return(n);
1331 if( !fd )
1332 cs_log("write_to_pipe: fd==0");
1333 return(write(fd, buf, n));
1334}
1335
1336/*
1337 * read_from_pipe():
1338 * read all kind of data from pipe specified by fd
1339 * special-flag redir: if set AND data is ECM: this will redirected to appr. client
1340 */
1341int read_from_pipe(int fd, uchar **data, int redir)
1342{
1343 int rc;
1344 static int hdr=0;
1345 static uchar buf[1024+1+3+sizeof(int)];
1346
1347 *data=(uchar *)0;
1348 rc=PIP_ID_NUL;
1349
1350 if (!hdr)
1351 {
1352 if (bytes_available(fd))
1353 {
1354 if (read(fd, buf, 3+sizeof(int))==3+sizeof(int))
1355 memcpy(&hdr, buf+3, sizeof(int));
1356 else
1357 cs_log("WARNING: pipe header to small !");
1358 }
1359 }
1360 if (hdr)
1361 {
1362 int l;
1363 for (l=0; (rc<0) && (PIP_ID_TXT[l]); l++)
1364 if (!memcmp(buf, PIP_ID_TXT[l], 3))
1365 rc=l;
1366
1367 if (rc<0)
1368 {
1369 fprintf(stderr, "WARNING: pipe garbage");
1370 fflush(stderr);
1371 cs_log("WARNING: pipe garbage");
1372 rc=PIP_ID_ERR;
1373 }
1374 else
1375 {
1376 l=hdr;
1377 if ((l+3-1+sizeof(int))>sizeof(buf))
1378 {
1379 cs_log("WARNING: packet size (%d) to large", l);
1380 l=sizeof(buf)+3-1+sizeof(int);
1381 }
1382 if (!bytes_available(fd))
1383 return(PIP_ID_NUL);
1384 hdr=0;
1385 if (read(fd, buf+3+sizeof(int), l)==l)
1386 *data=buf+3+sizeof(int);
1387 else
1388 {
1389 cs_log("WARNING: pipe data to small !");
1390 return(PIP_ID_ERR);
1391 }
1392 buf[l+3+sizeof(int)]=0;
1393 if ((redir) && (rc==PIP_ID_ECM))
1394 {
1395 //int idx;
1396 ECM_REQUEST *er;
1397 er=(ECM_REQUEST *)(buf+3+sizeof(int));
1398 if( er->cidx && client[er->cidx].fd_m2c )
1399 if (!write(client[er->cidx].fd_m2c, buf, l+3+sizeof(int))) cs_exit(1);
1400 rc=PIP_ID_DIR;
1401 }
1402 }
1403 }
1404 return(rc);
1405}
1406
1407/*
1408 * write_ecm_request():
1409 */
1410int write_ecm_request(int fd, ECM_REQUEST *er)
1411{
1412 return(write_to_pipe(fd, PIP_ID_ECM, (uchar *) er, sizeof(ECM_REQUEST)));
1413}
1414
1415int write_ecm_DCW(int fd, ECM_REQUEST *er)
1416{
1417 return(write_to_pipe(fd, PIP_ID_DCW, (uchar *) er, sizeof(ECM_REQUEST)));
1418}
1419
1420/*
1421 * This function writes the current CW from ECM struct to a cwl file.
1422 * The filename is re-calculated and file re-opened every time.
1423 * This will consume a bit cpu time, but nothing has to be stored between
1424 * each call. If not file exists, a header is prepended
1425 */
1426void logCWtoFile(ECM_REQUEST *er)
1427{
1428 FILE *pfCWL;
1429 char srvname[128];
1430 /* %s / %s _I %04X _ %s .cwl */
1431 char buf[256 + sizeof(srvname)];
1432 char date[7];
1433 unsigned char i, parity, writeheader = 0;
1434 time_t t;
1435 struct tm *timeinfo;
1436 struct s_srvid *this;
1437
1438 /*
1439 * search service name for that id and change characters
1440 * causing problems in file name
1441 */
1442 srvname[0] = 0;
1443 for (this=cfg->srvid; this; this = this->next) {
1444 if (this->srvid == er->srvid) {
1445 cs_strncpy(srvname, this->name, sizeof(srvname));
1446 srvname[sizeof(srvname)-1] = 0;
1447 for (i = 0; srvname[i]; i++)
1448 if (srvname[i] == ' ') srvname[i] = '_';
1449 break;
1450 }
1451 }
1452
1453 /* calc log file name */
1454 time(&t);
1455 timeinfo = localtime(&t);
1456 strftime(date, sizeof(date), "%y%m%d", timeinfo);
1457 sprintf(buf, "%s/%s_I%04X_%s.cwl", cfg->cwlogdir, date, er->srvid, srvname);
1458
1459 /* open failed, assuming file does not exist, yet */
1460 if((pfCWL = fopen(buf, "r")) == NULL) {
1461 writeheader = 1;
1462 } else {
1463 /* we need to close the file if it was opened correctly */
1464 fclose(pfCWL);
1465 }
1466
1467 if ((pfCWL = fopen(buf, "a+")) == NULL) {
1468 /* maybe this fails because the subdir does not exist. Is there a common function to create it?
1469 for the moment do not print to log on every ecm
1470 cs_log(""error opening cw logfile for writing: %s (errno %d)", buf, errno); */
1471 return;
1472 }
1473 if (writeheader) {
1474 /* no global macro for cardserver name :( */
1475 fprintf(pfCWL, "# OSCam cardserver v%s - http://streamboard.gmc.to:8001/oscam/wiki\n", CS_VERSION_X);
1476 fprintf(pfCWL, "# control word log file for use with tsdec offline decrypter\n");
1477 strftime(buf, sizeof(buf),"DATE %Y-%m-%d, TIME %H:%M:%S, TZ %Z\n", timeinfo);
1478 fprintf(pfCWL, "# %s", buf);
1479 fprintf(pfCWL, "# CAID 0x%04X, SID 0x%04X, SERVICE \"%s\"\n", er->caid, er->srvid, srvname);
1480 }
1481
1482 parity = er->ecm[0]&1;
1483 fprintf(pfCWL, "%d ", parity);
1484 for (i = parity * 8; i < 8 + parity * 8; i++)
1485 fprintf(pfCWL, "%02X ", er->cw[i]);
1486 /* better use incoming time er->tps rather than current time? */
1487 strftime(buf,sizeof(buf),"%H:%M:%S\n", timeinfo);
1488 fprintf(pfCWL, "# %s", buf);
1489 fflush(pfCWL);
1490 fclose(pfCWL);
1491}
1492
1493int write_ecm_answer(int fd, ECM_REQUEST *er)
1494{
1495 int i;
1496 uchar c;
1497 for (i=0; i<16; i+=4)
1498 {
1499 c=((er->cw[i]+er->cw[i+1]+er->cw[i+2]) & 0xff);
1500 if (er->cw[i+3]!=c)
1501 {
1502 cs_debug("notice: changed dcw checksum byte cw[%i] from %02x to %02x", i+3, er->cw[i+3],c);
1503 er->cw[i+3]=c;
1504 }
1505 }
1506
1507 er->reader[0]=ridx;
1508//cs_log("answer from reader %d (rc=%d)", er->reader[0], er->rc);
1509 er->caid=er->ocaid;
1510
1511#ifdef CS_WITH_GBOX
1512 if (er->rc==1||(er->gbxRidx&&er->rc==0)) {
1513#else
1514 if (er->rc==1) {
1515#endif
1516 store_ecm(er);
1517
1518 /* CWL logging only if cwlogdir is set in config */
1519 if (cfg->cwlogdir != NULL)
1520 logCWtoFile(er);
1521 }
1522
1523 return(write_ecm_request(fd, er));
1524}
1525/*
1526static int cs_read_timer(int fd, uchar *buf, int l, int msec)
1527{
1528 struct timeval tv;
1529 fd_set fds;
1530 int rc;
1531
1532 if (!fd) return(-1);
1533 tv.tv_sec = msec / 1000;
1534 tv.tv_usec = (msec % 1000) * 1000;
1535 FD_ZERO(&fds);
1536 FD_SET(pfd, &fds);
1537
1538 select(fd+1, &fds, 0, 0, &tv);
1539
1540 rc=0;
1541 if (FD_ISSET(pfd, &fds))
1542 if (!(rc=read(fd, buf, l)))
1543 rc=-1;
1544
1545 return(rc);
1546}*/
1547
1548ECM_REQUEST *get_ecmtask()
1549{
1550 int i, n;
1551 ECM_REQUEST *er=0;
1552
1553 if (!ecmtask)
1554 {
1555 n=(ph[client[cs_idx].ctyp].multi)?CS_MAXPENDING:1;
1556 if( (ecmtask=(ECM_REQUEST *)malloc(n*sizeof(ECM_REQUEST))) )
1557 memset(ecmtask, 0, n*sizeof(ECM_REQUEST));
1558 }
1559
1560 n=(-1);
1561 if (!ecmtask)
1562 {
1563 cs_log("Cannot allocate memory (errno=%d)", errno);
1564 n=(-2);
1565 }
1566 else
1567 if (ph[client[cs_idx].ctyp].multi)
1568 {
1569 for (i=0; (n<0) && (i<CS_MAXPENDING); i++)
1570 if (ecmtask[i].rc<100)
1571 er=&ecmtask[n=i];
1572 }
1573 else
1574 er=&ecmtask[n=0];
1575
1576 if (n<0)
1577 cs_log("WARNING: ecm pending table overflow !");
1578 else
1579 {
1580 memset(er, 0, sizeof(ECM_REQUEST));
1581 er->rc=100;
1582 er->cpti=n;
1583 er->cidx=cs_idx;
1584 cs_ftime(&er->tps);
1585 }
1586 return(er);
1587}
1588
1589int send_dcw(ECM_REQUEST *er)
1590{
1591 static char *stxt[]={"found", "cache1", "cache2", "emu",
1592 "not found", "timeout", "sleeping",
1593 "fake", "invalid", "corrupt", "no card", "expdate", "disabled"};
1594 static char *stxtEx[]={"", "group", "caid", "ident", "class", "chid", "queue", "peer"};
1595 static char *stxtWh[]={"", "user ", "reader ", "server ", "lserver "};
1596 char sby[32]="";
1597 char erEx[32]="";
1598 char uname[38]="";
1599 struct timeb tpe;
1600 ushort lc, *lp;
1601 for (lp=(ushort *)er->ecm+(er->l>>2), lc=0; lp>=(ushort *)er->ecm; lp--)
1602 lc^=*lp;
1603 cs_ftime(&tpe);
1604
1605#ifdef CS_WITH_GBOX
1606 if(er->gbxFrom)
1607 snprintf(uname,sizeof(uname)-1, "%s(%04X)", username(cs_idx), er->gbxFrom);
1608 else
1609#endif
1610 snprintf(uname,sizeof(uname)-1, "%s", username(cs_idx));
1611 if (er->rc==0)
1612 {
1613#ifdef CS_WITH_GBOX
1614 if(reader[er->reader[0]].typ==R_GBOX)
1615 snprintf(sby, sizeof(sby)-1, " by %s(%04X)", reader[er->reader[0]].label,er->gbxCWFrom);
1616 else
1617#endif
1618 // add marker to reader if ECM_REQUEST was betatunneled
1619 if(er->btun)
1620 snprintf(sby, sizeof(sby)-1, " by %s(btun)", reader[er->reader[0]].label);
1621 else
1622 snprintf(sby, sizeof(sby)-1, " by %s", reader[er->reader[0]].label);
1623 }
1624 if (er->rc<4) er->rcEx=0;
1625 if (er->rcEx)
1626 snprintf(erEx, sizeof(erEx)-1, "rejected %s%s", stxtWh[er->rcEx>>4],
1627 stxtEx[er->rcEx&0xf]);
1628
1629 client[cs_idx].cwlastresptime = 1000*(tpe.time-er->tps.time)+tpe.millitm-er->tps.millitm;
1630
1631 cs_log("%s (%04X&%06X/%04X/%02X:%04X): %s (%d ms)%s",
1632 uname, er->caid, er->prid, er->srvid, er->l, lc,
1633 er->rcEx?erEx:stxt[er->rc], client[cs_idx].cwlastresptime, sby);
1634
1635
1636 if(!client[cs_idx].ncd_server && client[cs_idx].autoau && er->rcEx==0)
1637 {
1638 if(client[cs_idx].au>=0 && er->caid!=reader[client[cs_idx].au].caid[0])
1639 {
1640 client[cs_idx].au=(-1);
1641 }
1642
1643 client[cs_idx].au=er->reader[0];
1644 if(client[cs_idx].au<0)
1645 {
1646 int r=0;
1647 for(r=0;r<CS_MAXREADER;r++)
1648 {
1649 if(er->caid==reader[r].caid[0])
1650 {
1651 client[cs_idx].au=r;
1652 break;
1653 }
1654 }
1655 if(r==CS_MAXREADER)
1656 {
1657 client[cs_idx].au=(-1);
1658 }
1659 }
1660 }
1661
1662 er->caid=er->ocaid;
1663 switch(er->rc)
1664 {
1665 case 0:
1666 case 3:
1667 // 0 - found
1668 // 3 - emu FIXME: obsolete ?
1669 client[cs_idx].cwfound++;
1670 break;
1671
1672 case 1:
1673 case 2:
1674 // 1 - cache1
1675 // 2 - cache2
1676 client[cs_idx].cwcache++;
1677 break;
1678
1679 case 4:
1680 case 9:
1681 case 10:
1682 // 4 - not found
1683 // 9 - corrupt
1684 // 10 - no card
1685 if (er->rcEx)
1686 client[cs_idx].cwignored++;
1687 else
1688 client[cs_idx].cwnot++;
1689 break;
1690
1691 case 5:
1692 // 5 - timeout
1693 client[cs_idx].cwtout++;
1694 break;
1695
1696 default:
1697 client[cs_idx].cwignored++;
1698 }
1699
1700#ifdef CS_ANTICASC
1701 ac_chk(er, 1);
1702#endif
1703
1704 cs_ddump_mask (D_ATR, er->cw, 16, "cw:");
1705 if (er->rc==7) er->rc=0;
1706 ph[client[cs_idx].ctyp].send_dcw(er);
1707 return 0;
1708}
1709
1710void chk_dcw(int fd)
1711{
1712 ECM_REQUEST *er, *ert;
1713 if (read_from_pipe(fd, (uchar **)&er, 0)!=PIP_ID_ECM)
1714 return;
1715 //cs_log("dcw check from reader %d for idx %d (rc=%d)", er->reader[0], er->cpti, er->rc);
1716 ert=&ecmtask[er->cpti];
1717 if (ert->rc<100)
1718 return; // already done
1719 if( (er->caid!=ert->caid) || memcmp(er->ecm , ert->ecm , sizeof(er->ecm)) )
1720 return; // obsolete
1721 ert->rcEx=er->rcEx;
1722 if (er->rc>0) // found
1723 {
1724 switch(er->rc)
1725 {
1726 case 2:
1727 ert->rc=2;
1728 break;
1729 case 3:
1730 ert->rc=3;
1731 break;
1732 default:
1733 ert->rc=0;
1734 }
1735 ert->rcEx=0;
1736 ert->reader[0]=er->reader[0];
1737 memcpy(ert->cw , er->cw , sizeof(er->cw));
1738#ifdef CS_WITH_GBOX
1739 ert->gbxCWFrom=er->gbxCWFrom;
1740#endif
1741 }
1742 else // not found (from ONE of the readers !)
1743 {
1744 int i;
1745 ert->reader[er->reader[0]]=0;
1746 for (i=0; (ert) && (i<CS_MAXREADER); i++)
1747 if (ert->reader[i]) // we have still another chance
1748 ert=(ECM_REQUEST *)0;
1749 if (ert) ert->rc=4;
1750 }
1751 if (ert) send_dcw(ert);
1752 return;
1753}
1754
1755ulong chk_provid(uchar *ecm, ushort caid)
1756{
1757 int i;
1758 ulong provid=0;
1759 switch(caid)
1760 {
1761 case 0x100: // seca
1762 provid=b2i(2, ecm+3);
1763 break;
1764 case 0x500: // viaccess
1765 i=(ecm[4]==0xD2) ? ecm[5] + 2 : 0; // skip d2 nano
1766 if ((ecm[5+i]==3) && ((ecm[4+i]==0x90) || (ecm[4+i]==0x40)))
1767 provid=(b2i(3, ecm+6+i) & 0xFFFFF0);
1768 default:
1769 // cryptoworks ?
1770 if( caid&0x0d00 && ecm[8]==0x83 && ecm[9]==1 )
1771 provid=(ulong)ecm[10];
1772 }
1773 return(provid);
1774}
1775
1776#ifdef IRDETO_GUESSING
1777void guess_irdeto(ECM_REQUEST *er)
1778{
1779 uchar b3;
1780 int b47;
1781 //ushort chid;
1782 struct s_irdeto_quess *ptr;
1783
1784 b3 = er->ecm[3];
1785 ptr = cfg->itab[b3];
1786 if( !ptr ) {
1787 cs_debug("unknown irdeto byte 3: %02X", b3);
1788 return;
1789 }
1790 b47 = b2i(4, er->ecm+4);
1791 //chid = b2i(2, er->ecm+6);
1792 //cs_debug("ecm: b47=%08X, ptr->b47=%08X, ptr->caid=%04X", b47, ptr->b47, ptr->caid);
1793 while( ptr )
1794 {
1795 if( b47==ptr->b47 )
1796 {
1797 if( er->srvid && (er->srvid!=ptr->sid) )
1798 {
1799 cs_debug("sid mismatched (ecm: %04X, guess: %04X), wrong oscam.ird file?",
1800 er->srvid, ptr->sid);
1801 return;
1802 }
1803 er->caid=ptr->caid;
1804 er->srvid=ptr->sid;
1805 er->chid=(ushort)ptr->b47;
1806// cs_debug("quess_irdeto() found caid=%04X, sid=%04X, chid=%04X",
1807// er->caid, er->srvid, er->chid);
1808 return;
1809 }
1810 ptr=ptr->next;
1811 }
1812}
1813#endif
1814
1815void cs_betatunnel(ECM_REQUEST *er)
1816{
1817 int n;
1818 ulong mask_all = 0xFFFF;
1819 TUNTAB *ttab;
1820 ttab = &client[cs_idx].ttab;
1821 for (n = 0; (n < CS_MAXTUNTAB); n++) {
1822 if ((er->caid==ttab->bt_caidfrom[n]) && ((er->srvid==ttab->bt_srvid[n]) || (ttab->bt_srvid[n])==mask_all)) {
1823 uchar hack_n3[13] = {0x70, 0x51, 0xc7, 0x00, 0x00, 0x00, 0x01, 0x10, 0x10, 0x00, 0x87, 0x12, 0x07};
1824 uchar hack_n2[13] = {0x70, 0x51, 0xc9, 0x00, 0x00, 0x00, 0x01, 0x10, 0x10, 0x00, 0x48, 0x12, 0x07};
1825 er->caid = ttab->bt_caidto[n];
1826 er->prid = 0;
1827 er->l = (er->ecm[2]+3);
1828 memmove(er->ecm+14, er->ecm+4, er->l-1);
1829 if (er->l > 0x88) {
1830 memcpy(er->ecm+1, hack_n3, 13);
1831 if (er->ecm[0] == 0x81)
1832 er->ecm[12] += 1;
1833 }
1834 else {
1835 memcpy(er->ecm+1, hack_n2, 13);
1836 }
1837 er->l += 10;
1838 er->ecm[2] = er->l-3;
1839 er->btun = 1;
1840 client[cs_idx].cwtun++;
1841 cs_debug("ECM converted from: 0x%X to BetaCrypt: 0x%X for service id:0x%X",
1842 ttab->bt_caidfrom[n], ttab->bt_caidto[n], ttab->bt_srvid[n]);
1843 }
1844 }
1845}
1846
1847void guess_cardsystem(ECM_REQUEST *er)
1848{
1849 ushort last_hope=0;
1850
1851 // viaccess - check by provid-search
1852 if( (er->prid=chk_provid(er->ecm, 0x500)) )
1853 er->caid=0x500;
1854
1855 // nagra
1856 // is ecm[1] always 0x30 ?
1857 // is ecm[3] always 0x07 ?
1858 if ((er->ecm[6]==1) && (er->ecm[4]==er->ecm[2]-2))
1859 er->caid=0x1801;
1860
1861 // seca2 - very poor
1862 if ((er->ecm[8]==0x10) && ((er->ecm[9]&0xF1)==1))
1863 last_hope=0x100;
1864
1865 // is cryptoworks, but which caid ?
1866 if ((er->ecm[3]==0x81) && (er->ecm[4]==0xFF) &&
1867 (!er->ecm[5]) && (!er->ecm[6]) && (er->ecm[7]==er->ecm[2]-5))
1868 last_hope=0xd00;
1869
1870#ifdef IRDETO_GUESSING
1871 if (!er->caid && er->ecm[2]==0x31 && er->ecm[0x0b]==0x28)
1872 guess_irdeto(er);
1873#endif
1874
1875 if (!er->caid) // guess by len ..
1876 er->caid=len4caid[er->ecm[2]+3];
1877
1878 if (!er->caid)
1879 er->caid=last_hope;
1880}
1881
1882void request_cw(ECM_REQUEST *er, int flag, int reader_types)
1883{
1884 int i;
1885 if ((reader_types == 0) || (reader_types == 2))
1886 er->level=flag;
1887 flag=(flag)?3:1; // flag specifies with/without fallback-readers
1888 for (i=0; i<CS_MAXREADER; i++)
1889 {
1890 switch (reader_types)
1891 {
1892 // network and local cards
1893 default:
1894 case 0:
1895 if (er->reader[i]&flag){
1896 write_ecm_request(reader[i].fd, er);
1897 }
1898 break;
1899 // only local cards
1900 case 1:
1901 if (!(reader[i].typ & R_IS_NETWORK))
1902 if (er->reader[i]&flag)
1903 write_ecm_request(reader[i].fd, er);
1904 break;
1905 // only network
1906 case 2:
1907 if ((reader[i].typ & R_IS_NETWORK))
1908 if (er->reader[i]&flag)
1909 write_ecm_request(reader[i].fd, er);
1910 break;
1911 }
1912 }
1913}
1914
1915void get_cw(ECM_REQUEST *er)
1916{
1917 int i, j, m;
1918 time_t now = time((time_t)0);
1919
1920 client[cs_idx].lastecm = now;
1921
1922 if (!er->caid)
1923 guess_cardsystem(er);
1924
1925 /* Quickfix Area */
1926
1927 if( (er->caid & 0xFF00) == 0x600 && !er->chid )
1928 er->chid = (er->ecm[6]<<8)|er->ecm[7];
1929
1930 // quickfix for 0100:000065
1931 if (er->caid == 0x100 && er->prid == 0x65 && er->srvid == 0)
1932 er->srvid = 0x0642;
1933
1934 // Quickfixes for Opticum/Globo HD9500
1935 // Quickfix for 0500:030300
1936 if (er->caid == 0x500 && er->prid == 0x030300)
1937 er->prid = 0x030600;
1938
1939 // Quickfix for 0500:D20200
1940 if (er->caid == 0x500 && er->prid == 0xD20200)
1941 er->prid = 0x030600;
1942
1943 /* END quickfixes */
1944
1945 if (!er->prid)
1946 er->prid = chk_provid(er->ecm, er->caid);
1947
1948 // Set providerid for newcamd clients if none is given
1949 if( (!er->prid) && client[cs_idx].ncd_server ) {
1950 int pi = client[cs_idx].port_idx;
1951 if( pi >= 0 && cfg->ncd_ptab.nports && cfg->ncd_ptab.nports >= pi )
1952 er->prid = cfg->ncd_ptab.ports[pi].ftab.filts[0].prids[0];
1953 }
1954
1955 // CAID not supported or found
1956 if (!er->caid) {
1957 er->rc = 8;
1958 er->rcEx = E2_CAID;
1959 }
1960
1961 // user expired
1962 if(client[cs_idx].expirationdate && client[cs_idx].expirationdate < client[cs_idx].lastecm)
1963 er->rc = 11;
1964
1965 // user disabled
1966 if(client[cs_idx].disabled != 0)
1967 er->rc = 12;
1968
1969 // rc<100 -> ecm error
1970 if (er->rc > 99) {
1971
1972 m = er->caid;
1973 er->ocaid = er->caid;
1974 i = er->srvid;
1975
1976 if ((i != client[cs_idx].last_srvid) || (!client[cs_idx].lastswitch)) {
1977 client[cs_idx].lastswitch = now;
1978 if(cfg->usrfileflag)
1979 cs_statistics(cs_idx);
1980 }
1981
1982 // user sleeping
1983 if ((client[cs_idx].tosleep) && (now - client[cs_idx].lastswitch > client[cs_idx].tosleep))
1984 er->rc = 6;
1985
1986 client[cs_idx].last_srvid = i;
1987 client[cs_idx].last_caid = m;
1988
1989 for (j = 0; (j < 6) && (er->rc > 99); j++)
1990 {
1991 switch(j) {
1992
1993 case 0:
1994 // fake (uniq)
1995 if (client[cs_idx].dup)
1996 er->rc = 7;
1997 break;
1998
1999 case 1:
2000 // invalid (caid)
2001 if (!chk_bcaid(er, &client[cs_idx].ctab)) {
2002 er->rc = 8;
2003 er->rcEx = E2_CAID;
2004 }
2005 break;
2006
2007 case 2:
2008 // invalid (srvid)
2009 if (!chk_srvid(er, cs_idx))
2010 er->rc = 8;
2011 break;
2012
2013 case 3:
2014 // invalid (ufilters)
2015 if (!chk_ufilters(er))
2016 er->rc = 8;
2017 break;
2018
2019 case 4:
2020 // invalid (sfilter)
2021 if (!chk_sfilter(er, ph[client[cs_idx].ctyp].ptab))
2022 er->rc = 8;
2023 break;
2024
2025 case 5:
2026 // corrupt
2027 if( (i = er->l - (er->ecm[2] + 3)) ) {
2028 if (i > 0) {
2029 cs_debug("warning: ecm size adjusted from 0x%X to 0x%X",
2030 er->l, er->ecm[2] + 3);
2031 er->l = (er->ecm[2] + 3);
2032 }
2033 else
2034 er->rc = 9;
2035 }
2036 break;
2037 }
2038 }
2039
2040 /*BetaCrypt tunneling
2041 *moved behind the check routines,
2042 *because newcamd ECM will fail
2043 *if ECM is converted before
2044 */
2045 if (&client[cs_idx].ttab)
2046 cs_betatunnel(er);
2047
2048 // store ECM in cache
2049 memcpy(er->ecmd5, MD5(er->ecm, er->l, NULL), CS_ECMSTORESIZE);
2050
2051 // cache1
2052 if (check_ecmcache(er, client[cs_idx].grp))
2053 er->rc = 1;
2054
2055#ifdef CS_ANTICASC
2056 ac_chk(er, 0);
2057#endif
2058 }
2059
2060 if(er->rc > 99 && er->rc != 1) {
2061
2062 for (i = m = 0; i < CS_MAXREADER; i++)
2063 if (matching_reader(er, &reader[i]) && (i != ridx))
2064 m|=er->reader[i] = (reader[i].fallback)? 2: 1;
2065
2066 switch(m) {
2067
2068 // no reader -> not found
2069 case 0:
2070 er->rc = 4;
2071 if (!er->rcEx)
2072 er->rcEx = E2_GROUP;
2073 break;
2074
2075 // fallbacks only, switch them
2076 case 2:
2077 for (i = 0; i < CS_MAXREADER; i++)
2078 er->reader[i]>>=1;
2079 }
2080 }
2081
2082 if (er->rc < 100) {
2083 if (cfg->delay)
2084 cs_sleepms(cfg->delay);
2085
2086 send_dcw(er);
2087 return;
2088 }
2089
2090 er->rcEx = 0;
2091 request_cw(er, 0, cfg->preferlocalcards ? 1 : 0);
2092}
2093
2094void log_emm_request(int auidx)
2095{
2096// cs_log("%s send emm-request (reader=%s, caid=%04X)",
2097// cs_inet_ntoa(client[cs_idx].ip), reader[auidx].label, reader[auidx].caid[0]);
2098 cs_log("%s emm-request sent (reader=%s, caid=%04X)",
2099 username(cs_idx), reader[auidx].label, reader[auidx].caid[0]);
2100}
2101
2102void do_emm(EMM_PACKET *ep)
2103{
2104 int au;//, ephs;
2105 au=client[cs_idx].au;
2106
2107 if ((au<0) || (au>=CS_MAXREADER))
2108 return;
2109 client[cs_idx].lastemm=time((time_t)0);
2110 cs_debug_mask(D_EMM,"reader %s has serial %s.", reader[au].label, cs_hexdump(0, reader[au].hexserial, 8));
2111 cs_ddump_mask(D_EMM, ep->hexserial, 8, "emm UA:");
2112 cs_ddump_mask(D_EMM, ep->emm, ep->l, "emm:");
2113// if ((!reader[au].fd) || (reader[au].b_nano[ep->emm[3]])) // blocknano is obsolete
2114 if ((!reader[au].fd) || // reader has no fd
2115 (reader[au].caid[0]!=b2i(2,ep->caid)) || // wrong caid
2116 (memcmp(reader[au].hexserial, ep->hexserial, 8))) /* wrong serial*/ {
2117#ifdef WEBIF
2118 client[cs_idx].emmnok++;
2119#endif
2120 return;
2121 }
2122#ifdef WEBIF
2123 client[cs_idx].emmok++;
2124#endif
2125 ep->cidx=cs_idx;
2126 write_to_pipe(reader[au].fd, PIP_ID_EMM, (uchar *) ep, sizeof(EMM_PACKET));
2127}
2128
2129static int comp_timeb(struct timeb *tpa, struct timeb *tpb)
2130{
2131 if (tpa->time>tpb->time) return(1);
2132 if (tpa->time<tpb->time) return(-1);
2133 if (tpa->millitm>tpb->millitm) return(1);
2134 if (tpa->millitm<tpb->millitm) return(-1);
2135 return(0);
2136}
2137
2138static void build_delay(struct timeb *tpe, struct timeb *tpc)
2139{
2140 if (comp_timeb(tpe, tpc)>0)
2141 {
2142 tpe->time=tpc->time;
2143 tpe->millitm=tpc->millitm;
2144 }
2145}
2146
2147struct timeval *chk_pending(struct timeb tp_ctimeout)
2148{
2149 int i;
2150 ulong td;
2151 struct timeb tpn, tpe, tpc; // <n>ow, <e>nd, <c>heck
2152 static struct timeval tv;
2153
2154 ECM_REQUEST *er;
2155 cs_ftime(&tpn);
2156 tpe=tp_ctimeout; // latest delay -> disconnect
2157
2158 if (ecmtask)
2159 i=(ph[client[cs_idx].ctyp].multi)?CS_MAXPENDING:1;
2160 else
2161 i=0;
2162//cs_log("num pend=%d", i);
2163 for (--i; i>=0; i--)
2164 if (ecmtask[i].rc>=100) // check all pending ecm-requests
2165 {
2166 int act, j;
2167 er=&ecmtask[i];
2168 tpc=er->tps;
2169 tpc.millitm += (er->stage) ? cfg->ctimeout : cfg->ftimeout;
2170 tpc.time += tpc.millitm / 1000;
2171 tpc.millitm = tpc.millitm % 1000;
2172 if (!er->stage)
2173 {
2174 for (j=0, act=1; (act) && (j<CS_MAXREADER); j++)
2175 {
2176 if (cfg->preferlocalcards && !er->locals_done)
2177 {
2178 if ((er->reader[j]&1) && !(reader[j].typ & R_IS_NETWORK))
2179 act=0;
2180 }
2181 else if (cfg->preferlocalcards && er->locals_done)
2182 {
2183 if ((er->reader[j]&1) && (reader[j].typ & R_IS_NETWORK))
2184 act=0;
2185 }
2186 else
2187 {
2188 if (er->reader[j]&1)
2189 act=0;
2190 }
2191 }
2192//cs_log("stage 0, act=%d r0=%d, r1=%d, r2=%d, r3=%d, r4=%d r5=%d", act,
2193// er->reader[0], er->reader[1], er->reader[2],
2194// er->reader[3], er->reader[4], er->reader[5]);
2195 if (act)
2196 {
2197 int inc_stage = 1;
2198
2199 if (cfg->preferlocalcards && !er->locals_done)
2200 {
2201 int i;
2202
2203 er->locals_done = 1;
2204 for (i = 0; i < CS_MAXREADER; i++)
2205 {
2206 if (reader[i].typ & R_IS_NETWORK)
2207 {
2208 inc_stage = 0;
2209 }
2210 }
2211 }
2212 if (!inc_stage)
2213 {
2214 request_cw(er, er->stage, 2);
2215 tpc.millitm += 1000 * (tpn.time - er->tps.time) + tpn.millitm - er->tps.millitm;
2216 tpc.time += tpc.millitm / 1000;
2217 tpc.millitm = tpc.millitm % 1000;
2218 }
2219 else
2220 {
2221 er->locals_done = 0;
2222 er->stage++;
2223 request_cw(er, er->stage, cfg->preferlocalcards ? 1 : 0);
2224
2225 tpc.millitm += (cfg->ctimeout-cfg->ftimeout);
2226 tpc.time += tpc.millitm / 1000;
2227 tpc.millitm = tpc.millitm % 1000;
2228 }
2229 }
2230 }
2231 if (comp_timeb(&tpn, &tpc)>0) // action needed
2232 {
2233//cs_log("Action now %d.%03d", tpn.time, tpn.millitm);
2234//cs_log(" %d.%03d", tpc.time, tpc.millitm);
2235 if (er->stage)
2236 {
2237 er->rc=5; // timeout
2238 send_dcw(er);
2239 continue;
2240 }
2241 else
2242 {
2243 er->stage++;
2244 request_cw(er, er->stage, 0);
2245 tpc.millitm += (cfg->ctimeout-cfg->ftimeout);
2246 tpc.time += tpc.millitm / 1000;
2247 tpc.millitm = tpc.millitm % 1000;
2248 }
2249 }
2250 build_delay(&tpe, &tpc);
2251 }
2252 td=(tpe.time-tpn.time)*1000+(tpe.millitm-tpn.millitm)+5;
2253 tv.tv_sec = td/1000;
2254 tv.tv_usec = (td%1000)*1000;
2255//cs_log("delay %d.%06d", tv.tv_sec, tv.tv_usec);
2256 return(&tv);
2257}
2258
2259int process_input(uchar *buf, int l, int timeout)
2260{
2261 int rc;
2262 fd_set fds;
2263 struct timeb tp;
2264
2265 if (master_pid!=getppid()) cs_exit(0);
2266 if (!pfd) return(-1);
2267 cs_ftime(&tp);
2268 tp.time+=timeout;
2269 if (ph[client[cs_idx].ctyp].watchdog)
2270 alarm(cfg->cmaxidle + (cfg->ctimeout + 500) / 1000 + 1);
2271 while (1)
2272 {
2273 FD_ZERO(&fds);
2274 FD_SET(pfd, &fds);
2275 FD_SET(fd_m2c, &fds);
2276
2277 rc=select(((pfd>fd_m2c)?pfd:fd_m2c)+1, &fds, 0, 0, chk_pending(tp));
2278 if (master_pid!=getppid()) cs_exit(0);
2279 if (rc<0)
2280 {
2281 if (errno==EINTR) continue;
2282 else return(0);
2283 }
2284
2285 if (FD_ISSET(fd_m2c, &fds)) // read from pipe
2286 chk_dcw(fd_m2c);
2287
2288 if (FD_ISSET(pfd, &fds)) // read from client
2289 {
2290 rc=ph[client[cs_idx].ctyp].recv(buf, l);
2291 break;
2292 }
2293 if (tp.time<=time((time_t *)0)) // client maxidle reached
2294 {
2295 rc=(-9);
2296 break;
2297 }
2298 }
2299 if (ph[client[cs_idx].ctyp].watchdog)
2300 alarm(cfg->cmaxidle + (cfg->ctimeout + 500) / 1000 + 1);
2301 return(rc);
2302}
2303
2304static void process_master_pipe()
2305{
2306 int n;
2307 uchar *ptr;
2308
2309 switch(n=read_from_pipe(mfdr, &ptr, 1))
2310 {
2311 case PIP_ID_LOG:
2312 cs_write_log((char *)ptr);
2313 break;
2314 case PIP_ID_HUP:
2315 cs_accounts_chk();
2316 break;
2317 }
2318}
2319
2320void cs_log_config()
2321{
2322 uchar buf[2048];
2323
2324 if (cfg->nice!=99)
2325 sprintf((char *)buf, ", nice=%d", cfg->nice);
2326 else
2327 buf[0]='\0';
2328 cs_log("version=%s, build #%s, system=%s%s", CS_VERSION_X, CS_SVN_VERSION, cs_platform((char *)buf+64), buf);
2329 cs_log("max. clients=%d, client max. idle=%d sec",
2330#ifdef CS_ANTICASC
2331 CS_MAXPID-3, cfg->cmaxidle);
2332#else
2333 CS_MAXPID-2, cfg->cmaxidle);
2334#endif
2335 if( cfg->max_log_size )
2336 sprintf((char *)buf, "%d Kb", cfg->max_log_size);
2337 else
2338 strcpy((char *)buf, "unlimited");
2339 cs_log("max. logsize=%s", buf);
2340 cs_log("client timeout=%lu ms, fallback timeout=%lu ms, cache delay=%d ms",
2341 cfg->ctimeout, cfg->ftimeout, cfg->delay);
2342#ifdef CS_NOSHM
2343 cs_log("shared memory initialized (size=%d, fd=%d)", shmsize, shmid);
2344#else
2345 cs_log("shared memory initialized (size=%d, id=%d)", shmsize, shmid);
2346#endif
2347}
2348
2349int main (int argc, char *argv[])
2350{
2351 struct sockaddr_in cad; /* structure to hold client's address */
2352 int scad; /* length of address */
2353 //int fd; /* socket descriptors */
2354 int i, j, n;
2355 int bg=0;
2356 int gfd; //nph,
2357 int fdp[2];
2358 uchar buf[2048];
2359 void (*mod_def[])(struct s_module *)=
2360 {
2361 module_monitor,
2362 module_camd33,
2363 module_camd35,
2364 module_camd35_tcp,
2365 module_newcamd,
2366 module_cccam,
2367#ifdef CS_WITH_GBOX
2368 module_gbox,
2369#endif
2370 module_radegast,
2371 module_oscam_ser,
2372#ifdef HAVE_DVBAPI
2373 module_dvbapi,
2374#endif
2375 0
2376 };
2377
2378 while ((i=getopt(argc, argv, "bc:d:hm:"))!=EOF)
2379 {
2380 switch(i)
2381 {
2382 case 'b': bg=1;
2383 break;
2384 case 'c': cs_strncpy(cs_confdir, optarg, sizeof(cs_confdir));
2385 break;
2386 case 'd': cs_dblevel=atoi(optarg);
2387 break;
2388 case 'm':
2389#ifdef CS_NOSHM
2390 cs_strncpy(cs_memfile, optarg, sizeof(cs_memfile));
2391 break;
2392#endif
2393 case 'h':
2394 default : usage();
2395 }
2396 }
2397 if (cs_confdir[strlen(cs_confdir)]!='/') strcat(cs_confdir, "/");
2398 init_shm();
2399 init_config();
2400 cfg->debuglvl = cs_dblevel; // give static debuglevel to outer world
2401 for (i=0; mod_def[i]; i++) // must be later BEFORE init_config()
2402 {
2403 memset(&ph[i], 0, sizeof(struct s_module));
2404 mod_def[i](&ph[i]);
2405 }
2406
2407 cs_log("auth size=%d", sizeof(struct s_auth));
2408
2409 init_sidtab();
2410 init_readerdb();
2411 init_userdb();
2412 init_signal();
2413 cs_set_mloc(30, "init");
2414 init_srvid();
2415 init_len4caid();
2416#ifdef IRDETO_GUESSING
2417 init_irdeto_guess_tab();
2418#endif
2419 cs_init_statistics(cfg->usrfile);
2420
2421 if (pipe(fdp))
2422 {
2423 cs_log("Cannot create pipe (errno=%d)", errno);
2424 cs_exit(1);
2425 }
2426 mfdr=fdp[0];
2427 fd_c2m=fdp[1];
2428 gfd=mfdr+1;
2429
2430#ifdef OS_MACOSX
2431 if (bg && daemon_compat(1,0))
2432#else
2433 if (bg && daemon(1,0))
2434#endif
2435 {
2436 cs_log("Error starting in background (errno=%d)", errno);
2437 cs_exit(1);
2438 }
2439 master_pid=client[0].pid=getpid();
2440 if (cfg->pidfile != NULL)
2441 {
2442 FILE *fp;
2443 if (!(fp=fopen(cfg->pidfile, "w")))
2444 {
2445 cs_log("Cannot open pid-file (errno=%d)", errno);
2446 cs_exit(1);
2447 }
2448 fprintf(fp, "%d\n", getpid());
2449 fclose(fp);
2450 }
2451
2452 for (i=0; i<CS_MAX_MOD; i++)
2453 if( (ph[i].type & MOD_CONN_NET) && ph[i].ptab )
2454 for(j=0; j<ph[i].ptab->nports; j++)
2455 {
2456 start_listener(&ph[i], j);
2457 if( ph[i].ptab->ports[j].fd+1>gfd )
2458 gfd=ph[i].ptab->ports[j].fd+1;
2459 }
2460
2461 //set time for server to now to avoid 0 in monitor/webif
2462 client[0].last=time((time_t *)0);
2463
2464 start_client_resolver();
2465 init_service(97); // logger
2466 init_service(98); // resolver
2467#ifdef WEBIF
2468 init_service(95); // http
2469#endif
2470 init_cardreader();
2471
2472 if (cfg->waitforcards)
2473 {
2474 int card_init_done;
2475 cs_log("waiting for local card init");
2476 cs_sleepms(3000); // short sleep for card detect to work proberly
2477 do {
2478 card_init_done = 1;
2479 for (i = 0; i < CS_MAXREADER; i++) {
2480 if (reader[i].card_status == CARD_NEED_INIT) {
2481 card_init_done = 0;
2482 break;
2483 }
2484 }
2485 cs_sleepms(300); // wait a little bit
2486 alarm(cfg->cmaxidle + cfg->ctimeout / 1000 + 1);
2487 } while (!card_init_done);
2488 cs_log("init for all local cards done");
2489
2490 }
2491
2492#ifdef CS_ANTICASC
2493 if( !cfg->ac_enabled )
2494 cs_log("anti cascading disabled");
2495 else
2496 {
2497 init_ac();
2498 init_service(96);
2499 }
2500#endif
2501
2502 for (i=0; i<CS_MAX_MOD; i++)
2503 if (ph[i].type & MOD_CONN_SERIAL) // for now: oscam_ser only
2504 if (ph[i].s_handler)
2505 ph[i].s_handler(i);
2506
2507 cs_close_log();
2508 *mcl=1;
2509 while (1)
2510 {
2511 fd_set fds;
2512
2513 do
2514 {
2515 FD_ZERO(&fds);
2516 FD_SET(mfdr, &fds);
2517 for (i=0; i<CS_MAX_MOD; i++)
2518 if ( (ph[i].type & MOD_CONN_NET) && ph[i].ptab )
2519 for (j=0; j<ph[i].ptab->nports; j++)
2520 if (ph[i].ptab->ports[j].fd)
2521 FD_SET(ph[i].ptab->ports[j].fd, &fds);
2522 errno=0;
2523 cs_set_mloc(0, "before select");
2524 select(gfd, &fds, 0, 0, 0);
2525 cs_set_mloc(60, "after select");
2526 } while (errno==EINTR);
2527 cs_set_mloc(-1, "event (global)");
2528
2529 client[0].last=time((time_t *)0);
2530 scad = sizeof(cad);
2531 if (FD_ISSET(mfdr, &fds))
2532 {
2533 cs_set_mloc(-1, "event: master-pipe");
2534 process_master_pipe();
2535 }
2536 for (i=0; i<CS_MAX_MOD; i++)
2537 {
2538 if( (ph[i].type & MOD_CONN_NET) && ph[i].ptab )
2539 {
2540 for( j=0; j<ph[i].ptab->nports; j++ )
2541 {
2542 if( ph[i].ptab->ports[j].fd && FD_ISSET(ph[i].ptab->ports[j].fd, &fds) )
2543 {
2544 if (ph[i].type==MOD_CONN_UDP)
2545 {
2546 cs_set_mloc(-1, "event: udp-socket");
2547 if ((n=recvfrom(ph[i].ptab->ports[j].fd, buf+3, sizeof(buf)-3, 0, (struct sockaddr *)&cad, (socklen_t *)&scad))>0)
2548 {
2549 int idx;
2550 idx=idx_from_ip(cs_inet_order(cad.sin_addr.s_addr), ntohs(cad.sin_port));
2551 if (!idx)
2552 {
2553 if (pipe(fdp))
2554 {
2555 cs_log("Cannot create pipe (errno=%d)", errno);
2556 cs_exit(1);
2557 }
2558 switch(cs_fork(cs_inet_order(cad.sin_addr.s_addr), ntohs(cad.sin_port)))
2559 {
2560 case -1:
2561 close(fdp[0]);
2562 close(fdp[1]);
2563 break;
2564 case 0:
2565 client[idx=cs_last_idx].ufd=fdp[1];
2566 close(fdp[0]);
2567 break;
2568 default:
2569// close(fdp[1]); // now used to simulate event
2570 pfd=fdp[0];
2571 wait4master();
2572 client[cs_idx].ctyp=i;
2573 client[cs_idx].port_idx=j;
2574 client[cs_idx].udp_fd=ph[i].ptab->ports[j].fd;
2575 client[cs_idx].udp_sa=cad;
2576 if (ph[client[cs_idx].ctyp].watchdog)
2577 alarm(cfg->cmaxidle + cfg->ctimeout / 1000 + 1);
2578 ph[i].s_handler(cad); // never return
2579 }
2580 }
2581 if (idx)
2582 {
2583 unsigned short rl;
2584 rl=n;
2585 buf[0]='U';
2586 memcpy(buf+1, &rl, 2);
2587 if (!write(client[idx].ufd, buf, n+3)) cs_exit(1);
2588 }
2589 }
2590 }
2591 else
2592 {
2593 cs_set_mloc(-1, "event: tcp-socket");
2594 if ((pfd=accept(ph[i].ptab->ports[j].fd, (struct sockaddr *)&cad, (socklen_t *)&scad))>0)
2595 {
2596 switch(cs_fork(cs_inet_order(cad.sin_addr.s_addr), ntohs(cad.sin_port)))
2597 {
2598 case -1:
2599 case 0:
2600 close(pfd);
2601 break;
2602 default:
2603 wait4master();
2604 client[cs_idx].ctyp=i;
2605 client[cs_idx].udp_fd=pfd;
2606 client[cs_idx].port_idx=j;
2607 if (ph[client[cs_idx].ctyp].watchdog)
2608 alarm(cfg->cmaxidle + cfg->ctimeout / 1000 + 1);
2609 ph[i].s_handler();
2610 }
2611 }
2612 }
2613 }
2614 }
2615 } // if (ph[i].type & MOD_CONN_NET)
2616 }
2617 }
2618 cs_exit(1);
2619}
Note: See TracBrowser for help on using the repository browser.