/*-
 * Public platform independent Near Field Communication (NFC) library
 * 
 * Copyright (C) 2009, Roel Verdult
 *
 * Revision 1.1 Copyright (C) 2010, Tomas Rosa, crypto.hyperlink.cz.
 * --- Modification of target mode initialization to use Direct Register Hack
 * (DRH) method 
 * --- CTRL-C handling (mostly taken from other existing libnfc source by R.V.)
 * --- Some minor improvements like consistent nfc_disconnect() invocation, etc.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 * 
 * This program 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 Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 * @file nfc-emulate.c
 * @brief
 */

#ifdef HAVE_CONFIG_H
  #include "config.h"
#endif // HAVE_CONFIG_H

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>

#include <nfc/nfc.h>

#include <nfc/nfc-messages.h>
#include "bitutils.h"
#include "chips.h"

#define MAX_FRAME_LEN 264

static byte_t abtRecv[MAX_FRAME_LEN];
static size_t szRecvBits;
static nfc_device_t* pnd;

// ISO14443A Anti-Collision response
byte_t abtAtqa      [2] = { 0x04,0x00 };
byte_t abtUidBcc    [5] = { 0xDE,0xAD,0xBE,0xAF,0x62 };
byte_t abtSak       [9] = { 0x08,0xb6,0xdd };

static volatile bool quitting=false;
void intr_hdlr(void)
{
  printf("\nQuitting...\n");
  printf("It can take some time to pass the timeouts, please be patient...\n");
  printf("You can speed it up by some RF activity with the device.\n");
  quitting=true;
  return;
}

void print_usage(char* argv[])
{
  printf("Usage: %s [OPTIONS] [UID]\n", argv[0]);
  printf("Options:\n");
  printf("\t-h\tHelp. Print this message.\n");
  printf("\t-q\tQuiet mode. Suppress output of READER and EMULATOR data (improves timing).\n");
  printf("\n");
  printf("\t[UID]\tUID to emulate, specified as 8 HEX digits (default is DEADBEAF).\n");
}

/* performs alternative target init */
bool target_init_alt2(nfc_device_t *pnd) {
  bool r = true;
/* 
*  Issue standard TgInitTAMATarget cmd (encapsulated in nfc_target_init()).
*  This gives a chance to use secondary starting reader.
*  If not successfull, the command will at least reset the PN53x context.
*  IMPORTANT: The context reset is neccessary, therefore this command
*  must NOT be omitted even if secondary reader is not considered!
*  It can be, however, issued directly, without the standard timeout then.
*  Direct issuing is effective and elegant, but the code is then dependent
*  on the particular transport layer (libusb, pcsc, etc.) used. Therefore,
*  it cannot be written in such a simple way like this demo.
*/
  printf("[+] Performing an enhanced passive target mode initialization.\n");
  printf("[+] Now, you can use secondary reader to break the anti-collision.\n");
  printf("[+] To do so, please send e.g. RATS after the anti-collision(select).\n");
  printf("[+] ...for the alternative init, please do nothing - just wait for the timeout.\n");
  if (nfc_target_init(pnd,abtRecv,&szRecvBits)) {
    printf("[+] Target mode successfully started.\n");
    printf("[+] Received initiator command: ");
    print_hex_bits(abtRecv,szRecvBits);
    return true;
  }
/*
  *  Well, the standard initialization has obviously failed.
  *  Nevermind - we will enforce the passive target mode by
  *  the direct register hack (DRH) method instead.
*/
  printf("[+] Secondary reader not met - performing DRH alternative setup.\n");
  // INITIALLY - Stop eventual running CL unit microcode command
  r *= pn53x_set_reg(pnd, 0x6331, 0x3f, 0x00);
  // Configure WaterLevel
  r *= pn53x_set_reg(pnd, 0x633b, 0x7f, 0x3a);
  // Configure Diverse Control
  r *= pn53x_set_reg(pnd, 0x633c, 0x7f, 0x00);
  // Configure TxMode, preserve TxCRCEn flag 
  r *= pn53x_set_reg(pnd, 0x6302, 0x7f, 0x00);
  // Configure RxMode, preserve RxCRCEn flag
  r *= pn53x_set_reg(pnd, 0x6303, 0x7f, 0x00);
  // Configure TxAuto 
  r *= pn53x_set_reg(pnd, 0x6305, 0xef, 0x00);
  // Configure RxThreshold
  r *= pn53x_set_reg(pnd, 0x6308, 0xf7, 0x85);
  // Configure Demod 
  r *= pn53x_set_reg(pnd, 0x6309, 0xef, 0x61);
  // Configure GsNLoadMod 
  r *= pn53x_set_reg(pnd, 0x6313, 0xff, 0x6f);
  // Configure RFCfg
  r *= pn53x_set_reg(pnd, 0x6316, 0xff, 0x59);
  // Configure GsN
  r *= pn53x_set_reg(pnd, 0x6317, 0xff, 0xf4);
  // Configure CWGsP
  r *= pn53x_set_reg(pnd, 0x6318, 0x3f, 0x3f);
  // Configure ModGsP
  r *= pn53x_set_reg(pnd, 0x6319, 0x3f, 0x30);
  // Configure TMode
  r *= pn53x_set_reg(pnd, 0x631a, 0xff, 0x00);
  // FINALLY - Start Transceive CL unit microcode command
  r *= pn53x_set_reg(pnd, 0x6331, 0x3f, 0x0c);
  if (!r) {
    printf("[+] DRH failed!\n");
    return false;
  }
  printf("[+] Done, welcome to the passive target mode.\n");
  // Force REG_CIU_BIT_FRAMING update before next Tx
  pnd->ui8TxBits = 255;
  // Restore the CRC and PARITY handling flags if needed
  if (!pnd->bCrc)
    if (!nfc_configure(pnd, NDO_HANDLE_CRC, false)) return false;
  if (!pnd->bPar)
    if (!nfc_configure(pnd, NDO_HANDLE_PARITY, false)) return false;

  return r;
}

