/*
 * Softcam plugin to VDR (C++)
 *
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
 */

#if defined(CONAX) && defined(OPENSSL)

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
#include <openssl/bn.h>

#include "common.h"
#include "system.h"
#include "system-common.h"
#include "data.h"
#include "misc.h"
#include "..\\main.h"

#define SYSTEM_CONAX         0x0B00

#define SYSTEM_NAME          "Conax"
#define SYSTEM_PRI           -10
#define SYSTEM_CAN_HANDLE(x) ((x)==SYSTEM_CONAX)

// -- cSystemConax ---------------------------------------------------------------

class cSystemConax : public cSystem {
private:
  void ParseECM(unsigned char *buf, int len);
public:
  cSystemConax(void);
  virtual bool ProcessECM(const cEcmInfo *ecm, unsigned char *source);
  };

cSystemConax::cSystemConax(void)
:cSystem(SYSTEM_NAME,SYSTEM_PRI)
{}

void cSystemConax::ParseECM(unsigned char *buf, int len)
{
  int i=0;
  while(i<len) {
    int nano=buf[i++];
    int nanolen=buf[i++];
    
    switch(nano) {
      case 0x80:
      case 0x82:
        ParseECM(buf+i+3,nanolen-3); break;
      case 0x81:
        ParseECM(buf+i+2,nanolen-2); break;
      case 0x30:
	memcpy(cw  ,buf+i+10,8);
	memcpy(cw+8,buf+i+2 ,8);
        break;
      }
    i+=nanolen;
    }
}

bool cSystemConax::ProcessECM(const cEcmInfo *ecmD, unsigned char *source)
{
  int length=source[4]-2;
  const int keynr=source[6];
  const int nano=source[5];
  source+=7;

  cKeySnoop ks(this,'C','M',keynr);
  cPlainKey *pk;
  cBN mod, exp;
  if(!(pk=FastKey('C','E',keynr))) return false;
  pk->Get(exp);
  if(!(pk=FastKey('C','M',keynr))) return false;
  pk->Get(mod);

  cBNctx temp;
  cBN r, ecm;
  for(int i=length ; i>0 ;) {
    int index=i-64;
    if(index<0) index=0;
    BN_bin2bn(source+index,64,ecm);
    BN_mod_exp(r,ecm,exp,mod,temp);

    int l=64-BN_num_bytes(r);
    memset(source+index,0,l);
    BN_bn2bin(r,source+index+l);
    if(nano==0x63) {
      // nano 0x63 block only decodes to 63 bytes
      memmove(source+index,source+index+1,length-(index+1));
      length-=1;
      }
    i-=(i%60 && index) ? i%60 : 64;
    }

  static const unsigned char hash[] = { 0x05,0x00,0x05 };
  if(memcmp(hash,source+2,3) || memcmp(source+5,source+length-5,3))
  {
    m_DLLInstance.Log("[Conax]Signature Incorrect! Check keys.\n");
    return false; // signature incorrect
  }

  ParseECM(source+10,length-10);
  ks.OK(pk);
  return true;
}

// -- cPlainKeyConax --------------------------------------------------------------

#define PLAINLEN_CONAX 64

class cPlainKeyConax : public cBNKey {
public:
  cPlainKeyConax(bool Super);
  virtual bool Parse(char *line);
  virtual bool Save(FILE *f);
  };

static cPlainKeyTypeReg<cPlainKeyConax,'C'> KeyReg;

cPlainKeyConax::cPlainKeyConax(bool Super)
:cBNKey(Super)
{}

bool cPlainKeyConax::Parse(char *line)
{
  unsigned char skeynr, skey[PLAINLEN_CONAX];

  char *sline=line;

  if(GetChar(line,&type,1) && GetHex(line,&skeynr,1) &&
     GetChar(line,&id,1) && GetHex(line,skey,PLAINLEN_CONAX)) {
    type=toupper(type); keynr=skeynr;
    SetKeyFromBin(skey,PLAINLEN_CONAX);
    return true;
    }
  m_DLLInstance.Log("[Conax]Bad key format.\nLine:'%s'\n",sline);
  return false;
}

bool cPlainKeyConax::Save(FILE *f)
{
  char *str=Print();
  fprintf(f,"%c %.2X %c %s\n",type,keynr,id,str);
  free(str);
  return ferror(f)==0;
}

// -- cSystemLinkConax ---------------------------------------------------------

class cSystemLinkConax : public cSystemLink {
public:
  cSystemLinkConax(void):cSystemLink(SYSTEM_NAME,SYSTEM_PRI) {}
  virtual bool CanHandle(unsigned short SysId);
  virtual cSystem *Create(void) { return new cSystemConax; }
  };

static cSystemLinkConax staticInit;

bool cSystemLinkConax::CanHandle(unsigned short SysId)
{
  SysId&=SYSTEM_MASK;
  return SYSTEM_CAN_HANDLE(SysId);
}

#else //#if defined(CONAX) && defined(OPENSSL)

// add dummy loader for Conax keys
#include "system-common.h"
static cPlainKeyTypeReg<cPlainKeyDummy,'C'> KeyReg;

#endif //#if defined(CONAX) && defined(OPENSSL)
