source: trunk/oscam.c@ 1721

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

Merge from UMP r1793

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