source: branches/monitor-improvement/oscam.c@ 1228

Last change on this file since 1228 was 1228, checked in by alno, 13 years ago

WebIf:

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