source: trunk/oscam.c@ 1687

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

Add some more Ifdefs for GBOX

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