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

Last change on this file since 1269 was 1269, checked in by alno, 11 years ago

WebIf:

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