source: trunk/oscam.c@ 1691

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

Merge Webinterface into Trunk - Use -DWEBIF=1 with cmake to build with Webinterface - For make add -DWEBIF to target in Makefile to build with Webinterface for, thanks to Alno and Streamboard community

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