source: trunk/oscam.c@ 1756

Last change on this file since 1756 was 1756, checked in by merek, 10 years ago

Update debug levels in credits

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