source: trunk/oscam.c@ 3181

Last change on this file since 3181 was 3181, checked in by dingo35, 10 years ago

Adding threadsafety FIXMEs, feel free to join checking..

File size: 80.4 KB
Line 
1//FIXME Not checked on threadsafety yet; after checking please remove this line
2#define CS_CORE
3#include "globals.h"
4#ifdef AZBOX
5# include "openxcas/openxcas_api.h"
6#endif
7#ifdef CS_WITH_GBOX
8# include "csgbox/gbox.h"
9# define CS_VERSION_X CS_VERSION "-gbx-" GBXVERSION
10#else
11# define CS_VERSION_X CS_VERSION
12#endif
13/*****************************************************************************
14 Globals
15*****************************************************************************/
16struct s_module ph[CS_MAX_MOD]; // Protocols
17struct s_cardsystem cardsystem[CS_MAX_MOD]; // Protocols
18
19int mfdr=0; // Master FD (read)
20int fd_c2m=0;
21
22ushort len4caid[256]; // table for guessing caid (by len)
23char cs_confdir[128]=CS_CONFDIR;
24int cs_dblevel=0; // Debug Level (TODO !!)
25char cs_tmpdir[200]={0x00};
26pthread_mutex_t gethostbyname_lock;
27ECM_REQUEST *ecmtask;
28#ifdef CS_ANTICASC
29struct s_acasc ac_stat[CS_MAXPID];
30#endif
31
32/*****************************************************************************
33 Shared Memory
34*****************************************************************************/
35int *ecmidx; // Shared Memory
36int *logidx; // Shared Memory
37int *oscam_sem; // sem (multicam.o)
38int *c_start; // idx of 1st client
39struct s_ecm *ecmcache; // Shared Memory
40struct s_client *client; // Shared Memory
41struct s_reader *reader; // Shared Memory
42
43#ifdef CS_WITH_GBOX
44struct card_struct *Cards; // Shared Memory
45struct idstore_struct *idstore; // Shared Memory
46unsigned long *IgnoreList; // Shared Memory
47#endif
48
49struct s_config *cfg; // Shared Memory
50#ifdef CS_ANTICASC
51struct s_acasc_shm *acasc; // anti-cascading table indexed by account.ac_idx
52#endif
53#ifdef CS_LOGHISTORY
54int *loghistidx; // ptr to current entry
55char *loghist; // ptr of log-history
56#endif
57
58static const int shmsize = CS_ECMCACHESIZE*(sizeof(struct s_ecm)) +
59 CS_MAXPID*(sizeof(struct s_client)) +
60 CS_MAXREADER*(sizeof(struct s_reader)) +
61#ifdef CS_WITH_GBOX
62 CS_MAXCARDS*(sizeof(struct card_struct))+
63 CS_MAXIGNORE*(sizeof(long))+
64 CS_MAXPID*(sizeof(struct idstore_struct))+
65#endif
66#ifdef CS_ANTICASC
67 CS_MAXPID*(sizeof(struct s_acasc_shm)) +
68#endif
69#ifdef CS_LOGHISTORY
70 CS_MAXLOGHIST*CS_LOGHISTSIZE + sizeof(int) +
71#endif
72 sizeof(struct s_config)+(6*sizeof(int));
73
74#ifdef CS_NOSHM
75char cs_memfile[128]=CS_MMAPFILE;
76#endif
77
78int get_csidx() {
79 int i;
80
81 for (i=1; i<CS_MAXPID; i++) {
82 if (pthread_equal(client[i].thread, pthread_self())) {
83 return i;
84 }
85 }
86
87 return 0; // main process
88}
89
90/*****************************************************************************
91 Statics
92*****************************************************************************/
93static int cs_last_idx=0; // client index of last fork (master only)
94static const char *logo = " ___ ____ ___ \n / _ \\/ ___| / __|__ _ _ __ ___ \n| | | \\___ \\| | / _` | '_ ` _ \\ \n| |_| |___) | |_| (_| | | | | | |\n \\___/|____/ \\___\\__,_|_| |_| |_|\n";
95
96static void usage()
97{
98 fprintf(stderr, "%s\n\n", logo);
99 fprintf(stderr, "OSCam cardserver v%s, build #%s (%s) - (w) 2009-2010 streamboard SVN\n", CS_VERSION_X, CS_SVN_VERSION, CS_OSTYPE);
100 fprintf(stderr, "\tsee http://streamboard.gmc.to:8001/wiki/ for more details\n");
101 fprintf(stderr, "\tbased on streamboard mp-cardserver v0.9d - (w) 2004-2007 by dukat\n");
102 fprintf(stderr, "\tinbuilt modules: ");
103#ifdef HAVE_DVBAPI
104#ifdef WITH_STAPI
105 fprintf(stderr, "dvbapi with stapi");
106#else
107 fprintf(stderr, "dvbapi ");
108#endif
109#endif
110#ifdef WEBIF
111 fprintf(stderr, "webinterface ");
112#endif
113#ifdef CS_ANTICASC
114 fprintf(stderr, "anticascading ");
115#endif
116#ifdef LIBUSB
117 fprintf(stderr, "smartreader ");
118#endif
119#ifdef HAVE_PCSC
120 fprintf(stderr, "pcsc ");
121#endif
122#ifdef CS_WITH_GBOX
123 fprintf(stderr, "gbox ");
124#endif
125#ifdef IRDETO_GUESSING
126 fprintf(stderr, "irdeto-guessing ");
127#endif
128#ifdef CS_LED
129 fprintf(stderr, "led-trigger ");
130#endif
131 fprintf(stderr, "\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, " [-h]");
137 fprintf(stderr, "\n\n\t-b : start in background\n");
138 fprintf(stderr, "\t-c <dir> : read configuration from <dir>\n");
139 fprintf(stderr, "\t default = %s\n", CS_CONFDIR);
140 fprintf(stderr, "\t-t <dir> : tmp dir <dir>\n");
141#ifdef CS_CYGWIN32
142 fprintf(stderr, "\t default = (OS-TMP)\n");
143#else
144 fprintf(stderr, "\t default = /tmp/.oscam\n");
145#endif
146 fprintf(stderr, "\t-d <level> : debug level mask\n");
147 fprintf(stderr, "\t 0 = no debugging (default)\n");
148 fprintf(stderr, "\t 1 = detailed error messages\n");
149 fprintf(stderr, "\t 2 = ATR parsing info, ECM, EMM and CW dumps\n");
150 fprintf(stderr, "\t 4 = traffic from/to the reader\n");
151 fprintf(stderr, "\t 8 = traffic from/to the clients\n");
152 fprintf(stderr, "\t 16 = traffic to the reader-device on IFD layer\n");
153 fprintf(stderr, "\t 32 = traffic to the reader-device on I/O layer\n");
154 fprintf(stderr, "\t 64 = EMM logging\n");
155 fprintf(stderr, "\t 255 = debug all\n");
156#ifdef CS_NOSHM
157 fprintf(stderr, "\t-m <file> : use <file> as mmaped memory file\n");
158 fprintf(stderr, "\t default = %s\n", CS_MMAPFILE);
159#endif
160 fprintf(stderr, "\t-h : show this help\n");
161 fprintf(stderr, "\n");
162 exit(1);
163}
164
165#ifdef NEED_DAEMON
166#ifdef OS_MACOSX
167// this is done because daemon is being deprecated starting with 10.5 and -Werror will always trigger an error
168static int daemon_compat(int nochdir, int noclose)
169#else
170static int daemon(int nochdir, int noclose)
171#endif
172{
173 int fd;
174
175 switch (fork())
176 {
177 case -1: return (-1);
178 case 0: break;
179 default: _exit(0);
180 }
181
182 if (setsid()==(-1))
183 return(-1);
184
185 if (!nochdir)
186 (void)chdir("/");
187
188 if (!noclose && (fd=open("/dev/null", O_RDWR, 0)) != -1)
189 {
190 (void)dup2(fd, STDIN_FILENO);
191 (void)dup2(fd, STDOUT_FILENO);
192 (void)dup2(fd, STDERR_FILENO);
193 if (fd>2)
194 (void)close(fd);
195 }
196 return(0);
197}
198#endif
199
200int recv_from_udpipe(uchar *buf)
201{
202 unsigned short n;
203 if (!client[cs_idx].pfd) return(-9);
204 if (!read(client[cs_idx].pfd, buf, 3)) cs_exit(1);
205 if (buf[0]!='U')
206 {
207 cs_log("INTERNAL PIPE-ERROR");
208 cs_exit(1);
209 }
210 memcpy(&n, buf+1, 2);
211 return(read(client[cs_idx].pfd, buf, n));
212}
213
214char *username(int idx)
215{
216 if (client[idx].usr[0])
217 return(client[idx].usr);
218 else
219 return("anonymous");
220}
221
222static int idx_from_ip(in_addr_t ip, in_port_t port)
223{
224 int i, idx;
225 for (i=idx=0; (i<CS_MAXPID) && (!idx); i++)
226 if ((client[i].ip==ip) && (client[i].port==port) &&
227 ((client[i].typ=='c') || (client[i].typ=='m')))
228 idx=i;
229 return(idx);
230}
231
232int idx_from_pid(pid_t pid)
233{
234 int i, idx;
235 for (i=0, idx=(-1); (i<CS_MAXPID) && (idx<0); i++)
236 if (client[i].pid==pid)
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_master_alarm()
288{
289 cs_log("PANIC: master deadlock!");
290 fprintf(stderr, "PANIC: master deadlock!");
291 fflush(stderr);
292}
293
294static void cs_sigpipe()
295{
296
297 cs_log("Got sigpipe signal -> captured");
298}
299
300void cs_exit(int sig)
301{
302 set_signal_handler(SIGCHLD, 1, SIG_IGN);
303 set_signal_handler(SIGHUP , 1, SIG_IGN);
304
305 set_signal_handler(SIGCHLD, 1, SIG_IGN);
306 set_signal_handler(SIGHUP , 1, SIG_IGN);
307 if (sig && (sig!=SIGQUIT))
308 cs_log("exit with signal %d", sig);
309 switch(client[cs_idx].typ)
310 {
311 case 'c':
312 cs_statistics(cs_idx);
313 client[cs_idx].last_caid = 0xFFFF;
314 client[cs_idx].last_srvid = 0xFFFF;
315 cs_statistics(cs_idx);
316 break;
317 case 'm': break;
318 case 'n': break;
319 case 'r':
320 // free AES entries allocated memory
321 if(reader[client[cs_idx].ridx].aes_list) {
322 aes_clear_entries(&reader[client[cs_idx].ridx]);
323 }
324 // close the device
325 reader_device_close(&reader[client[cs_idx].ridx]);
326 break;
327 case 'h':
328 case 's': {
329 int i;
330 for (i=1; i<CS_MAXPID; i++)
331 if (client[i].pid)
332 kill(client[i].pid, SIGQUIT);
333 }
334#ifdef CS_LED
335 cs_switch_led(LED1B, LED_OFF);
336 cs_switch_led(LED2, LED_OFF);
337 cs_switch_led(LED3, LED_OFF);
338 cs_switch_led(LED1A, LED_ON);
339#endif
340 if (cfg->pidfile != NULL) {
341 if (unlink(cfg->pidfile) < 0)
342 cs_log("cannot remove pid file %s errno=(%d)", cfg->pidfile, errno);
343 }
344#ifndef OS_CYGWIN32
345 if (unlink("/tmp/oscam.version") < 0)
346 cs_log("cannot remove /tmp/oscam.version errno=(%d)", errno);
347#endif
348 cs_log("cardserver down");
349 break;
350 }
351
352 int i;
353 for (i=1; i<CS_MAXPID; i++) {
354 if (pthread_equal(client[i].thread, pthread_self())) {
355 client[i].pid=0;
356 if(client[i].ecmtask) free(client[i].ecmtask);
357 if(client[i].ecmtask) free(client[i].emmcache);
358 if(client[i].req) free(client[i].req);
359 if(client[i].prefix) free(client[i].prefix);
360 if(client[i].cc) free(client[i].cc);
361 cs_log("thread %d ended!", i);
362 pthread_exit(NULL);
363 return;
364 }
365 }
366
367
368
369 for (i=0; i<CS_MAXPID; i++) {
370 if(client[i].ecmtask) free(client[i].ecmtask);
371 if(client[i].ecmtask) free(client[i].emmcache);
372 if(client[i].req) free(client[i].req);
373 if(client[i].prefix) free(client[i].prefix);
374 if(client[i].cc) free(client[i].cc);
375 }
376 cs_log("memory freed");
377
378 cs_close_log();
379
380 if (ecmcache) free((void *)ecmcache);
381
382 exit(sig);
383}
384
385void cs_reinit_clients()
386{
387 int i;
388 struct s_auth *account;
389
390 for( i = 1; i < CS_MAXPID; i++ )
391 if( client[i].pid && client[i].typ == 'c' && client[i].usr[0] ) {
392 for (account = cfg->account; (account) ; account = account->next)
393 if (!strcmp(client[i].usr, account->usr))
394 break;
395
396 if (account && client[i].pcrc == crc32(0L, MD5((uchar *)account->pwd, strlen(account->pwd), NULL), 16)) {
397 client[i].grp = account->grp;
398 client[i].au = account->au;
399 client[i].autoau = account->autoau;
400 client[i].expirationdate = account->expirationdate;
401 client[i].allowedtimeframe[0] = account->allowedtimeframe[0];
402 client[i].allowedtimeframe[1] = account->allowedtimeframe[1];
403 client[i].ncd_keepalive = account->ncd_keepalive;
404 client[i].c35_suppresscmd08 = account->c35_suppresscmd08;
405 client[i].tosleep = (60*account->tosleep);
406 client[i].c35_sleepsend = account->c35_sleepsend;
407 client[i].monlvl = account->monlvl;
408 client[i].disabled = account->disabled;
409 client[i].fchid = account->fchid; // CHID filters
410 client[i].cltab = account->cltab; // Class
411
412 // newcamd module dosent like ident reloading
413 if(!client[i].ncd_server)
414 client[i].ftab = account->ftab; // Ident
415
416 client[i].sidtabok = account->sidtabok; // services
417 client[i].sidtabno = account->sidtabno; // services
418
419 memcpy(&client[i].ctab, &account->ctab, sizeof(client[i].ctab));
420 memcpy(&client[i].ttab, &account->ttab, sizeof(client[i].ttab));
421
422#ifdef CS_ANTICASC
423 client[i].ac_idx = account->ac_idx;
424 client[i].ac_penalty= account->ac_penalty;
425 client[i].ac_limit = (account->ac_users * 100 + 80) * cfg->ac_stime;
426#endif
427 } else {
428 if (ph[client[i].ctyp].type & MOD_CONN_NET) {
429 cs_debug("client '%s', pid=%d not found in db (or password changed)", client[i].usr, client[i].pid);
430 pthread_cancel(client[i].thread);
431 }
432 }
433 }
434}
435
436static void cs_sighup()
437{
438 uchar dummy[1]={0x00};
439 write_to_pipe(fd_c2m, PIP_ID_HUP, dummy, 1);
440}
441
442static void cs_accounts_chk()
443{
444 init_userdb(&cfg->account);
445 cs_reinit_clients();
446#ifdef CS_ANTICASC
447 int i;
448 for (i=0; i<CS_MAXPID; i++)
449 if (client[i].typ=='a')
450 {
451 //kill(client[i].pid, SIGHUP);
452 break;
453 }
454#endif
455}
456
457static void cs_debug_level()
458{
459 //switch debuglevel forward one step if not set from outside
460 if(cfg->debuglvl == cs_dblevel) {
461 switch (cs_dblevel) {
462 case 0:
463 cs_dblevel = 1;
464 break;
465 case 64:
466 cs_dblevel = 255;
467 break;
468 case 255:
469 cs_dblevel = 0;
470 break;
471 default:
472 cs_dblevel <<= 1;
473 }
474 } else {
475 cs_dblevel = cfg->debuglvl;
476 }
477
478 cfg->debuglvl = cs_dblevel;
479 cs_log("%sdebug_level=%d", "all", cs_dblevel);
480}
481
482static void cs_card_info(int i)
483{
484 uchar dummy[1]={0x00};
485
486 for( i=1; i<CS_MAXPID; i++ )
487 if( client[i].pid && client[i].typ=='r' && client[i].fd_m2c ){
488 write_to_pipe(client[i].fd_m2c, PIP_ID_CIN, dummy, 1);
489 }
490
491 //kill(client[i].pid, SIGUSR2);
492}
493
494int cs_fork(in_addr_t ip, in_port_t port) {
495 int i;
496
497 pid_t pid=getpid();
498 for (i=1; (i<CS_MAXPID) && (client[i].pid); i++); //find next available client index i
499 if (i<CS_MAXPID) {
500 int fdp[2];
501 memset(&client[i], 0, sizeof(struct s_client));
502 client[i].au=(-1);
503 if (pipe(fdp)) {
504 cs_log("Cannot create pipe (errno=%d)", errno);
505 cs_exit(1);
506 }
507 //client part
508
509 //make_non_blocking(fdp[0]);
510 //make_non_blocking(fdp[1]);
511
512 client[i].is_server=((ip) || (port<90)) ? 1 : 0; //FIXME global should be local per thread
513
514 client[i].cs_ptyp=D_CLIENT;
515 client[i].fd_m2c_c = fdp[0]; //store client read fd
516 client[i].fd_m2c = fdp[1]; //store client read fd
517
518 //master part
519 client[i].stat=1;
520
521 client[i].login=client[i].last=time((time_t *)0);
522 client[i].pid=pid; // MUST be last -> wait4master()
523
524 cs_last_idx=i;
525
526
527 } else {
528 cs_log("max connections reached -> reject client %s", cs_inet_ntoa(ip));
529 i=(-1);
530 }
531 return(i);
532}
533
534static void init_signal()
535{
536 int i;
537 for (i=1; i<NSIG; i++)
538 set_signal_handler(i, 3, cs_exit);
539 set_signal_handler(SIGWINCH, 1, SIG_IGN);
540 // set_signal_handler(SIGPIPE , 0, SIG_IGN);
541 set_signal_handler(SIGPIPE , 0, cs_sigpipe);
542 // set_signal_handler(SIGALRM , 0, cs_alarm);
543 set_signal_handler(SIGALRM , 0, cs_master_alarm);
544 // set_signal_handler(SIGCHLD , 1, cs_child_chk);
545 // set_signal_handler(SIGHUP , 1, cs_accounts_chk);
546 set_signal_handler(SIGHUP , 1, cs_sighup);
547 set_signal_handler(SIGUSR1, 1, cs_debug_level);
548 set_signal_handler(SIGUSR2, 1, cs_card_info);
549 set_signal_handler(SIGCONT, 1, SIG_IGN);
550 cs_log("signal handling initialized (type=%s)",
551#ifdef CS_SIGBSD
552 "bsd"
553#else
554 "sysv"
555#endif
556 );
557 return;
558}
559
560static void init_shm()
561{
562 ecmcache=(struct s_ecm *)malloc(shmsize);
563 memset(ecmcache, 0, shmsize);
564
565#ifdef CS_ANTICASC
566 acasc=(struct s_acasc_shm *)&ecmcache[CS_ECMCACHESIZE];
567 ecmidx=(int *)&acasc[CS_MAXPID];
568#else
569 ecmidx=(int *)&ecmcache[CS_ECMCACHESIZE];
570#endif
571 logidx=(int *)((void *)ecmidx+sizeof(int));
572 c_start=(int *)((void *)logidx+sizeof(int));
573 oscam_sem=(int *)((void *)c_start+sizeof(int));
574 client=(struct s_client *)((void *)oscam_sem+sizeof(int));
575 reader=(struct s_reader *)&client[CS_MAXPID];
576#ifdef CS_WITH_GBOX
577 Cards=(struct card_struct*)&reader[CS_MAXREADER];
578 IgnoreList=(unsigned long*)&Cards[CS_MAXCARDS];
579 idstore=(struct idstore_struct*)&IgnoreList[CS_MAXIGNORE];
580 cfg=(struct s_config *)&idstore[CS_MAXPID];
581#else
582 cfg=(struct s_config *)&reader[CS_MAXREADER];
583#endif
584#ifdef CS_LOGHISTORY
585 loghistidx=(int *)((void *)cfg+sizeof(struct s_config));
586 loghist=(char *)((void *)loghistidx+sizeof(int));
587#endif
588
589
590 *ecmidx=0;
591 *logidx=0;
592 *oscam_sem=0;
593 client[0].pid=getpid();
594 client[0].login=time((time_t *)0);
595 client[0].ip=cs_inet_addr("127.0.0.1");
596 client[0].typ='s';
597 client[0].au=(-1);
598
599 // get username master running under
600 struct passwd *pwd;
601 if ((pwd = getpwuid(getuid())) != NULL)
602 strcpy(client[0].usr, pwd->pw_name);
603 else
604 strcpy(client[0].usr, "root");
605
606 pthread_mutex_init(&gethostbyname_lock, NULL);
607
608#ifdef CS_LOGHISTORY
609 *loghistidx=0;
610 memset(loghist, 0, CS_MAXLOGHIST*CS_LOGHISTSIZE);
611#endif
612}
613
614static int start_listener(struct s_module *ph, int port_idx)
615{
616 int ov=1, timeout, is_udp, i;
617 char ptxt[2][32];
618 //struct hostent *ptrh; /* pointer to a host table entry */
619 struct protoent *ptrp; /* pointer to a protocol table entry */
620 struct sockaddr_in sad; /* structure to hold server's address */
621
622 ptxt[0][0]=ptxt[1][0]='\0';
623 if (!ph->ptab->ports[port_idx].s_port)
624 {
625 cs_log("%s: disabled", ph->desc);
626 return(0);
627 }
628 is_udp=(ph->type==MOD_CONN_UDP);
629
630 memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
631 sad.sin_family = AF_INET; /* set family to Internet */
632 if (!ph->s_ip)
633 ph->s_ip=cfg->srvip;
634 if (ph->s_ip)
635 {
636 sad.sin_addr.s_addr=ph->s_ip;
637 sprintf(ptxt[0], ", ip=%s", inet_ntoa(sad.sin_addr));
638 }
639 else
640 sad.sin_addr.s_addr=INADDR_ANY;
641 timeout=cfg->bindwait;
642 //ph->fd=0;
643 ph->ptab->ports[port_idx].fd = 0;
644
645 if (ph->ptab->ports[port_idx].s_port > 0) /* test for illegal value */
646 sad.sin_port = htons((u_short)ph->ptab->ports[port_idx].s_port);
647 else
648 {
649 cs_log("%s: Bad port %d", ph->desc, ph->ptab->ports[port_idx].s_port);
650 return(0);
651 }
652
653 /* Map transport protocol name to protocol number */
654
655 if( (ptrp=getprotobyname(is_udp ? "udp" : "tcp")) )
656 ov=ptrp->p_proto;
657 else
658 ov=(is_udp) ? 17 : 6; // use defaults on error
659
660 if ((ph->ptab->ports[port_idx].fd=socket(PF_INET,is_udp ? SOCK_DGRAM : SOCK_STREAM, ov))<0)
661 {
662 cs_log("%s: Cannot create socket (errno=%d)", ph->desc, errno);
663 return(0);
664 }
665
666 ov=1;
667 if (setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_REUSEADDR, (void *)&ov, sizeof(ov))<0)
668 {
669 cs_log("%s: setsockopt failed (errno=%d)", ph->desc, errno);
670 close(ph->ptab->ports[port_idx].fd);
671 return(ph->ptab->ports[port_idx].fd=0);
672 }
673
674#ifdef SO_REUSEPORT
675 setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_REUSEPORT, (void *)&ov, sizeof(ov));
676#endif
677
678#ifdef SO_PRIORITY
679 if (cfg->netprio)
680 if (!setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_PRIORITY, (void *)&cfg->netprio, sizeof(ulong)))
681 sprintf(ptxt[1], ", prio=%ld", cfg->netprio);
682#endif
683
684 if( !is_udp )
685 {
686 ulong keep_alive = 1;
687 setsockopt(ph->ptab->ports[port_idx].fd, SOL_SOCKET, SO_KEEPALIVE,
688 (void *)&keep_alive, sizeof(ulong));
689 }
690
691 while (timeout--)
692 {
693 if (bind(ph->ptab->ports[port_idx].fd, (struct sockaddr *)&sad, sizeof (sad))<0)
694 {
695 if (timeout)
696 {
697 cs_log("%s: Bind request failed, waiting another %d seconds",
698 ph->desc, timeout);
699 cs_sleepms(1000);
700 }
701 else
702 {
703 cs_log("%s: Bind request failed, giving up", ph->desc);
704 close(ph->ptab->ports[port_idx].fd);
705 return(ph->ptab->ports[port_idx].fd=0);
706 }
707 }
708 else timeout=0;
709 }
710
711 if (!is_udp)
712 if (listen(ph->ptab->ports[port_idx].fd, CS_QLEN)<0)
713 {
714 cs_log("%s: Cannot start listen mode (errno=%d)", ph->desc, errno);
715 close(ph->ptab->ports[port_idx].fd);
716 return(ph->ptab->ports[port_idx].fd=0);
717 }
718
719 cs_log("%s: initialized (fd=%d, port=%d%s%s%s)",
720 ph->desc, ph->ptab->ports[port_idx].fd,
721 ph->ptab->ports[port_idx].s_port,
722 ptxt[0], ptxt[1], ph->logtxt ? ph->logtxt : "");
723
724 for( i=0; i<ph->ptab->ports[port_idx].ftab.nfilts; i++ ) {
725 int j;
726 cs_log("CAID: %04X", ph->ptab->ports[port_idx].ftab.filts[i].caid );
727 for( j=0; j<ph->ptab->ports[port_idx].ftab.filts[i].nprids; j++ )
728 cs_log("provid #%d: %06X", j, ph->ptab->ports[port_idx].ftab.filts[i].prids[j]);
729 }
730 return(ph->ptab->ports[port_idx].fd);
731}
732
733int cs_user_resolve(struct s_auth *account)
734{
735 struct hostent *rht;
736 struct sockaddr_in udp_sa;
737 int result=0;
738 if (account->dyndns[0])
739 {
740 pthread_mutex_lock(&gethostbyname_lock);
741 in_addr_t lastip = account->dynip;
742 //Resolve with gethostbyname:
743 if (cfg->resolve_gethostbyname) {
744 rht = gethostbyname((char*)account->dyndns);
745 if (!rht)
746 cs_log("can't resolve %s", account->dyndns);
747 else {
748 memcpy(&udp_sa.sin_addr, rht->h_addr, sizeof(udp_sa.sin_addr));
749 account->dynip=cs_inet_order(udp_sa.sin_addr.s_addr);
750 result=1;
751 }
752 }
753 else { //Resolve with getaddrinfo:
754 struct addrinfo hints, *res = NULL;
755 memset(&hints, 0, sizeof(hints));
756 hints.ai_socktype = SOCK_STREAM;
757 hints.ai_family = AF_INET;
758 hints.ai_protocol = IPPROTO_TCP;
759
760 int err = getaddrinfo((const char*)account->dyndns, NULL, &hints, &res);
761 if (err != 0 || !res || !res->ai_addr) {
762 cs_log("can't resolve %s, error: %s", account->dyndns, err ? gai_strerror(err) : "unknown");
763 }
764 else {
765 account->dynip=cs_inet_order(((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr);
766 result=1;
767 }
768 if (res) freeaddrinfo(res);
769 }
770 if (lastip != account->dynip) {
771 uchar *ip = (uchar*) &account->dynip;
772 cs_log("%s: resolved ip=%d.%d.%d.%d", (char*)account->dyndns, ip[3], ip[2], ip[1], ip[0]);
773 }
774 pthread_mutex_unlock(&gethostbyname_lock);
775 }
776 if (!result)
777 account->dynip=0;
778 return result;
779}
780
781static void start_thread(void * startroutine, char * nameroutine, char typ) {
782 int i,o;
783
784 if (typ == 'h')
785 o=cs_fork(0,95);
786 else
787 o=cs_fork(0,97);
788
789 if (o<0) return;
790
791 client[o].typ=typ;
792
793 client[o].ip=client[0].ip;
794 strcpy(client[o].usr, client[0].usr);
795
796 i=pthread_create(&client[o].thread, (pthread_attr_t *)0, startroutine, (void *) 0);
797
798 if (i)
799 cs_log("ERROR: can't create %s thread (err=%d)", i, nameroutine);
800 else {
801 cs_log("%s thread started", nameroutine);
802 pthread_detach(client[o].thread);
803 }
804}
805
806#ifdef CS_ANTICASC
807void start_anticascader()
808{
809 set_signal_handler(SIGHUP, 1, ac_init_stat);
810
811 ac_init_stat();
812 while(1)
813 {
814 ac_do_stat();
815 }
816}
817#endif
818
819static void restart_cardreader(int reader_idx, int restart) {
820 int i,n;
821 if ((reader[reader_idx].device[0]) && (reader[reader_idx].enable == 1) && (!reader[reader_idx].deleted)) {
822
823 if (restart) {
824 cs_sleepms(cfg->reader_restart_seconds * 1000); // SS: wait
825 cs_log("restarting reader %s (index=%d)", reader[reader_idx].label, reader_idx);
826 }
827
828 if ((reader[reader_idx].typ & R_IS_CASCADING)) {
829 n=0;
830 for (i=0; i<CS_MAX_MOD; i++) {
831 if (ph[i].num) {
832 if (reader[reader_idx].typ==ph[i].num) {
833 cs_debug("reader %s protocol: %s", reader[reader_idx].label, ph[i].desc);
834 reader[reader_idx].ph=ph[i];
835 n=1;
836 break;
837 }
838 }
839 }
840 if (!n) {
841 cs_log("Protocol Support missing.");
842 return;
843 }
844 }
845
846 i=cs_fork(0, 99);
847
848 if (i<0) return;
849
850 reader[reader_idx].fd=client[i].fd_m2c;
851 client[i].ridx=reader_idx;
852 cs_log("creating thread for device %s slot %i with ridx %i cs_idx %i", reader[reader_idx].device, reader[reader_idx].slot, reader_idx, i);
853
854 client[i].sidtabok=reader[reader_idx].sidtabok;
855 client[i].sidtabno=reader[reader_idx].sidtabno;
856
857 reader[reader_idx].pid=getpid();
858
859 reader[reader_idx].cidx=i;
860
861 client[i].typ='r';
862 //client[i].ctyp=99;
863 pthread_create(&client[i].thread, NULL, start_cardreader, (void *)&reader[reader_idx]);
864
865 if (reader[reader_idx].r_port)
866 cs_log("proxy thread started (pid=%d, server=%s)",reader[reader_idx].pid, reader[reader_idx].device);
867 else {
868 switch(reader[reader_idx].typ) {
869 case R_MOUSE:
870 case R_SMART:
871 cs_log("reader thread started (pid=%d, device=%s, detect=%s%s, mhz=%d, cardmhz=%d)",reader[reader_idx].pid,
872 reader[reader_idx].device,reader[reader_idx].detect&0x80 ? "!" : "",RDR_CD_TXT[reader[reader_idx].detect&0x7f],
873 reader[reader_idx].mhz,reader[reader_idx].cardmhz);
874 break;
875 case R_SC8in1:
876 cs_log("reader thread started (pid=%d, device=%s:%i, detect=%s%s, mhz=%d, cardmhz=%d)",reader[reader_idx].pid,
877 reader[reader_idx].device,reader[reader_idx].slot,reader[reader_idx].detect&0x80 ? "!" : "",
878 RDR_CD_TXT[reader[reader_idx].detect&0x7f],reader[reader_idx].mhz,reader[reader_idx].cardmhz);
879 break;
880 default:
881 cs_log("reader thread started (pid=%d, device=%s)",reader[reader_idx].pid, reader[reader_idx].device);
882 }
883 client[i].ip=client[0].ip;
884 strcpy(client[i].usr, client[0].usr);
885 }
886 }
887}
888
889static void init_cardreader() {
890 int reader_idx;
891 for (reader_idx=0; reader_idx<CS_MAXREADER; reader_idx++) {
892 if ((reader[reader_idx].device[0]) && (reader[reader_idx].enable == 1)) {
893 restart_cardreader(reader_idx, 0);
894 }
895 }
896}
897
898void wait4master()
899{
900 //int i;
901 //for (i=0; (i<1000) && (client[cs_idx].pid!=getpid()); i++)
902 //cs_sleepms(1);
903 if (client[cs_idx].pid!=getpid())
904 {
905 cs_log("PANIC: client not found in shared memory");
906 //cs_exit(1);
907 }
908 cs_debug("starting client %d with ip %s",
909 cs_idx-cdiff, cs_inet_ntoa(client[cs_idx].ip));
910}
911
912static void cs_fake_client(char *usr, int uniq, in_addr_t ip)
913{
914 /* Uniq = 1: only one connection per user
915 *
916 * Uniq = 2: set (new connected) user only to fake if source
917 * ip is different (e.g. for newcamd clients with
918 * different CAID's -> Ports)
919 *
920 * Uniq = 3: only one connection per user, but only the last
921 * login will survive (old mpcs behavior)
922 *
923 * Uniq = 4: set user only to fake if source ip is
924 * different, but only the last login will survive
925 */
926
927 int i;
928 for (i=cdiff+1; i<CS_MAXPID; i++)
929 {
930 if (client[i].pid && (client[i].typ == 'c') && !client[i].dup && !strcmp(client[i].usr, usr)
931 && (uniq < 5) && ((uniq % 2) || (client[i].ip != ip)))
932 {
933 if (uniq == 3 || uniq == 4)
934 {
935 client[i].dup = 1;
936 client[i].au = -1;
937 cs_log("client(%d) duplicate user '%s' from %s set to fake (uniq=%d)", i-cdiff, usr, cs_inet_ntoa(ip), uniq);
938 }
939 else
940 {
941 client[cs_idx].dup = 1;
942 client[cs_idx].au = -1;
943 cs_log("client(%d) duplicate user '%s' from %s set to fake (uniq=%d)", cs_idx-cdiff, usr, cs_inet_ntoa(ip), uniq);
944 break;
945 }
946
947 }
948 }
949
950}
951
952int cs_auth_client(struct s_auth *account, const char *e_txt)
953{
954 int rc=0;
955 char buf[32];
956 char *t_crypt="encrypted";
957 char *t_plain="plain";
958 char *t_grant=" granted";
959 char *t_reject=" rejected";
960 char *t_msg[]= { buf, "invalid access", "invalid ip", "unknown reason" };
961 client[cs_idx].grp=0xffffffff;
962 client[cs_idx].au=(-1);
963 switch((long)account)
964 {
965#ifdef CS_WITH_GBOX
966 case -2: // gbx-dummy
967 client[cs_idx].dup=0;
968 break;
969#endif
970 case 0: // reject access
971 rc=1;
972 cs_log("%s %s-client %s%s (%s)",
973 client[cs_idx].crypted ? t_crypt : t_plain,
974 ph[client[cs_idx].ctyp].desc,
975 client[cs_idx].ip ? cs_inet_ntoa(client[cs_idx].ip) : "",
976 client[cs_idx].ip ? t_reject : t_reject+1,
977 e_txt ? e_txt : t_msg[rc]);
978 break;
979 default: // grant/check access
980 if (client[cs_idx].ip && account->dyndns[0]) {
981 if (cfg->clientdyndns) {
982 if (client[cs_idx].ip != account->dynip)
983 cs_user_resolve(account);
984 if (client[cs_idx].ip != account->dynip)
985 rc=2;
986 }
987 else
988 cs_log("Warning: clientdyndns disabled in config. Enable clientdyndns to use hostname restrictions");
989 }
990
991 if (!rc)
992 {
993 client[cs_idx].dup=0;
994 if (client[cs_idx].typ=='c')
995 {
996 client[cs_idx].last_caid = 0xFFFE;
997 client[cs_idx].last_srvid = 0xFFFE;
998 client[cs_idx].expirationdate=account->expirationdate;
999 client[cs_idx].disabled=account->disabled;
1000 client[cs_idx].c35_suppresscmd08 = account->c35_suppresscmd08;
1001 client[cs_idx].ncd_keepalive = account->ncd_keepalive;
1002 client[cs_idx].grp=account->grp;
1003 client[cs_idx].au=account->au;
1004 client[cs_idx].autoau=account->autoau;
1005 client[cs_idx].tosleep=(60*account->tosleep);
1006 client[cs_idx].c35_sleepsend = account->c35_sleepsend;
1007 memcpy(&client[cs_idx].ctab, &account->ctab, sizeof(client[cs_idx].ctab));
1008 if (account->uniq)
1009 cs_fake_client(account->usr, account->uniq, client[cs_idx].ip);
1010 client[cs_idx].ftab = account->ftab; // IDENT filter
1011 client[cs_idx].cltab = account->cltab; // CLASS filter
1012 client[cs_idx].fchid = account->fchid; // CHID filter
1013 client[cs_idx].sidtabok= account->sidtabok; // services
1014 client[cs_idx].sidtabno= account->sidtabno; // services
1015 client[cs_idx].pcrc = crc32(0L, MD5((uchar *)account->pwd, strlen(account->pwd), NULL), 16);
1016 memcpy(&client[cs_idx].ttab, &account->ttab, sizeof(client[cs_idx].ttab));
1017#ifdef CS_ANTICASC
1018 ac_init_client(account);
1019#endif
1020 }
1021 }
1022 client[cs_idx].monlvl=account->monlvl;
1023 strcpy(client[cs_idx].usr, account->usr);
1024 case -1: // anonymous grant access
1025 if (rc)
1026 t_grant=t_reject;
1027 else
1028 {
1029 if (client[cs_idx].typ=='m')
1030 sprintf(t_msg[0], "lvl=%d", client[cs_idx].monlvl);
1031 else
1032 {
1033 if(client[cs_idx].autoau)
1034 {
1035 if(client[cs_idx].ncd_server)
1036 {
1037 int r=0;
1038 for(r=0;r<CS_MAXREADER;r++)
1039 {
1040 if(reader[r].caid[0]==cfg->ncd_ptab.ports[client[cs_idx].port_idx].ftab.filts[0].caid)
1041 {
1042 client[cs_idx].au=r;
1043 break;
1044 }
1045 }
1046 if(client[cs_idx].au<0) sprintf(t_msg[0], "au(auto)=%d", client[cs_idx].au+1);
1047 else sprintf(t_msg[0], "au(auto)=%s", reader[client[cs_idx].au].label);
1048 }
1049 else
1050 {
1051 sprintf(t_msg[0], "au=auto");
1052 }
1053 }
1054 else
1055 {
1056 if(client[cs_idx].au<0) sprintf(t_msg[0], "au=%d", client[cs_idx].au+1);
1057 else sprintf(t_msg[0], "au=%s", reader[client[cs_idx].au].label);
1058 }
1059 }
1060 }
1061 if(client[cs_idx].ncd_server)
1062 {
1063 cs_log("%s %s:%d-client %s%s (%s, %s)",
1064 client[cs_idx].crypted ? t_crypt : t_plain,
1065 e_txt ? e_txt : ph[client[cs_idx].ctyp].desc,
1066 cfg->ncd_ptab.ports[client[cs_idx].port_idx].s_port,
1067 client[cs_idx].ip ? cs_inet_ntoa(client[cs_idx].ip) : "",
1068 client[cs_idx].ip ? t_grant : t_grant+1,
1069 username(cs_idx), t_msg[rc]);
1070 }
1071 else
1072 {
1073 cs_log("%s %s-client %s%s (%s, %s)",
1074 client[cs_idx].crypted ? t_crypt : t_plain,
1075 e_txt ? e_txt : ph[client[cs_idx].ctyp].desc,
1076 client[cs_idx].ip ? cs_inet_ntoa(client[cs_idx].ip) : "",
1077 client[cs_idx].ip ? t_grant : t_grant+1,
1078 username(cs_idx), t_msg[rc]);
1079 }
1080
1081 break;
1082 }
1083 return(rc);
1084}
1085
1086void cs_disconnect_client(void)
1087{
1088 char buf[32]={0};
1089 if (client[cs_idx].ip)
1090 sprintf(buf, " from %s", cs_inet_ntoa(client[cs_idx].ip));
1091 cs_log("%s disconnected %s", username(cs_idx), buf);
1092 cs_exit(0);
1093}
1094
1095/**
1096 * cache 1: client-invoked
1097 * returns found ecm task index
1098 **/
1099int check_ecmcache1(ECM_REQUEST *er, ulong grp)
1100{
1101 int i;
1102 //cs_ddump(ecmd5, CS_ECMSTORESIZE, "ECM search");
1103 //cs_log("cache1 CHECK: grp=%lX", grp);
1104 for(i=0; i<CS_ECMCACHESIZE; i++) {
1105 if ((grp & ecmcache[i].grp) &&
1106 ecmcache[i].caid==er->caid &&
1107 (!memcmp(ecmcache[i].ecmd5, er->ecmd5, CS_ECMSTORESIZE)))
1108 {
1109 //cs_log("cache1 found: grp=%lX cgrp=%lX", grp, ecmcache[i].grp);
1110 memcpy(er->cw, ecmcache[i].cw, 16);
1111 er->reader[0] = ecmcache[i].reader;
1112 return(1);
1113 }
1114 }
1115 return(0);
1116}
1117
1118/**
1119 * cache 2: reader-invoked
1120 * returns 1 if found in cache. cw is copied to er
1121 **/
1122int check_ecmcache2(ECM_REQUEST *er, ulong grp)
1123{
1124 // disable cache2
1125 if (!reader[client[get_csidx()].ridx].cachecm) return(0);
1126
1127 int i;
1128 //cs_ddump(ecmd5, CS_ECMSTORESIZE, "ECM search");
1129 //cs_log("cache2 CHECK: grp=%lX", grp);
1130 for(i=0; i<CS_ECMCACHESIZE; i++) {
1131 if ((grp & ecmcache[i].grp) &&
1132 ecmcache[i].caid==er->caid &&
1133 (!memcmp(ecmcache[i].ecmd5, er->ecmd5, CS_ECMSTORESIZE)))
1134 {
1135 //cs_log("cache2 found: grp=%lX cgrp=%lX", grp, ecmcache[i].grp);
1136 memcpy(er->cw, ecmcache[i].cw, 16);
1137 return(1);
1138 }
1139 }
1140 return(0);
1141}
1142
1143
1144static void store_ecm(ECM_REQUEST *er)
1145{
1146#ifdef CS_WITH_DOUBLECHECK
1147 if (cfg->double_check && er->checked < 2)
1148 return;
1149#endif
1150 int rc;
1151 rc=*ecmidx;
1152 *ecmidx=(*ecmidx+1) % CS_ECMCACHESIZE;
1153 //cs_log("store ecm from reader %d", er->reader[0]);
1154 memcpy(ecmcache[rc].ecmd5, er->ecmd5, CS_ECMSTORESIZE);
1155 memcpy(ecmcache[rc].cw, er->cw, 16);
1156 ecmcache[rc].caid = er->caid;
1157 ecmcache[rc].grp = reader[er->reader[0]].grp;
1158 ecmcache[rc].reader = er->reader[0];
1159 //cs_ddump(ecmcache[*ecmidx].ecmd5, CS_ECMSTORESIZE, "ECM stored (idx=%d)", *ecmidx);
1160}
1161
1162void store_logentry(char *txt)
1163{
1164#ifdef CS_LOGHISTORY
1165 char *ptr;
1166 ptr=(char *)(loghist+(*loghistidx*CS_LOGHISTSIZE));
1167 ptr[0]='\1'; // make username unusable
1168 ptr[1]='\0';
1169 if ((client[cs_idx].typ=='c') || (client[cs_idx].typ=='m'))
1170 cs_strncpy(ptr, client[cs_idx].usr, 31);
1171 cs_strncpy(ptr+32, txt, CS_LOGHISTSIZE-33);
1172 *loghistidx=(*loghistidx+1) % CS_MAXLOGHIST;
1173#endif
1174}
1175
1176/*
1177 * write_to_pipe():
1178 * write all kind of data to pipe specified by fd
1179 */
1180int write_to_pipe(int fd, int id, uchar *data, int n)
1181{
1182 if( !fd ) {
1183 cs_log("write_to_pipe: fd==0 id: %d", id);
1184 return -1;
1185 }
1186
1187//printf("WRITE_START pid=%d", getpid()); fflush(stdout);
1188
1189 uchar buf[1024+3+sizeof(int)];
1190
1191 if ((id<0) || (id>PIP_ID_MAX))
1192 return(PIP_ID_ERR);
1193 memcpy(buf, PIP_ID_TXT[id], 3);
1194 memcpy(buf+3, &n, sizeof(int));
1195 memcpy(buf+3+sizeof(int), data, n);
1196 n+=3+sizeof(int);
1197
1198//n=write(fd, buf, n);
1199//printf("WRITE_END pid=%d", getpid()); fflush(stdout);
1200//return(n);
1201
1202 if( !fd ) {
1203 cs_log("write_to_pipe: fd==0");
1204 return(PIP_ID_ERR);
1205 }
1206
1207 return(write(fd, buf, n));
1208}
1209
1210/*
1211 * read_from_pipe():
1212 * read all kind of data from pipe specified by fd
1213 * special-flag redir: if set AND data is ECM: this will redirected to appr. client
1214 */
1215int read_from_pipe(int fd, uchar **data, int redir)
1216{
1217 int rc;
1218 static int hdr=0;
1219 static uchar buf[1024+1+3+sizeof(int)];
1220
1221 *data=(uchar *)0;
1222 rc=PIP_ID_NUL;
1223
1224 if (!hdr)
1225 {
1226 if (bytes_available(fd))
1227 {
1228 if (read(fd, buf, 3+sizeof(int))==3+sizeof(int))
1229 memcpy(&hdr, buf+3, sizeof(int));
1230 else
1231 cs_log("WARNING: pipe header to small !");
1232 }
1233 }
1234 if (hdr)
1235 {
1236 int l;
1237 for (l=0; (rc<0) && (PIP_ID_TXT[l]); l++)
1238 if (!memcmp(buf, PIP_ID_TXT[l], 3))
1239 rc=l;
1240
1241 if (rc<0)
1242 {
1243 fprintf(stderr, "WARNING: pipe garbage from pipe %i", fd);
1244 fflush(stderr);
1245 cs_log("WARNING: pipe garbage from pipe %i", fd);
1246 rc=PIP_ID_ERR;
1247 }
1248 else
1249 {
1250 l=hdr;
1251 if ((l+3-1+sizeof(int))>sizeof(buf))
1252 {
1253 cs_log("WARNING: packet size (%d) to large", l);
1254 l=sizeof(buf)+3-1+sizeof(int);
1255 }
1256 if (!bytes_available(fd))
1257 return(PIP_ID_NUL);
1258 hdr=0;
1259 if (read(fd, buf+3+sizeof(int), l)==l)
1260 *data=buf+3+sizeof(int);
1261 else
1262 {
1263 cs_log("WARNING: pipe data to small !");
1264 return(PIP_ID_ERR);
1265 }
1266 buf[l+3+sizeof(int)]=0;
1267 if ((redir) && (rc==PIP_ID_ECM))
1268 {
1269 //int idx;
1270 ECM_REQUEST *er;
1271 er=(ECM_REQUEST *)(buf+3+sizeof(int));
1272 if( er->cidx && client[er->cidx].fd_m2c )
1273 if (!write(client[er->cidx].fd_m2c, buf, l+3+sizeof(int))) cs_exit(1);
1274 rc=PIP_ID_DIR;
1275 }
1276 }
1277 }
1278 return(rc);
1279}
1280
1281/*
1282 * write_ecm_request():
1283 */
1284int write_ecm_request(int fd, ECM_REQUEST *er)
1285{
1286 return(write_to_pipe(fd, PIP_ID_ECM, (uchar *) er, sizeof(ECM_REQUEST)));
1287}
1288
1289int write_ecm_DCW(int fd, ECM_REQUEST *er)
1290{
1291 return(write_to_pipe(fd, PIP_ID_DCW, (uchar *) er, sizeof(ECM_REQUEST)));
1292}
1293
1294/*
1295 * This function writes the current CW from ECM struct to a cwl file.
1296 * The filename is re-calculated and file re-opened every time.
1297 * This will consume a bit cpu time, but nothing has to be stored between
1298 * each call. If not file exists, a header is prepended
1299 */
1300void logCWtoFile(ECM_REQUEST *er)
1301{
1302 FILE *pfCWL;
1303 char srvname[128];
1304 /* %s / %s _I %04X _ %s .cwl */
1305 char buf[256 + sizeof(srvname)];
1306 char date[7];
1307 unsigned char i, parity, writeheader = 0;
1308 time_t t;
1309 struct tm *timeinfo;
1310 struct s_srvid *this;
1311
1312 /*
1313 * search service name for that id and change characters
1314 * causing problems in file name
1315 */
1316 srvname[0] = 0;
1317 for (this=cfg->srvid; this; this = this->next) {
1318 if (this->srvid == er->srvid) {
1319 cs_strncpy(srvname, this->name, sizeof(srvname));
1320 srvname[sizeof(srvname)-1] = 0;
1321 for (i = 0; srvname[i]; i++)
1322 if (srvname[i] == ' ') srvname[i] = '_';
1323 break;
1324 }
1325 }
1326
1327 /* calc log file name */
1328 time(&t);
1329 timeinfo = localtime(&t);
1330 strftime(date, sizeof(date), "%Y%m%d", timeinfo);
1331 sprintf(buf, "%s/%s_I%04X_%s.cwl", cfg->cwlogdir, date, er->srvid, srvname);
1332
1333 /* open failed, assuming file does not exist, yet */
1334 if((pfCWL = fopen(buf, "r")) == NULL) {
1335 writeheader = 1;
1336 } else {
1337 /* we need to close the file if it was opened correctly */
1338 fclose(pfCWL);
1339 }
1340
1341 if ((pfCWL = fopen(buf, "a+")) == NULL) {
1342 /* maybe this fails because the subdir does not exist. Is there a common function to create it?
1343 for the moment do not print to log on every ecm
1344 cs_log(""error opening cw logfile for writing: %s (errno %d)", buf, errno); */
1345 return;
1346 }
1347 if (writeheader) {
1348 /* no global macro for cardserver name :( */
1349 fprintf(pfCWL, "# OSCam cardserver v%s - http://streamboard.gmc.to:8001/oscam/wiki\n", CS_VERSION_X);
1350 fprintf(pfCWL, "# control word log file for use with tsdec offline decrypter\n");
1351 strftime(buf, sizeof(buf),"DATE %Y-%m-%d, TIME %H:%M:%S, TZ %Z\n", timeinfo);
1352 fprintf(pfCWL, "# %s", buf);
1353 fprintf(pfCWL, "# CAID 0x%04X, SID 0x%04X, SERVICE \"%s\"\n", er->caid, er->srvid, srvname);
1354 }
1355
1356 parity = er->ecm[0]&1;
1357 fprintf(pfCWL, "%d ", parity);
1358 for (i = parity * 8; i < 8 + parity * 8; i++)
1359 fprintf(pfCWL, "%02X ", er->cw[i]);
1360 /* better use incoming time er->tps rather than current time? */
1361 strftime(buf,sizeof(buf),"%H:%M:%S\n", timeinfo);
1362 fprintf(pfCWL, "# %s", buf);
1363 fflush(pfCWL);
1364 fclose(pfCWL);
1365}
1366
1367int write_ecm_answer(struct s_reader * reader, int fd, ECM_REQUEST *er)
1368{
1369 int i;
1370 uchar c;
1371 for (i=0; i<16; i+=4)
1372 {
1373 c=((er->cw[i]+er->cw[i+1]+er->cw[i+2]) & 0xff);
1374 if (er->cw[i+3]!=c)
1375 {
1376 cs_debug("notice: changed dcw checksum byte cw[%i] from %02x to %02x", i+3, er->cw[i+3],c);
1377 er->cw[i+3]=c;
1378 }
1379 }
1380
1381 er->reader[0]=client[reader->cidx].ridx;
1382//cs_log("answer from reader %d (rc=%d)", er->reader[0], er->rc);
1383 er->caid=er->ocaid;
1384
1385#ifdef CS_WITH_GBOX
1386 if (er->rc==1||(er->gbxRidx&&er->rc==0)) {
1387#else
1388 if (er->rc==1) {
1389#endif
1390 store_ecm(er);
1391
1392 /* CWL logging only if cwlogdir is set in config */
1393 if (cfg->cwlogdir != NULL)
1394 logCWtoFile(er);
1395 }
1396
1397 return(write_ecm_request(fd, er));
1398}
1399
1400 /*
1401static int cs_read_timer(int fd, uchar *buf, int l, int msec)
1402{
1403 struct timeval tv;
1404 fd_set fds;
1405 int rc;
1406
1407 if (!fd) return(-1);
1408 tv.tv_sec = msec / 1000;
1409 tv.tv_usec = (msec % 1000) * 1000;
1410 FD_ZERO(&fds);
1411 FD_SET(client[cs_idx].pfd, &fds);
1412
1413 select(fd+1, &fds, 0, 0, &tv);
1414
1415 rc=0;
1416 if (FD_ISSET(client[cs_idx].pfd, &fds))
1417 if (!(rc=read(fd, buf, l)))
1418 rc=-1;
1419
1420 return(rc);
1421}*/
1422
1423ECM_REQUEST *get_ecmtask()
1424{
1425 int i, n;
1426 ECM_REQUEST *er=0;
1427
1428 if (!client[cs_idx].ecmtask)
1429 {
1430 n=(ph[client[cs_idx].ctyp].multi)?CS_MAXPENDING:1;
1431 if( (client[cs_idx].ecmtask=(ECM_REQUEST *)malloc(n*sizeof(ECM_REQUEST))) )
1432 memset(client[cs_idx].ecmtask, 0, n*sizeof(ECM_REQUEST));
1433 }
1434
1435 n=(-1);
1436 if (!client[cs_idx].ecmtask)
1437 {
1438 cs_log("Cannot allocate memory (errno=%d)", errno);
1439 n=(-2);
1440 }
1441 else
1442 if (ph[client[cs_idx].ctyp].multi)
1443 {
1444 for (i=0; (n<0) && (i<CS_MAXPENDING); i++)
1445 if (client[cs_idx].ecmtask[i].rc<100)
1446 er=&client[cs_idx].ecmtask[n=i];
1447 }
1448 else
1449 er=&client[cs_idx].ecmtask[n=0];
1450
1451 if (n<0)
1452 cs_log("WARNING: ecm pending table overflow !");
1453 else
1454 {
1455 memset(er, 0, sizeof(ECM_REQUEST));
1456 er->rc=100;
1457 er->cpti=n;
1458 er->cidx=cs_idx;
1459 cs_ftime(&er->tps);
1460 }
1461 return(er);
1462}
1463
1464void send_reader_stat(int ridx9, ECM_REQUEST *er, int rc)
1465{
1466 if (!cfg->lb_mode || rc == 100)
1467 return;
1468 struct timeb tpe;
1469 cs_ftime(&tpe);
1470 int time = 1000*(tpe.time-er->tps.time)+tpe.millitm-er->tps.millitm;
1471
1472 ADD_READER_STAT add_stat;
1473 memset(&add_stat, 0, sizeof(ADD_READER_STAT));
1474 add_stat.ridx = ridx9;
1475 add_stat.time = time;
1476 add_stat.rc = rc;
1477 add_stat.caid = er->caid;
1478 add_stat.prid = er->prid;
1479 add_stat.srvid = er->srvid;
1480 add_reader_stat(&add_stat);
1481}
1482
1483int hexserialset(int ridx)
1484{
1485 int i;
1486 for (i = 0; i < 8; i++)
1487 if (reader[ridx].hexserial[i])
1488 return 1;
1489 return 0;
1490}
1491
1492// rc codes:
1493// 0 = found
1494// 1 = cache1
1495// 2 = cache2
1496// 3 = emu
1497// 4 = not found
1498// 5 = timeout
1499// 6 = sleeping
1500// 7 = fake
1501// 8 = invalid
1502// 9 = corrupt
1503// 10= no card
1504// 11= expdate
1505// 12= disabled
1506// 13= stopped
1507// 100=unhandled
1508
1509int send_dcw(ECM_REQUEST *er)
1510{
1511 static const char *stxt[]={"found", "cache1", "cache2", "emu",
1512 "not found", "timeout", "sleeping",
1513 "fake", "invalid", "corrupt", "no card", "expdate", "disabled", "stopped"};
1514 static const char *stxtEx[]={"", "group", "caid", "ident", "class", "chid", "queue", "peer"};
1515 static const char *stxtWh[]={"", "user ", "reader ", "server ", "lserver "};
1516 char sby[32]="", sreason[32]="", schaninfo[32]="";
1517 char erEx[32]="";
1518 char uname[38]="";
1519 struct timeb tpe;
1520 ushort lc, *lp;
1521 for (lp=(ushort *)er->ecm+(er->l>>2), lc=0; lp>=(ushort *)er->ecm; lp--)
1522 lc^=*lp;
1523
1524#ifdef CS_WITH_GBOX
1525 if(er->gbxFrom)
1526 snprintf(uname,sizeof(uname)-1, "%s(%04X)", username(cs_idx), er->gbxFrom);
1527 else
1528#endif
1529 snprintf(uname,sizeof(uname)-1, "%s", username(cs_idx));
1530 if (er->rc==0)
1531 {
1532#ifdef CS_WITH_GBOX
1533 if(reader[er->reader[0]].typ==R_GBOX)
1534 snprintf(sby, sizeof(sby)-1, " by %s(%04X)", reader[er->reader[0]].label,er->gbxCWFrom);
1535 else
1536#endif
1537 // add marker to reader if ECM_REQUEST was betatunneled
1538 if(er->btun)
1539 snprintf(sby, sizeof(sby)-1, " by %s(btun)", reader[er->reader[0]].label);
1540 else
1541 snprintf(sby, sizeof(sby)-1, " by %s", reader[er->reader[0]].label);
1542 }
1543 if (er->rc<4) er->rcEx=0;
1544 if (er->rcEx)
1545 snprintf(erEx, sizeof(erEx)-1, "rejected %s%s", stxtWh[er->rcEx>>4],
1546 stxtEx[er->rcEx&0xf]);
1547
1548 if(cfg->mon_appendchaninfo)
1549 snprintf(schaninfo, sizeof(schaninfo)-1, " - %s", get_servicename(er->srvid, er->caid));
1550
1551 if(er->msglog[0])
1552 snprintf(sreason, sizeof(sreason)-1, " (%s)", er->msglog);
1553
1554 cs_ftime(&tpe);
1555 client[cs_idx].cwlastresptime = 1000*(tpe.time-er->tps.time)+tpe.millitm-er->tps.millitm;
1556
1557#ifdef CS_LED
1558 if(!er->rc) cs_switch_led(LED2, LED_BLINK_OFF);
1559#endif
1560
1561 send_reader_stat(er->reader[0], er, er->rc);
1562
1563 cs_log("%s (%04X&%06X/%04X/%02X:%04X): %s (%d ms)%s%s%s",
1564 uname, er->caid, er->prid, er->srvid, er->l, lc,
1565 er->rcEx?erEx:stxt[er->rc], client[cs_idx].cwlastresptime, sby, schaninfo, sreason);
1566
1567#ifdef WEBIF
1568 if(er->rc == 0)
1569 snprintf(client[cs_idx].lastreader, sizeof(client[cs_idx].lastreader)-1, "%s", sby);
1570 else if ((er->rc == 1) || (er->rc == 2))
1571 snprintf(client[cs_idx].lastreader, sizeof(client[cs_idx].lastreader)-1, "by %s (cache)", reader[er->reader[0]].label);
1572 else
1573 snprintf(client[cs_idx].lastreader, sizeof(client[cs_idx].lastreader)-1, "%s", stxt[er->rc]);
1574#endif
1575
1576 if(!client[cs_idx].ncd_server && client[cs_idx].autoau && er->rcEx==0)
1577 {
1578 if(client[cs_idx].au>=0 && er->caid!=reader[client[cs_idx].au].caid[0])
1579 {
1580 client[cs_idx].au=(-1);
1581 }
1582 //martin
1583 //client[cs_idx].au=er->reader[0];
1584 //if(client[cs_idx].au<0)
1585 //{
1586 struct s_reader *cur = &reader[er->reader[0]];
1587
1588 if (cur->typ == R_CCCAM && !cur->caid[0] && !cur->audisabled &&
1589 cur->card_system == get_cardsystem(er->caid) && hexserialset(er->reader[0]))
1590 client[cs_idx].au = er->reader[0];
1591 else if((er->caid == cur->caid[0]) && (!cur->audisabled)) {
1592 client[cs_idx].au = er->reader[0]; // First chance - check whether actual reader can AU
1593 } else {
1594 int r=0;
1595 for(r=0;r<CS_MAXREADER;r++) //second chance loop through all readers to find an AU reader
1596 {
1597 cur = &reader[r];
1598 if (matching_reader(er, cur)) {
1599 if (cur->typ == R_CCCAM && !cur->caid[0] && !cur->audisabled &&
1600 cur->card_system == get_cardsystem(er->caid) && hexserialset(r))
1601 {
1602 client[cs_idx].au = r;
1603 break;
1604 }
1605 else if((er->caid == cur->caid[0]) && (er->prid == cur->auprovid) && (!cur->audisabled))
1606 {
1607 client[cs_idx].au=r;
1608 break;
1609 }
1610 }
1611 }
1612 if(r==CS_MAXREADER)
1613 {
1614 client[cs_idx].au=(-1);
1615 }
1616 }
1617 //}
1618 }
1619
1620 er->caid = er->ocaid;
1621 switch(er->rc) {
1622 case 0:
1623 case 3:
1624 // 0 - found
1625 // 3 - emu FIXME: obsolete ?
1626 client[cs_idx].cwfound++;
1627 break;
1628
1629 case 1:
1630 case 2:
1631 // 1 - cache1
1632 // 2 - cache2
1633 client[cs_idx].cwcache++;
1634 break;
1635
1636 case 4:
1637 case 9:
1638 case 10:
1639 // 4 - not found
1640 // 9 - corrupt
1641 // 10 - no card
1642 if (er->rcEx)
1643 client[cs_idx].cwignored++;
1644 else
1645 client[cs_idx].cwnot++;
1646 break;
1647
1648 case 5:
1649 // 5 - timeout
1650 client[cs_idx].cwtout++;
1651 break;
1652
1653 default:
1654 client[cs_idx].cwignored++;
1655 }
1656
1657#ifdef CS_ANTICASC
1658 ac_chk(er, 1);
1659#endif
1660
1661 cs_ddump_mask (D_ATR, er->cw, 16, "cw:");
1662 if (er->rc==7) er->rc=0;
1663
1664#ifdef CS_WITH_DOUBLECHECK
1665 if (cfg->double_check && er->rc < 4) {
1666 if (er->checked == 0) {//First CW, save it and wait for next one
1667 er->checked = 1;
1668 er->origin_reader = er->reader[0]; //contains ridx
1669 memcpy(er->cw_checked, er->cw, sizeof(er->cw));
1670 cs_log("DOUBLE CHECK FIRST CW by %s idx %d cpti %d", reader[er->origin_reader].label, er->idx, er->cpti);
1671 }
1672 else if (er->origin_reader != er->reader[0]) { //Second (or third and so on) cw. We have to compare
1673 if (memcmp(er->cw_checked, er->cw, sizeof(er->cw)) == 0) {
1674 er->checked++;
1675 cs_log("DOUBLE CHECKED! %d. CW by %s idx %d cpti %d", er->checked, reader[er->reader[0]].label, er->idx, er->cpti);
1676 }
1677 else {
1678 cs_log("DOUBLE CHECKED NONMATCHING! %d. CW by %s idx %d cpti %d", er->checked, reader[er->reader[0]].label, er->idx, er->cpti);
1679 }
1680 }
1681
1682 if (er->checked < 2) { //less as two same cw? mark as pending!
1683 er->rc = 100;
1684 return 0;
1685 }
1686
1687 store_ecm(er); //Store in cache!
1688 }
1689#endif
1690
1691 ph[client[cs_idx].ctyp].send_dcw(er);
1692 return 0;
1693}
1694
1695void chk_dcw(int fd)
1696{
1697 ECM_REQUEST *er, *ert;
1698 if (read_from_pipe(fd, (uchar **)(void *)&er, 0) != PIP_ID_ECM)
1699 return;
1700 //cs_log("dcw check from reader %d for idx %d (rc=%d)", er->reader[0], er->cpti, er->rc);
1701 ert=&client[cs_idx].ecmtask[er->cpti];
1702 if (ert->rc<100) {
1703 //cs_debug_mask(D_TRACE, "chk_dcw: already done rc=%d %s", er->rc, reader[er->reader[0]].label);
1704 send_reader_stat(er->reader[0], er, (er->rc <= 0)?4:0);
1705 return; // already done
1706 }
1707 if( (er->caid!=ert->caid) || memcmp(er->ecm , ert->ecm , sizeof(er->ecm)) )
1708 return; // obsolete
1709 ert->rcEx=er->rcEx;
1710 strcpy(ert->msglog, er->msglog);
1711 if (er->rc>0) // found
1712 {
1713 switch(er->rc)
1714 {
1715 case 2:
1716 ert->rc=2;
1717 break;
1718 case 3:
1719 ert->rc=3;
1720 break;
1721 default:
1722 ert->rc=0;
1723 }
1724 ert->rcEx=0;
1725 ert->reader[0]=er->reader[0];
1726 memcpy(ert->cw , er->cw , sizeof(er->cw));
1727#ifdef CS_WITH_GBOX
1728 ert->gbxCWFrom=er->gbxCWFrom;
1729#endif
1730 }
1731 else // not found (from ONE of the readers !)
1732 {
1733 //save reader informations for loadbalance-statistics:
1734 ECM_REQUEST *save_ert = ert;
1735 int save_ridx = er->reader[0];
1736
1737 //
1738 int i;
1739 ert->reader[er->reader[0]]=0;
1740 for (i=0; (ert) && (i<CS_MAXREADER); i++)
1741 if (ert->reader[i]) {// we have still another chance
1742 ert=(ECM_REQUEST *)0;
1743 }
1744 if (ert) ert->rc=4;
1745 else send_reader_stat(save_ridx, save_ert, 4);
1746 }
1747 if (ert) send_dcw(ert);
1748 return;
1749}
1750
1751ulong chk_provid(uchar *ecm, ushort caid) {
1752 int i, len, descriptor_length = 0;
1753 ulong provid = 0;
1754
1755 switch(caid >> 8) {
1756 case 0x01:
1757 // seca
1758 provid = b2i(2, ecm+3);
1759 break;
1760
1761 case 0x05:
1762 // viaccess
1763 i = (ecm[4] == 0xD2) ? ecm[5]+2 : 0; // skip d2 nano
1764 if((ecm[5+i] == 3) && ((ecm[4+i] == 0x90) || (ecm[4+i] == 0x40)))
1765 provid = (b2i(3, ecm+6+i) & 0xFFFFF0);
1766
1767 i = (ecm[6] == 0xD2) ? ecm[7]+2 : 0; // skip d2 nano long ecm
1768 if((ecm[7+i] == 7) && ((ecm[6+i] == 0x90) || (ecm[6+i] == 0x40)))
1769 provid = (b2i(3, ecm+8+i) & 0xFFFFF0);
1770
1771 break;
1772
1773 case 0x0D:
1774 // cryptoworks
1775 len = (((ecm[1] & 0xf) << 8) | ecm[2])+3;
1776 for(i=8; i<len; i+=descriptor_length+2) {
1777 descriptor_length = ecm[i+1];
1778 if (ecm[i] == 0x83) {
1779 provid = (ulong)ecm[i+2] & 0xFE;
1780 break;
1781 }
1782 }
1783 break;
1784 }
1785 return(provid);
1786}
1787
1788#ifdef IRDETO_GUESSING
1789void guess_irdeto(ECM_REQUEST *er)
1790{
1791 uchar b3;
1792 int b47;
1793 //ushort chid;
1794 struct s_irdeto_quess *ptr;
1795
1796 b3 = er->ecm[3];
1797 ptr = cfg->itab[b3];
1798 if( !ptr ) {
1799 cs_debug("unknown irdeto byte 3: %02X", b3);
1800 return;
1801 }
1802 b47 = b2i(4, er->ecm+4);
1803 //chid = b2i(2, er->ecm+6);
1804 //cs_debug("ecm: b47=%08X, ptr->b47=%08X, ptr->caid=%04X", b47, ptr->b47, ptr->caid);
1805 while( ptr )
1806 {
1807 if( b47==ptr->b47 )
1808 {
1809 if( er->srvid && (er->srvid!=ptr->sid) )
1810 {
1811 cs_debug("sid mismatched (ecm: %04X, guess: %04X), wrong oscam.ird file?",
1812 er->srvid, ptr->sid);
1813 return;
1814 }
1815 er->caid=ptr->caid;
1816 er->srvid=ptr->sid;
1817 er->chid=(ushort)ptr->b47;
1818// cs_debug("quess_irdeto() found caid=%04X, sid=%04X, chid=%04X",
1819// er->caid, er->srvid, er->chid);
1820 return;
1821 }
1822 ptr=ptr->next;
1823 }
1824}
1825#endif
1826
1827void cs_betatunnel(ECM_REQUEST *er)
1828{
1829 int n;
1830 ulong mask_all = 0xFFFF;
1831 TUNTAB *ttab;
1832 ttab = &client[cs_idx].ttab;
1833 for (n = 0; (n < CS_MAXTUNTAB); n++) {
1834 if ((er->caid==ttab->bt_caidfrom[n]) && ((er->srvid==ttab->bt_srvid[n]) || (ttab->bt_srvid[n])==mask_all)) {
1835 uchar hack_n3[13] = {0x70, 0x51, 0xc7, 0x00, 0x00, 0x00, 0x01, 0x10, 0x10, 0x00, 0x87, 0x12, 0x07};
1836 uchar hack_n2[13] = {0x70, 0x51, 0xc9, 0x00, 0x00, 0x00, 0x01, 0x10, 0x10, 0x00, 0x48, 0x12, 0x07};
1837 er->caid = ttab->bt_caidto[n];
1838 er->prid = 0;
1839 er->l = (er->ecm[2]+3);
1840 memmove(er->ecm+14, er->ecm+4, er->l-1);
1841 if (er->l > 0x88) {
1842 memcpy(er->ecm+1, hack_n3, 13);
1843 if (er->ecm[0] == 0x81)
1844 er->ecm[12] += 1;
1845 }
1846 else {
1847 memcpy(er->ecm+1, hack_n2, 13);
1848 }
1849 er->l += 10;
1850 er->ecm[2] = er->l-3;
1851 er->btun = 1;
1852 client[cs_idx].cwtun++;
1853 cs_debug("ECM converted from: 0x%X to BetaCrypt: 0x%X for service id:0x%X",
1854 ttab->bt_caidfrom[n], ttab->bt_caidto[n], ttab->bt_srvid[n]);
1855 }
1856 }
1857}
1858
1859void guess_cardsystem(ECM_REQUEST *er)
1860{
1861 ushort last_hope=0;
1862
1863 // viaccess - check by provid-search
1864 if( (er->prid=chk_provid(er->ecm, 0x500)) )
1865 er->caid=0x500;
1866
1867 // nagra
1868 // is ecm[1] always 0x30 ?
1869 // is ecm[3] always 0x07 ?
1870 if ((er->ecm[6]==1) && (er->ecm[4]==er->ecm[2]-2))
1871 er->caid=0x1801;
1872
1873 // seca2 - very poor
1874 if ((er->ecm[8]==0x10) && ((er->ecm[9]&0xF1)==1))
1875 last_hope=0x100;
1876
1877 // is cryptoworks, but which caid ?
1878 if ((er->ecm[3]==0x81) && (er->ecm[4]==0xFF) &&
1879 (!er->ecm[5]) && (!er->ecm[6]) && (er->ecm[7]==er->ecm[2]-5))
1880 last_hope=0xd00;
1881
1882#ifdef IRDETO_GUESSING
1883 if (!er->caid && er->ecm[2]==0x31 && er->ecm[0x0b]==0x28)
1884 guess_irdeto(er);
1885#endif
1886
1887 if (!er->caid) // guess by len ..
1888 er->caid=len4caid[er->ecm[2]+3];
1889
1890 if (!er->caid)
1891 er->caid=last_hope;
1892}
1893
1894void request_cw(ECM_REQUEST *er, int flag, int reader_types)
1895{
1896 int i;
1897 if ((reader_types == 0) || (reader_types == 2))
1898 er->level=flag;
1899 flag=(flag)?3:1; // flag specifies with/without fallback-readers
1900 for (i=0; i<CS_MAXREADER; i++)
1901 {
1902 //if (reader[i].pid)
1903 // cs_log("active reader: %d pid %d fd %d", i, reader[i].pid, reader[i].fd);
1904 int status = 0;
1905 switch (reader_types)
1906 {
1907 // network and local cards
1908 default:
1909 case 0:
1910 if (er->reader[i]&flag){
1911 cs_debug_mask(D_TRACE, "request_cw1 to reader %s ridx=%d fd=%d", reader[i].label, i, reader[i].fd);
1912 status = write_ecm_request(reader[i].fd, er);
1913 }
1914 break;
1915 // only local cards
1916 case 1:
1917 if (!(reader[i].typ & R_IS_NETWORK))
1918 if (er->reader[i]&flag) {
1919 cs_debug_mask(D_TRACE, "request_cw2 to reader %s ridx=%d fd=%d", reader[i].label, i, reader[i].fd);
1920 status = write_ecm_request(reader[i].fd, er);
1921 }
1922 break;
1923 // only network
1924 case 2:
1925 //cs_log("request_cw3 ridx=%d fd=%d", i, reader[i].fd);
1926 if ((reader[i].typ & R_IS_NETWORK))
1927 if (er->reader[i]&flag) {
1928 cs_debug_mask(D_TRACE, "request_cw3 to reader %s ridx=%d fd=%d", reader[i].label, i, reader[i].fd);
1929 status = write_ecm_request(reader[i].fd, er);
1930 }
1931 break;
1932 }
1933 if (status == -1) {
1934 cs_log("request_cw() failed on reader %s (%d) errno=%d, %s", reader[i].label, i, errno, strerror(errno));
1935 if (reader[i].fd) {
1936 reader[i].fd_error++;
1937 if (reader[i].fd_error > 5) {
1938 reader[i].fd_error = 0;
1939 send_restart_cardreader(i, 1); //Schlocke: This restarts the reader!
1940 }
1941 }
1942 }
1943 else
1944 reader[i].fd_error = 0;
1945 }
1946}
1947
1948//receive best reader from master process. Call this function from client!
1949void recv_best_reader(ECM_REQUEST *er, int *reader_avail)
1950{
1951 GET_READER_STAT grs;
1952 memset(&grs, 0, sizeof(grs));
1953 grs.caid = er->caid;
1954 grs.prid = er->prid;
1955 grs.srvid = er->srvid;
1956 grs.cidx = cs_idx;
1957 memcpy(grs.ecmd5, er->ecmd5, sizeof(er->ecmd5));
1958 memcpy(grs.reader_avail, reader_avail, sizeof(int)*CS_MAXREADER);
1959 cs_debug_mask(D_TRACE, "requesting client %s best reader for %04X/%06X/%04X", username(cs_idx), grs.caid, grs.prid, grs.srvid);
1960
1961 get_best_reader(&grs, reader_avail);
1962}
1963
1964void get_cw(ECM_REQUEST *er)
1965{
1966 int i, j, m;
1967 time_t now = time((time_t)0);
1968
1969 client[cs_idx].lastecm = now;
1970
1971 if (!er->caid)
1972 guess_cardsystem(er);
1973
1974 /* Quickfix Area */
1975
1976 if( (er->caid & 0xFF00) == 0x600 && !er->chid )
1977 er->chid = (er->ecm[6]<<8)|er->ecm[7];
1978
1979 // quickfix for 0100:000065
1980 if (er->caid == 0x100 && er->prid == 0x65 && er->srvid == 0)
1981 er->srvid = 0x0642;
1982
1983 // Quickfixes for Opticum/Globo HD9500
1984 // Quickfix for 0500:030300
1985 if (er->caid == 0x500 && er->prid == 0x030300)
1986 er->prid = 0x030600;
1987
1988 // Quickfix for 0500:D20200
1989 if (er->caid == 0x500 && er->prid == 0xD20200)
1990 er->prid = 0x030600;
1991
1992 /* END quickfixes */
1993
1994 if (!er->prid)
1995 er->prid = chk_provid(er->ecm, er->caid);
1996
1997 // Set providerid for newcamd clients if none is given
1998 if( (!er->prid) && client[cs_idx].ncd_server ) {
1999 int pi = client[cs_idx].port_idx;
2000 if( pi >= 0 && cfg->ncd_ptab.nports && cfg->ncd_ptab.nports >= pi )
2001 er->prid = cfg->ncd_ptab.ports[pi].ftab.filts[0].prids[0];
2002 }
2003
2004 // CAID not supported or found
2005 if (!er->caid) {
2006 er->rc = 8;
2007 er->rcEx = E2_CAID;
2008 snprintf( er->msglog, MSGLOGSIZE, "CAID not supported or found" );
2009 }
2010
2011 // user expired
2012 if(client[cs_idx].expirationdate && client[cs_idx].expirationdate < client[cs_idx].lastecm)
2013 er->rc = 11;
2014
2015 // out of timeframe
2016 if(client[cs_idx].allowedtimeframe[0] && client[cs_idx].allowedtimeframe[1]) {
2017 struct tm *acttm;
2018 acttm = localtime(&now);
2019 int curtime = (acttm->tm_hour * 60) + acttm->tm_min;
2020 int mintime = client[cs_idx].allowedtimeframe[0];
2021 int maxtime = client[cs_idx].allowedtimeframe[1];
2022 if(!((mintime <= maxtime && curtime > mintime && curtime < maxtime) || (mintime > maxtime && (curtime > mintime || curtime < maxtime)))) {
2023 er->rc = 11;
2024 }
2025 cs_debug("Check Timeframe - result: %d, start: %d, current: %d, end: %d\n",er->rc, mintime, curtime, maxtime);
2026 }
2027
2028 // user disabled
2029 if(client[cs_idx].disabled != 0)
2030 er->rc = 12;
2031
2032 // rc<100 -> ecm error
2033 if (er->rc > 99) {
2034
2035 m = er->caid;
2036 er->ocaid = er->caid;
2037 i = er->srvid;
2038
2039 if ((i != client[cs_idx].last_srvid) || (!client[cs_idx].lastswitch)) {
2040 if(cfg->usrfileflag)
2041 cs_statistics(cs_idx);
2042 client[cs_idx].lastswitch = now;
2043 }
2044
2045 // user sleeping
2046 if ((client[cs_idx].tosleep) && (now - client[cs_idx].lastswitch > client[cs_idx].tosleep)) {
2047 if (client[cs_idx].c35_sleepsend != 0) {
2048 er->rc = 13; // send stop command CMD08 {00 xx}
2049 } else {
2050 er->rc = 6;
2051 }
2052 }
2053
2054 client[cs_idx].last_srvid = i;
2055 client[cs_idx].last_caid = m;
2056
2057 for (j = 0; (j < 6) && (er->rc > 99); j++)
2058 {
2059 switch(j) {
2060
2061 case 0:
2062 // fake (uniq)
2063 if (client[cs_idx].dup)
2064 er->rc = 7;
2065 break;
2066
2067 case 1:
2068 // invalid (caid)
2069 if (!chk_bcaid(er, &client[cs_idx].ctab)) {
2070 er->rc = 8;
2071 er->rcEx = E2_CAID;
2072 snprintf( er->msglog, MSGLOGSIZE, "invalid caid %x",er->caid );
2073 }
2074 break;
2075
2076 case 2:
2077 // invalid (srvid)
2078 if (!chk_srvid(er, cs_idx))
2079 {
2080 er->rc = 8;
2081 snprintf( er->msglog, MSGLOGSIZE, "invalid SID" );
2082 }
2083
2084 break;
2085
2086 case 3:
2087 // invalid (ufilters)
2088 if (!chk_ufilters(er))
2089 er->rc = 8;
2090 break;
2091
2092 case 4:
2093 // invalid (sfilter)
2094 if (!chk_sfilter(er, ph[client[cs_idx].ctyp].ptab))
2095 er->rc = 8;
2096 break;
2097
2098 case 5:
2099 // corrupt
2100 if( (i = er->l - (er->ecm[2] + 3)) ) {
2101 if (i > 0) {
2102 cs_debug("warning: ecm size adjusted from 0x%X to 0x%X",
2103 er->l, er->ecm[2] + 3);
2104 er->l = (er->ecm[2] + 3);
2105 }
2106 else
2107 er->rc = 9;
2108 }
2109 break;
2110 }
2111 }
2112 }
2113
2114 //Schlocke: above checks could change er->rc so
2115 if (er->rc > 99) {
2116 /*BetaCrypt tunneling
2117 *moved behind the check routines,
2118 *because newcamd ECM will fail
2119 *if ECM is converted before
2120 */
2121 if (&client[cs_idx].ttab)
2122 cs_betatunnel(er);
2123
2124 // store ECM in cache
2125 memcpy(er->ecmd5, MD5(er->ecm, er->l, NULL), CS_ECMSTORESIZE);
2126
2127 // cache1
2128 if (check_ecmcache1(er, client[cs_idx].grp))
2129 er->rc = 1;
2130
2131#ifdef CS_ANTICASC
2132 ac_chk(er, 0);
2133#endif
2134 }
2135
2136 if(er->rc > 99) {
2137
2138 if (cfg->lb_mode) {
2139 int reader_avail[CS_MAXREADER];
2140 for (i =0; i < CS_MAXREADER; i++)
2141 reader_avail[i] = matching_reader(er, &reader[i]);
2142
2143 recv_best_reader(er, reader_avail);
2144
2145 for (i = m = 0; i < CS_MAXREADER; i++) {
2146 if (reader_avail[i]) {
2147 m|=er->reader[i] = reader_avail[i];
2148 }
2149 }
2150 }
2151 else
2152 {
2153 for (i = m = 0; i < CS_MAXREADER; i++)
2154 if (matching_reader(er, &reader[i]))
2155 m|=er->reader[i] = (reader[i].fallback)? 2: 1;
2156 }
2157
2158 switch(m) {
2159 // no reader -> not found
2160 case 0:
2161 er->rc = 4;
2162 if (!er->rcEx)
2163 er->rcEx = E2_GROUP;
2164 break;
2165
2166 // fallbacks only, switch them
2167 case 2:
2168 for (i = 0; i < CS_MAXREADER; i++)
2169 er->reader[i]>>=1;
2170 }
2171 }
2172
2173 if (er->rc < 100) {
2174 if (cfg->delay)
2175 cs_sleepms(cfg->delay);
2176
2177 send_dcw(er);
2178 return;
2179 }
2180
2181 er->rcEx = 0;
2182 request_cw(er, 0, cfg->preferlocalcards ? 1 : 0);
2183}
2184
2185void log_emm_request(int auidx)
2186{
2187 cs_log("%s emm-request sent (reader=%s, caid=%04X, auprovid=%06lX)",
2188 username(cs_idx), reader[auidx].label, reader[auidx].caid[0],
2189 reader[auidx].auprovid ? reader[auidx].auprovid : b2i(4, reader[auidx].prid[0]));
2190}
2191
2192void do_emm(EMM_PACKET *ep)
2193{
2194 int au;
2195 char *typtext[]={"UNKNOWN", "UNIQUE", "SHARED", "GLOBAL"};
2196
2197 au = client[cs_idx].au;
2198 cs_ddump_mask(D_ATR, ep->emm, ep->l, "emm:");
2199
2200 //Unique Id matching for pay-per-view channels:
2201 if (client[cs_idx].autoau) {
2202 int i;
2203 for (i=0;i<CS_MAXREADER;i++) {
2204 if (reader[i].card_system>0 && !reader[i].audisabled) {
2205 if (reader_get_emm_type(ep, &reader[i])) { //decodes ep->type and ep->hexserial from the EMM
2206 if (memcmp(ep->hexserial, reader[i].hexserial, sizeof(ep->hexserial))==0) {
2207 au = i;
2208 break; //
2209 }
2210 }
2211 }
2212 }
2213 }
2214
2215 if ((au < 0) || (au >= CS_MAXREADER)) {
2216 cs_debug_mask(D_EMM, "emm disabled, client has no au-reader!");
2217 return;
2218 }
2219
2220 if (reader[au].card_system>0) {
2221 if (!reader_get_emm_type(ep, &reader[au])) { //decodes ep->type and ep->hexserial from the EMM
2222 cs_debug_mask(D_EMM, "emm skipped");
2223 return;
2224 }
2225 }
2226 else {
2227 cs_debug_mask(D_EMM, "emm skipped, reader %s (%d) has no cardsystem defined!", reader[au].label, au);
2228 return;
2229 }
2230
2231 //test: EMM becomes skipped if auprivid doesn't match with provid from EMM
2232 if(reader[au].auprovid) {
2233 if(reader[au].auprovid != b2i(4, ep->provid)) {
2234 cs_debug_mask(D_EMM, "emm skipped, reader %s (%d) auprovid doesn't match %06lX != %06lX!", reader[au].label, au, reader[au].auprovid, b2i(4, ep->provid));
2235 return;
2236 }
2237 }
2238
2239 cs_debug_mask(D_EMM, "emmtype %s. Reader %s has serial %s.", typtext[ep->type], reader[au].label, cs_hexdump(0, reader[au].hexserial, 8));
2240 cs_ddump_mask(D_EMM, ep->hexserial, 8, "emm UA/SA:");
2241 cs_ddump_mask(D_EMM, ep->emm, ep->l, "emm:");
2242
2243 client[cs_idx].last=time((time_t)0);
2244 if (reader[au].b_nano[ep->emm[0]] & 0x02) //should this nano be saved?
2245 {
2246 char token[256];
2247 FILE *fp;
2248 time_t rawtime;
2249 time (&rawtime);
2250 struct tm *timeinfo;
2251 timeinfo = localtime (&rawtime); /* to access LOCAL date/time info */
2252 char buf[80];
2253 strftime (buf, 80, "%Y/%m/%d %H:%M:%S", timeinfo);
2254 sprintf (token, "%s%s_emm.log", cs_confdir, reader[au].label);
2255 int emm_length = ((ep->emm[1] & 0x0f) << 8) | ep->emm[2];
2256
2257 if (!(fp = fopen (token, "a")))
2258 {
2259 cs_log ("ERROR: Cannot open file '%s' (errno=%d)\n", token, errno);
2260 }
2261 else
2262 {
2263 fprintf (fp, "%s %s ", buf, cs_hexdump(0, ep->hexserial, 8));
2264 fprintf (fp, "%s\n", cs_hexdump(0, ep->emm, emm_length + 3));
2265 fclose (fp);
2266 cs_log ("Succesfully added EMM to %s.", token);
2267 }
2268
2269 sprintf (token, "%s%s_emm.bin", cs_confdir, reader[au].label);
2270 if (!(fp = fopen (token, "ab")))
2271 {
2272 cs_log ("ERROR: Cannot open file '%s' (errno=%d)\n", token, errno);
2273 }
2274 else
2275 {
2276 if ((int)fwrite(ep->emm, 1, emm_length+3, fp) == emm_length+3)
2277 {
2278 cs_log ("Succesfully added binary EMM to %s.", token);
2279 }
2280 else
2281 {
2282 cs_log ("ERROR: Cannot write binary EMM to %s (errno=%d)\n", token, errno);
2283 }
2284 fclose (fp);
2285 }
2286 }
2287
2288 switch (ep->type) {
2289 case UNKNOWN:
2290 if (reader[au].blockemm_unknown) {
2291#ifdef WEBIF
2292 reader[au].emmblocked[UNKNOWN]++;
2293#endif
2294 return;
2295 }
2296 break;
2297
2298 case UNIQUE:
2299 if (reader[au].blockemm_u) {
2300#ifdef WEBIF
2301 reader[au].emmblocked[UNIQUE]++;
2302#endif
2303 return;
2304 }
2305 break;
2306
2307 case SHARED:
2308 if (reader[au].blockemm_s) {
2309#ifdef WEBIF
2310 reader[au].emmblocked[SHARED]++;
2311#endif
2312 return;
2313 }
2314 break;
2315
2316 // FIXME only camd33 delivers hexserial from the net, newcamd, camd35 copy
2317 // cardreader hexserial in; reader_get_emm_type overwrites this with real SA value if known!
2318 case GLOBAL:
2319 if (reader[au].blockemm_g) {
2320#ifdef WEBIF
2321 reader[au].emmblocked[GLOBAL]++;
2322#endif
2323 return;
2324 }
2325 break;
2326 }
2327
2328 client[cs_idx].lastemm = time((time_t)0);
2329
2330 if (reader[au].card_system > 0) {
2331 if (!check_emm_cardsystem(&reader[au], ep)) { // wrong caid
2332 client[cs_idx].emmnok++;
2333 return;
2334 }
2335 client[cs_idx].emmok++;
2336 }
2337 ep->cidx = cs_idx;
2338 cs_debug_mask(D_EMM, "emm is being sent to reader %s.", reader[au].label);
2339 write_to_pipe(reader[au].fd, PIP_ID_EMM, (uchar *) ep, sizeof(EMM_PACKET));
2340}
2341
2342static int comp_timeb(struct timeb *tpa, struct timeb *tpb)
2343{
2344 if (tpa->time>tpb->time) return(1);
2345 if (tpa->time<tpb->time) return(-1);
2346 if (tpa->millitm>tpb->millitm) return(1);
2347 if (tpa->millitm<tpb->millitm) return(-1);
2348 return(0);
2349}
2350
2351struct timeval *chk_pending(struct timeb tp_ctimeout)
2352{
2353 int i;
2354 ulong td;
2355 struct timeb tpn, tpe, tpc; // <n>ow, <e>nd, <c>heck
2356 static struct timeval tv;
2357
2358 ECM_REQUEST *er;
2359 cs_ftime(&tpn);
2360 tpe=tp_ctimeout; // latest delay -> disconnect
2361
2362 if (client[cs_idx].ecmtask)
2363 i=(ph[client[cs_idx].ctyp].multi)?CS_MAXPENDING:1;
2364 else
2365 i=0;
2366
2367 //cs_log("num pend=%d", i);
2368
2369 for (--i; i>=0; i--) {
2370 if (client[cs_idx].ecmtask[i].rc>=100) { // check all pending ecm-requests
2371 er=&client[cs_idx].ecmtask[i];
2372 if (check_ecmcache1(er, client[cs_idx].grp)) { //Schlocke: caching dupplicate requests from different clients
2373 er->rc = 1;
2374 send_dcw(er);
2375 }
2376 }
2377 if (client[cs_idx].ecmtask[i].rc>=100) { // check all pending ecm-requests
2378 int act, j;
2379 er=&client[cs_idx].ecmtask[i];
2380 tpc=er->tps;
2381 tpc.millitm += (er->stage) ? cfg->ctimeout : cfg->ftimeout;
2382 tpc.time += tpc.millitm / 1000;
2383 tpc.millitm = tpc.millitm % 1000;
2384 if (!er->stage) {
2385 for (j=0, act=1; (act) && (j<CS_MAXREADER); j++) {
2386 if (cfg->preferlocalcards && !er->locals_done) {
2387 if ((er->reader[j]&1) && !(reader[j].typ & R_IS_NETWORK))
2388 act=0;
2389 } else if (cfg->preferlocalcards && er->locals_done) {
2390 if ((er->reader[j]&1) && (reader[j].typ & R_IS_NETWORK))
2391 act=0;
2392 } else {
2393 if (er->reader[j]&1)
2394 act=0;
2395 }
2396 }
2397
2398 //cs_log("stage 0, act=%d r0=%d, r1=%d, r2=%d, r3=%d, r4=%d r5=%d", act,
2399 // er->reader[0], er->reader[1], er->reader[2],
2400 // er->reader[3], er->reader[4], er->reader[5]);
2401
2402 if (act) {
2403 int inc_stage = 1;
2404 if (cfg->preferlocalcards && !er->locals_done) {
2405 er->locals_done = 1;
2406 for (j = 0; j < CS_MAXREADER; j++) {
2407 if (reader[j].typ & R_IS_NETWORK)
2408 inc_stage = 0;
2409 }
2410 }
2411 if (!inc_stage) {
2412 request_cw(er, er->stage, 2);
2413 tpc.millitm += 1000 * (tpn.time - er->tps.time) + tpn.millitm - er->tps.millitm;
2414 tpc.time += tpc.millitm / 1000;
2415 tpc.millitm = tpc.millitm % 1000;
2416 } else {
2417 er->locals_done = 0;
2418 er->stage++;
2419 request_cw(er, er->stage, cfg->preferlocalcards ? 1 : 0);
2420
2421 tpc.millitm += (cfg->ctimeout-cfg->ftimeout);
2422 tpc.time += tpc.millitm / 1000;
2423 tpc.millitm = tpc.millitm % 1000;
2424 }
2425 }
2426 }
2427 if (comp_timeb(&tpn, &tpc)>0) { // action needed
2428 //cs_log("Action now %d.%03d", tpn.time, tpn.millitm);
2429 //cs_log(" %d.%03d", tpc.time, tpc.millitm);
2430 if (er->stage) {
2431 er->rc=5; // timeout
2432 if (cfg->lb_mode) {
2433 int r;
2434 for (r=0; r<CS_MAXREADER; r++)
2435 if (er->reader[r])
2436 send_reader_stat(r, er, 5);
2437 }
2438 send_dcw(er);
2439 continue;
2440 } else {
2441 er->stage++;
2442 request_cw(er, er->stage, 0);
2443 tpc.millitm += (cfg->ctimeout-cfg->ftimeout);
2444 tpc.time += tpc.millitm / 1000;
2445 tpc.millitm = tpc.millitm % 1000;
2446 }
2447 }
2448 //build_delay(&tpe, &tpc);
2449 if (comp_timeb(&tpe, &tpc)>0) {
2450 tpe.time=tpc.time;
2451 tpe.millitm=tpc.millitm;
2452 }
2453 }
2454 }
2455
2456 td=(tpe.time-tpn.time)*1000+(tpe.millitm-tpn.millitm)+5;
2457 tv.tv_sec = td/1000;
2458 tv.tv_usec = (td%1000)*1000;
2459 //cs_log("delay %d.%06d", tv.tv_sec, tv.tv_usec);
2460 return(&tv);
2461}
2462
2463int process_input(uchar *buf, int l, int timeout)
2464{
2465 int rc;
2466 fd_set fds;
2467 struct timeb tp;
2468
2469 if (!client[cs_idx].pfd) return(-1);
2470 cs_ftime(&tp);
2471 tp.time+=timeout;
2472 if (ph[client[cs_idx].ctyp].watchdog)
2473 alarm(cfg->cmaxidle + (cfg->ctimeout + 500) / 1000 + 1);
2474 while (1)
2475 {
2476 FD_ZERO(&fds);
2477 FD_SET(client[cs_idx].pfd, &fds);
2478 FD_SET(client[cs_idx].fd_m2c_c, &fds);
2479
2480 rc=select(((client[cs_idx].pfd>client[cs_idx].fd_m2c_c)?client[cs_idx].pfd:client[cs_idx].fd_m2c_c)+1, &fds, 0, 0, chk_pending(tp));
2481 if (rc<0)
2482 {
2483 if (errno==EINTR) continue;
2484 else return(0);
2485 }
2486
2487 if (FD_ISSET(client[cs_idx].fd_m2c_c, &fds)) // read from pipe
2488 chk_dcw(client[cs_idx].fd_m2c_c);
2489
2490 if (FD_ISSET(client[cs_idx].pfd, &fds)) // read from client
2491 {
2492 rc=ph[client[cs_idx].ctyp].recv(buf, l);
2493 break;
2494 }
2495 if (tp.time<=time((time_t *)0)) // client maxidle reached
2496 {
2497 rc=(-9);
2498 break;
2499 }
2500 }
2501 if (ph[client[cs_idx].ctyp].watchdog)
2502 alarm(cfg->cmaxidle + (cfg->ctimeout + 500) / 1000 + 1);
2503 return(rc);
2504}
2505
2506static void restart_clients()
2507{
2508 int i;
2509 cs_log("restarting clients");
2510 for (i=0; i<CS_MAXPID; i++) {
2511 if (client[i].pid && client[i].typ=='c' && ph[client[i].ctyp].type & MOD_CONN_NET) {
2512 pthread_cancel(client[i].thread);
2513 cs_log("killing client c%02d pid %d", i, client[i].pid);
2514 }
2515 }
2516}
2517
2518
2519void send_clear_reader_stat(int ridx)
2520{
2521 write_to_pipe(fd_c2m, PIP_ID_RES, (uchar*)&ridx, sizeof(ridx));
2522}
2523
2524void send_restart_cardreader(int ridx, int force_now)
2525{
2526 int restart_info[2];
2527 restart_info[0] = ridx;
2528 restart_info[1] = force_now;
2529 write_to_pipe(fd_c2m, PIP_ID_RST, (uchar*)&restart_info, sizeof(restart_info));
2530}
2531
2532static void process_master_pipe()
2533{
2534 int n;
2535 uchar *ptr;
2536
2537 switch(n=read_from_pipe(mfdr, &ptr, 1))
2538 {
2539 case PIP_ID_HUP:
2540 cs_accounts_chk();
2541 break;
2542 case PIP_ID_RST:{ //Restart Cardreader with ridx=prt[0]
2543 int *restart_info = (int *)ptr;
2544 restart_cardreader(restart_info[0], restart_info[1]);
2545 break; }
2546 case PIP_ID_KCL: //Kill all clients
2547 restart_clients();
2548 break;
2549 case PIP_ID_RES: //Reset reader statistics
2550 clear_reader_stat(*(int*)ptr);
2551 break;
2552 }
2553}
2554
2555void cs_log_config()
2556{
2557 uchar buf[20];
2558
2559 if (cfg->nice!=99)
2560 sprintf((char *)buf, ", nice=%d", cfg->nice);
2561 else
2562 buf[0]='\0';
2563 cs_log("version=%s, build #%s, system=%s-%s-%s%s", CS_VERSION_X, CS_SVN_VERSION, CS_OS_CPU, CS_OS_HW, CS_OS_SYS, buf);
2564 cs_log("max. clients=%d, client max. idle=%d sec",
2565#ifdef CS_ANTICASC
2566 CS_MAXPID-3, cfg->cmaxidle);
2567#else
2568 CS_MAXPID-2, cfg->cmaxidle);
2569#endif
2570 if( cfg->max_log_size )
2571 sprintf((char *)buf, "%d Kb", cfg->max_log_size);
2572 else
2573 strcpy((char *)buf, "unlimited");
2574 cs_log("max. logsize=%s", buf);
2575 cs_log("client timeout=%lu ms, fallback timeout=%lu ms, cache delay=%d ms",
2576 cfg->ctimeout, cfg->ftimeout, cfg->delay);
2577#ifdef CS_NOSHM
2578 cs_log("shared memory initialized (size=%d)", shmsize);
2579#else
2580 cs_log("shared memory initialized (size=%d)", shmsize);
2581#endif
2582}
2583
2584void cs_waitforcardinit()
2585{
2586 if (cfg->waitforcards)
2587 {
2588 cs_log("waiting for local card init");
2589 int card_init_done, i;
2590 cs_sleepms(3000); // short sleep for card detect to work proberly
2591 do {
2592 card_init_done = 1;
2593 for (i = 0; i < CS_MAXREADER; i++) {
2594 if (reader[i].card_status == CARD_NEED_INIT) {
2595 card_init_done = 0;
2596 break;
2597 }
2598 }
2599 cs_sleepms(300); // wait a little bit
2600 alarm(cfg->cmaxidle + cfg->ctimeout / 1000 + 1);
2601 } while (!card_init_done);
2602 cs_log("init for all local cards done");
2603 }
2604}
2605
2606int accept_connection(int i, int j) {
2607 struct sockaddr_in cad;
2608 int scad,n,o;
2609 scad = sizeof(cad);
2610 uchar buf[2048];
2611 int fdp[2];
2612
2613 if (ph[i].type==MOD_CONN_UDP) {
2614
2615 if ((n=recvfrom(ph[i].ptab->ports[j].fd, buf+3, sizeof(buf)-3, 0, (struct sockaddr *)&cad, (socklen_t *)&scad))>0) {
2616 int idx;
2617 idx=idx_from_ip(cs_inet_order(cad.sin_addr.s_addr), ntohs(cad.sin_port));
2618
2619 if (!idx) {
2620 if (pipe(fdp)) {
2621 cs_log("Cannot create pipe (errno=%d)", errno);
2622 return 0;
2623 }
2624 o=cs_fork(cs_inet_order(cad.sin_addr.s_addr), ntohs(cad.sin_port));
2625
2626 if (o<0) return 0;
2627
2628 client[o].ufd=fdp[1];
2629 client[o].pfd=fdp[0];
2630
2631 client[o].is_server=1; //FIXME global should be local per thread
2632
2633 client[o].ctyp=i;
2634 client[o].port_idx=j;
2635 client[o].udp_fd=ph[i].ptab->ports[j].fd;
2636 client[o].udp_sa=cad;
2637
2638 client[o].ip=cs_inet_order(cad.sin_addr.s_addr);
2639 client[o].port=ntohs(cad.sin_port);
2640 client[o].typ='c';
2641
2642 //if (ph[client[o].ctyp].watchdog)
2643 // alarm(cfg->cmaxidle + cfg->ctimeout / 1000 + 1);
2644
2645 //ph[i].s_handler(cad); // never return
2646 pthread_create(&client[o].thread, NULL, (void *)ph[i].s_handler, (void *) o);
2647 pthread_detach(client[o].thread);
2648 } else {
2649 unsigned short rl;
2650 rl=n;
2651 buf[0]='U';
2652 memcpy(buf+1, &rl, 2);
2653 if (!write(client[idx].ufd, buf, n+3)) return 0;
2654 }
2655 }
2656 } else { //TCP
2657
2658 int pfd3;
2659 if ((pfd3=accept(ph[i].ptab->ports[j].fd, (struct sockaddr *)&cad, (socklen_t *)&scad))>0) {
2660 o=cs_fork(cs_inet_order(cad.sin_addr.s_addr), ntohs(cad.sin_port));
2661
2662 if (o<0) return 0;
2663
2664 client[o].ctyp=i;
2665 client[o].udp_fd=pfd3;
2666 client[o].port_idx=j;
2667
2668 client[o].pfd=pfd3;
2669
2670 client[o].is_server=1; //FIXME global should be local per thread
2671
2672 client[o].ip=cs_inet_order(cad.sin_addr.s_addr);
2673 client[o].port=ntohs(cad.sin_port);
2674 client[o].typ='c';
2675
2676 //if (ph[client[o].ctyp].watchdog)
2677 // alarm(cfg->cmaxidle + cfg->ctimeout / 1000 + 1);
2678
2679 pthread_create(&client[o].thread, NULL, (void *)ph[i].s_handler, (void*) o);
2680 pthread_detach(client[o].thread);
2681 }
2682 }
2683 return 0;
2684}
2685//void cs_resolve()
2686//{
2687// int i;
2688// for (i=0; i<CS_MAXREADER; i++)
2689// if (reader[i].enable && !reader[i].deleted && (reader[i].cs_idx) && (reader[i].typ & R_IS_NETWORK) && (reader[i].typ!=R_CONSTCW))
2690// hostResolve(i);
2691//}
2692
2693//static void loop_resolver(void *dummy __attribute__ ((unused)))
2694//{
2695// cs_sleepms(1000); // wait for reader
2696// while(cfg->resolvedelay > 0)
2697// {
2698// cs_resolve();
2699// cs_sleepms(1000*cfg->resolvedelay);
2700// }
2701//}
2702
2703
2704/**
2705 * get tmp dir
2706 **/
2707char * get_tmp_dir()
2708{
2709 if (cs_tmpdir[0])
2710 return cs_tmpdir;
2711
2712#ifdef OS_CYGWIN32
2713 char *d = getenv("TMPDIR");
2714 if (!d || !d[0])
2715 d = getenv("TMP");
2716 if (!d || !d[0])
2717 d = getenv("TEMP");
2718 if (!d || !d[0])
2719 getcwd(cs_tmpdir, sizeof(cs_tmpdir)-1);
2720
2721 strcpy(cs_tmpdir, d);
2722 char *p = cs_tmpdir;
2723 while(*p) p++;
2724 p--;
2725 if (*p != '/' && *p != '\\')
2726 strcat(cs_tmpdir, "/");
2727 strcat(cs_tmpdir, "_oscam");
2728#else
2729 strcpy(cs_tmpdir, "/tmp/.oscam");
2730#endif
2731 mkdir(cs_tmpdir, S_IRWXU);
2732 return cs_tmpdir;
2733}
2734
2735
2736int main (int argc, char *argv[])
2737{
2738
2739#ifdef CS_LED
2740 cs_switch_led(LED1A, LED_DEFAULT);
2741 cs_switch_led(LED1A, LED_ON);
2742#endif
2743
2744 //struct sockaddr_in cad; /* structure to hold client's address */
2745 //int scad; /* length of address */
2746 //int fd; /* socket descriptors */
2747 int i, j;
2748 int bg=0;
2749 int gfd; //nph,
2750 int fdp[2];
2751 //uchar buf[2048];
2752 void (*mod_def[])(struct s_module *)=
2753 {
2754#ifdef MODULE_MONITOR
2755 module_monitor,
2756#endif
2757#ifdef MODULE_CAMD33
2758 module_camd33,
2759#endif
2760#ifdef MODULE_CAMD35
2761 module_camd35,
2762#endif
2763#ifdef MODULE_CAMD35_TCP
2764 module_camd35_tcp,
2765#endif
2766#ifdef MODULE_NEWCAMD
2767 module_newcamd,
2768#endif
2769#ifdef MODULE_CCCAM
2770 module_cccam,
2771#endif
2772#ifdef MODULE_CONSTCW
2773 module_constcw,
2774#endif
2775#ifdef CS_WITH_GBOX
2776 module_gbox,
2777#endif
2778#ifdef MODULE_RADEGAST
2779 module_radegast,
2780#endif
2781#ifdef MODULE_SERIAL
2782 module_oscam_ser,
2783#endif
2784#ifdef HAVE_DVBAPI
2785 module_dvbapi,
2786#endif
2787 0
2788 };
2789
2790 void (*cardsystem_def[])(struct s_cardsystem *)=
2791 {
2792#ifdef READER_NAGRA
2793 reader_nagra,
2794#endif
2795#ifdef READER_IRDETO
2796 reader_irdeto,
2797#endif
2798#ifdef READER_CONAX
2799 reader_conax,
2800#endif
2801#ifdef READER_CRYPTOWORKS
2802 reader_cryptoworks,
2803#endif
2804#ifdef READER_SECA
2805 reader_seca,
2806#endif
2807#ifdef READER_VIACCESS
2808 reader_viaccess,
2809#endif
2810#ifdef READER_VIDEOGUARD
2811 reader_videoguard1,
2812 reader_videoguard2,
2813 reader_videoguard12,
2814#endif
2815#ifdef READER_DRE
2816 reader_dre,
2817#endif
2818 reader_tongfang,
2819 0
2820 };
2821
2822 while ((i=getopt(argc, argv, "bc:t:d:hm:"))!=EOF)
2823 {
2824 switch(i)
2825 {
2826 case 'b': bg=1;
2827 break;
2828 case 'c': cs_strncpy(cs_confdir, optarg, sizeof(cs_confdir));
2829 break;
2830 case 'd': cs_dblevel=atoi(optarg);
2831 break;
2832 case 't': cs_strncpy(cs_tmpdir, optarg, sizeof(cs_tmpdir));
2833 case 'm':
2834#ifdef CS_NOSHM
2835 cs_strncpy(cs_memfile, optarg, sizeof(cs_memfile));
2836 break;
2837#endif
2838 case 'h':
2839 default : usage();
2840 }
2841 }
2842 if (cs_confdir[strlen(cs_confdir)]!='/') strcat(cs_confdir, "/");
2843 init_shm();
2844 init_config();
2845 init_stat();
2846 cfg->debuglvl = cs_dblevel; // give static debuglevel to outer world
2847 for (i=0; mod_def[i]; i++) // must be later BEFORE init_config()
2848 {
2849 memset(&ph[i], 0, sizeof(struct s_module));
2850 mod_def[i](&ph[i]);
2851 }
2852 for (i=0; cardsystem_def[i]; i++) // must be later BEFORE init_config()
2853 {
2854 memset(&cardsystem[i], 0, sizeof(struct s_cardsystem));
2855 cardsystem_def[i](&cardsystem[i]);
2856 }
2857
2858
2859 cs_log("auth size=%d", sizeof(struct s_auth));
2860
2861 init_sidtab();
2862 init_readerdb();
2863 init_userdb(&cfg->account);
2864 init_signal();
2865 init_srvid();
2866 init_tierid();
2867 //Todo #ifdef CCCAM
2868 init_provid();
2869
2870 init_len4caid();
2871#ifdef IRDETO_GUESSING
2872 init_irdeto_guess_tab();
2873#endif
2874
2875
2876 if (pipe(fdp))
2877 {
2878 cs_log("Cannot create pipe (errno=%d)", errno);
2879 cs_exit(1);
2880 }
2881 mfdr=fdp[0];
2882 fd_c2m=fdp[1];
2883 gfd=mfdr+1;
2884
2885#ifdef OS_MACOSX
2886 if (bg && daemon_compat(1,0))
2887#else
2888 if (bg && daemon(1,0))
2889#endif
2890 {
2891 cs_log("Error starting in background (errno=%d)", errno);
2892 cs_exit(1);
2893 }
2894
2895 if (cfg->pidfile != NULL)
2896 {
2897 FILE *fp;
2898 if (!(fp=fopen(cfg->pidfile, "w")))
2899 {
2900 cs_log("Cannot open pid-file (errno=%d)", errno);
2901 cs_exit(1);
2902 }
2903 fprintf(fp, "%d\n", getpid());
2904 fclose(fp);
2905 }
2906
2907#ifndef OS_CYGWIN32
2908 // /tmp/oscam.version file (Uptime + Version)
2909 char targetfile[256];
2910 snprintf(targetfile, 255,"%s%s", get_tmp_dir(), "/oscam.version");
2911 FILE *fp;
2912
2913 if (!(fp=fopen(targetfile, "w"))) {
2914 cs_log("Cannot open %s (errno=%d)", targetfile, errno);
2915 } else {
2916 time_t now = time((time_t)0);
2917 struct tm *st;
2918 st = localtime(&now);
2919 fprintf(fp, "uxstarttime: %d\n", (int)now);
2920 fprintf(fp, "starttime: %02d.%02d.%02d", st->tm_mday, st->tm_mon+1, st->tm_year%100);
2921 fprintf(fp, " %02d:%02d:%02d\n", st->tm_hour, st->tm_min, st->tm_sec);
2922 fprintf(fp, "version: %s#%s\n", CS_VERSION, CS_SVN_VERSION);
2923 fprintf(fp, "maxpid: %d\n", CS_MAXPID);
2924#ifdef WEBIF
2925 fprintf(fp, "webifsupport: yes\n");
2926#else
2927 fprintf(fp, "webifsupport: no\n");
2928#endif
2929#ifdef HAVE_DVBAPI
2930 fprintf(fp, "dvbapisupport: yes\n");
2931#else
2932 fprintf(fp, "dvbapisupport: no\n");
2933#endif
2934#ifdef CS_WITH_GBOX
2935 fprintf(fp, "gboxsupport: yes\n");
2936#else
2937 fprintf(fp, "gboxsupport: no\n");
2938#endif
2939#ifdef CS_ANTICASC
2940 fprintf(fp, "anticascsupport: yes\n");
2941#else
2942 fprintf(fp, "anticascsupport: no\n");
2943#endif
2944#ifdef CS_WITH_DOUBLECHECK
2945 fprintf(fp, "ECM doublecheck: yes\n");
2946#else
2947 fprintf(fp, "ECM doublecheck: no\n");
2948#endif
2949 fclose(fp);
2950 }
2951#endif
2952
2953
2954#ifdef AZBOX
2955 openxcas_debug_message_onoff(1); // debug
2956
2957 if (openxcas_open_with_smartcard("oscamCAS") < 0) {
2958 cs_log("openxcas: could not init");
2959 }
2960#endif
2961
2962 for (i=0; i<CS_MAX_MOD; i++)
2963 if( (ph[i].type & MOD_CONN_NET) && ph[i].ptab )
2964 for(j=0; j<ph[i].ptab->nports; j++)
2965 {
2966 start_listener(&ph[i], j);
2967 if( ph[i].ptab->ports[j].fd+1>gfd )
2968 gfd=ph[i].ptab->ports[j].fd+1;
2969 }
2970
2971 //set time for server to now to avoid 0 in monitor/webif
2972 client[0].last=time((time_t *)0);
2973
2974 //start_thread((void *) &cs_logger, "logger", 'l'); //97;
2975
2976#ifdef WEBIF
2977 if(cfg->http_port == 0)
2978 cs_log("http disabled");
2979 else
2980 start_thread((void *) &http_srv, "http", 'h');
2981#endif
2982
2983 init_cardreader();
2984
2985 //cs_waitforcardinit();
2986
2987#ifdef CS_LED
2988 cs_switch_led(LED1A, LED_OFF);
2989 cs_switch_led(LED1B, LED_ON);
2990#endif
2991
2992#ifdef CS_ANTICASC
2993 if( !cfg->ac_enabled )
2994 cs_log("anti cascading disabled");
2995 else {
2996 init_ac();
2997 start_thread((void *) &start_anticascader, "anticascader", 'a'); // 96
2998
2999 }
3000#endif
3001
3002 for (i=0; i<CS_MAX_MOD; i++)
3003 if (ph[i].type & MOD_CONN_SERIAL) // for now: oscam_ser only
3004 if (ph[i].s_handler)
3005 ph[i].s_handler(i);
3006
3007 //cs_close_log();
3008 while (1) {
3009 fd_set fds;
3010
3011 do {
3012 FD_ZERO(&fds);
3013 FD_SET(mfdr, &fds);
3014 for (i=0; i<CS_MAX_MOD; i++)
3015 if ( (ph[i].type & MOD_CONN_NET) && ph[i].ptab )
3016 for (j=0; j<ph[i].ptab->nports; j++)
3017 if (ph[i].ptab->ports[j].fd)
3018 FD_SET(ph[i].ptab->ports[j].fd, &fds);
3019 errno=0;
3020 select(gfd, &fds, 0, 0, 0);
3021 } while (errno==EINTR);
3022
3023 client[0].last=time((time_t *)0);
3024
3025 if (FD_ISSET(mfdr, &fds)) {
3026 process_master_pipe();
3027 }
3028 for (i=0; i<CS_MAX_MOD; i++) {
3029 if( (ph[i].type & MOD_CONN_NET) && ph[i].ptab ) {
3030 for( j=0; j<ph[i].ptab->nports; j++ ) {
3031 if( ph[i].ptab->ports[j].fd && FD_ISSET(ph[i].ptab->ports[j].fd, &fds) ) {
3032 accept_connection(i,j);
3033 }
3034 }
3035 } // if (ph[i].type & MOD_CONN_NET)
3036 }
3037 }
3038
3039#ifdef AZBOX
3040 if (openxcas_close() < 0) {
3041 cs_log("openxcas: could not close");
3042 }
3043#endif
3044
3045 cs_exit(1);
3046}
3047
3048#ifdef CS_LED
3049void cs_switch_led(int led, int action) {
3050
3051 if(action < 2) { // only LED_ON and LED_OFF
3052 char ledfile[256];
3053 FILE *f;
3054
3055 #ifdef DOCKSTAR
3056 switch(led){
3057 case LED1A:snprintf(ledfile, 255, "/sys/class/leds/dockstar:orange:misc/brightness");
3058 break;
3059 case LED1B:snprintf(ledfile, 255, "/sys/class/leds/dockstar:green:health/brightness");
3060 break;
3061 case LED2:snprintf(ledfile, 255, "/sys/class/leds/dockstar:green:health/brightness");
3062 break;
3063 case LED3:snprintf(ledfile, 255, "/sys/class/leds/dockstar:orange:misc/brightness");
3064 break;
3065 }
3066 #else
3067 switch(led){
3068 case LED1A:snprintf(ledfile, 255, "/sys/class/leds/nslu2:red:status/brightness");
3069 break;
3070 case LED1B:snprintf(ledfile, 255, "/sys/class/leds/nslu2:green:ready/brightness");
3071 break;
3072 case LED2:snprintf(ledfile, 255, "/sys/class/leds/nslu2:green:disk-1/brightness");
3073 break;
3074 case LED3:snprintf(ledfile, 255, "/sys/class/leds/nslu2:green:disk-2/brightness");
3075 break;
3076 }
3077 #endif
3078
3079 if (!(f=fopen(ledfile, "w"))){
3080 // FIXME: sometimes cs_log was not available when calling cs_switch_led -> signal 11
3081 //cs_log("Cannot open file \"%s\" (errno=%d)", ledfile, errno);
3082 return;
3083 }
3084 fprintf(f,"%d", action);
3085 fclose(f);
3086 } else { // LED Macros
3087 switch(action){
3088 case LED_DEFAULT:
3089 cs_switch_led(LED1A, LED_OFF);
3090 cs_switch_led(LED1B, LED_OFF);
3091 cs_switch_led(LED2, LED_ON);
3092 cs_switch_led(LED3, LED_OFF);
3093 break;
3094 case LED_BLINK_OFF:
3095 cs_switch_led(led, LED_OFF);
3096 cs_sleepms(100);
3097 cs_switch_led(led, LED_ON);
3098 break;
3099 case LED_BLINK_ON:
3100 cs_switch_led(led, LED_ON);
3101 cs_sleepms(300);
3102 cs_switch_led(led, LED_OFF);
3103 break;
3104 }
3105 }
3106}
3107#endif
Note: See TracBrowser for help on using the repository browser.