int main(int argc, char *argv[])
{
  byte_t* pbtTx = NULL;
  size_t szTxBits;
  bool quiet_output = false;

  int arg, i;

  // Get commandline options
  for (arg=1;arg<argc;arg++) {
    if (0 == strcmp(argv[arg], "-h")) {
      print_usage(argv);
      return 0;
    } else if (0 == strcmp(argv[arg], "-q")) {
      INFO("%s", "Quiet mode.");
      quiet_output = true;
    } else if((arg == argc-1) && (strlen(argv[arg]) == 8)) { // See if UID was specified as HEX string
      byte_t abtTmp[3] = { 0x00,0x00,0x00 };
      printf("[+] Using UID: %s\n",argv[arg]);
      abtUidBcc[4]= 0x00;
      for(i= 0; i < 4; ++i)
      {
        memcpy(abtTmp,argv[arg]+i*2,2);
        abtUidBcc[i]= (byte_t) strtol((char*)abtTmp,NULL,16);
        abtUidBcc[4] ^= abtUidBcc[i];
      }
    } else {
      ERR("%s is not supported option.", argv[arg]);
      print_usage(argv);
      return -1;
    }
  }

#ifdef WIN32
  signal(SIGINT, (void (__cdecl*)(int)) intr_hdlr);
#else
  signal(SIGINT, (void (*)()) intr_hdlr);
#endif

  // Try to open the NFC reader
  pnd = nfc_connect(NULL);
  if (pnd == NULL)
  {
    printf("Error connecting NFC reader\n");
    return 1;
  }

  printf("\n");
  printf("[+] Connected to NFC reader: %s\n",pnd->acName);

  // Initialize the passive target mode
  if (!target_init_alt2(pnd)) {
    printf("Error: Could not initialize target mode.\n");
    nfc_disconnect(pnd);
    return 1;
  }

  printf("[+] Configuring communication\n");
  nfc_configure(pnd,NDO_HANDLE_CRC,false);
  nfc_configure(pnd,NDO_HANDLE_PARITY,true);
  printf("[+] Done, the emulated tag is initialized with UID: %02X%02X%02X%02X\n\n",abtUidBcc[0],abtUidBcc[1],abtUidBcc[2],abtUidBcc[3]);

  while(!quitting)
  {
    // Test if we received a frame
    if (nfc_target_receive_bits(pnd,abtRecv,&szRecvBits,NULL))
    {
      // Prepare the command to send back for the anti-collision request
      switch(szRecvBits)
      {
        case 7: // Request or Wakeup
          pbtTx = abtAtqa;
          szTxBits = 16;
          // New anti-collsion session started
          if (!quiet_output) printf("\n"); 
        break;

        case 16: // Select All
          pbtTx = abtUidBcc;
          szTxBits = 40;
        break;

        case 72: // Select Tag
          pbtTx = abtSak;
          szTxBits = 24;
        break;

        default: // unknown length?
          szTxBits = 0;
        break;
      }

      if(!quiet_output)
      {
        printf("R: ");
        print_hex_bits(abtRecv,szRecvBits);
      }

      // Test if we know how to respond
      if(szTxBits)
      {
        // Send and print the command to the screen
        nfc_target_send_bits(pnd,pbtTx,szTxBits,NULL);
        if(!quiet_output)
        {
          printf("T: ");
          print_hex_bits(pbtTx,szTxBits);
        }
      }
    }
  }

  nfc_disconnect(pnd);
}


