source: trunk/oscam.c@ 1706

Last change on this file since 1706 was 1706, checked in by merek, 11 years ago

Show inbuilt modules in credits

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