source: trunk/oscam.c@ 1272

Last change on this file since 1272 was 1272, checked in by landlord, 11 years ago

New parameter 'disabled' for 'oscam.user', backport from 'monitor-improvement'

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