source: trunk/oscam.c@ 835

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

fix for realoding oscam.user causes problems with decoding, thanks to merek

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