- Add support of ORF P4 Irdeto mode
[oscam.git] / module-gbox.c
blobe27e0e30d3bc72455c443abaeb739dc646381e52
1 #define MODULE_LOG_PREFIX "gbox"
3 #include "globals.h"
4 #ifdef MODULE_GBOX
6 #include "module-gbox.h"
7 #include "module-gbox-helper.h"
8 #include "module-gbox-sms.h"
9 #include "module-gbox-cards.h"
10 #include "module-cccam.h"
11 #include "module-cccam-data.h"
12 #include "oscam-failban.h"
13 #include "oscam-client.h"
14 #include "oscam-ecm.h"
15 #include "oscam-lock.h"
16 #include "oscam-net.h"
17 #include "oscam-chk.h"
18 #include "oscam-string.h"
19 #include "oscam-time.h"
20 #include "oscam-reader.h"
21 #include "oscam-garbage.h"
22 #include "oscam-files.h"
24 #define RECEIVE_BUFFER_SIZE 1024
25 #define MIN_GBOX_MESSAGE_LENGTH 10 //CMD + pw + pw. TODO: Check if is really min
26 #define MIN_ECM_LENGTH 8
27 #define HELLO_KEEPALIVE_TIME 120 //send hello to peer every 2 min in case no ecm received
28 #define STATS_WRITE_TIME 300 //write stats file every 5 min
29 #define MAX_GBOX_CARDS 1024 //send max. 1024 to peer
31 #define LOCAL_GBOX_MAJOR_VERSION 0x02
33 static struct gbox_data local_gbox;
34 static uint8_t local_gbox_initialized = 0;
35 static time_t last_stats_written;
37 static int32_t gbox_send_ecm(struct s_client *cli, ECM_REQUEST *er);
39 char *get_gbox_tmp_fname(char *fext)
41 static char gbox_tmpfile_buf[64] = { 0 };
42 const char *slash = "/";
43 if(!cfg.gbox_tmp_dir)
45 snprintf(gbox_tmpfile_buf, sizeof(gbox_tmpfile_buf), "%s%s%s",get_tmp_dir(), slash, fext);
47 else
49 if(cfg.gbox_tmp_dir[strlen(cfg.gbox_tmp_dir) - 1] == '/') { slash = ""; }
50 snprintf(gbox_tmpfile_buf, sizeof(gbox_tmpfile_buf), "%s%s%s", cfg.gbox_tmp_dir, slash, fext);
52 return gbox_tmpfile_buf;
55 uint16_t gbox_get_local_gbox_id(void)
57 return local_gbox.id;
60 uint32_t gbox_get_local_gbox_password(void)
62 return local_gbox.password;
65 static uint8_t gbox_get_my_vers (void)
67 uint8_t gbx_vers = a2i(cfg.gbox_my_vers,1);
69 return gbx_vers;
72 static uint8_t gbox_get_my_cpu_api (void)
74 /* For configurable later adapt according to these functions:
75 unsigned char *GboxAPI( unsigned char a ) {
76 a = a & 7 ;
77 switch ( a ) {
78 case 0 : strcpy ( s_24,"No API");
79 break;
80 case 1 : strcpy ( s_24,"API 1");
81 break;
82 case 2 : strcpy ( s_24,"API 2");
83 break;
84 case 3 : strcpy ( s_24,"API 3");
85 break;
86 case 4 : strcpy ( s_24,"IBM API");
87 break;
88 default : strcpy ( s_24," ");
90 return s_24 ;
93 unsigned char *GboxCPU( unsigned char a ) {
94 a = a & 112 ;
95 a = a >> 4 ;
96 switch ( a ) {
97 case 1 : strcpy ( s_23,"80X86 compatible CPU");
98 break;
99 case 2 : strcpy ( s_23,"Motorola PowerPC MPC823 CPU");
100 break;
101 case 3 : strcpy ( s_23,"IBM PowerPC STB CPU");
102 break;
103 default : strcpy ( s_23," ");
105 return s_23:
108 return a2i(cfg.gbox_my_cpu_api,1);
111 static void write_msg_to_osd (struct s_client *cli, uint8_t msg_id)
113 char *fext= FILE_MSG_OSD;
114 char *fname = get_gbox_tmp_fname(fext);
115 if (file_exists(fname))
117 char buf[50];
118 memset(buf, 0, sizeof(buf));
119 snprintf(buf, sizeof(buf), "%s %d %s %s", fname, msg_id, username(cli), cli->reader->device);
120 cs_log_dbg(D_READER, "found driver %s - write msg (id= %d) from %s %s to OSD", fname, msg_id, username(cli),cli->reader->device);
121 char *cmd = buf;
122 FILE *p;
123 if ((p = popen(cmd, "w")) == NULL)
125 cs_log("Error %s",fname);
126 return;
128 pclose(p);
130 return;
133 void gbox_write_peer_onl(void)
135 char *fext= FILE_GBOX_PEER_ONL;
136 char *fname = get_gbox_tmp_fname(fext);
137 FILE *fhandle = fopen(fname, "w");
138 if(!fhandle)
140 cs_log("Couldn't open %s: %s", fname, strerror(errno));
141 return;
143 cs_readlock(__func__, &clientlist_lock);
144 struct s_client *cl;
145 for(cl = first_client; cl; cl = cl->next)
147 if(cl->gbox && cl->typ == 'p')
149 struct gbox_peer *peer = cl->gbox;
150 if (peer->online)
151 { fprintf(fhandle, "1 %s %s %04X 2.%02X\n",cl->reader->device, cs_inet_ntoa(cl->ip),peer->gbox.id, peer->gbox.minor_version); }
152 else
153 { fprintf(fhandle, "0 %s %s %04X 0.00\n",cl->reader->device, cs_inet_ntoa(cl->ip),peer->gbox.id); }
156 cs_readunlock(__func__, &clientlist_lock);
157 fclose(fhandle);
158 return;
161 void gbox_write_version(void)
163 char *fext= FILE_GBOX_VERSION;
164 char *fname = get_gbox_tmp_fname(fext);
165 FILE *fhandle = fopen(fname, "w");
166 if(!fhandle)
168 cs_log("Couldn't open %s: %s", get_gbox_tmp_fname(FILE_GBOX_VERSION), strerror(errno));
169 return;
171 fprintf(fhandle, "%02X.%02X\n", LOCAL_GBOX_MAJOR_VERSION, gbox_get_my_vers());
172 fclose(fhandle);
175 void hostname2ip(char *hostname, IN_ADDR_T *ip)
177 cs_resolve(hostname, ip, NULL, NULL);
180 static uint16_t gbox_convert_password_to_id(uint32_t password)
182 return (((password >> 24) & 0xff) ^ ((password >> 8) & 0xff)) << 8 | (((password >> 16) & 0xff) ^ (password & 0xff));
185 static int8_t gbox_remove_all_bad_sids(ECM_REQUEST *er, uint16_t sid)
187 if (!er) { return -1; }
189 struct gbox_card_pending *pending = NULL;
190 LL_LOCKITER *li = ll_li_create(er->gbox_cards_pending, 0);
191 while ((pending = ll_li_next(li)))
192 { gbox_remove_bad_sid(pending->id.peer, pending->id.slot, sid); }
193 ll_li_destroy(li);
194 return 0;
197 void gbox_free_cards_pending(ECM_REQUEST *er)
199 ll_destroy_free_data(&er->gbox_cards_pending);
202 void gbox_init_ecm_request_ext(struct gbox_ecm_request_ext *ere)
204 ere->gbox_hops = 0;
205 ere->gbox_peer = 0;
206 ere->gbox_mypeer = 0;
207 ere->gbox_slot = 0;
208 ere->gbox_version = 0;
209 ere->gbox_unknown = 0;
210 ere->gbox_type = 0;
213 struct s_client *get_gbox_proxy(uint16_t gbox_id)
215 struct s_client *cl;
216 struct s_client *found = NULL;
217 cs_readlock(__func__, &clientlist_lock);
218 for(cl = first_client; cl; cl = cl->next)
220 if(cl->typ == 'p' && cl->gbox && cl->gbox_peer_id == gbox_id)
222 found = cl;
223 break;
226 cs_readunlock(__func__, &clientlist_lock);
227 return found;
230 static int8_t gbox_peer_online(struct gbox_peer *peer, uint8_t online)
232 if (!peer) { return -1; }
234 peer->online = online;
235 gbox_write_peer_onl();
236 return 0;
239 static int8_t gbox_reinit_peer(struct gbox_peer *peer)
241 if (!peer) { return -1; }
243 peer->ecm_idx = 0;
244 peer->next_hello = 0;
245 gbox_delete_cards(GBOX_DELETE_FROM_PEER, peer->gbox.id);
246 gbox_peer_online(peer, GBOX_PEER_OFFLINE);
248 return 0;
251 static int8_t gbox_reinit_proxy(struct s_client *proxy)
253 if (!proxy) { return -1; }
255 struct gbox_peer *peer = proxy->gbox;
256 gbox_reinit_peer(peer);
257 if (!proxy->reader) { return -1; }
258 proxy->reader->tcp_connected = 0;
259 proxy->reader->card_status = NO_CARD;
260 proxy->reader->last_s = proxy->reader->last_g = 0;
262 return 0;
265 void gbox_send(struct s_client *cli, uchar *buf, int32_t l)
267 struct gbox_peer *peer = cli->gbox;
269 cs_log_dump_dbg(D_READER, buf, l, "<- data (%d bytes):", l);
271 hostname2ip(cli->reader->device, &SIN_GET_ADDR(cli->udp_sa));
272 SIN_GET_FAMILY(cli->udp_sa) = AF_INET;
273 SIN_GET_PORT(cli->udp_sa) = htons((uint16_t)cli->reader->r_port);
275 gbox_encrypt(buf, l, peer->gbox.password);
276 sendto(cli->udp_fd, buf, l, 0, (struct sockaddr *)&cli->udp_sa, cli->udp_sa_len);
277 cs_log_dump_dbg(D_READER, buf, l, "<- encrypted data (%d bytes):", l);
280 void gbox_send_hello_packet(struct s_client *cli, int8_t number, uchar *outbuf, uchar *ptr, int32_t nbcards, uint8_t hello_stat)
282 struct gbox_peer *peer = cli->gbox;
283 int32_t hostname_len = strlen(cfg.gbox_hostname);
284 int32_t len;
285 gbox_message_header(outbuf, MSG_HELLO, peer->gbox.password, local_gbox.password);
286 // initial HELLO = 0, subsequent = 1
287 if(hello_stat > GBOX_STAT_HELLOS)
288 { outbuf[10] = 1; }
289 else
290 { outbuf[10] = 0; }
291 outbuf[11] = number; // 0x80 (if last packet) else 0x00 | packet number
293 if((number & 0x0F) == 0)
295 if(hello_stat != GBOX_STAT_HELLOL)
296 { memcpy(++ptr, gbox_get_checkcode(), 7); }
297 else
298 { memset(++ptr, 0, 7); }
299 ptr += 7;
300 *ptr = local_gbox.minor_version;
301 *(++ptr) = local_gbox.cpu_api;
302 memcpy(++ptr, cfg.gbox_hostname, hostname_len);
303 ptr += hostname_len;
304 *ptr = hostname_len;
306 len = ptr - outbuf + 1;
307 switch(hello_stat)
309 case GBOX_STAT_HELLOL:
310 if (cfg.log_hello)
311 { cs_log("<- HelloL to %s", cli->reader->label);}
312 else
313 { cs_log_dbg(D_READER,"<- HelloL to %s", cli->reader->label);}
314 break;
315 case GBOX_STAT_HELLOS:
316 if (cfg.log_hello)
317 { cs_log("<- HelloS total cards %d to %s", nbcards, cli->reader->label);}
318 else
319 { cs_log_dbg(D_READER,"<- HelloS total cards %d to %s", nbcards, cli->reader->label);}
320 break;
321 case GBOX_STAT_HELLOR:
322 if (cfg.log_hello)
323 { cs_log("<- HelloR total cards %d to %s", nbcards, cli->reader->label);}
324 else
325 { cs_log_dbg(D_READER,"<- HelloR total cards %d to %s", nbcards, cli->reader->label);}
326 break;
327 default:
328 if (cfg.log_hello)
329 { cs_log("<- hello total cards %d to %s", nbcards, cli->reader->label);}
330 else
331 { cs_log_dbg(D_READER,"<- hello total cards %d to %s", nbcards, cli->reader->label);}
332 break;
334 cs_log_dump_dbg(D_READER, outbuf, len, "<- hello, (len=%d):", len);
336 gbox_compress(outbuf, len, &len);
338 gbox_send(cli, outbuf, len);
341 void gbox_send_hello(struct s_client *proxy, uint8_t hello_stat)
343 if (!proxy)
345 cs_log("Invalid call to gbox_send_hello with proxy");
346 return;
348 uint16_t nbcards = 0;
349 uint16_t nbcards_cnt = 0;
350 uint8_t packet;
351 uchar buf[2048];
352 packet = 0;
353 uchar *ptr = buf + 11;
354 if(gbox_count_cards() != 0 && hello_stat > GBOX_STAT_HELLOL)
356 struct gbox_peer *peer = proxy->gbox;
357 if (!peer || !peer->my_user || !peer->my_user->account)
359 cs_log("Invalid call to gbox_send_hello with peer");
360 return;
362 memset(buf, 0, sizeof(buf));
363 struct gbox_card *card;
364 GBOX_CARDS_ITER *gci = gbox_cards_iter_create();
365 while((card = gbox_cards_iter_next(gci)))
367 //send to user only cards which matching CAID from account and lvl > 0
368 //and cccmaxhops from account
369 //do not send peer cards back
370 if(chk_ctab(gbox_get_caid(card->caprovid), &peer->my_user->account->ctab) && (card->lvl > 0) &&
371 #ifdef MODULE_CCCAM
372 (card->dist <= peer->my_user->account->cccmaxhops) &&
373 #endif
374 (!card->origin_peer || (card->origin_peer && card->origin_peer->gbox.id != peer->gbox.id)))
376 *(++ptr) = card->caprovid >> 24;
377 *(++ptr) = card->caprovid >> 16;
378 *(++ptr) = card->caprovid >> 8;
379 *(++ptr) = card->caprovid & 0xff;
380 *(++ptr) = 1; //note: original gbx is more efficient and sends all cards of one caid as package
381 *(++ptr) = card->id.slot;
382 *(++ptr) = ((card->lvl - 1) << 4) + card->dist + 1;
383 *(++ptr) = card->id.peer >> 8;
384 *(++ptr) = card->id.peer & 0xff;
385 nbcards++;
386 nbcards_cnt++;
387 if(nbcards_cnt == MAX_GBOX_CARDS )
389 cs_log("max cards gbox_send_hello with peer reached");
390 break;
392 if(nbcards == 100) //check if 100 is good or we need more sophisticated algorithm
394 gbox_send_hello_packet(proxy, packet, buf, ptr, nbcards, hello_stat);
395 packet++;
396 nbcards = 0;
397 ptr = buf + 11;
398 memset(buf, 0, sizeof(buf));
402 gbox_cards_iter_destroy(gci);
403 } // end if local card exists
404 //last packet has bit 0x80 set
405 gbox_send_hello_packet(proxy, 0x80 | packet, buf, ptr, nbcards, hello_stat);
406 return;
409 void gbox_reconnect_client(uint16_t gbox_id)
411 struct s_client *cl;
412 cs_readlock(__func__, &clientlist_lock);
413 for(cl = first_client; cl; cl = cl->next)
415 if(cl->gbox && cl->typ == 'p' && cl->gbox_peer_id == gbox_id)
417 hostname2ip(cl->reader->device, &SIN_GET_ADDR(cl->udp_sa));
418 SIN_GET_FAMILY(cl->udp_sa) = AF_INET;
419 SIN_GET_PORT(cl->udp_sa) = htons((uint16_t)cl->reader->r_port);
420 hostname2ip(cl->reader->device, &(cl->ip));
421 gbox_reinit_proxy(cl);
422 gbox_send_hello(cl, GBOX_STAT_HELLOL);
425 cs_readunlock(__func__, &clientlist_lock);
428 static void *gbox_server(struct s_client *cli, uchar *UNUSED(b), int32_t l)
430 if(l > 0)
432 cs_log("gbox_server %s/%d", cli->reader->label, cli->port);
433 // gbox_check_header(cli, NULL, b, l);
435 return 0;
438 char *gbox_username(struct s_client *client)
440 if(!client) { return "anonymous"; }
441 if(client->reader)
442 if(client->reader->r_usr[0])
443 { return client->reader->r_usr; }
444 return "anonymous";
447 static int8_t gbox_disconnect_double_peers(struct s_client *cli)
449 struct s_client *cl;
450 cs_writelock(__func__, &clientlist_lock);
451 for(cl = first_client; cl; cl = cl->next)
453 if (cl->typ == 'c' && cl->gbox_peer_id == cli->gbox_peer_id && cl != cli)
455 cl->reader = NULL;
456 cl->gbox = NULL;
457 cs_log_dbg(D_READER, "disconnected double client %s",username(cl));
458 cs_disconnect_client(cl);
461 cs_writeunlock(__func__, &clientlist_lock);
462 return 0;
465 static int8_t gbox_auth_client(struct s_client *cli, uint32_t gbox_password)
467 if (!cli) { return -1; }
469 uint16_t gbox_id = gbox_convert_password_to_id(gbox_password);
470 struct s_client *cl = get_gbox_proxy(gbox_id);
472 if(cl->typ == 'p' && cl->gbox && cl->reader)
474 struct gbox_peer *peer = cl->gbox;
475 struct s_auth *account = get_account_by_name(gbox_username(cl));
477 if ((peer->gbox.password == gbox_password) && account)
479 cli->crypted = 1; //display as crypted
480 cli->gbox = cl->gbox; //point to the same gbox as proxy
481 cli->reader = cl->reader; //point to the same reader as proxy
482 cli->gbox_peer_id = cl->gbox_peer_id; //signal authenticated
483 gbox_disconnect_double_peers(cli);
484 cs_auth_client(cli, account, NULL);
485 cli->account = account;
486 cli->grp = account->grp;
487 cli->lastecm = time(NULL);
488 peer->my_user = cli;
489 return 0;
492 return -1;
495 static void gbox_server_init(struct s_client *cl)
497 cs_writelock(__func__, &clientlist_lock);
498 if(!cl->init_done)
500 if(IP_ISSET(cl->ip))
501 { cs_log("new connection from %s", cs_inet_ntoa(cl->ip)); }
502 //We cannot authenticate here, because we don't know gbox pw
503 cl->gbox_peer_id = NO_GBOX_ID;
504 cl->init_done = 1;
506 start_sms_sender();
508 cs_writeunlock(__func__, &clientlist_lock);
509 return;
512 static uint16_t gbox_decode_cmd(uchar *buf)
514 return buf[0] << 8 | buf[1];
517 int8_t gbox_message_header(uchar *buf, uint16_t cmd, uint32_t peer_password, uint32_t local_password)
519 if (!buf) { return -1; }
520 i2b_buf(2, cmd, buf);
521 if (cmd == MSG_GSMS_1) { return 0; }
522 i2b_buf(4, peer_password, buf + 2);
523 if (cmd == MSG_CW) { return 0; }
524 i2b_buf(4, local_password, buf + 6);
525 return 0;
528 //returns number of cards in a hello packet or -1 in case of error
529 int16_t read_cards_from_hello(uint8_t *ptr, uint8_t *len, CAIDTAB *ctab, uint8_t maxdist, struct gbox_peer *peer)
531 uint8_t *current_ptr = 0;
532 uint32_t caprovid;
533 int16_t ncards_in_msg = 0;
535 while(ptr < len)
537 caprovid = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
539 ncards_in_msg += ptr[4];
540 //caid check
541 if(chk_ctab(gbox_get_caid(caprovid), ctab))
543 current_ptr = ptr;
544 ptr += 5;
546 // for all cards of current caid/provid,
547 while (ptr < current_ptr + 5 + current_ptr[4] * 4)
549 if ((ptr[1] & 0xf) <= maxdist)
550 { gbox_add_card(ptr[2] << 8 | ptr[3], caprovid, ptr[0], ptr[1] >> 4, ptr[1] & 0xf, GBOX_CARD_TYPE_GBOX, peer); }
551 ptr += 4; //next card
552 } // end while cards for provider
554 else
555 { ptr += 5 + ptr[4] * 4; } //skip cards because caid
556 } // end while < len
557 return ncards_in_msg;
560 //returns 1 if checkcode changed / 0 if not
561 static int32_t gbox_checkcode_recv(struct s_client *cli, uchar *checkcode)
563 struct gbox_peer *peer = cli->gbox;
564 char tmp[14];
566 if(memcmp(peer->checkcode, checkcode, 7))
568 memcpy(peer->checkcode, checkcode, 7);
569 cs_log_dbg(D_READER, "-> new checkcode=%s", cs_hexdump(0, peer->checkcode, 14, tmp, sizeof(tmp)));
570 return 1;
572 return 0;
575 static void gbox_send_checkcode(struct s_client *cli)
577 struct gbox_peer *peer = cli->gbox;
578 uchar outbuf[20];
580 gbox_message_header(outbuf, MSG_CHECKCODE, peer->gbox.password, local_gbox.password);
581 memcpy(outbuf + 10, gbox_get_checkcode(), 7);
583 gbox_send(cli, outbuf, 17);
586 int32_t gbox_cmd_hello(struct s_client *cli, uchar *data, int32_t n)
588 if (!cli || !cli->gbox || !cli->reader || !data) { return -1; }
590 struct gbox_peer *peer = cli->gbox;
591 int16_t cards_number = 0;
592 int32_t payload_len = n;
593 int32_t hostname_len = 0;
594 int32_t footer_len = 0;
595 uint8_t *ptr = 0;
597 if(!(gbox_decode_cmd(data) == MSG_HELLO1))
599 gbox_decompress(data, &payload_len);
600 cs_log_dump_dbg(D_READER, data, payload_len, "decompressed data (%d bytes):", payload_len);
601 ptr = data + 12;
603 else
605 ptr = data + 11;
606 cs_log_dump_dbg(D_READER, data, payload_len, "decrypted data (%d bytes):", payload_len);
608 if ((data[11] & 0xf) != peer->next_hello) //out of sync hellos
610 cs_log("-> out of sync hello from %s %s, expected: %02X, received: %02X"
611 ,username(cli), cli->reader->device, peer->next_hello, data[11] & 0xf);
612 peer->next_hello = 0;
613 gbox_send_hello(cli, GBOX_STAT_HELLOL);
614 return 0;
617 if (!(data[11] & 0xf)) //is first packet
619 gbox_delete_cards(GBOX_DELETE_FROM_PEER, peer->gbox.id);
620 hostname_len = data[payload_len - 1];
621 footer_len = hostname_len + 2 + 7;
622 if(!peer->hostname || memcmp(peer->hostname, data + payload_len - 1 - hostname_len, hostname_len))
624 NULLFREE(peer->hostname);
625 if(!cs_malloc(&peer->hostname, hostname_len + 1))
627 return -1;
629 memcpy(peer->hostname, data + payload_len - 1 - hostname_len, hostname_len);
630 peer->hostname[hostname_len] = '\0';
632 gbox_checkcode_recv(cli, data + payload_len - footer_len - 1);
633 peer->gbox.minor_version = data[payload_len - footer_len - 1 + 7];
634 peer->gbox.cpu_api = data[payload_len - footer_len + 7];
635 peer->total_cards = 0;
638 cs_log_dbg(D_READER, "-> Hello packet no. %d received", (data[11] & 0xF) + 1);
639 // read cards from hello
640 cards_number = read_cards_from_hello(ptr, data + payload_len - footer_len - 1, &cli->reader->ctab, cli->reader->gbox_maxdist, peer);
641 if (cards_number < 0)
642 { return -1; }
643 else
644 { peer->total_cards += cards_number; }
646 if(data[11] & 0x80) //last packet
648 uchar tmpbuf[8];
649 memset(&tmpbuf[0], 0xff, 7);
650 if(data[10] == 0x01 && !memcmp(data+12,tmpbuf,7)) //good night message
652 //This is a good night / reset packet (good night data[0xA] / reset !data[0xA]
653 cs_log("-> Good Night from %s %s",username(cli), cli->reader->device);
654 write_msg_to_osd(cli, MSGID_GOODNIGHT_OSD);
655 gbox_reinit_proxy(cli);
657 else //last packet of Hello
659 peer->filtered_cards = gbox_count_peer_cards(peer->gbox.id);
660 if(!data[10])
662 memset(&tmpbuf[0], 0, 7);
663 if (data[11] == 0x80 && !memcmp(data+12,tmpbuf,7))
665 if (cfg.log_hello)
666 {cs_log("-> HelloL in %d packets from %s (%s:%d) V2.%02X with %d cards filtered to %d cards", (data[0x0B] & 0x0f)+1, cli->reader->label, cs_inet_ntoa(cli->ip), cli->reader->r_port, peer->gbox.minor_version, peer->total_cards, peer->filtered_cards);}
667 else
668 { cs_log_dbg(D_READER,"-> HelloL in %d packets from %s (%s:%d) V2.%02X with %d cards filtered to %d cards", (data[0x0B] & 0x0f)+1, cli->reader->label, cs_inet_ntoa(cli->ip), cli->reader->r_port, peer->gbox.minor_version, peer->total_cards, peer->filtered_cards);}
669 gbox_peer_online(peer, GBOX_PEER_ONLINE);
671 else
672 if (cfg.log_hello)
673 { cs_log("-> HelloS in %d packets from %s (%s:%d) V2.%02X with %d cards filtered to %d cards", (data[0x0B] & 0x0f)+1, cli->reader->label, cs_inet_ntoa(cli->ip), cli->reader->r_port, peer->gbox.minor_version, peer->total_cards, peer->filtered_cards); }
674 else
675 { cs_log_dbg(D_READER,"-> HelloS in %d packets from %s (%s:%d) V2.%02X with %d cards filtered to %d cards", (data[0x0B] & 0x0f)+1, cli->reader->label, cs_inet_ntoa(cli->ip), cli->reader->r_port, peer->gbox.minor_version, peer->total_cards, peer->filtered_cards); }
676 gbox_send_hello(cli, GBOX_STAT_HELLOR);
678 else
680 if (cfg.log_hello)
681 { cs_log("-> HelloR in %d packets from %s (%s:%d) V2.%02X with %d cards filtered to %d cards", (data[0x0B] & 0x0f)+1, cli->reader->label, cs_inet_ntoa(cli->ip), cli->reader->r_port, peer->gbox.minor_version, peer->total_cards, peer->filtered_cards);}
682 else
683 { cs_log_dbg(D_READER,"-> HelloR in %d packets from %s (%s:%d) V2.%02X with %d cards filtered to %d cards", (data[0x0B] & 0x0f)+1, cli->reader->label, cs_inet_ntoa(cli->ip), cli->reader->r_port, peer->gbox.minor_version, peer->total_cards, peer->filtered_cards);}
684 gbox_send_checkcode(cli);
686 if(!peer->online)
688 gbox_send_hello(cli, GBOX_STAT_HELLOS);
689 gbox_peer_online(peer, GBOX_PEER_ONLINE);
691 cli->reader->tcp_connected = 2; //we have card
692 if(!peer->filtered_cards)
693 { cli->reader->card_status = NO_CARD; }
694 else
695 { cli->reader->card_status = CARD_INSERTED; }
697 peer->next_hello = 0;
698 gbox_write_share_cards_info();
699 cli->last = time((time_t *)0); //hello is activity on proxy
701 else { peer->next_hello++; }
702 return 0;
705 static int8_t is_blocked_peer(uint16_t peer)
707 if (peer == NO_GBOX_ID) { return 1; }
708 else { return 0; }
711 static int8_t gbox_incoming_ecm(struct s_client *cli, uchar *data, int32_t n)
713 if (!cli || !cli->gbox || !data || !cli->reader) { return -1; }
715 struct gbox_peer *peer;
716 struct s_client *cl;
717 int32_t diffcheck = 0;
719 peer = cli->gbox;
720 if (!peer || !peer->my_user) { return -1; }
721 cl = peer->my_user;
723 if(n < 21)
724 { return -1; }
726 // No ECMs with length < MIN_LENGTH expected
727 if ((((data[19] & 0x0f) << 8) | data[20]) < MIN_ECM_LENGTH) { return -1; }
729 // GBOX_MAX_HOPS not violated
730 if (data[n - 15] + 1 > GBOX_MAXHOPS) { return -1; }
732 // ECM must not take more hops than allowed by gbox_reshare
733 if (data[n - 15] + 1 > cli->reader->gbox_reshare)
735 cs_log("-> ECM took more hops than allowed from gbox_reshare. Hops stealing detected!");
736 return -1;
739 //Check for blocked peers
740 uint16_t requesting_peer = data[(((data[19] & 0x0f) << 8) | data[20]) + 21] << 8 |
741 data[(((data[19] & 0x0f) << 8) | data[20]) + 22];
742 if (is_blocked_peer(requesting_peer))
744 cs_log_dbg(D_READER, "ECM from peer %04X blocked", requesting_peer);
745 return -1;
748 ECM_REQUEST *er;
749 if(!(er = get_ecmtask())) { return -1; }
751 struct gbox_ecm_request_ext *ere;
752 if(!cs_malloc(&ere, sizeof(struct gbox_ecm_request_ext)))
754 NULLFREE(er);
755 return -1;
758 uchar *ecm = data + 18; //offset of ECM in gbx message
760 er->src_data = ere;
761 gbox_init_ecm_request_ext(ere);
763 er->gbox_ecm_id = peer->gbox.id;
765 if(peer->ecm_idx == 100) { peer->ecm_idx = 0; }
767 er->idx = peer->ecm_idx++;
768 er->ecmlen = SCT_LEN(ecm);
770 if(er->ecmlen < 3 || er->ecmlen > MAX_ECM_SIZE || er->ecmlen+18 > n)
771 { NULLFREE(ere); NULLFREE(er); return -1; }
773 er->pid = b2i(2, data + 10);
774 er->srvid = b2i(2, data + 12);
776 if(ecm[er->ecmlen + 5] == 0x05)
777 { er->caid = (ecm[er->ecmlen + 5] << 8); }
778 else
779 { er->caid = b2i(2, ecm + er->ecmlen + 5); }
781 // ei->extra = data[14] << 8 | data[15];
782 memcpy(er->ecm, data + 18, er->ecmlen);
783 ere->gbox_peer = b2i(2, ecm + er->ecmlen);
784 ere->gbox_version = ecm[er->ecmlen + 2];
785 ere->gbox_unknown = ecm[er->ecmlen + 3];
786 ere->gbox_type = ecm[er->ecmlen + 4];
787 uint32_t caprovid = b2i(4, ecm + er->ecmlen + 5);
788 ere->gbox_mypeer = b2i(2, ecm + er->ecmlen + 10);
789 ere->gbox_slot = ecm[er->ecmlen + 12];
791 diffcheck = gbox_checkcode_recv(cl, data + n - 14);
792 //TODO: What do we do with our own checkcode @-7?
793 er->gbox_crc = gbox_get_ecmchecksum(&er->ecm[0], er->ecmlen);
794 ere->gbox_hops = data[n - 15] + 1;
795 memcpy(&ere->gbox_routing_info[0], &data[n - 15 - ere->gbox_hops + 1], ere->gbox_hops - 1);
797 er->caid = gbox_get_caid(caprovid);
798 er->prid = gbox_get_provid(caprovid);
799 cs_log_dbg(D_READER, "-> ECM (-> %d) SID %04X from %04X (%s:%d)", ere->gbox_hops, er->srvid, ere->gbox_peer, peer->hostname, cli->port);
800 get_cw(cl, er);
802 //checkcode did not match gbox->peer checkcode
803 if(diffcheck)
805 // TODO: Send HelloS here?
806 // gbox->peer.hello_stat = GBOX_STAT_HELLOS;
807 // gbox_send_hello(cli);
809 return 0;
812 static uint32_t gbox_get_pending_time(ECM_REQUEST *er, uint16_t peer_id, uint8_t slot)
814 if (!er) { return 0; }
816 uint32_t ret_time = 0;
817 struct gbox_card_pending *pending = NULL;
818 LL_LOCKITER *li = ll_li_create(er->gbox_cards_pending, 0);
819 while ((pending = ll_li_next(li)))
821 if ((pending->id.peer == peer_id) && (pending->id.slot == slot))
823 ret_time = pending->pending_time;
824 break;
827 ll_li_destroy(li);
828 return ret_time;
831 static int32_t gbox_recv_chk(struct s_client *cli, uchar *dcw, int32_t *rc, uchar *data, int32_t n)
833 if(!cli || gbox_decode_cmd(data) != MSG_CW || n < 44)
834 { return -1; }
836 int i;
837 uint16_t id_card = 0;
838 struct s_client *proxy;
839 if(cli->typ != 'p')
840 { proxy = get_gbox_proxy(cli->gbox_peer_id); }
841 else
842 { proxy = cli; }
843 if (!proxy || !proxy->reader)
845 cs_log("error, gbox_recv_chk, proxy not found");
846 gbox_send_goodbye(cli);
847 return -1;
849 proxy->last = time((time_t *)0);
850 *rc = 1;
851 memcpy(dcw, data + 14, 16);
852 uint32_t crc = b2i(4, data + 30);
853 char tmp[32];
854 cs_log_dbg(D_READER, "-> cws=%s, peer=%04X, ecm_pid=%04X, sid=%04X, crc=%08X, type=%02X, dist=%01X, unkn1=%01X, unkn2=%02X, chid/0x0000/0xffff=%04X",
855 cs_hexdump(0, dcw, 32, tmp, sizeof(tmp)),
856 data[10] << 8 | data[11], data[6] << 8 | data[7], data[8] << 8 | data[9], crc, data[41], data[42] & 0x0f, data[42] >> 4, data[43], data[37] << 8 | data[38]);
857 struct timeb t_now;
858 cs_ftime(&t_now);
859 int64_t cw_time = GBOX_DEFAULT_CW_TIME;
860 for(i = 0; i < cfg.max_pending; i++)
862 if(proxy->ecmtask[i].gbox_crc == crc)
864 id_card = b2i(2, data + 10);
865 cw_time = comp_timeb(&t_now, &proxy->ecmtask[i].tps) - gbox_get_pending_time(&proxy->ecmtask[i], id_card, data[36]);
866 gbox_add_good_sid(id_card, proxy->ecmtask[i].caid, data[36], proxy->ecmtask[i].srvid, cw_time);
867 proxy->reader->currenthops = data[42] & 0x0f;
868 gbox_remove_all_bad_sids(&proxy->ecmtask[i], proxy->ecmtask[i].srvid);
869 if(proxy->ecmtask[i].gbox_ecm_status == GBOX_ECM_NOT_ASKED || proxy->ecmtask[i].gbox_ecm_status == GBOX_ECM_ANSWERED)
870 { return -1; }
871 proxy->ecmtask[i].gbox_ecm_status = GBOX_ECM_ANSWERED;
872 proxy->ecmtask[i].gbox_ecm_id = id_card;
873 *rc = 1;
874 return proxy->ecmtask[i].idx;
877 //late answers from other peers,timing not possible
878 gbox_add_good_sid(id_card, data[34] << 8 | data[35], data[36], data[8] << 8 | data[9], GBOX_DEFAULT_CW_TIME);
879 cs_log_dbg(D_READER, "no task found for crc=%08x", crc);
880 gbox_send_goodbye(cli);
881 return -1;
884 static int8_t gbox_cw_received(struct s_client *cli, uchar *data, int32_t n)
886 int32_t rc = 0, i = 0, idx = 0;
887 uchar dcw[16];
889 idx = gbox_recv_chk(cli, dcw, &rc, data, n);
890 if(idx < 0) { return -1; } // no dcw received
891 if(!idx) { idx = cli->last_idx; }
892 cli->reader->last_g = time((time_t *)0); // for reconnect timeout
893 for(i = 0; i < cfg.max_pending; i++)
895 if(cli->ecmtask[i].idx == idx)
897 cli->pending--;
898 casc_check_dcw(cli->reader, i, rc, dcw);
899 return 0;
902 gbox_send_goodbye(cli);
903 return -1;
906 int32_t gbox_cmd_switch(struct s_client *proxy, uchar *data, int32_t n)
908 if (!data || !proxy) { return -1; }
909 uint16_t cmd = gbox_decode_cmd(data);
910 switch(cmd)
912 case MSG_BOXINFO:
913 cs_log("-> HERE? to %s",username(proxy));
914 gbox_send_hello(proxy, GBOX_STAT_HELLOR);
915 break;
916 case MSG_GOODBYE:
917 cs_log("-> goodbye message to %s",username(proxy));
918 //msg goodbye is an indication from peer that requested ECM failed (not found/rejected...)
919 //TODO: implement on suitable place - rebroadcast ECM to other peers
920 break;
921 case MSG_UNKNWN:
922 cs_log("-> MSG_UNKNWN 48F9 to %s", username(proxy));
923 break;
924 case MSG_GSMS_1:
925 if (!cfg.gsms_dis)
927 cs_log("-> MSG_GSMS_1 to %s", username(proxy));
928 gbox_send_gsms_ack(proxy,1);
929 write_gsms_msg(proxy, data +4, data[3], data[2]);
931 else
933 gsms_unavail();
935 break;
936 case MSG_GSMS_2:
937 if (!cfg.gsms_dis)
939 cs_log("-> MSG_GSMS_2 to %s", username(proxy));
940 gbox_send_gsms_ack(proxy,2);
941 write_gsms_msg(proxy, data +16, data[14], data[15]);
943 else
945 gsms_unavail();
947 break;
948 case MSG_GSMS_ACK_1:
949 if (!cfg.gsms_dis)
951 cs_log("-> MSG_GSMS_ACK_1 to %s", username(proxy));
952 write_gsms_ack(proxy,1);
954 else
956 gsms_unavail();
958 break;
959 case MSG_GSMS_ACK_2:
960 if (!cfg.gsms_dis)
962 cs_log("-> MSG_GSMS_ACK_2 to %s", username(proxy));
963 write_gsms_ack(proxy,2);
965 else
967 gsms_unavail();
969 break;
970 case MSG_HELLO1:
971 case MSG_HELLO:
972 if (gbox_cmd_hello(proxy, data, n) < 0)
973 { return -1; }
974 break;
975 case MSG_CW:
976 gbox_cw_received(proxy, data, n);
977 break;
978 case MSG_CHECKCODE:
979 gbox_checkcode_recv(proxy, data + 10);
980 break;
981 case MSG_ECM:
982 gbox_incoming_ecm(proxy, data, n);
983 break;
984 default:
985 cs_log("-> unknown command %04X received for %s", cmd, username(proxy));
986 cs_log_dump_dbg(D_READER, data, n, "unknown data received (%d bytes):", n);
987 } // end switch
988 if ((time(NULL) - last_stats_written) > STATS_WRITE_TIME)
990 gbox_write_stats();
991 last_stats_written = time(NULL);
993 return 0;
996 static void gbox_local_cards(struct s_reader *reader, TUNTAB *ttab)
998 int32_t i;
999 uint32_t prid = 0;
1000 int8_t slot = 0;
1001 #ifdef MODULE_CCCAM
1002 LL_ITER it, it2;
1003 struct cc_card *card = NULL;
1004 struct cc_data *cc;
1005 uint32_t checksum = 0;
1006 uint16_t cc_peer_id = 0;
1007 struct cc_provider *provider;
1008 uint8_t *node1 = NULL;
1009 uint8_t min_reshare = 0;
1010 gbox_delete_cards(GBOX_DELETE_WITH_TYPE, GBOX_CARD_TYPE_CCCAM);
1011 #endif
1012 gbox_delete_cards(GBOX_DELETE_WITH_ID, local_gbox.id);
1013 struct s_client *cl;
1014 cs_readlock(__func__, &clientlist_lock);
1015 for(cl = first_client; cl; cl = cl->next)
1017 if(cl->typ == 'r' && cl->reader && cl->reader->card_status == CARD_INSERTED)
1019 slot = gbox_next_free_slot(local_gbox.id);
1020 //SECA, Viaccess and Cryptoworks have multiple providers
1021 if(caid_is_seca(cl->reader->caid) || caid_is_viaccess(cl->reader->caid) || caid_is_cryptoworks(cl->reader->caid))
1023 for(i = 0; i < cl->reader->nprov; i++)
1025 prid = cl->reader->prid[i][1] << 16 |
1026 cl->reader->prid[i][2] << 8 | cl->reader->prid[i][3];
1027 gbox_add_card(local_gbox.id, gbox_get_caprovid(cl->reader->caid, prid), slot, reader->gbox_reshare, 0, GBOX_CARD_TYPE_LOCAL, NULL);
1030 else
1032 gbox_add_card(local_gbox.id, gbox_get_caprovid(cl->reader->caid, 0), slot, reader->gbox_reshare, 0, GBOX_CARD_TYPE_LOCAL, NULL);
1034 //Check for Betatunnel on gbox account in oscam.user
1035 if (chk_is_betatunnel_caid(cl->reader->caid) == 1 && ttab->ttdata && cl->reader->caid == ttab->ttdata[0].bt_caidto)
1037 //For now only first entry in tunnel tab. No sense in iteration?
1038 //Add betatunnel card to transmitted list
1039 gbox_add_card(local_gbox.id, gbox_get_caprovid(ttab->ttdata[0].bt_caidfrom, 0), slot, reader->gbox_reshare, 0, GBOX_CARD_TYPE_BETUN, NULL);
1040 cs_log_dbg(D_READER, "gbox created betatunnel card for caid: %04X->%04X", ttab->ttdata[0].bt_caidfrom, cl->reader->caid);
1043 } //end local readers
1044 #ifdef MODULE_CCCAM
1045 if((cfg.ccc_reshare) && (cfg.cc_reshare > -1) && (reader->gbox_cccam_reshare) && cl->typ == 'p' && cl->reader && cl->reader->typ == R_CCCAM && cl->cc)
1047 cc = cl->cc;
1048 it = ll_iter_create(cc->cards);
1049 while((card = ll_iter_next(&it)))
1051 //calculate gbox id from cc node
1052 node1 = ll_has_elements(card->remote_nodes);
1053 checksum = ((node1[0] ^ node1[7]) << 8) |
1054 ((node1[1] ^ node1[6]) << 24) |
1055 (node1[2] ^ node1[5]) |
1056 ((node1[3] ^ node1[4]) << 16);
1057 cc_peer_id = ((((checksum >> 24) & 0xFF) ^((checksum >> 8) & 0xFF)) << 8 |
1058 (((checksum >> 16) & 0xFF) ^(checksum & 0xFF)));
1059 slot = gbox_next_free_slot(cc_peer_id);
1060 min_reshare = cfg.cc_reshare;
1061 if (card->reshare < min_reshare)
1062 { min_reshare = card->reshare; }
1063 min_reshare++; //strange CCCam logic. 0 means direct peers
1064 if (reader->gbox_cccam_reshare < min_reshare)
1065 { min_reshare = reader->gbox_cccam_reshare; }
1066 if(caid_is_seca(card->caid) || caid_is_viaccess(card->caid) || caid_is_cryptoworks(card->caid))
1068 it2 = ll_iter_create(card->providers);
1069 while((provider = ll_iter_next(&it2)))
1070 { gbox_add_card(cc_peer_id, gbox_get_caprovid(card->caid, provider->prov), slot, min_reshare, card->hop, GBOX_CARD_TYPE_CCCAM, NULL); }
1072 else
1073 { gbox_add_card(cc_peer_id, gbox_get_caprovid(card->caid, 0), slot, min_reshare, card->hop, GBOX_CARD_TYPE_CCCAM, NULL); }
1075 } //end cccam
1076 #endif
1077 } //end for clients
1078 cs_readunlock(__func__, &clientlist_lock);
1080 if (cfg.gbox_proxy_cards_num > 0)
1082 for (i = 0; i < cfg.gbox_proxy_cards_num; i++)
1084 slot = gbox_next_free_slot(local_gbox.id);
1085 gbox_add_card(local_gbox.id, cfg.gbox_proxy_card[i], slot, reader->gbox_reshare, 0, GBOX_CARD_TYPE_PROXY, NULL);
1086 cs_log_dbg(D_READER,"add proxy card: slot %d %04X:%06X",slot, gbox_get_caid(cfg.gbox_proxy_card[i]), gbox_get_provid(cfg.gbox_proxy_card[i]));
1088 } //end add proxy reader cards
1089 gbox_write_local_cards_info();
1090 } //end add local gbox cards
1092 //returns -1 in case of error, 1 if authentication was performed, 0 else
1093 static int8_t gbox_check_header(struct s_client *cli, struct s_client *proxy, uchar *data, int32_t l)
1095 struct gbox_peer *peer = NULL;
1096 if (proxy) { peer = proxy->gbox; }
1098 char tmp[0x50];
1099 int32_t n = l;
1100 uint8_t authentication_done = 0;
1101 uint32_t my_received_pw = 0;
1102 uint32_t peer_received_pw = 0;
1103 cs_log_dump_dbg(D_READER, data, n, "-> encrypted data (%d bytes):", n);
1104 gbox_decrypt(data, n, local_gbox.password);
1105 cs_log_dump_dbg(D_READER, data, n, "-> decrypted data (%d bytes):", n);
1106 //verify my pass received
1107 my_received_pw = b2i(4, data + 2);
1108 if (my_received_pw == local_gbox.password)
1110 cs_log_dbg(D_READER, "-> data, peer : %04X data: %s", cli->gbox_peer_id, cs_hexdump(0, data, l, tmp, sizeof(tmp)));
1112 if (gbox_decode_cmd(data) != MSG_CW)
1114 if (cli->gbox_peer_id == NO_GBOX_ID)
1116 if (gbox_auth_client(cli, b2i(4, data + 6)) < 0)
1118 cs_log ("Authentication failed. Please check user in oscam.server and oscam.user");
1119 return -1;
1121 authentication_done = 1;
1122 proxy = get_gbox_proxy(cli->gbox_peer_id);
1123 gbox_local_cards(proxy->reader, &cli->ttab);
1124 peer = proxy->gbox;
1126 if (!peer) { return -1; }
1127 peer_received_pw = b2i(4, data + 6);
1128 if (peer_received_pw != peer->gbox.password)
1130 cs_log("gbox peer: %04X sends wrong password", peer->gbox.id);
1131 return -1;
1132 //continue; // next client
1134 } else
1136 // if my pass ok verify CW | pass to peer
1137 if((data[39] != ((local_gbox.id >> 8) & 0xff)) || (data[40] != (local_gbox.id & 0xff)))
1139 cs_log("gbox peer: %04X sends CW for other than my id: %04X", cli->gbox_peer_id, local_gbox.id);
1140 return -1;
1141 //continue; // next client
1144 } // error my pass
1145 else if (gbox_decode_cmd(data) == MSG_GSMS_1 || gbox_decode_cmd(data) == MSG_GSMS_ACK_1 )
1147 // MSG_GSMS_1 dont have passw and would fail. Just let them pass through for processing later
1149 else
1151 cs_log("ATTACK ALERT from IP %s", cs_inet_ntoa(cli->ip));
1152 cs_log_dbg(D_READER,"received data, data: %s", cs_hexdump(0, data, n, tmp, sizeof(tmp)));
1153 return -1;
1154 //continue; // next client
1156 if (!proxy) { return -1; }
1158 if (!IP_EQUAL(cli->ip, proxy->ip))
1160 cs_log("Received IP %s did not match previous IP %s. Try to reconnect.", cs_inet_ntoa(cli->ip), cs_inet_ntoa(proxy->ip));
1161 gbox_reconnect_client(cli->gbox_peer_id);
1162 return -1;
1164 if(!peer) { return -1; }
1166 return authentication_done;
1169 static int32_t gbox_recv(struct s_client *cli, uchar *buf, int32_t l)
1171 uchar data[RECEIVE_BUFFER_SIZE];
1172 int32_t n = l, tmp;
1173 int8_t ret = 0;
1175 if(!cli->udp_fd || !cli->is_udp || cli->typ != 'c')
1176 { return -1; }
1178 n = recv_from_udpipe(buf);
1179 if (n < MIN_GBOX_MESSAGE_LENGTH || n >= RECEIVE_BUFFER_SIZE) //protect against too short or too long messages
1180 { return -1; }
1182 struct s_client *proxy = get_gbox_proxy(cli->gbox_peer_id);
1184 memcpy(&data[0], buf, n);
1186 ret = gbox_check_header(cli, proxy, &data[0], n);
1187 if (ret < 0) { return -1; }
1189 //in case of new authentication the proxy gbox can now be found
1190 if (ret) { proxy = get_gbox_proxy(cli->gbox_peer_id); }
1192 if (!proxy) { return -1; }
1194 cli->last = time((time_t *)0);
1195 //clients may timeout - attach to peer's gbox/reader
1196 cli->gbox = proxy->gbox; //point to the same gbox as proxy
1197 cli->reader = proxy->reader; //point to the same reader as proxy
1198 struct gbox_peer *peer = proxy->gbox;
1200 cs_writelock(__func__, &peer->lock);
1201 tmp = gbox_cmd_switch(proxy, data, n);
1202 cs_writeunlock(__func__, &peer->lock);
1204 if(tmp < 0)
1205 { return -1; }
1207 //clients may timeout - dettach from peer's gbox/reader
1208 cli->gbox = NULL;
1209 cli->reader = NULL;
1210 return 0;
1213 static void gbox_send_dcw(struct s_client *cl, ECM_REQUEST *er)
1215 if (!cl || !er) { return; }
1217 struct s_client *cli = get_gbox_proxy(cl->gbox_peer_id);
1218 if (!cli || !cli->gbox) { return; }
1219 struct gbox_peer *peer = cli->gbox;
1221 if(er->rc >= E_NOTFOUND)
1223 cs_log_dbg(D_READER, "unable to decode!");
1224 gbox_send_goodbye(cli);
1225 return;
1228 uchar buf[60];
1229 memset(buf, 0, sizeof(buf));
1231 struct gbox_ecm_request_ext *ere = er->src_data;
1233 gbox_message_header(buf, MSG_CW , peer->gbox.password, 0);
1234 i2b_buf(2, er->pid, buf + 6); //PID
1235 i2b_buf(2, er->srvid, buf + 8); //SrvID
1236 i2b_buf(2, ere->gbox_mypeer, buf + 10); //From peer
1237 buf[12] = (ere->gbox_slot << 4) | (er->ecm[0] & 0x0f); //slot << 4 | even/odd
1238 buf[13] = er->caid >> 8; //CAID first byte
1239 memcpy(buf + 14, er->cw, 16); //CW
1240 i2b_buf(4, er->gbox_crc, buf + 30); //CRC
1241 i2b_buf(2, er->caid, buf + 34); //CAID
1242 buf[36] = ere->gbox_slot; //Slot
1243 if (buf[34] == 0x06) //if irdeto
1244 { i2b_buf(2, er->chid, buf + 37); } //CHID
1245 else
1247 if (local_gbox.minor_version == 0x2A)
1249 buf[37] = 0xff; //gbox.net sends 0xff
1250 buf[38] = 0xff; //gbox.net sends 0xff
1252 else
1254 buf[37] = 0; //gbox sends 0
1255 buf[38] = 0; //gbox sends 0
1258 i2b_buf(2, ere->gbox_peer, buf + 39); //Target peer
1259 if (er->rc == E_CACHE1 || er->rc == E_CACHE2 || er->rc == E_CACHEEX)
1260 { buf[41] = 0x03; } //cache
1261 else
1262 { buf[41] = 0x01; } //card, emu, needs probably further investigation
1263 buf[42] = 0x30; //1st nibble unknown / 2nd nibble distance
1264 buf[43] = ere->gbox_unknown; //meaning unknown, copied from ECM request
1266 //This copies the routing info from ECM to answer.
1267 //Each hop adds one byte and number of hops is in er->gbox_hops.
1268 memcpy(&buf[44], &ere->gbox_routing_info, ere->gbox_hops - 1);
1269 buf[44 + ere->gbox_hops - 1] = ere->gbox_hops - 1; //Hops
1271 char tmp[0x50];
1272 cs_log("sending dcw to peer : %04x data: %s", er->gbox_peer, cs_hexdump(0, buf, er->gbox_hops + 44, tmp, sizeof(tmp)));
1274 gbox_send(cli, buf, ere->gbox_hops + 44);
1276 cs_log_dbg(D_READER, "<- CW (<- %d) to %04X from %s:%d", ere->gbox_hops, ere->gbox_peer, cli->reader->label, cli->port);
1278 /* // see r11270
1279 void *gbox_rebroadcast_thread(struct gbox_rbc_thread_args *args)
1281 if (!args) { return NULL; }
1283 struct s_client *cli = args->cli;
1284 ECM_REQUEST *er = args->er;
1285 uint32_t waittime = args->waittime;
1287 //NEEDFIX currently the next line avoids a second rebroadcast
1288 if (!is_valid_client(cli)) { return NULL; }
1290 SAFE_MUTEX_LOCK(&cli->thread_lock);
1291 cli->thread_active = 1;
1292 SAFE_SETSPECIFIC(getclient, cli);
1293 set_thread_name(__func__);
1294 cli->thread_active = 0;
1295 SAFE_MUTEX_UNLOCK(&cli->thread_lock);
1297 cs_sleepms(waittime);
1298 if (!cli || cli->kill || !cli->gbox || !er) { return NULL; }
1299 SAFE_MUTEX_LOCK(&cli->thread_lock);
1300 cli->thread_active = 1;
1302 struct gbox_peer *peer = cli->gbox;
1304 struct timeb t_now, tbc;
1305 cs_ftime(&t_now);
1307 tbc = er->tps;
1308 add_ms_to_timeb_diff(&tbc, cfg.ctimeout);
1309 int32_t time_to_timeout = (int32_t) comp_timeb(&tbc, &t_now);
1311 //ecm is not answered yet and still chance to get CW
1312 if (er->rc >= E_NOTFOUND && time_to_timeout > GBOX_DEFAULT_CW_TIME)
1314 cs_writelock(__func__, &peer->lock);
1315 gbox_send_ecm(cli, er);
1316 cs_writeunlock(__func__, &peer->lock);
1318 cli->thread_active = 0;
1319 SAFE_MUTEX_UNLOCK(&cli->thread_lock);
1321 return NULL;
1324 static int32_t gbox_send_ecm(struct s_client *cli, ECM_REQUEST *er)
1326 if(!cli || !er || !cli->reader)
1327 { return -1; }
1329 if(!cli->gbox || !cli->reader->tcp_connected)
1331 cs_log_dbg(D_READER, "%s server not init!", cli->reader->label);
1332 write_ecm_answer(cli->reader, er, E_NOTFOUND, 0x27, NULL, NULL, 0, NULL);
1333 return -1;
1336 struct gbox_peer *peer = cli->gbox;
1337 int32_t cont_1;
1339 if(!peer->filtered_cards)
1341 cs_log_dbg(D_READER, "%s NO CARDS!", cli->reader->label);
1342 write_ecm_answer(cli->reader, er, E_NOTFOUND, E2_CCCAM_NOCARD, NULL, NULL, 0, NULL);
1343 return -1;
1346 if(!peer->online)
1348 cs_log_dbg(D_READER, "peer is OFFLINE!");
1349 write_ecm_answer(cli->reader, er, E_NOTFOUND, 0x27, NULL, NULL, 0, NULL);
1350 // gbox_send_hello(cli,0);
1351 return -1;
1354 if(er->gbox_ecm_status == GBOX_ECM_ANSWERED)
1355 { cs_log_dbg(D_READER, "%s replied to this ecm already", cli->reader->label); }
1357 if(er->gbox_ecm_status == GBOX_ECM_NOT_ASKED)
1358 { er->gbox_cards_pending = ll_create("pending_gbox_cards"); }
1360 if(er->gbox_ecm_id == peer->gbox.id)
1362 cs_log_dbg(D_READER, "%s provided ecm", cli->reader->label);
1363 write_ecm_answer(cli->reader, er, E_NOTFOUND, 0x27, NULL, NULL, 0, NULL);
1364 return 0;
1367 uchar send_buf_1[1024];
1368 int32_t len2;
1370 if(!er->ecmlen) { return 0; }
1372 len2 = er->ecmlen + 18;
1373 er->gbox_crc = gbox_get_ecmchecksum(&er->ecm[0], er->ecmlen);
1375 memset(send_buf_1, 0, sizeof(send_buf_1));
1377 uint8_t cont_card_1 = 0;
1378 uint8_t max_ecm_reached = 0;
1379 uint32_t current_avg_card_time = 0;
1381 gbox_message_header(send_buf_1, MSG_ECM , peer->gbox.password, local_gbox.password);
1383 i2b_buf(2, er->pid, send_buf_1 + 10);
1384 i2b_buf(2, er->srvid, send_buf_1 + 12);
1385 send_buf_1[14] = 0x00;
1386 send_buf_1[15] = 0x00;
1388 send_buf_1[16] = cont_card_1;
1389 send_buf_1[17] = 0x00;
1391 memcpy(send_buf_1 + 18, er->ecm, er->ecmlen);
1393 i2b_buf(2, local_gbox.id, send_buf_1 + len2);
1395 send_buf_1[len2 + 2] = gbox_get_my_vers();
1396 send_buf_1[len2 + 3] = 0x00;
1397 send_buf_1[len2 + 4] = gbox_get_my_cpu_api();
1399 uint32_t caprovid = gbox_get_caprovid(er->caid, er->prid);
1400 i2b_buf(4, caprovid, send_buf_1 + len2 + 5);
1402 send_buf_1[len2 + 9] = 0x00;
1403 cont_1 = len2 + 10;
1405 cont_card_1 = gbox_get_cards_for_ecm(&send_buf_1[0], len2 + 10, cli->reader->gbox_maxecmsend, er, &current_avg_card_time, peer->gbox.id);
1406 if (cont_card_1 == cli->reader->gbox_maxecmsend)
1407 { max_ecm_reached = 1; }
1408 cont_1 += cont_card_1 * 3;
1410 if(!cont_card_1 && er->gbox_ecm_status == GBOX_ECM_NOT_ASKED)
1412 cs_log_dbg(D_READER, "no valid card found for CAID: %04X PROVID: %04X", er->caid, er->prid);
1413 write_ecm_answer(cli->reader, er, E_NOTFOUND, E2_CCCAM_NOCARD, NULL, NULL, 0, NULL);
1414 return -1;
1416 if(cont_card_1)
1418 send_buf_1[16] = cont_card_1;
1420 //Hops
1421 send_buf_1[cont_1] = 0;
1422 cont_1++;
1424 memcpy(&send_buf_1[cont_1], gbox_get_checkcode(), 7);
1425 cont_1 = cont_1 + 7;
1426 memcpy(&send_buf_1[cont_1], peer->checkcode, 7);
1427 cont_1 = cont_1 + 7;
1429 cs_log_dbg(D_READER, "gbox sending ecm for %04X@%06X:%04X to %d cards -> %s", er->caid, er->prid , er->srvid, cont_card_1, cli->reader->label);
1430 uint32_t i = 0;
1431 struct gbox_card_pending *pending = NULL;
1432 struct timeb t_now;
1433 cs_ftime(&t_now);
1434 for (i = 0; i < cont_card_1; i++)
1436 if(!cs_malloc(&pending, sizeof(struct gbox_card_pending)))
1438 cs_log("Can't allocate gbox card pending");
1439 return -1;
1441 pending->id.peer = (send_buf_1[len2+10+i*3] << 8) | send_buf_1[len2+11+i*3];
1442 pending->id.slot = send_buf_1[len2+12+i*3];
1443 pending->pending_time = comp_timeb(&t_now, &er->tps);
1444 ll_append(er->gbox_cards_pending, pending);
1445 cs_log_dbg(D_READER, "gbox card %d: ID: %04X, Slot: %02X", i+1, (send_buf_1[len2+10+i*3] << 8) | send_buf_1[len2+11+i*3], send_buf_1[len2+12+i*3]);
1448 LL_LOCKITER *li = ll_li_create(er->gbox_cards_pending, 0);
1449 while ((pending = ll_li_next(li)))
1450 { cs_log_dbg(D_READER, "Pending Card ID: %04X Slot: %02X Time: %d", pending->id.peer, pending->id.slot, pending->pending_time); }
1451 ll_li_destroy(li);
1453 if(er->gbox_ecm_status > GBOX_ECM_NOT_ASKED)
1454 { er->gbox_ecm_status++; }
1455 else
1457 if(max_ecm_reached)
1458 { er->gbox_ecm_status = GBOX_ECM_SENT; }
1459 else
1460 { er->gbox_ecm_status = GBOX_ECM_SENT_ALL; }
1461 cli->pending++;
1463 gbox_send(cli, send_buf_1, cont_1);
1464 cli->reader->last_s = time((time_t *) 0);
1465 /* // see r11270
1466 if(er->gbox_ecm_status < GBOX_ECM_ANSWERED)
1468 //Create thread to rebroacast ecm after time
1469 struct gbox_rbc_thread_args args;
1470 args.cli = cli;
1471 args.er = er;
1472 if ((current_avg_card_time > 0) && (cont_card_1 == 1))
1474 args.waittime = current_avg_card_time + (current_avg_card_time / 2);
1475 if (args.waittime < GBOX_MIN_REBROADCAST_TIME)
1476 { args.waittime = GBOX_MIN_REBROADCAST_TIME; }
1478 else
1479 { args.waittime = GBOX_REBROADCAST_TIMEOUT; }
1480 cs_log_dbg(D_READER, "Creating rebroadcast thread with waittime: %d", args.waittime);
1481 int32_t ret = start_thread("rebroadcast", (void *)gbox_rebroadcast_thread, &args, NULL, 1, 1);
1482 if(ret)
1484 return -1;
1487 else
1488 */ { er->gbox_ecm_status--; }
1491 return 0;
1494 static int32_t gbox_send_emm(EMM_PACKET *UNUSED(ep))
1496 // emms not yet supported
1498 return 0;
1501 //init my gbox with id, password and cards crc
1502 static void init_local_gbox(void)
1504 local_gbox.id = 0;
1505 local_gbox.password = 0;
1506 local_gbox.minor_version = gbox_get_my_vers();
1507 local_gbox.cpu_api = gbox_get_my_cpu_api();
1508 init_gbox_cards();
1510 if(!cfg.gbox_my_password || strlen(cfg.gbox_my_password) != 8) { return; }
1512 local_gbox.password = a2i(cfg.gbox_my_password, 4);
1513 cs_log_dbg(D_READER, "gbox my password: %s:", cfg.gbox_my_password);
1515 local_gbox.id = gbox_convert_password_to_id(local_gbox.password);
1516 if (local_gbox.id == NO_GBOX_ID)
1518 cs_log("invalid local gbox id: %04X", local_gbox.id);
1520 last_stats_written = time(NULL);
1521 gbox_write_version();
1522 local_gbox_initialized = 1;
1525 static int32_t gbox_client_init(struct s_client *cli)
1527 if (!cli || cli->typ != 'p' || !cli->reader)
1529 cs_log("error, wrong call to gbox_proxy_init!");
1530 return -1;
1533 if (!local_gbox_initialized)
1534 { init_local_gbox(); }
1536 if(!cfg.gbx_port[0] || cfg.gbx_port[0] > 65535)
1538 cs_log("error, no/invalid port=%d configured in oscam.conf!",
1539 cfg.gbx_port[0] ? cfg.gbx_port[0] : 0);
1540 return -1;
1543 if(!cfg.gbox_hostname || strlen(cfg.gbox_hostname) > 128)
1545 cs_log("error, no/invalid hostname '%s' configured in oscam.conf!",
1546 cfg.gbox_hostname ? cfg.gbox_hostname : "");
1547 return -1;
1550 if(!local_gbox.id)
1552 cs_log("error, no/invalid password '%s' configured in oscam.conf!",
1553 cfg.gbox_my_password ? cfg.gbox_my_password : "");
1554 return -1;
1557 if(!cs_malloc(&cli->gbox, sizeof(struct gbox_peer)))
1558 { return -1; }
1560 struct s_reader *rdr = cli->reader;
1561 struct gbox_peer *peer = cli->gbox;
1563 memset(peer, 0, sizeof(struct gbox_peer));
1565 peer->gbox.password = a2i(rdr->r_pwd, 4);
1566 cs_log_dbg(D_READER, "gbox peer password: %s:", rdr->r_pwd);
1568 peer->gbox.id = gbox_convert_password_to_id(peer->gbox.password);
1569 if (get_gbox_proxy(peer->gbox.id) || peer->gbox.id == NO_GBOX_ID || peer->gbox.id == local_gbox.id)
1571 cs_log("error, double/invalid gbox id: %04X", peer->gbox.id);
1572 return -1;
1574 cs_lock_create(__func__, &peer->lock, "gbox_lock", 5000);
1576 gbox_reinit_peer(peer);
1578 cli->gbox_peer_id = peer->gbox.id;
1580 cli->pfd = 0;
1581 cli->crypted = 1;
1583 rdr->card_status = CARD_NEED_INIT;
1584 rdr->tcp_connected = 0;
1586 set_null_ip(&cli->ip);
1588 if((cli->udp_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
1590 cs_log("socket creation failed (errno=%d %s)", errno, strerror(errno));
1591 cs_disconnect_client(cli);
1594 int32_t opt = 1;
1595 setsockopt(cli->udp_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1597 set_so_reuseport(cli->udp_fd);
1599 set_socket_priority(cli->udp_fd, cfg.netprio);
1601 memset((char *)&cli->udp_sa, 0, sizeof(cli->udp_sa));
1603 if(!hostResolve(rdr))
1604 { return 0; }
1606 cli->port = rdr->r_port;
1607 SIN_GET_FAMILY(cli->udp_sa) = AF_INET;
1608 SIN_GET_PORT(cli->udp_sa) = htons((uint16_t)rdr->r_port);
1609 hostname2ip(cli->reader->device, &SIN_GET_ADDR(cli->udp_sa));
1611 cs_log("proxy %s (fd=%d, peer id=%04X, my id=%04X, my hostname=%s, peer's listen port=%d)",
1612 rdr->device, cli->udp_fd, peer->gbox.id, local_gbox.id, cfg.gbox_hostname, rdr->r_port);
1614 cli->pfd = cli->udp_fd;
1616 gbox_send_hello(cli, GBOX_STAT_HELLOL);
1618 if(!cli->reader->gbox_maxecmsend)
1619 { cli->reader->gbox_maxecmsend = DEFAULT_GBOX_MAX_ECM_SEND; }
1621 if(!cli->reader->gbox_maxdist)
1622 { cli->reader->gbox_maxdist = DEFAULT_GBOX_MAX_DIST; }
1624 //value > DEFAULT_GBOX_RESHARE not allowed in gbox network
1625 if(!cli->reader->gbox_reshare || cli->reader->gbox_reshare > DEFAULT_GBOX_RESHARE)
1626 { cli->reader->gbox_reshare = DEFAULT_GBOX_RESHARE; }
1628 if(!cli->reader->gbox_cccam_reshare || cli->reader->gbox_cccam_reshare > DEFAULT_GBOX_RESHARE)
1629 { cli->reader->gbox_cccam_reshare = DEFAULT_GBOX_RESHARE; }
1631 start_sms_sender();
1633 return 0;
1636 static void gbox_s_idle(struct s_client *cl)
1638 uint32_t time_since_last;
1639 struct s_client *proxy = get_gbox_proxy(cl->gbox_peer_id);
1640 struct gbox_peer *peer;
1642 if (proxy && proxy->gbox)
1644 if (llabs(proxy->last - time(NULL)) > llabs(cl->lastecm - time(NULL)))
1645 { time_since_last = llabs(cl->lastecm - time(NULL)); }
1646 else { time_since_last = llabs(proxy->last - time(NULL)); }
1647 if (time_since_last > (HELLO_KEEPALIVE_TIME*3) && cl->gbox_peer_id != NO_GBOX_ID)
1649 //gbox peer apparently died without saying goodnight
1650 peer = proxy->gbox;
1651 cs_writelock(__func__, &peer->lock);
1652 cs_log_dbg(D_READER, "time since last proxy activity in sec: %d => taking gbox peer offline",time_since_last);
1653 gbox_reinit_proxy(proxy);
1654 cs_writeunlock(__func__, &peer->lock);
1657 time_since_last = llabs(cl->lastecm - time(NULL));
1658 if (time_since_last > HELLO_KEEPALIVE_TIME && cl->gbox_peer_id != NO_GBOX_ID)
1660 peer = proxy->gbox;
1661 cs_writelock(__func__, &peer->lock);
1662 cs_log_dbg(D_READER, "time since last ecm in sec: %d => trigger keepalive hello",time_since_last);
1663 if (!peer->online)
1664 { gbox_send_hello(proxy, GBOX_STAT_HELLOL); }
1665 else
1666 { gbox_send_hello(proxy, GBOX_STAT_HELLOS); }
1667 cs_writeunlock(__func__, &peer->lock);
1670 //prevent users from timing out
1671 cs_log_dbg(D_READER, "client idle prevented: %s", username(cl));
1672 cl->last = time((time_t *)0);
1675 static int8_t gbox_send_peer_good_night(struct s_client *proxy)
1677 uchar outbuf[64];
1678 int32_t hostname_len = 0;
1679 if (cfg.gbox_hostname)
1680 hostname_len = strlen(cfg.gbox_hostname);
1681 int32_t len = hostname_len + 22;
1682 if(proxy->gbox && proxy->typ == 'p')
1684 struct gbox_peer *peer = proxy->gbox;
1685 struct s_reader *rdr = proxy->reader;
1686 if (peer->online)
1688 gbox_message_header(outbuf, MSG_HELLO, peer->gbox.password, local_gbox.password);
1689 outbuf[10] = 0x01;
1690 outbuf[11] = 0x80;
1691 memset(&outbuf[12], 0xff, 7);
1692 outbuf[19] = gbox_get_my_vers();
1693 outbuf[20] = gbox_get_my_cpu_api();
1694 memcpy(&outbuf[21], cfg.gbox_hostname, hostname_len);
1695 outbuf[21 + hostname_len] = hostname_len;
1696 cs_log("<- good night to %s:%d id: %04X", rdr->device, rdr->r_port, peer->gbox.id);
1697 gbox_compress(outbuf, len, &len);
1698 gbox_send(proxy, outbuf, len);
1699 gbox_reinit_proxy(proxy);
1702 return 0;
1705 void gbox_send_good_night(void)
1707 gbox_free_cardlist();
1708 struct s_client *cli;
1709 cs_readlock(__func__, &clientlist_lock);
1710 for(cli = first_client; cli; cli = cli->next)
1712 if(cli->gbox && cli->typ == 'p')
1713 { gbox_send_peer_good_night(cli); }
1715 cs_readunlock(__func__, &clientlist_lock);
1718 void gbox_send_goodbye(struct s_client *cli) // indication that requested ECM failed
1720 uchar outbuf[15];
1721 struct gbox_peer *peer = cli->gbox;
1722 gbox_message_header(outbuf, MSG_GOODBYE, peer->gbox.password, local_gbox.password);
1723 cs_log_dbg(D_READER,"<- goodbye - ecm failed info to boxid: %04X", peer->gbox.id);
1724 gbox_send(cli, outbuf, 10);
1728 void gbox_send_HERE_query (uint16_t boxid) //gbox.net send this cmd
1730 uchar outbuf[30];
1731 int32_t hostname_len = strlen(cfg.gbox_hostname);
1732 struct s_client *cli;
1733 cs_readlock(__func__, &clientlist_lock);
1734 for (cli = first_client; cli; cli = cli->next)
1736 if(cli->gbox && cli->typ == 'p')
1738 struct gbox_peer *peer = cli->gbox;
1739 if (peer->online && boxid == peer->gbox.id)
1741 gbox_message_header(outbuf, MSG_HERE, peer->gbox.password, local_gbox.password);
1742 outbuf[0xA] = gbox_get_my_vers();
1743 outbuf[0xB] = gbox_get_my_cpu_api();
1744 memcpy(&outbuf[0xC], cfg.gbox_hostname, hostname_len);
1745 cs_log("gbox send 'HERE?' to boxid: %04X", peer->gbox.id);
1746 gbox_send(cli, outbuf, hostname_len + 0xC);
1750 cs_readunlock(__func__, &clientlist_lock);
1752 //This is most likely the same as MSG_HERE. Don't know what would be the difference
1753 static void gbox_send_boxinfo(struct s_client *cli)
1755 struct gbox_peer *peer = cli->gbox;
1756 uchar outbuf[256];
1757 int32_t hostname_len = strlen(cfg.gbox_hostname);
1759 gbox_message_header(outbuf, MSG_BOXINFO, peer);
1760 outbuf[0xA] = local_gbox.minor_version;
1761 outbuf[0xB] = local_gbox.type;
1762 memcpy(&outbuf[0xC], cfg.gbox_hostname, hostname_len);
1763 gbox_send(cli, outbuf, hostname_len + 0xC);
1766 void module_gbox(struct s_module *ph)
1768 int32_t i;
1769 for(i = 0; i < CS_MAXPORTS; i++)
1771 if(!cfg.gbx_port[i]) { break; }
1772 ph->ptab.nports++;
1773 ph->ptab.ports[i].s_port = cfg.gbx_port[i];
1775 ph->desc = "gbox";
1776 ph->num = R_GBOX;
1777 ph->type = MOD_CONN_UDP;
1778 ph->large_ecm_support = 1;
1779 ph->listenertype = LIS_GBOX;
1781 ph->s_handler = gbox_server;
1782 ph->s_init = gbox_server_init;
1784 ph->send_dcw = gbox_send_dcw;
1786 ph->recv = gbox_recv;
1787 ph->c_init = gbox_client_init;
1788 ph->c_recv_chk = gbox_recv_chk;
1789 ph->c_send_ecm = gbox_send_ecm;
1790 ph->c_send_emm = gbox_send_emm;
1792 ph->s_idle = gbox_s_idle;
1794 #endif