source: trunk/oscam.c@ 1090

Last change on this file since 1090 was 1090, checked in by C.H.A.D.o, 11 years ago

Fix parentheses warnings

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