astyle --formatted --mode=c --indent=spaces=2 --indent-switches --indent-preprocessor --keep-one-line-blocks --max-instatement-indent=60 --brackets=linux --pad-oper --unpad-paren --pad-header

This commit is contained in:
Philippe Teuwen 2012-05-29 15:54:36 +00:00
parent 562205cc14
commit 01303fab0d
59 changed files with 3178 additions and 3178 deletions

View file

@ -14,52 +14,52 @@
#include "libnfc/chips/pn53x.h" #include "libnfc/chips/pn53x.h"
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
nfc_device *pnd; nfc_device *pnd;
nfc_target nt; nfc_target nt;
nfc_init (NULL); nfc_init(NULL);
// Display libnfc version // Display libnfc version
const char *acLibnfcVersion = nfc_version (); const char *acLibnfcVersion = nfc_version();
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
// Open, using the first available NFC device // Open, using the first available NFC device
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR ("%s", "Unable to open NFC device."); ERR("%s", "Unable to open NFC device.");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
// Set opened NFC device to initiator mode // Set opened NFC device to initiator mode
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC reader: %s opened\n", nfc_device_get_name (pnd)); printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
// Poll for a ISO14443A (MIFARE) tag // Poll for a ISO14443A (MIFARE) tag
const nfc_modulation nmMifare = { const nfc_modulation nmMifare = {
.nmt = NMT_ISO14443A, .nmt = NMT_ISO14443A,
.nbr = NBR_106, .nbr = NBR_106,
}; };
if (nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt) > 0) { if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
printf ("The following (NFC) ISO14443A tag was found:\n"); printf("The following (NFC) ISO14443A tag was found:\n");
printf (" ATQA (SENS_RES): "); printf(" ATQA (SENS_RES): ");
print_hex (nt.nti.nai.abtAtqa, 2); print_hex(nt.nti.nai.abtAtqa, 2);
printf (" UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1')); printf(" UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
print_hex (nt.nti.nai.abtUid, nt.nti.nai.szUidLen); print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
printf (" SAK (SEL_RES): "); printf(" SAK (SEL_RES): ");
print_hex (&nt.nti.nai.btSak, 1); print_hex(&nt.nti.nai.btSak, 1);
if (nt.nti.nai.szAtsLen) { if (nt.nti.nai.szAtsLen) {
printf (" ATS (ATR): "); printf(" ATS (ATR): ");
print_hex (nt.nti.nai.abtAts, nt.nti.nai.szAtsLen); print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen);
} }
} }
// Close NFC device // Close NFC device
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View file

@ -75,21 +75,21 @@ uint8_t abtHalt[4] = { 0x50, 0x00, 0x00, 0x00 };
#define CASCADE_BIT 0x04 #define CASCADE_BIT 0x04
static bool static bool
transmit_bits (const uint8_t *pbtTx, const size_t szTxBits) transmit_bits(const uint8_t *pbtTx, const size_t szTxBits)
{ {
// Show transmitted command // Show transmitted command
if (!quiet_output) { if (!quiet_output) {
printf ("Sent bits: "); printf("Sent bits: ");
print_hex_bits (pbtTx, szTxBits); print_hex_bits(pbtTx, szTxBits);
} }
// Transmit the bit frame command, we don't use the arbitrary parity feature // Transmit the bit frame command, we don't use the arbitrary parity feature
if ((szRxBits = nfc_initiator_transceive_bits (pnd, pbtTx, szTxBits, NULL, abtRx, NULL)) < 0) if ((szRxBits = nfc_initiator_transceive_bits(pnd, pbtTx, szTxBits, NULL, abtRx, NULL)) < 0)
return false; return false;
// Show received answer // Show received answer
if (!quiet_output) { if (!quiet_output) {
printf ("Received bits: "); printf("Received bits: ");
print_hex_bits (abtRx, szRxBits); print_hex_bits(abtRx, szRxBits);
} }
// Succesful transfer // Succesful transfer
return true; return true;
@ -97,103 +97,103 @@ transmit_bits (const uint8_t *pbtTx, const size_t szTxBits)
static bool static bool
transmit_bytes (const uint8_t *pbtTx, const size_t szTx) transmit_bytes(const uint8_t *pbtTx, const size_t szTx)
{ {
// Show transmitted command // Show transmitted command
if (!quiet_output) { if (!quiet_output) {
printf ("Sent bits: "); printf("Sent bits: ");
print_hex (pbtTx, szTx); print_hex(pbtTx, szTx);
} }
int res; int res;
// Transmit the command bytes // Transmit the command bytes
if ((res = nfc_initiator_transceive_bytes (pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0) if ((res = nfc_initiator_transceive_bytes(pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0)
return false; return false;
// Show received answer // Show received answer
if (!quiet_output) { if (!quiet_output) {
printf ("Received bits: "); printf("Received bits: ");
print_hex (abtRx, res); print_hex(abtRx, res);
} }
// Succesful transfer // Succesful transfer
return true; return true;
} }
static void static void
print_usage (char *argv[]) print_usage(char *argv[])
{ {
printf ("Usage: %s [OPTIONS]\n", argv[0]); printf("Usage: %s [OPTIONS]\n", argv[0]);
printf ("Options:\n"); printf("Options:\n");
printf ("\t-h\tHelp. Print this message.\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("\t-q\tQuiet mode. Suppress output of READER and EMULATOR data (improves timing).\n");
printf ("\t-f\tForce RATS.\n"); printf("\t-f\tForce RATS.\n");
} }
int int
main (int argc, char *argv[]) main(int argc, char *argv[])
{ {
int arg; int arg;
// Get commandline options // Get commandline options
for (arg = 1; arg < argc; arg++) { for (arg = 1; arg < argc; arg++) {
if (0 == strcmp (argv[arg], "-h")) { if (0 == strcmp(argv[arg], "-h")) {
print_usage (argv); print_usage(argv);
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} else if (0 == strcmp (argv[arg], "-q")) { } else if (0 == strcmp(argv[arg], "-q")) {
quiet_output = true; quiet_output = true;
} else if (0 == strcmp (argv[arg], "-f")) { } else if (0 == strcmp(argv[arg], "-f")) {
force_rats = true; force_rats = true;
} else { } else {
ERR ("%s is not supported option.", argv[arg]); ERR("%s is not supported option.", argv[arg]);
print_usage (argv); print_usage(argv);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC reader // Try to open the NFC reader
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (!pnd) { if (!pnd) {
printf ("Error opening NFC reader\n"); printf("Error opening NFC reader\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Initialise NFC device as "initiator" // Initialise NFC device as "initiator"
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Configure the CRC // Configure the CRC
if (nfc_device_set_property_bool (pnd, NP_HANDLE_CRC, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Use raw send/receive methods // Use raw send/receive methods
if (nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Disable 14443-4 autoswitching // Disable 14443-4 autoswitching
if (nfc_device_set_property_bool (pnd, NP_AUTO_ISO14443_4, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC reader: %s opened\n\n", nfc_device_get_name (pnd)); printf("NFC reader: %s opened\n\n", nfc_device_get_name(pnd));
// Send the 7 bits request command specified in ISO 14443A (0x26) // Send the 7 bits request command specified in ISO 14443A (0x26)
if (!transmit_bits (abtReqa, 7)) { if (!transmit_bits(abtReqa, 7)) {
printf ("Error: No tag available\n"); printf("Error: No tag available\n");
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return 1; return 1;
} }
memcpy (abtAtqa, abtRx, 2); memcpy(abtAtqa, abtRx, 2);
// Anti-collision // Anti-collision
transmit_bytes (abtSelectAll, 2); transmit_bytes(abtSelectAll, 2);
// Check answer // Check answer
if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
@ -201,12 +201,12 @@ main (int argc, char *argv[])
} }
// Save the UID CL1 // Save the UID CL1
memcpy (abtRawUid, abtRx, 4); memcpy(abtRawUid, abtRx, 4);
//Prepare and send CL1 Select-Command //Prepare and send CL1 Select-Command
memcpy (abtSelectTag + 2, abtRx, 5); memcpy(abtSelectTag + 2, abtRx, 5);
iso14443a_crc_append (abtSelectTag, 7); iso14443a_crc_append(abtSelectTag, 7);
transmit_bytes (abtSelectTag, 9); transmit_bytes(abtSelectTag, 9);
abtSak = abtRx[0]; abtSak = abtRx[0];
// Test if we are dealing with a CL2 // Test if we are dealing with a CL2
@ -218,14 +218,14 @@ main (int argc, char *argv[])
} }
} }
if(szCL == 2) { if (szCL == 2) {
// We have to do the anti-collision for cascade level 2 // We have to do the anti-collision for cascade level 2
// Prepare CL2 commands // Prepare CL2 commands
abtSelectAll[0] = 0x95; abtSelectAll[0] = 0x95;
// Anti-collision // Anti-collision
transmit_bytes (abtSelectAll, 2); transmit_bytes(abtSelectAll, 2);
// Check answer // Check answer
if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
@ -233,13 +233,13 @@ main (int argc, char *argv[])
} }
// Save UID CL2 // Save UID CL2
memcpy (abtRawUid + 4, abtRx, 4); memcpy(abtRawUid + 4, abtRx, 4);
// Selection // Selection
abtSelectTag[0] = 0x95; abtSelectTag[0] = 0x95;
memcpy (abtSelectTag + 2, abtRx, 5); memcpy(abtSelectTag + 2, abtRx, 5);
iso14443a_crc_append (abtSelectTag, 7); iso14443a_crc_append(abtSelectTag, 7);
transmit_bytes (abtSelectTag, 9); transmit_bytes(abtSelectTag, 9);
abtSak = abtRx[0]; abtSak = abtRx[0];
// Test if we are dealing with a CL3 // Test if we are dealing with a CL3
@ -251,12 +251,12 @@ main (int argc, char *argv[])
} }
} }
if ( szCL == 3) { if (szCL == 3) {
// We have to do the anti-collision for cascade level 3 // We have to do the anti-collision for cascade level 3
// Prepare and send CL3 AC-Command // Prepare and send CL3 AC-Command
abtSelectAll[0] = 0x97; abtSelectAll[0] = 0x97;
transmit_bytes (abtSelectAll, 2); transmit_bytes(abtSelectAll, 2);
// Check answer // Check answer
if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
@ -264,13 +264,13 @@ main (int argc, char *argv[])
} }
// Save UID CL3 // Save UID CL3
memcpy (abtRawUid + 8, abtRx, 4); memcpy(abtRawUid + 8, abtRx, 4);
// Prepare and send final Select-Command // Prepare and send final Select-Command
abtSelectTag[0] = 0x97; abtSelectTag[0] = 0x97;
memcpy (abtSelectTag + 2, abtRx, 5); memcpy(abtSelectTag + 2, abtRx, 5);
iso14443a_crc_append (abtSelectTag, 7); iso14443a_crc_append(abtSelectTag, 7);
transmit_bytes (abtSelectTag, 9); transmit_bytes(abtSelectTag, 9);
abtSak = abtRx[0]; abtSak = abtRx[0];
} }
} }
@ -281,29 +281,29 @@ main (int argc, char *argv[])
} }
if ((abtRx[0] & SAK_FLAG_ATS_SUPPORTED) || force_rats) { if ((abtRx[0] & SAK_FLAG_ATS_SUPPORTED) || force_rats) {
iso14443a_crc_append(abtRats, 2); iso14443a_crc_append(abtRats, 2);
if (transmit_bytes (abtRats, 4)) { if (transmit_bytes(abtRats, 4)) {
memcpy (abtAts, abtRx, szRx); memcpy(abtAts, abtRx, szRx);
szAts = szRx; szAts = szRx;
} }
} }
// Done, halt the tag now // Done, halt the tag now
iso14443a_crc_append(abtHalt, 2); iso14443a_crc_append(abtHalt, 2);
transmit_bytes (abtHalt, 4); transmit_bytes(abtHalt, 4);
printf ("\nFound tag with\n UID: "); printf("\nFound tag with\n UID: ");
switch (szCL) { switch (szCL) {
case 1: case 1:
printf ("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]);
break; break;
case 2: case 2:
printf ("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
printf ("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]); printf("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]);
break; break;
case 3: case 3:
printf ("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
printf ("%02x%02x%02x", abtRawUid[5], abtRawUid[6], abtRawUid[7]); printf("%02x%02x%02x", abtRawUid[5], abtRawUid[6], abtRawUid[7]);
printf ("%02x%02x%02x%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]); printf("%02x%02x%02x%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]);
break; break;
} }
printf("\n"); printf("\n");
@ -313,10 +313,10 @@ main (int argc, char *argv[])
printf(" RATS forced\n"); printf(" RATS forced\n");
} }
printf(" ATS: "); printf(" ATS: ");
print_hex (abtAts, szAts); print_hex(abtAts, szAts);
} }
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return 0; return 0;
} }

View file

@ -50,66 +50,66 @@
static nfc_device *pnd; static nfc_device *pnd;
static void stop_dep_communication (int sig) static void stop_dep_communication(int sig)
{ {
(void) sig; (void) sig;
if (pnd) if (pnd)
nfc_abort_command (pnd); nfc_abort_command(pnd);
else else
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
nfc_target nt; nfc_target nt;
uint8_t abtRx[MAX_FRAME_LEN]; uint8_t abtRx[MAX_FRAME_LEN];
uint8_t abtTx[] = "Hello World!"; uint8_t abtTx[] = "Hello World!";
if (argc > 1) { if (argc > 1) {
printf ("Usage: %s\n", argv[0]); printf("Usage: %s\n", argv[0]);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
nfc_init (NULL); nfc_init(NULL);
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (!pnd) { if (!pnd) {
printf("Unable to open NFC device.\n"); printf("Unable to open NFC device.\n");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("NFC device: %s\n opened", nfc_device_get_name (pnd)); printf("NFC device: %s\n opened", nfc_device_get_name(pnd));
signal (SIGINT, stop_dep_communication); signal(SIGINT, stop_dep_communication);
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror(pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
goto error; goto error;
} }
if(nfc_initiator_select_dep_target (pnd, NDM_PASSIVE, NBR_212, NULL, &nt, 1000) < 0) { if (nfc_initiator_select_dep_target(pnd, NDM_PASSIVE, NBR_212, NULL, &nt, 1000) < 0) {
nfc_perror(pnd, "nfc_initiator_select_dep_target"); nfc_perror(pnd, "nfc_initiator_select_dep_target");
goto error; goto error;
} }
print_nfc_target (nt, false); print_nfc_target(nt, false);
printf ("Sending: %s\n", abtTx); printf("Sending: %s\n", abtTx);
int res; int res;
if ((res = nfc_initiator_transceive_bytes (pnd, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 0)) < 0) { if ((res = nfc_initiator_transceive_bytes(pnd, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 0)) < 0) {
nfc_perror(pnd, "nfc_initiator_transceive_bytes"); nfc_perror(pnd, "nfc_initiator_transceive_bytes");
goto error; goto error;
} }
abtRx[res] = 0; abtRx[res] = 0;
printf ("Received: %s\n", abtRx); printf("Received: %s\n", abtRx);
if (nfc_initiator_deselect_target (pnd) < 0) { if (nfc_initiator_deselect_target(pnd) < 0) {
nfc_perror(pnd, "nfc_initiator_deselect_target"); nfc_perror(pnd, "nfc_initiator_deselect_target");
goto error; goto error;
} }
error: error:
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View file

@ -49,40 +49,40 @@
static nfc_device *pnd; static nfc_device *pnd;
static void stop_dep_communication (int sig) static void stop_dep_communication(int sig)
{ {
(void) sig; (void) sig;
if (pnd) if (pnd)
nfc_abort_command (pnd); nfc_abort_command(pnd);
else else
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
uint8_t abtRx[MAX_FRAME_LEN]; uint8_t abtRx[MAX_FRAME_LEN];
int szRx; int szRx;
uint8_t abtTx[] = "Hello Mars!"; uint8_t abtTx[] = "Hello Mars!";
#define MAX_DEVICE_COUNT 2 #define MAX_DEVICE_COUNT 2
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
size_t szDeviceFound = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t szDeviceFound = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
// Little hack to allow using nfc-dep-initiator & nfc-dep-target from // Little hack to allow using nfc-dep-initiator & nfc-dep-target from
// the same machine: if there is more than one readers opened // the same machine: if there is more than one readers opened
// nfc-dep-target will open the second reader // nfc-dep-target will open the second reader
// (we hope they're always detected in the same order) // (we hope they're always detected in the same order)
nfc_init (NULL); nfc_init(NULL);
if (szDeviceFound == 1) { if (szDeviceFound == 1) {
pnd = nfc_open (NULL, connstrings[0]); pnd = nfc_open(NULL, connstrings[0]);
} else if (szDeviceFound > 1) { } else if (szDeviceFound > 1) {
pnd = nfc_open (NULL, connstrings[1]); pnd = nfc_open(NULL, connstrings[1]);
} else { } else {
printf("No device found.\n"); printf("No device found.\n");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (argc > 1) { if (argc > 1) {
printf ("Usage: %s\n", argv[0]); printf("Usage: %s\n", argv[0]);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -111,36 +111,36 @@ main (int argc, const char *argv[])
printf("Unable to open NFC device.\n"); printf("Unable to open NFC device.\n");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("NFC device: %s opened\n", nfc_device_get_name (pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
signal (SIGINT, stop_dep_communication); signal(SIGINT, stop_dep_communication);
printf ("NFC device will now act as: "); printf("NFC device will now act as: ");
print_nfc_target (nt, false); print_nfc_target(nt, false);
printf ("Waiting for initiator request...\n"); printf("Waiting for initiator request...\n");
if ((szRx = nfc_target_init (pnd, &nt, abtRx, sizeof(abtRx), 0)) < 0) { if ((szRx = nfc_target_init(pnd, &nt, abtRx, sizeof(abtRx), 0)) < 0) {
nfc_perror(pnd, "nfc_target_init"); nfc_perror(pnd, "nfc_target_init");
goto error; goto error;
} }
printf("Initiator request received. Waiting for data...\n"); printf("Initiator request received. Waiting for data...\n");
if ((szRx = nfc_target_receive_bytes (pnd, abtRx, sizeof (abtRx), 0)) < 0) { if ((szRx = nfc_target_receive_bytes(pnd, abtRx, sizeof(abtRx), 0)) < 0) {
nfc_perror(pnd, "nfc_target_receive_bytes"); nfc_perror(pnd, "nfc_target_receive_bytes");
goto error; goto error;
} }
abtRx[(size_t) szRx] = '\0'; abtRx[(size_t) szRx] = '\0';
printf ("Received: %s\n", abtRx); printf("Received: %s\n", abtRx);
printf ("Sending: %s\n", abtTx); printf("Sending: %s\n", abtTx);
if (nfc_target_send_bytes (pnd, abtTx, sizeof(abtTx), 0) < 0) { if (nfc_target_send_bytes(pnd, abtTx, sizeof(abtTx), 0) < 0) {
nfc_perror(pnd, "nfc_target_send_bytes"); nfc_perror(pnd, "nfc_target_send_bytes");
goto error; goto error;
} }
printf("Data sent.\n"); printf("Data sent.\n");
error: error:
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View file

@ -74,13 +74,13 @@
static nfc_device *pnd; static nfc_device *pnd;
static void static void
stop_emulation (int sig) stop_emulation(int sig)
{ {
(void)sig; (void)sig;
if (pnd) { if (pnd) {
nfc_abort_command(pnd); nfc_abort_command(pnd);
} else { } else {
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
@ -112,14 +112,14 @@ static uint8_t __nfcforum_tag2_memory_area[] = {
#define HALT 0x50 #define HALT 0x50
static int static int
nfcforum_tag2_io (struct nfc_emulator *emulator, const uint8_t *data_in, const size_t data_in_len, uint8_t *data_out, const size_t data_out_len) nfcforum_tag2_io(struct nfc_emulator *emulator, const uint8_t *data_in, const size_t data_in_len, uint8_t *data_out, const size_t data_out_len)
{ {
int res = 0; int res = 0;
uint8_t *nfcforum_tag2_memory_area = (uint8_t *)(emulator->user_data); uint8_t *nfcforum_tag2_memory_area = (uint8_t *)(emulator->user_data);
printf (" In: "); printf(" In: ");
print_hex (data_in, data_in_len); print_hex(data_in, data_in_len);
switch (data_in[0]) { switch (data_in[0]) {
case READ: case READ:
@ -131,19 +131,19 @@ nfcforum_tag2_io (struct nfc_emulator *emulator, const uint8_t *data_in, const s
} }
break; break;
case HALT: case HALT:
printf ("HALT sent\n"); printf("HALT sent\n");
res = -ECONNABORTED; res = -ECONNABORTED;
break; break;
default: default:
printf ("Unknown command: 0x%02x\n", data_in[0]); printf("Unknown command: 0x%02x\n", data_in[0]);
res = -ENOTSUP; res = -ENOTSUP;
} }
if (res < 0) { if (res < 0) {
ERR ("%s (%d)", strerror (-res), -res); ERR("%s (%d)", strerror(-res), -res);
} else { } else {
printf (" Out: "); printf(" Out: ");
print_hex (data_out, res); print_hex(data_out, res);
} }
return res; return res;
@ -181,31 +181,31 @@ main(int argc, char *argv[])
.user_data = __nfcforum_tag2_memory_area, .user_data = __nfcforum_tag2_memory_area,
}; };
signal (SIGINT, stop_emulation); signal(SIGINT, stop_emulation);
nfc_init (NULL); nfc_init(NULL);
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR("Unable to open NFC device"); ERR("Unable to open NFC device");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC device: %s opened\n", nfc_device_get_name (pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
printf ("Emulating NDEF tag now, please touch it with a second NFC device\n"); printf("Emulating NDEF tag now, please touch it with a second NFC device\n");
if (nfc_emulate_target (pnd, &emulator) < 0) { if (nfc_emulate_target(pnd, &emulator) < 0) {
goto error; goto error;
} }
nfc_close(pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
error: error:
if (pnd) { if (pnd) {
nfc_perror (pnd, argv[0]); nfc_perror(pnd, argv[0]);
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
} }
} }

View file

@ -61,30 +61,30 @@ static bool quiet_output = false;
static bool init_mfc_auth = false; static bool init_mfc_auth = false;
static void static void
intr_hdlr (int sig) intr_hdlr(int sig)
{ {
(void) sig; (void) sig;
printf ("\nQuitting...\n"); printf("\nQuitting...\n");
if (pnd != NULL) { if (pnd != NULL) {
nfc_close(pnd); nfc_close(pnd);
} }
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
static bool static bool
target_io( nfc_target *pnt, const uint8_t *pbtInput, const size_t szInput, uint8_t *pbtOutput, size_t *pszOutput ) target_io(nfc_target *pnt, const uint8_t *pbtInput, const size_t szInput, uint8_t *pbtOutput, size_t *pszOutput)
{ {
bool loop = true; bool loop = true;
*pszOutput = 0; *pszOutput = 0;
// Show transmitted command // Show transmitted command
if (!quiet_output) { if (!quiet_output) {
printf (" In: "); printf(" In: ");
print_hex (pbtInput, szInput); print_hex(pbtInput, szInput);
} }
if(szInput) { if (szInput) {
switch(pbtInput[0]) { switch (pbtInput[0]) {
case 0x30: // Mifare read case 0x30: // Mifare read
// block address is in pbtInput[1] // block address is in pbtInput[1]
*pszOutput = 15; *pszOutput = 15;
@ -110,7 +110,7 @@ target_io( nfc_target *pnt, const uint8_t *pbtInput, const size_t szInput, uint8
// Send ATS // Send ATS
*pszOutput = pnt->nti.nai.szAtsLen + 1; *pszOutput = pnt->nti.nai.szAtsLen + 1;
pbtOutput[0] = pnt->nti.nai.szAtsLen + 1; // ISO14443-4 says that ATS contains ATS_Length as first byte pbtOutput[0] = pnt->nti.nai.szAtsLen + 1; // ISO14443-4 says that ATS contains ATS_Length as first byte
if(pnt->nti.nai.szAtsLen) { if (pnt->nti.nai.szAtsLen) {
memcpy(pbtOutput + 1, pnt->nti.nai.abtAts, pnt->nti.nai.szAtsLen); memcpy(pbtOutput + 1, pnt->nti.nai.abtAts, pnt->nti.nai.szAtsLen);
} }
break; break;
@ -129,8 +129,8 @@ target_io( nfc_target *pnt, const uint8_t *pbtInput, const size_t szInput, uint8
} }
// Show transmitted command // Show transmitted command
if ((!quiet_output) && *pszOutput) { if ((!quiet_output) && *pszOutput) {
printf (" Out: "); printf(" Out: ");
print_hex (pbtOutput, *pszOutput); print_hex(pbtOutput, *pszOutput);
} }
return loop; return loop;
} }
@ -142,26 +142,26 @@ nfc_target_emulate_tag(nfc_device *dev, nfc_target *pnt)
uint8_t abtTx[MAX_FRAME_LEN]; uint8_t abtTx[MAX_FRAME_LEN];
bool loop = true; bool loop = true;
if ((szRx = nfc_target_init (dev, pnt, abtRx, sizeof(abtRx), 0)) < 0) { if ((szRx = nfc_target_init(dev, pnt, abtRx, sizeof(abtRx), 0)) < 0) {
nfc_perror (dev, "nfc_target_init"); nfc_perror(dev, "nfc_target_init");
return false; return false;
} }
while ( loop ) { while (loop) {
loop = target_io( pnt, abtRx, (size_t) szRx, abtTx, &szTx ); loop = target_io(pnt, abtRx, (size_t) szRx, abtTx, &szTx);
if (szTx) { if (szTx) {
if (nfc_target_send_bytes(dev, abtTx, szTx, 0) < 0) { if (nfc_target_send_bytes(dev, abtTx, szTx, 0) < 0) {
nfc_perror (dev, "nfc_target_send_bytes"); nfc_perror(dev, "nfc_target_send_bytes");
return false; return false;
} }
} }
if ( loop ) { if (loop) {
if ( init_mfc_auth ) { if (init_mfc_auth) {
nfc_device_set_property_bool (dev, NP_HANDLE_CRC, false); nfc_device_set_property_bool(dev, NP_HANDLE_CRC, false);
init_mfc_auth = false; init_mfc_auth = false;
} }
if ((szRx = nfc_target_receive_bytes(dev, abtRx, sizeof (abtRx), 0)) < 0) { if ((szRx = nfc_target_receive_bytes(dev, abtRx, sizeof(abtRx), 0)) < 0) {
nfc_perror (dev, "nfc_target_receive_bytes"); nfc_perror(dev, "nfc_target_receive_bytes");
return false; return false;
} }
} }
@ -170,32 +170,32 @@ nfc_target_emulate_tag(nfc_device *dev, nfc_target *pnt)
} }
int int
main (int argc, char *argv[]) main(int argc, char *argv[])
{ {
(void) argc; (void) argc;
const char *acLibnfcVersion; const char *acLibnfcVersion;
#ifdef WIN32 #ifdef WIN32
signal (SIGINT, (void (__cdecl *) (int)) intr_hdlr); signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr);
#else #else
signal (SIGINT, intr_hdlr); signal(SIGINT, intr_hdlr);
#endif #endif
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC reader // Try to open the NFC reader
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
// Display libnfc version // Display libnfc version
acLibnfcVersion = nfc_version (); acLibnfcVersion = nfc_version();
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
if (pnd == NULL) { if (pnd == NULL) {
ERR("Unable to open NFC device"); ERR("Unable to open NFC device");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC device: %s opened\n", nfc_device_get_name (pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
// Notes for ISO14443-A emulated tags: // Notes for ISO14443-A emulated tags:
// * Only short UIDs are supported // * Only short UIDs are supported
@ -258,19 +258,19 @@ main (int argc, char *argv[])
}; };
*/ */
printf ("%s will emulate this ISO14443-A tag:\n", argv[0]); printf("%s will emulate this ISO14443-A tag:\n", argv[0]);
print_nfc_iso14443a_info (nt.nti.nai, true); print_nfc_iso14443a_info(nt.nti.nai, true);
// Switch off NP_EASY_FRAMING if target is not ISO14443-4 // Switch off NP_EASY_FRAMING if target is not ISO14443-4
nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, (nt.nti.nai.btSak & SAK_ISO14443_4_COMPLIANT)); nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, (nt.nti.nai.btSak & SAK_ISO14443_4_COMPLIANT));
printf ("NFC device (configured as target) is now emulating the tag, please touch it with a second NFC device (initiator)\n"); printf("NFC device (configured as target) is now emulating the tag, please touch it with a second NFC device (initiator)\n");
if (!nfc_target_emulate_tag (pnd, &nt)) { if (!nfc_target_emulate_tag(pnd, &nt)) {
nfc_perror (pnd, "nfc_target_emulate_tag"); nfc_perror(pnd, "nfc_target_emulate_tag");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
nfc_close(pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }

View file

@ -66,28 +66,28 @@ uint8_t abtUidBcc[5] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x62 };
uint8_t abtSak[9] = { 0x08, 0xb6, 0xdd }; uint8_t abtSak[9] = { 0x08, 0xb6, 0xdd };
static void static void
intr_hdlr (int sig) intr_hdlr(int sig)
{ {
(void) sig; (void) sig;
if (pnd != NULL) { if (pnd != NULL) {
printf ("\nAborting current command...\n"); printf("\nAborting current command...\n");
nfc_abort_command (pnd); nfc_abort_command(pnd);
} }
} }
static void static void
print_usage (char *argv[]) print_usage(char *argv[])
{ {
printf ("Usage: %s [OPTIONS] [UID]\n", argv[0]); printf("Usage: %s [OPTIONS] [UID]\n", argv[0]);
printf ("Options:\n"); printf("Options:\n");
printf ("\t-h\tHelp. Print this message.\n"); printf("\t-h\tHelp. Print this message.\n");
printf ("\t-q\tQuiet mode. Silent output: received and sent frames will not be shown (improves timing).\n"); printf("\t-q\tQuiet mode. Silent output: received and sent frames will not be shown (improves timing).\n");
printf ("\n"); printf("\n");
printf ("\t[UID]\tUID to emulate, specified as 8 HEX digits (default is DEADBEEF).\n"); printf("\t[UID]\tUID to emulate, specified as 8 HEX digits (default is DEADBEEF).\n");
} }
int int
main (int argc, char *argv[]) main(int argc, char *argv[])
{ {
uint8_t *pbtTx = NULL; uint8_t *pbtTx = NULL;
size_t szTxBits; size_t szTxBits;
@ -98,49 +98,49 @@ main (int argc, char *argv[])
// Get commandline options // Get commandline options
for (arg = 1; arg < argc; arg++) { for (arg = 1; arg < argc; arg++) {
if (0 == strcmp (argv[arg], "-h")) { if (0 == strcmp(argv[arg], "-h")) {
print_usage (argv); print_usage(argv);
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} else if (0 == strcmp (argv[arg], "-q")) { } else if (0 == strcmp(argv[arg], "-q")) {
printf ("Quiet mode.\n"); printf("Quiet mode.\n");
quiet_output = true; quiet_output = true;
} else if ((arg == argc - 1) && (strlen (argv[arg]) == 8)) { // See if UID was specified as HEX string } else if ((arg == argc - 1) && (strlen(argv[arg]) == 8)) { // See if UID was specified as HEX string
uint8_t abtTmp[3] = { 0x00, 0x00, 0x00 }; uint8_t abtTmp[3] = { 0x00, 0x00, 0x00 };
printf ("[+] Using UID: %s\n", argv[arg]); printf("[+] Using UID: %s\n", argv[arg]);
abtUidBcc[4] = 0x00; abtUidBcc[4] = 0x00;
for (i = 0; i < 4; ++i) { for (i = 0; i < 4; ++i) {
memcpy (abtTmp, argv[arg] + i * 2, 2); memcpy(abtTmp, argv[arg] + i * 2, 2);
abtUidBcc[i] = (uint8_t) strtol ((char *) abtTmp, NULL, 16); abtUidBcc[i] = (uint8_t) strtol((char *) abtTmp, NULL, 16);
abtUidBcc[4] ^= abtUidBcc[i]; abtUidBcc[4] ^= abtUidBcc[i];
} }
} else { } else {
ERR ("%s is not supported option.", argv[arg]); ERR("%s is not supported option.", argv[arg]);
print_usage (argv); print_usage(argv);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
#ifdef WIN32 #ifdef WIN32
signal (SIGINT, (void (__cdecl *) (int)) intr_hdlr); signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr);
#else #else
signal (SIGINT, intr_hdlr); signal(SIGINT, intr_hdlr);
#endif #endif
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC device // Try to open the NFC device
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
printf ("Unable to open NFC device\n"); printf("Unable to open NFC device\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("\n"); printf("\n");
printf ("NFC device: %s opened\n", nfc_device_get_name (pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
printf ("[+] Try to break out the auto-emulation, this requires a second NFC device!\n"); printf("[+] Try to break out the auto-emulation, this requires a second NFC device!\n");
printf ("[+] To do this, please send any command after the anti-collision\n"); printf("[+] To do this, please send any command after the anti-collision\n");
printf ("[+] For example, send a RATS command or use the \"nfc-anticol\" or \"nfc-list\" tool.\n"); printf("[+] For example, send a RATS command or use the \"nfc-anticol\" or \"nfc-list\" tool.\n");
// Note: We have to build a "fake" nfc_target in order to do exactly the same that was done before the new nfc_target_init() was introduced. // Note: We have to build a "fake" nfc_target in order to do exactly the same that was done before the new nfc_target_init() was introduced.
nfc_target nt = { nfc_target nt = {
@ -158,24 +158,24 @@ main (int argc, char *argv[])
}, },
}, },
}; };
if ((szRecvBits = nfc_target_init (pnd, &nt, abtRecv, sizeof (abtRecv), 0)) < 0) { if ((szRecvBits = nfc_target_init(pnd, &nt, abtRecv, sizeof(abtRecv), 0)) < 0) {
nfc_perror (pnd, "nfc_target_init"); nfc_perror(pnd, "nfc_target_init");
ERR ("Could not come out of auto-emulation, no command was received"); ERR("Could not come out of auto-emulation, no command was received");
goto error; goto error;
} }
printf ("[+] Received initiator command: "); printf("[+] Received initiator command: ");
print_hex_bits (abtRecv, (size_t) szRecvBits); print_hex_bits(abtRecv, (size_t) szRecvBits);
printf ("[+] Configuring communication\n"); printf("[+] Configuring communication\n");
if ((nfc_device_set_property_bool (pnd, NP_HANDLE_CRC, false) < 0) || (nfc_device_set_property_bool (pnd, NP_HANDLE_PARITY, true) < 0)) { if ((nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) || (nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, true) < 0)) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("[+] Done, the emulated tag is initialized with UID: %02X%02X%02X%02X\n\n", abtUidBcc[0], abtUidBcc[1], printf("[+] Done, the emulated tag is initialized with UID: %02X%02X%02X%02X\n\n", abtUidBcc[0], abtUidBcc[1],
abtUidBcc[2], abtUidBcc[3]); abtUidBcc[2], abtUidBcc[3]);
while (true) { while (true) {
// Test if we received a frame // Test if we received a frame
if ((szRecvBits = nfc_target_receive_bits (pnd, abtRecv, sizeof (abtRecv), 0)) > 0) { if ((szRecvBits = nfc_target_receive_bits(pnd, abtRecv, sizeof(abtRecv), 0)) > 0) {
// Prepare the command to send back for the anti-collision request // Prepare the command to send back for the anti-collision request
switch (szRecvBits) { switch (szRecvBits) {
case 7: // Request or Wakeup case 7: // Request or Wakeup
@ -183,7 +183,7 @@ main (int argc, char *argv[])
szTxBits = 16; szTxBits = 16;
// New anti-collsion session started // New anti-collsion session started
if (!quiet_output) if (!quiet_output)
printf ("\n"); printf("\n");
break; break;
case 16: // Select All case 16: // Select All
@ -202,29 +202,29 @@ main (int argc, char *argv[])
} }
if (!quiet_output) { if (!quiet_output) {
printf ("R: "); printf("R: ");
print_hex_bits (abtRecv, (size_t) szRecvBits); print_hex_bits(abtRecv, (size_t) szRecvBits);
} }
// Test if we know how to respond // Test if we know how to respond
if (szTxBits) { if (szTxBits) {
// Send and print the command to the screen // Send and print the command to the screen
if (nfc_target_send_bits (pnd, pbtTx, szTxBits, NULL) < 0) { if (nfc_target_send_bits(pnd, pbtTx, szTxBits, NULL) < 0) {
nfc_perror (pnd, "nfc_target_send_bits"); nfc_perror(pnd, "nfc_target_send_bits");
goto error; goto error;
} }
if (!quiet_output) { if (!quiet_output) {
printf ("T: "); printf("T: ");
print_hex_bits (pbtTx, szTxBits); print_hex_bits(pbtTx, szTxBits);
} }
} }
} }
} }
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
error: error:
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }

View file

@ -87,21 +87,21 @@ uint8_t abtBlank[18] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x80, 0
static bool static bool
transmit_bits (const uint8_t *pbtTx, const size_t szTxBits) transmit_bits(const uint8_t *pbtTx, const size_t szTxBits)
{ {
// Show transmitted command // Show transmitted command
if (!quiet_output) { if (!quiet_output) {
printf ("Sent bits: "); printf("Sent bits: ");
print_hex_bits (pbtTx, szTxBits); print_hex_bits(pbtTx, szTxBits);
} }
// Transmit the bit frame command, we don't use the arbitrary parity feature // Transmit the bit frame command, we don't use the arbitrary parity feature
if ((szRxBits = nfc_initiator_transceive_bits (pnd, pbtTx, szTxBits, NULL, abtRx, NULL)) < 0) if ((szRxBits = nfc_initiator_transceive_bits(pnd, pbtTx, szTxBits, NULL, abtRx, NULL)) < 0)
return false; return false;
// Show received answer // Show received answer
if (!quiet_output) { if (!quiet_output) {
printf ("Received bits: "); printf("Received bits: ");
print_hex_bits (abtRx, szRxBits); print_hex_bits(abtRx, szRxBits);
} }
// Succesful transfer // Succesful transfer
return true; return true;
@ -109,43 +109,43 @@ transmit_bits (const uint8_t *pbtTx, const size_t szTxBits)
static bool static bool
transmit_bytes (const uint8_t *pbtTx, const size_t szTx) transmit_bytes(const uint8_t *pbtTx, const size_t szTx)
{ {
// Show transmitted command // Show transmitted command
if (!quiet_output) { if (!quiet_output) {
printf ("Sent bits: "); printf("Sent bits: ");
print_hex (pbtTx, szTx); print_hex(pbtTx, szTx);
} }
int res; int res;
// Transmit the command bytes // Transmit the command bytes
if ((res = nfc_initiator_transceive_bytes (pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0) if ((res = nfc_initiator_transceive_bytes(pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0)
return false; return false;
// Show received answer // Show received answer
if (!quiet_output) { if (!quiet_output) {
printf ("Received bits: "); printf("Received bits: ");
print_hex (abtRx, res); print_hex(abtRx, res);
} }
// Succesful transfer // Succesful transfer
return true; return true;
} }
static void static void
print_usage (char *argv[]) print_usage(char *argv[])
{ {
printf ("Usage: %s [OPTIONS] [UID]\n", argv[0]); printf("Usage: %s [OPTIONS] [UID]\n", argv[0]);
printf ("Options:\n"); printf("Options:\n");
printf ("\t-h\tHelp. Print this message.\n"); printf("\t-h\tHelp. Print this message.\n");
printf ("\t-f\tFormat. Delete all data (set to 0xFF) and reset ACLs to default.\n"); printf("\t-f\tFormat. Delete all data (set to 0xFF) and reset ACLs to default.\n");
printf ("\t-q\tQuiet mode. Suppress output of READER and CARD data (improves timing).\n"); printf("\t-q\tQuiet mode. Suppress output of READER and CARD data (improves timing).\n");
printf ("\n\tSpecify UID (4 HEX bytes) to set UID, or leave blank for default '01234567'.\n"); printf("\n\tSpecify UID (4 HEX bytes) to set UID, or leave blank for default '01234567'.\n");
printf ("\tThis utility can be used to recover cards that have been damaged by writing bad\n"); printf("\tThis utility can be used to recover cards that have been damaged by writing bad\n");
printf ("\tdata (e.g. wrong BCC), thus making them non-selectable by most tools/readers.\n"); printf("\tdata (e.g. wrong BCC), thus making them non-selectable by most tools/readers.\n");
printf ("\n\t*** Note: this utility only works with special Mifare 1K cards (Chinese clones).\n\n"); printf("\n\t*** Note: this utility only works with special Mifare 1K cards (Chinese clones).\n\n");
} }
int int
main (int argc, char *argv[]) main(int argc, char *argv[])
{ {
int arg, i; int arg, i;
bool format = false; bool format = false;
@ -155,73 +155,73 @@ main (int argc, char *argv[])
// Get commandline options // Get commandline options
for (arg = 1; arg < argc; arg++) { for (arg = 1; arg < argc; arg++) {
if (0 == strcmp (argv[arg], "-h")) { if (0 == strcmp(argv[arg], "-h")) {
print_usage (argv); print_usage(argv);
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} else if (0 == strcmp (argv[arg], "-f")) { } else if (0 == strcmp(argv[arg], "-f")) {
format = true; format = true;
} else if (0 == strcmp (argv[arg], "-q")) { } else if (0 == strcmp(argv[arg], "-q")) {
quiet_output = true; quiet_output = true;
} else if (strlen(argv[arg]) == 8) { } else if (strlen(argv[arg]) == 8) {
for(i = 0 ; i < 4 ; ++i) { for (i = 0 ; i < 4 ; ++i) {
memcpy(tmp, argv[arg] + i * 2, 2); memcpy(tmp, argv[arg] + i * 2, 2);
sscanf(tmp, "%02x", &c); sscanf(tmp, "%02x", &c);
abtData[i] = (char) c; abtData[i] = (char) c;
} }
abtData[4] = abtData[0] ^ abtData[1] ^ abtData[2] ^ abtData[3]; abtData[4] = abtData[0] ^ abtData[1] ^ abtData[2] ^ abtData[3];
iso14443a_crc_append (abtData, 16); iso14443a_crc_append(abtData, 16);
} else { } else {
ERR ("%s is not supported option.", argv[arg]); ERR("%s is not supported option.", argv[arg]);
print_usage (argv); print_usage(argv);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC reader // Try to open the NFC reader
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (!pnd) { if (!pnd) {
printf ("Error opening NFC reader\n"); printf("Error opening NFC reader\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Initialise NFC device as "initiator" // Initialise NFC device as "initiator"
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Configure the CRC // Configure the CRC
if (nfc_device_set_property_bool (pnd, NP_HANDLE_CRC, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Use raw send/receive methods // Use raw send/receive methods
if (nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Disable 14443-4 autoswitching // Disable 14443-4 autoswitching
if (nfc_device_set_property_bool (pnd, NP_AUTO_ISO14443_4, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC reader: %s opened\n", nfc_device_get_name (pnd)); printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
// Send the 7 bits request command specified in ISO 14443A (0x26) // Send the 7 bits request command specified in ISO 14443A (0x26)
if (!transmit_bits (abtReqa, 7)) { if (!transmit_bits(abtReqa, 7)) {
printf ("Error: No tag available\n"); printf("Error: No tag available\n");
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return 1; return 1;
} }
memcpy (abtAtqa, abtRx, 2); memcpy(abtAtqa, abtRx, 2);
// Anti-collision // Anti-collision
transmit_bytes (abtSelectAll, 2); transmit_bytes(abtSelectAll, 2);
// Check answer // Check answer
if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
@ -229,12 +229,12 @@ main (int argc, char *argv[])
} }
// Save the UID CL1 // Save the UID CL1
memcpy (abtRawUid, abtRx, 4); memcpy(abtRawUid, abtRx, 4);
//Prepare and send CL1 Select-Command //Prepare and send CL1 Select-Command
memcpy (abtSelectTag + 2, abtRx, 5); memcpy(abtSelectTag + 2, abtRx, 5);
iso14443a_crc_append (abtSelectTag, 7); iso14443a_crc_append(abtSelectTag, 7);
transmit_bytes (abtSelectTag, 9); transmit_bytes(abtSelectTag, 9);
abtSak = abtRx[0]; abtSak = abtRx[0];
// Test if we are dealing with a CL2 // Test if we are dealing with a CL2
@ -246,14 +246,14 @@ main (int argc, char *argv[])
} }
} }
if(szCL == 2) { if (szCL == 2) {
// We have to do the anti-collision for cascade level 2 // We have to do the anti-collision for cascade level 2
// Prepare CL2 commands // Prepare CL2 commands
abtSelectAll[0] = 0x95; abtSelectAll[0] = 0x95;
// Anti-collision // Anti-collision
transmit_bytes (abtSelectAll, 2); transmit_bytes(abtSelectAll, 2);
// Check answer // Check answer
if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
@ -261,13 +261,13 @@ main (int argc, char *argv[])
} }
// Save UID CL2 // Save UID CL2
memcpy (abtRawUid + 4, abtRx, 4); memcpy(abtRawUid + 4, abtRx, 4);
// Selection // Selection
abtSelectTag[0] = 0x95; abtSelectTag[0] = 0x95;
memcpy (abtSelectTag + 2, abtRx, 5); memcpy(abtSelectTag + 2, abtRx, 5);
iso14443a_crc_append (abtSelectTag, 7); iso14443a_crc_append(abtSelectTag, 7);
transmit_bytes (abtSelectTag, 9); transmit_bytes(abtSelectTag, 9);
abtSak = abtRx[0]; abtSak = abtRx[0];
// Test if we are dealing with a CL3 // Test if we are dealing with a CL3
@ -279,12 +279,12 @@ main (int argc, char *argv[])
} }
} }
if ( szCL == 3) { if (szCL == 3) {
// We have to do the anti-collision for cascade level 3 // We have to do the anti-collision for cascade level 3
// Prepare and send CL3 AC-Command // Prepare and send CL3 AC-Command
abtSelectAll[0] = 0x97; abtSelectAll[0] = 0x97;
transmit_bytes (abtSelectAll, 2); transmit_bytes(abtSelectAll, 2);
// Check answer // Check answer
if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
@ -292,13 +292,13 @@ main (int argc, char *argv[])
} }
// Save UID CL3 // Save UID CL3
memcpy (abtRawUid + 8, abtRx, 4); memcpy(abtRawUid + 8, abtRx, 4);
// Prepare and send final Select-Command // Prepare and send final Select-Command
abtSelectTag[0] = 0x97; abtSelectTag[0] = 0x97;
memcpy (abtSelectTag + 2, abtRx, 5); memcpy(abtSelectTag + 2, abtRx, 5);
iso14443a_crc_append (abtSelectTag, 7); iso14443a_crc_append(abtSelectTag, 7);
transmit_bytes (abtSelectTag, 9); transmit_bytes(abtSelectTag, 9);
abtSak = abtRx[0]; abtSak = abtRx[0];
} }
} }
@ -308,52 +308,52 @@ main (int argc, char *argv[])
iso_ats_supported = true; iso_ats_supported = true;
} }
printf ("\nFound tag with\n UID: "); printf("\nFound tag with\n UID: ");
switch (szCL) { switch (szCL) {
case 1: case 1:
printf ("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]);
break; break;
case 2: case 2:
printf ("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
printf ("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]); printf("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]);
break; break;
case 3: case 3:
printf ("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
printf ("%02x%02x%02x", abtRawUid[5], abtRawUid[6], abtRawUid[7]); printf("%02x%02x%02x", abtRawUid[5], abtRawUid[6], abtRawUid[7]);
printf ("%02x%02x%02x%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]); printf("%02x%02x%02x%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]);
break; break;
} }
printf("\n"); printf("\n");
printf("ATQA: %02x%02x\n SAK: %02x\n", abtAtqa[1], abtAtqa[0], abtSak); printf("ATQA: %02x%02x\n SAK: %02x\n", abtAtqa[1], abtAtqa[0], abtSak);
if (szAts > 1) { // if = 1, it's not actual ATS but error code if (szAts > 1) { // if = 1, it's not actual ATS but error code
printf(" ATS: "); printf(" ATS: ");
print_hex (abtAts, szAts); print_hex(abtAts, szAts);
} }
printf("\n"); printf("\n");
// now reset UID // now reset UID
iso14443a_crc_append(abtHalt, 2); iso14443a_crc_append(abtHalt, 2);
transmit_bytes (abtHalt, 4); transmit_bytes(abtHalt, 4);
transmit_bits (abtUnlock1, 7); transmit_bits(abtUnlock1, 7);
if(format) { if (format) {
transmit_bytes (abtWipe, 1); transmit_bytes(abtWipe, 1);
transmit_bytes (abtHalt, 4); transmit_bytes(abtHalt, 4);
transmit_bits (abtUnlock1, 7); transmit_bits(abtUnlock1, 7);
} }
transmit_bytes (abtUnlock2, 1); transmit_bytes(abtUnlock2, 1);
transmit_bytes (abtWrite, 4); transmit_bytes(abtWrite, 4);
transmit_bytes (abtData, 18); transmit_bytes(abtData, 18);
if(format) { if (format) {
for(i = 3 ; i < 64 ; i += 4) { for (i = 3 ; i < 64 ; i += 4) {
abtWrite[1] = (char) i; abtWrite[1] = (char) i;
iso14443a_crc_append (abtWrite, 2); iso14443a_crc_append(abtWrite, 2);
transmit_bytes (abtWrite, 4); transmit_bytes(abtWrite, 4);
transmit_bytes (abtBlank, 18); transmit_bytes(abtBlank, 18);
} }
} }
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return 0; return 0;
} }

View file

@ -53,39 +53,39 @@
static nfc_device *pnd = NULL; static nfc_device *pnd = NULL;
static void stop_polling (int sig) static void stop_polling(int sig)
{ {
(void) sig; (void) sig;
if (pnd) if (pnd)
nfc_abort_command (pnd); nfc_abort_command(pnd);
else else
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
static void static void
print_usage (const char* progname) print_usage(const char* progname)
{ {
printf ("usage: %s [-v]\n", progname); printf("usage: %s [-v]\n", progname);
printf (" -v\t verbose display\n"); printf(" -v\t verbose display\n");
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
bool verbose = false; bool verbose = false;
signal (SIGINT, stop_polling); signal(SIGINT, stop_polling);
// Display libnfc version // Display libnfc version
const char *acLibnfcVersion = nfc_version (); const char *acLibnfcVersion = nfc_version();
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
if (argc != 1) { if (argc != 1) {
if ((argc == 2) && (0 == strcmp ("-v", argv[1]))) { if ((argc == 2) && (0 == strcmp("-v", argv[1]))) {
verbose = true; verbose = true;
} else { } else {
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
@ -103,35 +103,35 @@ main (int argc, const char *argv[])
nfc_target nt; nfc_target nt;
int res = 0; int res = 0;
nfc_init (NULL); nfc_init(NULL);
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR ("%s", "Unable to open NFC device."); ERR("%s", "Unable to open NFC device.");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC reader: %s opened\n", nfc_device_get_name (pnd)); printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
printf ("NFC device will poll during %ld ms (%u pollings of %lu ms for %zd modulations)\n", (unsigned long) uiPollNr * szModulations * uiPeriod * 150, uiPollNr, (unsigned long) uiPeriod * 150, szModulations); printf("NFC device will poll during %ld ms (%u pollings of %lu ms for %zd modulations)\n", (unsigned long) uiPollNr * szModulations * uiPeriod * 150, uiPollNr, (unsigned long) uiPeriod * 150, szModulations);
if ((res = nfc_initiator_poll_target (pnd, nmModulations, szModulations, uiPollNr, uiPeriod, &nt)) < 0) { if ((res = nfc_initiator_poll_target(pnd, nmModulations, szModulations, uiPollNr, uiPeriod, &nt)) < 0) {
nfc_perror (pnd, "nfc_initiator_poll_target"); nfc_perror(pnd, "nfc_initiator_poll_target");
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (res > 0) { if (res > 0) {
print_nfc_target ( nt, verbose ); print_nfc_target(nt, verbose);
} else { } else {
printf ("No target found.\n"); printf("No target found.\n");
} }
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }

View file

@ -61,77 +61,77 @@ static nfc_device *pndTag;
static bool quitting = false; static bool quitting = false;
static void static void
intr_hdlr (int sig) intr_hdlr(int sig)
{ {
(void) sig; (void) sig;
printf ("\nQuitting...\n"); printf("\nQuitting...\n");
quitting = true; quitting = true;
return; return;
} }
static void static void
print_usage (char *argv[]) print_usage(char *argv[])
{ {
printf ("Usage: %s [OPTIONS]\n", argv[0]); printf("Usage: %s [OPTIONS]\n", argv[0]);
printf ("Options:\n"); printf("Options:\n");
printf ("\t-h\tHelp. Print this message.\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("\t-q\tQuiet mode. Suppress output of READER and EMULATOR data (improves timing).\n");
} }
int int
main (int argc, char *argv[]) main(int argc, char *argv[])
{ {
int arg; int arg;
bool quiet_output = false; bool quiet_output = false;
const char *acLibnfcVersion = nfc_version (); const char *acLibnfcVersion = nfc_version();
// Get commandline options // Get commandline options
for (arg = 1; arg < argc; arg++) { for (arg = 1; arg < argc; arg++) {
if (0 == strcmp (argv[arg], "-h")) { if (0 == strcmp(argv[arg], "-h")) {
print_usage (argv); print_usage(argv);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} else if (0 == strcmp (argv[arg], "-q")) { } else if (0 == strcmp(argv[arg], "-q")) {
quiet_output = true; quiet_output = true;
} else { } else {
ERR ("%s is not supported option.", argv[arg]); ERR("%s is not supported option.", argv[arg]);
print_usage (argv); print_usage(argv);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
// Display libnfc version // Display libnfc version
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
#ifdef WIN32 #ifdef WIN32
signal (SIGINT, (void (__cdecl *) (int)) intr_hdlr); signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr);
#else #else
signal (SIGINT, intr_hdlr); signal(SIGINT, intr_hdlr);
#endif #endif
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
// List available devices // List available devices
size_t szFound = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t szFound = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
if (szFound < 2) { if (szFound < 2) {
ERR ("%zd device found but two opened devices are needed to relay NFC.", szFound); ERR("%zd device found but two opened devices are needed to relay NFC.", szFound);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC emulator device // Try to open the NFC emulator device
pndTag = nfc_open (NULL, connstrings[0]); pndTag = nfc_open(NULL, connstrings[0]);
if (pndTag == NULL) { if (pndTag == NULL) {
printf ("Error opening NFC emulator device\n"); printf("Error opening NFC emulator device\n");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n"); printf("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n");
printf ("NFC emulator device: %s opened\n", nfc_device_get_name (pndTag)); printf("NFC emulator device: %s opened\n", nfc_device_get_name(pndTag));
printf ("[+] Try to break out the auto-emulation, this requires a second reader!\n"); printf("[+] Try to break out the auto-emulation, this requires a second reader!\n");
printf ("[+] To do this, please send any command after the anti-collision\n"); printf("[+] To do this, please send any command after the anti-collision\n");
printf ("[+] For example, send a RATS command or use the \"nfc-anticol\" tool\n"); printf("[+] For example, send a RATS command or use the \"nfc-anticol\" tool\n");
nfc_target nt = { nfc_target nt = {
.nm = { .nm = {
@ -149,79 +149,79 @@ main (int argc, char *argv[])
}, },
}; };
if ((szReaderRxBits = nfc_target_init (pndTag, &nt, abtReaderRx, sizeof (abtReaderRx), 0)) < 0) { if ((szReaderRxBits = nfc_target_init(pndTag, &nt, abtReaderRx, sizeof(abtReaderRx), 0)) < 0) {
ERR ("%s", "Initialization of NFC emulator failed"); ERR("%s", "Initialization of NFC emulator failed");
nfc_close (pndTag); nfc_close(pndTag);
nfc_exit (NULL); nfc_exit(NULL);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("%s", "Configuring emulator settings..."); printf("%s", "Configuring emulator settings...");
if ((nfc_device_set_property_bool (pndTag, NP_HANDLE_CRC, false) < 0) || if ((nfc_device_set_property_bool(pndTag, NP_HANDLE_CRC, false) < 0) ||
(nfc_device_set_property_bool (pndTag, NP_HANDLE_PARITY, false) < 0) || (nfc_device_set_property_bool (pndTag, NP_ACCEPT_INVALID_FRAMES, true)) < 0) { (nfc_device_set_property_bool(pndTag, NP_HANDLE_PARITY, false) < 0) || (nfc_device_set_property_bool(pndTag, NP_ACCEPT_INVALID_FRAMES, true)) < 0) {
nfc_perror (pndTag, "nfc_device_set_property_bool"); nfc_perror(pndTag, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("%s", "Done, emulated tag is initialized"); printf("%s", "Done, emulated tag is initialized");
// Try to open the NFC reader // Try to open the NFC reader
pndReader = nfc_open (NULL, connstrings[1]); pndReader = nfc_open(NULL, connstrings[1]);
printf ("NFC reader device: %s opened", nfc_device_get_name (pndReader)); printf("NFC reader device: %s opened", nfc_device_get_name(pndReader));
printf ("%s", "Configuring NFC reader settings..."); printf("%s", "Configuring NFC reader settings...");
if (nfc_initiator_init (pndReader) < 0) { if (nfc_initiator_init(pndReader) < 0) {
nfc_perror (pndReader, "nfc_initiator_init"); nfc_perror(pndReader, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if ((nfc_device_set_property_bool (pndReader, NP_HANDLE_CRC, false) < 0) || if ((nfc_device_set_property_bool(pndReader, NP_HANDLE_CRC, false) < 0) ||
(nfc_device_set_property_bool (pndReader, NP_HANDLE_PARITY, false) < 0) || (nfc_device_set_property_bool(pndReader, NP_HANDLE_PARITY, false) < 0) ||
(nfc_device_set_property_bool (pndReader, NP_ACCEPT_INVALID_FRAMES, true)) < 0) { (nfc_device_set_property_bool(pndReader, NP_ACCEPT_INVALID_FRAMES, true)) < 0) {
nfc_perror (pndReader, "nfc_device_set_property_bool"); nfc_perror(pndReader, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("%s", "Done, relaying frames now!"); printf("%s", "Done, relaying frames now!");
while (!quitting) { while (!quitting) {
// Test if we received a frame from the reader // Test if we received a frame from the reader
if ((szReaderRxBits = nfc_target_receive_bits (pndTag, abtReaderRx, sizeof (abtReaderRx), abtReaderRxPar)) > 0) { if ((szReaderRxBits = nfc_target_receive_bits(pndTag, abtReaderRx, sizeof(abtReaderRx), abtReaderRxPar)) > 0) {
// Drop down the field before sending a REQA command and start a new session // Drop down the field before sending a REQA command and start a new session
if (szReaderRxBits == 7 && abtReaderRx[0] == 0x26) { if (szReaderRxBits == 7 && abtReaderRx[0] == 0x26) {
// Drop down field for a very short time (original tag will reboot) // Drop down field for a very short time (original tag will reboot)
if (nfc_device_set_property_bool (pndReader, NP_ACTIVATE_FIELD, false) < 0) { if (nfc_device_set_property_bool(pndReader, NP_ACTIVATE_FIELD, false) < 0) {
nfc_perror (pndReader, "nfc_device_set_property_bool"); nfc_perror(pndReader, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (!quiet_output) if (!quiet_output)
printf ("\n"); printf("\n");
if (nfc_device_set_property_bool (pndReader, NP_ACTIVATE_FIELD, true) < 0) { if (nfc_device_set_property_bool(pndReader, NP_ACTIVATE_FIELD, true) < 0) {
nfc_perror (pndReader, "nfc_device_set_property_bool"); nfc_perror(pndReader, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
// Print the reader frame to the screen // Print the reader frame to the screen
if (!quiet_output) { if (!quiet_output) {
printf ("R: "); printf("R: ");
print_hex_par (abtReaderRx, (size_t) szReaderRxBits, abtReaderRxPar); print_hex_par(abtReaderRx, (size_t) szReaderRxBits, abtReaderRxPar);
} }
// Forward the frame to the original tag // Forward the frame to the original tag
if ((szTagRxBits = nfc_initiator_transceive_bits if ((szTagRxBits = nfc_initiator_transceive_bits
(pndReader, abtReaderRx, (size_t) szReaderRxBits, abtReaderRxPar, abtTagRx, abtTagRxPar)) > 0) { (pndReader, abtReaderRx, (size_t) szReaderRxBits, abtReaderRxPar, abtTagRx, abtTagRxPar)) > 0) {
// Redirect the answer back to the reader // Redirect the answer back to the reader
if (nfc_target_send_bits (pndTag, abtTagRx, szTagRxBits, abtTagRxPar) < 0) { if (nfc_target_send_bits(pndTag, abtTagRx, szTagRxBits, abtTagRxPar) < 0) {
nfc_perror (pndTag, "nfc_target_send_bits"); nfc_perror(pndTag, "nfc_target_send_bits");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Print the tag frame to the screen // Print the tag frame to the screen
if (!quiet_output) { if (!quiet_output) {
printf ("T: "); printf("T: ");
print_hex_par (abtTagRx, szTagRxBits, abtTagRxPar); print_hex_par(abtTagRx, szTagRxBits, abtTagRxPar);
} }
} }
} }
} }
nfc_close (pndTag); nfc_close(pndTag);
nfc_close (pndReader); nfc_close(pndReader);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }

View file

@ -50,7 +50,7 @@
#define MAX_DEVICE_COUNT 16 #define MAX_DEVICE_COUNT 16
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
size_t i; size_t i;
nfc_device *pnd; nfc_device *pnd;
@ -65,59 +65,59 @@ main (int argc, const char *argv[])
const uint8_t pncmd_diagnose_ram_test[] = { Diagnose, 0x02 }; const uint8_t pncmd_diagnose_ram_test[] = { Diagnose, 0x02 };
if (argc > 1) { if (argc > 1) {
errx (1, "usage: %s", argv[0]); errx(1, "usage: %s", argv[0]);
} }
nfc_init (NULL); nfc_init(NULL);
// Display libnfc version // Display libnfc version
acLibnfcVersion = nfc_version (); acLibnfcVersion = nfc_version();
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
size_t szFound = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t szFound = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
if (szFound == 0) { if (szFound == 0) {
printf ("No NFC device found.\n"); printf("No NFC device found.\n");
} }
for (i = 0; i < szFound; i++) { for (i = 0; i < szFound; i++) {
pnd = nfc_open (NULL, connstrings[i]); pnd = nfc_open(NULL, connstrings[i]);
if (pnd == NULL) { if (pnd == NULL) {
ERR ("%s", "Unable to open NFC device."); ERR("%s", "Unable to open NFC device.");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("NFC device [%s] opened.\n", nfc_device_get_name (pnd)); printf("NFC device [%s] opened.\n", nfc_device_get_name(pnd));
res = pn53x_transceive (pnd, pncmd_diagnose_communication_line_test, sizeof (pncmd_diagnose_communication_line_test), abtRx, szRx, 0); res = pn53x_transceive(pnd, pncmd_diagnose_communication_line_test, sizeof(pncmd_diagnose_communication_line_test), abtRx, szRx, 0);
if (res > 0) { if (res > 0) {
szRx = (size_t) res; szRx = (size_t) res;
// Result of Diagnose ping for RC-S360 doesn't contain status byte so we've to handle both cases // Result of Diagnose ping for RC-S360 doesn't contain status byte so we've to handle both cases
result = (memcmp (pncmd_diagnose_communication_line_test + 1, abtRx, sizeof (pncmd_diagnose_communication_line_test) - 1) == 0) || result = (memcmp(pncmd_diagnose_communication_line_test + 1, abtRx, sizeof(pncmd_diagnose_communication_line_test) - 1) == 0) ||
(memcmp (pncmd_diagnose_communication_line_test + 2, abtRx, sizeof (pncmd_diagnose_communication_line_test) - 2) == 0); (memcmp(pncmd_diagnose_communication_line_test + 2, abtRx, sizeof(pncmd_diagnose_communication_line_test) - 2) == 0);
printf (" Communication line test: %s\n", result ? "OK" : "Failed"); printf(" Communication line test: %s\n", result ? "OK" : "Failed");
} else { } else {
nfc_perror (pnd, "pn53x_transceive: cannot diagnose communication line"); nfc_perror(pnd, "pn53x_transceive: cannot diagnose communication line");
} }
res = pn53x_transceive (pnd, pncmd_diagnose_rom_test, sizeof (pncmd_diagnose_rom_test), abtRx, szRx, 0); res = pn53x_transceive(pnd, pncmd_diagnose_rom_test, sizeof(pncmd_diagnose_rom_test), abtRx, szRx, 0);
if (res > 0) { if (res > 0) {
szRx = (size_t) res; szRx = (size_t) res;
result = ((szRx == 1) && (abtRx[0] == 0x00)); result = ((szRx == 1) && (abtRx[0] == 0x00));
printf (" ROM test: %s\n", result ? "OK" : "Failed"); printf(" ROM test: %s\n", result ? "OK" : "Failed");
} else { } else {
nfc_perror (pnd, "pn53x_transceive: cannot diagnose ROM"); nfc_perror(pnd, "pn53x_transceive: cannot diagnose ROM");
} }
res = pn53x_transceive (pnd, pncmd_diagnose_ram_test, sizeof (pncmd_diagnose_ram_test), abtRx, szRx, 0); res = pn53x_transceive(pnd, pncmd_diagnose_ram_test, sizeof(pncmd_diagnose_ram_test), abtRx, szRx, 0);
if (res > 0) { if (res > 0) {
szRx = (size_t) res; szRx = (size_t) res;
result = ((szRx == 1) && (abtRx[0] == 0x00)); result = ((szRx == 1) && (abtRx[0] == 0x00));
printf (" RAM test: %s\n", result ? "OK" : "Failed"); printf(" RAM test: %s\n", result ? "OK" : "Failed");
} else { } else {
nfc_perror (pnd, "pn53x_transceive: cannot diagnose RAM"); nfc_perror(pnd, "pn53x_transceive: cannot diagnose RAM");
} }
} }
} }

View file

@ -52,60 +52,60 @@
#define TIMEOUT 60 // secs. #define TIMEOUT 60 // secs.
static void static void
wait_one_minute (void) wait_one_minute(void)
{ {
int secs = 0; int secs = 0;
printf ("|"); printf("|");
fflush (stdout); fflush(stdout);
while (secs < TIMEOUT) { while (secs < TIMEOUT) {
sleep (1); sleep(1);
secs++; secs++;
printf ("."); printf(".");
fflush (stdout); fflush(stdout);
} }
printf ("|\n"); printf("|\n");
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
(void) argc; (void) argc;
(void) argv; (void) argv;
int ret = EXIT_FAILURE; int ret = EXIT_FAILURE;
nfc_init (NULL); nfc_init(NULL);
// Display libnfc version // Display libnfc version
const char *acLibnfcVersion = nfc_version (); const char *acLibnfcVersion = nfc_version();
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
// Open using the first available NFC device // Open using the first available NFC device
nfc_device *pnd; nfc_device *pnd;
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR ("%s", "Unable to open NFC device."); ERR("%s", "Unable to open NFC device.");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("NFC device: %s opened\n", nfc_device_get_name (pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
// Print the example's menu // Print the example's menu
printf ("\nSelect the communication mode:\n"); printf("\nSelect the communication mode:\n");
printf ("[1] Virtual card mode.\n"); printf("[1] Virtual card mode.\n");
printf ("[2] Wired card mode.\n"); printf("[2] Wired card mode.\n");
printf ("[3] Dual card mode.\n"); printf("[3] Dual card mode.\n");
printf (">> "); printf(">> ");
// Take user's choice // Take user's choice
char input = getchar (); char input = getchar();
printf ("\n"); printf("\n");
if ((input < '1') || (input > '3')) { if ((input < '1') || (input > '3')) {
ERR ("%s", "Invalid selection."); ERR("%s", "Invalid selection.");
goto error; goto error;
} }
@ -119,15 +119,15 @@ main (int argc, const char *argv[])
// Connect with the SAM // Connect with the SAM
// FIXME: Its a private pn53x function // FIXME: Its a private pn53x function
if (pn53x_SAMConfiguration (pnd, mode, 0) < 0) { if (pn53x_SAMConfiguration(pnd, mode, 0) < 0) {
nfc_perror (pnd, "pn53x_SAMConfiguration"); nfc_perror(pnd, "pn53x_SAMConfiguration");
goto error; goto error;
} }
switch (mode) { switch (mode) {
case PSM_VIRTUAL_CARD: { case PSM_VIRTUAL_CARD: {
printf ("Now the SAM is readable for 1 minute from an external reader.\n"); printf("Now the SAM is readable for 1 minute from an external reader.\n");
wait_one_minute (); wait_one_minute();
} }
break; break;
@ -135,14 +135,14 @@ main (int argc, const char *argv[])
nfc_target nt; nfc_target nt;
// Set opened NFC device to initiator mode // Set opened NFC device to initiator mode
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
goto error; goto error;
} }
// Let the reader only try once to find a tag // Let the reader only try once to find a tag
if (nfc_device_set_property_bool (pnd, NP_INFINITE_SELECT, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
goto error; goto error;
} }
// Read the SAM's info // Read the SAM's info
@ -151,17 +151,17 @@ main (int argc, const char *argv[])
.nbr = NBR_106, .nbr = NBR_106,
}; };
int res; int res;
if ((res = nfc_initiator_select_passive_target (pnd, nmSAM, NULL, 0, &nt)) < 0) { if ((res = nfc_initiator_select_passive_target(pnd, nmSAM, NULL, 0, &nt)) < 0) {
nfc_perror (pnd, "nfc_initiator_select_passive_target"); nfc_perror(pnd, "nfc_initiator_select_passive_target");
goto error; goto error;
} else if (res == 0) { } else if (res == 0) {
ERR ("No SAM found."); ERR("No SAM found.");
goto error; goto error;
} else if (res == 1) { } else if (res == 1) {
printf ("The following ISO14443A tag (SAM) was found:\n"); printf("The following ISO14443A tag (SAM) was found:\n");
print_nfc_iso14443a_info (nt.nti.nai, true); print_nfc_iso14443a_info(nt.nti.nai, true);
} else { } else {
ERR ("%s", "More than one ISO14442 tag found as SAM."); ERR("%s", "More than one ISO14442 tag found as SAM.");
goto error; goto error;
} }
} }
@ -185,9 +185,9 @@ main (int argc, const char *argv[])
}, },
}, },
}; };
printf ("Now both, NFC device (configured as target) and SAM are readables from an external NFC initiator.\n"); printf("Now both, NFC device (configured as target) and SAM are readables from an external NFC initiator.\n");
printf ("Please note that NFC device (configured as target) stay in target mode until it receive RATS, ATR_REQ or proprietary command.\n"); printf("Please note that NFC device (configured as target) stay in target mode until it receive RATS, ATR_REQ or proprietary command.\n");
if (nfc_target_init (pnd, &nt, abtRx, sizeof(abtRx), 0) < 0) { if (nfc_target_init(pnd, &nt, abtRx, sizeof(abtRx), 0) < 0) {
nfc_perror(pnd, "nfc_target_init"); nfc_perror(pnd, "nfc_target_init");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -201,11 +201,11 @@ main (int argc, const char *argv[])
error: error:
// Disconnect from the SAM // Disconnect from the SAM
pn53x_SAMConfiguration (pnd, PSM_NORMAL, 0); pn53x_SAMConfiguration(pnd, PSM_NORMAL, 0);
// Close NFC device // Close NFC device
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (ret); exit(ret);
} }

View file

@ -77,31 +77,31 @@ int main(int argc, const char* argv[])
FILE* input = NULL; FILE* input = NULL;
if (argc >= 2) { if (argc >= 2) {
if((input = fopen(argv[1], "r")) == NULL) { if ((input = fopen(argv[1], "r")) == NULL) {
ERR ("%s", "Cannot open file."); ERR("%s", "Cannot open file.");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC reader // Try to open the NFC reader
pnd = nfc_open(NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR ("%s", "Unable to open NFC device."); ERR("%s", "Unable to open NFC device.");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("NFC reader: %s opened\n", nfc_device_get_name (pnd)); printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
char *cmd; char *cmd;
const char *prompt = "> "; const char *prompt = "> ";
while(1) { while (1) {
int offset = 0; int offset = 0;
#if defined(HAVE_READLINE) #if defined(HAVE_READLINE)
if (input == NULL) { // means we use stdin if (input == NULL) { // means we use stdin
@ -154,14 +154,14 @@ int main(int argc, const char* argv[])
continue; continue;
} }
szTx = 0; szTx = 0;
for(int i = 0; i < MAX_FRAME_LEN - 10; i++) { for (int i = 0; i < MAX_FRAME_LEN - 10; i++) {
int size; int size;
unsigned int byte; unsigned int byte;
while (isspace(cmd[offset])) { while (isspace(cmd[offset])) {
offset++; offset++;
} }
size = sscanf(cmd + offset, "%2x", &byte); size = sscanf(cmd + offset, "%2x", &byte);
if (size < 1 ) { if (size < 1) {
break; break;
} }
abtTx[i] = byte; abtTx[i] = byte;
@ -181,9 +181,9 @@ int main(int argc, const char* argv[])
szRx = sizeof(abtRx); szRx = sizeof(abtRx);
int res = 0; int res = 0;
if ((res = pn53x_transceive (pnd, abtTx, szTx, abtRx, szRx, 0)) < 0) { if ((res = pn53x_transceive(pnd, abtTx, szTx, abtRx, szRx, 0)) < 0) {
free(cmd); free(cmd);
nfc_perror (pnd, "Rx"); nfc_perror(pnd, "Rx");
continue; continue;
} }
szRx = (size_t) res; szRx = (size_t) res;
@ -197,6 +197,6 @@ int main(int argc, const char* argv[])
fclose(input); fclose(input);
} }
nfc_close(pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return 1; return 1;
} }

View file

@ -54,7 +54,7 @@ extern "C" {
void *data; void *data;
}; };
NFC_EXPORT int nfc_emulate_target (nfc_device* pnd, struct nfc_emulator *emulator); NFC_EXPORT int nfc_emulate_target(nfc_device* pnd, struct nfc_emulator *emulator);
#ifdef __cplusplus #ifdef __cplusplus
} }

View file

@ -67,61 +67,61 @@ extern "C" {
NFC_EXPORT void nfc_exit(nfc_context *context); NFC_EXPORT void nfc_exit(nfc_context *context);
/* NFC Device/Hardware manipulation */ /* NFC Device/Hardware manipulation */
NFC_EXPORT bool nfc_get_default_device (nfc_connstring *connstring); NFC_EXPORT bool nfc_get_default_device(nfc_connstring *connstring);
NFC_EXPORT nfc_device *nfc_open (nfc_context *context, const nfc_connstring connstring); NFC_EXPORT nfc_device *nfc_open(nfc_context *context, const nfc_connstring connstring);
NFC_EXPORT void nfc_close (nfc_device *pnd); NFC_EXPORT void nfc_close(nfc_device *pnd);
NFC_EXPORT int nfc_abort_command (nfc_device *pnd); NFC_EXPORT int nfc_abort_command(nfc_device *pnd);
NFC_EXPORT size_t nfc_list_devices (nfc_context *context, nfc_connstring connstrings[], size_t connstrings_len); NFC_EXPORT size_t nfc_list_devices(nfc_context *context, nfc_connstring connstrings[], size_t connstrings_len);
NFC_EXPORT int nfc_idle (nfc_device *pnd); NFC_EXPORT int nfc_idle(nfc_device *pnd);
/* NFC initiator: act as "reader" */ /* NFC initiator: act as "reader" */
NFC_EXPORT int nfc_initiator_init (nfc_device *pnd); NFC_EXPORT int nfc_initiator_init(nfc_device *pnd);
NFC_EXPORT int nfc_initiator_select_passive_target (nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt); NFC_EXPORT int nfc_initiator_select_passive_target(nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt);
NFC_EXPORT int nfc_initiator_list_passive_targets (nfc_device *pnd, const nfc_modulation nm, nfc_target ant[], const size_t szTargets); NFC_EXPORT int nfc_initiator_list_passive_targets(nfc_device *pnd, const nfc_modulation nm, nfc_target ant[], const size_t szTargets);
NFC_EXPORT int nfc_initiator_poll_target (nfc_device *pnd, const nfc_modulation *pnmTargetTypes, const size_t szTargetTypes, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt); NFC_EXPORT int nfc_initiator_poll_target(nfc_device *pnd, const nfc_modulation *pnmTargetTypes, const size_t szTargetTypes, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt);
NFC_EXPORT int nfc_initiator_select_dep_target (nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout); NFC_EXPORT int nfc_initiator_select_dep_target(nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout);
NFC_EXPORT int nfc_initiator_poll_dep_target (nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout); NFC_EXPORT int nfc_initiator_poll_dep_target(nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout);
NFC_EXPORT int nfc_initiator_deselect_target (nfc_device *pnd); NFC_EXPORT int nfc_initiator_deselect_target(nfc_device *pnd);
NFC_EXPORT int nfc_initiator_transceive_bytes (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout); NFC_EXPORT int nfc_initiator_transceive_bytes(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout);
NFC_EXPORT int nfc_initiator_transceive_bits (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar); NFC_EXPORT int nfc_initiator_transceive_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar);
NFC_EXPORT int nfc_initiator_transceive_bytes_timed (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, uint32_t *cycles); NFC_EXPORT int nfc_initiator_transceive_bytes_timed(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, uint32_t *cycles);
NFC_EXPORT int nfc_initiator_transceive_bits_timed (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles); NFC_EXPORT int nfc_initiator_transceive_bits_timed(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles);
NFC_EXPORT int nfc_initiator_target_is_present (nfc_device *pnd, const nfc_target nt); NFC_EXPORT int nfc_initiator_target_is_present(nfc_device *pnd, const nfc_target nt);
/* NFC target: act as tag (i.e. MIFARE Classic) or NFC target device. */ /* NFC target: act as tag (i.e. MIFARE Classic) or NFC target device. */
NFC_EXPORT int nfc_target_init (nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout); NFC_EXPORT int nfc_target_init(nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout);
NFC_EXPORT int nfc_target_send_bytes (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout); NFC_EXPORT int nfc_target_send_bytes(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout);
NFC_EXPORT int nfc_target_receive_bytes (nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, int timeout); NFC_EXPORT int nfc_target_receive_bytes(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, int timeout);
NFC_EXPORT int nfc_target_send_bits (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar); NFC_EXPORT int nfc_target_send_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar);
NFC_EXPORT int nfc_target_receive_bits (nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar); NFC_EXPORT int nfc_target_receive_bits(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar);
/* Error reporting */ /* Error reporting */
NFC_EXPORT const char *nfc_strerror (const nfc_device *pnd); NFC_EXPORT const char *nfc_strerror(const nfc_device *pnd);
NFC_EXPORT int nfc_strerror_r (const nfc_device *pnd, char *buf, size_t buflen); NFC_EXPORT int nfc_strerror_r(const nfc_device *pnd, char *buf, size_t buflen);
NFC_EXPORT void nfc_perror (const nfc_device *pnd, const char *s); NFC_EXPORT void nfc_perror(const nfc_device *pnd, const char *s);
NFC_EXPORT int nfc_device_get_last_error (const nfc_device *pnd); NFC_EXPORT int nfc_device_get_last_error(const nfc_device *pnd);
/* Special data accessors */ /* Special data accessors */
NFC_EXPORT const char *nfc_device_get_name (nfc_device *pnd); NFC_EXPORT const char *nfc_device_get_name(nfc_device *pnd);
NFC_EXPORT const char *nfc_device_get_connstring (nfc_device *pnd); NFC_EXPORT const char *nfc_device_get_connstring(nfc_device *pnd);
NFC_EXPORT int nfc_device_get_supported_modulation (nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt); NFC_EXPORT int nfc_device_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt);
NFC_EXPORT int nfc_device_get_supported_baud_rate (nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); NFC_EXPORT int nfc_device_get_supported_baud_rate(nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br);
/* Properties accessors */ /* Properties accessors */
NFC_EXPORT int nfc_device_set_property_int (nfc_device *pnd, const nfc_property property, const int value); NFC_EXPORT int nfc_device_set_property_int(nfc_device *pnd, const nfc_property property, const int value);
NFC_EXPORT int nfc_device_set_property_bool (nfc_device *pnd, const nfc_property property, const bool bEnable); NFC_EXPORT int nfc_device_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable);
/* Misc. functions */ /* Misc. functions */
NFC_EXPORT void iso14443a_crc (uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc); NFC_EXPORT void iso14443a_crc(uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc);
NFC_EXPORT void iso14443a_crc_append (uint8_t *pbtData, size_t szLen); NFC_EXPORT void iso14443a_crc_append(uint8_t *pbtData, size_t szLen);
NFC_EXPORT uint8_t *iso14443a_locate_historical_bytes (uint8_t *pbtAts, size_t szAts, size_t *pszTk); NFC_EXPORT uint8_t *iso14443a_locate_historical_bytes(uint8_t *pbtAts, size_t szAts, size_t *pszTk);
NFC_EXPORT const char *nfc_version (void); NFC_EXPORT const char *nfc_version(void);
NFC_EXPORT int nfc_device_get_information_about (nfc_device *pnd, char *buf, size_t buflen); NFC_EXPORT int nfc_device_get_information_about(nfc_device *pnd, char *buf, size_t buflen);
/* String converter functions */ /* String converter functions */
NFC_EXPORT const char * str_nfc_modulation_type (const nfc_modulation_type nmt); NFC_EXPORT const char * str_nfc_modulation_type(const nfc_modulation_type nmt);
NFC_EXPORT const char * str_nfc_baud_rate (const nfc_baud_rate nbr); NFC_EXPORT const char * str_nfc_baud_rate(const nfc_baud_rate nbr);
/* Error codes */ /* Error codes */

View file

@ -42,16 +42,16 @@ typedef void *serial_port;
# define INVALID_SERIAL_PORT (void*)(~1) # define INVALID_SERIAL_PORT (void*)(~1)
# define CLAIMED_SERIAL_PORT (void*)(~2) # define CLAIMED_SERIAL_PORT (void*)(~2)
serial_port uart_open (const char *pcPortName); serial_port uart_open(const char *pcPortName);
void uart_close (const serial_port sp); void uart_close(const serial_port sp);
void uart_flush_input (const serial_port sp); void uart_flush_input(const serial_port sp);
void uart_set_speed (serial_port sp, const uint32_t uiPortSpeed); void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed);
uint32_t uart_get_speed (const serial_port sp); uint32_t uart_get_speed(const serial_port sp);
int uart_receive (serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout); int uart_receive(serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout);
int uart_send (serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout); int uart_send(serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout);
char **uart_list_ports (void); char **uart_list_ports(void);
#endif // __NFC_BUS_UART_H__ #endif // __NFC_BUS_UART_H__

View file

@ -68,29 +68,29 @@ struct serial_port_unix {
#define UART_DATA( X ) ((struct serial_port_unix *) X) #define UART_DATA( X ) ((struct serial_port_unix *) X)
void uart_close_ext (const serial_port sp, const bool restore_termios); void uart_close_ext(const serial_port sp, const bool restore_termios);
serial_port serial_port
uart_open (const char *pcPortName) uart_open(const char *pcPortName)
{ {
struct serial_port_unix *sp = malloc (sizeof (struct serial_port_unix)); struct serial_port_unix *sp = malloc(sizeof(struct serial_port_unix));
if (sp == 0) if (sp == 0)
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
sp->fd = open (pcPortName, O_RDWR | O_NOCTTY | O_NONBLOCK); sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (sp->fd == -1) { if (sp->fd == -1) {
uart_close_ext (sp, false); uart_close_ext(sp, false);
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
} }
if (tcgetattr (sp->fd, &sp->termios_backup) == -1) { if (tcgetattr(sp->fd, &sp->termios_backup) == -1) {
uart_close_ext (sp, false); uart_close_ext(sp, false);
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
} }
// Make sure the port is not claimed already // Make sure the port is not claimed already
if (sp->termios_backup.c_iflag & CCLAIMED) { if (sp->termios_backup.c_iflag & CCLAIMED) {
uart_close_ext (sp, false); uart_close_ext(sp, false);
return CLAIMED_SERIAL_PORT; return CLAIMED_SERIAL_PORT;
} }
// Copy the old terminal info struct // Copy the old terminal info struct
@ -104,40 +104,40 @@ uart_open (const char *pcPortName)
sp->termios_new.c_cc[VMIN] = 0; // block until n bytes are received sp->termios_new.c_cc[VMIN] = 0; // block until n bytes are received
sp->termios_new.c_cc[VTIME] = 0; // block until a timer expires (n * 100 mSec.) sp->termios_new.c_cc[VTIME] = 0; // block until a timer expires (n * 100 mSec.)
if (tcsetattr (sp->fd, TCSANOW, &sp->termios_new) == -1) { if (tcsetattr(sp->fd, TCSANOW, &sp->termios_new) == -1) {
uart_close_ext (sp, true); uart_close_ext(sp, true);
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
} }
return sp; return sp;
} }
void void
uart_flush_input (serial_port sp) uart_flush_input(serial_port sp)
{ {
// This line seems to produce absolutely no effect on my system (GNU/Linux 2.6.35) // This line seems to produce absolutely no effect on my system (GNU/Linux 2.6.35)
tcflush (UART_DATA(sp)->fd, TCIFLUSH); tcflush(UART_DATA(sp)->fd, TCIFLUSH);
// So, I wrote this byte-eater // So, I wrote this byte-eater
// Retrieve the count of the incoming bytes // Retrieve the count of the incoming bytes
int available_bytes_count = 0; int available_bytes_count = 0;
int res; int res;
res = ioctl (UART_DATA(sp)->fd, FIONREAD, &available_bytes_count); res = ioctl(UART_DATA(sp)->fd, FIONREAD, &available_bytes_count);
if (res != 0) { if (res != 0) {
return; return;
} }
if (available_bytes_count == 0) { if (available_bytes_count == 0) {
return; return;
} }
char* rx = malloc (available_bytes_count); char* rx = malloc(available_bytes_count);
// There is something available, read the data // There is something available, read the data
res = read (UART_DATA(sp)->fd, rx, available_bytes_count); res = read(UART_DATA(sp)->fd, rx, available_bytes_count);
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d bytes have eatten.", available_bytes_count); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d bytes have eatten.", available_bytes_count);
free (rx); free(rx);
} }
void void
uart_set_speed (serial_port sp, const uint32_t uiPortSpeed) uart_set_speed(serial_port sp, const uint32_t uiPortSpeed)
{ {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Serial port speed requested to be set to %d bauds.", uiPortSpeed); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Serial port speed requested to be set to %d bauds.", uiPortSpeed);
// Portability note: on some systems, B9600 != 9600 so we have to do // Portability note: on some systems, B9600 != 9600 so we have to do
// uint32_t <=> speed_t associations by hand. // uint32_t <=> speed_t associations by hand.
@ -173,24 +173,24 @@ uart_set_speed (serial_port sp, const uint32_t uiPortSpeed)
break; break;
# endif # endif
default: default:
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set serial port speed to %d bauds. Speed value must be one of those defined in termios(3).", log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set serial port speed to %d bauds. Speed value must be one of those defined in termios(3).",
uiPortSpeed); uiPortSpeed);
return; return;
}; };
// Set port speed (Input and Output) // Set port speed (Input and Output)
cfsetispeed (&(UART_DATA(sp)->termios_new), stPortSpeed); cfsetispeed(&(UART_DATA(sp)->termios_new), stPortSpeed);
cfsetospeed (&(UART_DATA(sp)->termios_new), stPortSpeed); cfsetospeed(&(UART_DATA(sp)->termios_new), stPortSpeed);
if (tcsetattr (UART_DATA(sp)->fd, TCSADRAIN, &(UART_DATA(sp)->termios_new)) == -1) { if (tcsetattr(UART_DATA(sp)->fd, TCSADRAIN, &(UART_DATA(sp)->termios_new)) == -1) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to apply new speed settings."); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to apply new speed settings.");
} }
} }
uint32_t uint32_t
uart_get_speed (serial_port sp) uart_get_speed(serial_port sp)
{ {
uint32_t uiPortSpeed = 0; uint32_t uiPortSpeed = 0;
switch (cfgetispeed (&UART_DATA(sp)->termios_new)) { switch (cfgetispeed(&UART_DATA(sp)->termios_new)) {
case B9600: case B9600:
uiPortSpeed = 9600; uiPortSpeed = 9600;
break; break;
@ -226,20 +226,20 @@ uart_get_speed (serial_port sp)
} }
void void
uart_close_ext (const serial_port sp, const bool restore_termios) uart_close_ext(const serial_port sp, const bool restore_termios)
{ {
if (UART_DATA(sp)->fd >= 0) { if (UART_DATA(sp)->fd >= 0) {
if (restore_termios) if (restore_termios)
tcsetattr (UART_DATA(sp)->fd, TCSANOW, &UART_DATA(sp)->termios_backup); tcsetattr(UART_DATA(sp)->fd, TCSANOW, &UART_DATA(sp)->termios_backup);
close (UART_DATA(sp)->fd); close(UART_DATA(sp)->fd);
} }
free (sp); free(sp);
} }
void void
uart_close (const serial_port sp) uart_close(const serial_port sp)
{ {
uart_close_ext (sp, true); uart_close_ext(sp, true);
} }
/** /**
@ -248,7 +248,7 @@ uart_close (const serial_port sp)
* @return 0 on success, otherwise driver error code * @return 0 on success, otherwise driver error code
*/ */
int int
uart_receive (serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout) uart_receive(serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout)
{ {
int iAbortFd = abort_p ? *((int*)abort_p) : 0; int iAbortFd = abort_p ? *((int*)abort_p) : 0;
int received_bytes_count = 0; int received_bytes_count = 0;
@ -259,11 +259,11 @@ uart_receive (serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p,
do { do {
select: select:
// Reset file descriptor // Reset file descriptor
FD_ZERO (&rfds); FD_ZERO(&rfds);
FD_SET (UART_DATA(sp)->fd, &rfds); FD_SET(UART_DATA(sp)->fd, &rfds);
if (iAbortFd) { if (iAbortFd) {
FD_SET (iAbortFd, &rfds); FD_SET(iAbortFd, &rfds);
} }
struct timeval timeout_tv; struct timeval timeout_tv;
@ -272,7 +272,7 @@ select:
timeout_tv.tv_usec = ((timeout % 1000) * 1000); timeout_tv.tv_usec = ((timeout % 1000) * 1000);
} }
res = select (MAX(UART_DATA(sp)->fd, iAbortFd) + 1, &rfds, NULL, NULL, timeout ? &timeout_tv : NULL); res = select(MAX(UART_DATA(sp)->fd, iAbortFd) + 1, &rfds, NULL, NULL, timeout ? &timeout_tv : NULL);
if ((res < 0) && (EINTR == errno)) { if ((res < 0) && (EINTR == errno)) {
// The system call was interupted by a signal and a signal handler was // The system call was interupted by a signal and a signal handler was
@ -282,29 +282,29 @@ select:
// Read error // Read error
if (res < 0) { if (res < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Error: %s", strerror(errno)); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Error: %s", strerror(errno));
return NFC_EIO; return NFC_EIO;
} }
// Read time-out // Read time-out
if (res == 0) { if (res == 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Timeout!"); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Timeout!");
return NFC_ETIMEOUT; return NFC_ETIMEOUT;
} }
if (FD_ISSET (iAbortFd, &rfds)) { if (FD_ISSET(iAbortFd, &rfds)) {
// Abort requested // Abort requested
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Abort!"); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Abort!");
close (iAbortFd); close(iAbortFd);
return NFC_EOPABORTED; return NFC_EOPABORTED;
} }
// Retrieve the count of the incoming bytes // Retrieve the count of the incoming bytes
res = ioctl (UART_DATA(sp)->fd, FIONREAD, &available_bytes_count); res = ioctl(UART_DATA(sp)->fd, FIONREAD, &available_bytes_count);
if (res != 0) { if (res != 0) {
return NFC_EIO; return NFC_EIO;
} }
// There is something available, read the data // There is something available, read the data
res = read (UART_DATA(sp)->fd, pbtRx + received_bytes_count, MIN(available_bytes_count, (expected_bytes_count - received_bytes_count))); res = read(UART_DATA(sp)->fd, pbtRx + received_bytes_count, MIN(available_bytes_count, (expected_bytes_count - received_bytes_count)));
// Stop if the OS has some troubles reading the data // Stop if the OS has some troubles reading the data
if (res <= 0) { if (res <= 0) {
return NFC_EIO; return NFC_EIO;
@ -312,7 +312,7 @@ select:
received_bytes_count += res; received_bytes_count += res;
} while (expected_bytes_count > received_bytes_count); } while (expected_bytes_count > received_bytes_count);
LOG_HEX ("RX", pbtRx, szRx); LOG_HEX("RX", pbtRx, szRx);
return NFC_SUCCESS; return NFC_SUCCESS;
} }
@ -322,20 +322,20 @@ select:
* @return 0 on success, otherwise a driver error is returned * @return 0 on success, otherwise a driver error is returned
*/ */
int int
uart_send (serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout) uart_send(serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout)
{ {
(void) timeout; (void) timeout;
LOG_HEX ("TX", pbtTx, szTx); LOG_HEX("TX", pbtTx, szTx);
if ((int) szTx == write (UART_DATA(sp)->fd, pbtTx, szTx)) if ((int) szTx == write(UART_DATA(sp)->fd, pbtTx, szTx))
return NFC_SUCCESS; return NFC_SUCCESS;
else else
return NFC_EIO; return NFC_EIO;
} }
char ** char **
uart_list_ports (void) uart_list_ports(void)
{ {
char **res = malloc (sizeof (char *)); char **res = malloc(sizeof(char *));
size_t szRes = 1; size_t szRes = 1;
res[0] = NULL; res[0] = NULL;
@ -343,21 +343,21 @@ uart_list_ports (void)
DIR *pdDir = opendir("/dev"); DIR *pdDir = opendir("/dev");
struct dirent *pdDirEnt; struct dirent *pdDirEnt;
while ((pdDirEnt = readdir(pdDir)) != NULL) { while ((pdDirEnt = readdir(pdDir)) != NULL) {
if (!isdigit (pdDirEnt->d_name[strlen (pdDirEnt->d_name) - 1])) if (!isdigit(pdDirEnt->d_name[strlen(pdDirEnt->d_name) - 1]))
continue; continue;
const char **p = serial_ports_device_radix; const char **p = serial_ports_device_radix;
while (*p) { while (*p) {
if (!strncmp(pdDirEnt->d_name, *p, strlen (*p))) { if (!strncmp(pdDirEnt->d_name, *p, strlen(*p))) {
char **res2 = realloc (res, (szRes + 1) * sizeof (char *)); char **res2 = realloc(res, (szRes + 1) * sizeof(char *));
if (!res2) if (!res2)
goto oom; goto oom;
res = res2; res = res2;
if (!(res[szRes - 1] = malloc (6 + strlen (pdDirEnt->d_name)))) if (!(res[szRes - 1] = malloc(6 + strlen(pdDirEnt->d_name))))
goto oom; goto oom;
sprintf (res[szRes - 1], "/dev/%s", pdDirEnt->d_name); sprintf(res[szRes - 1], "/dev/%s", pdDirEnt->d_name);
szRes++; szRes++;
res[szRes - 1] = NULL; res[szRes - 1] = NULL;
@ -366,7 +366,7 @@ uart_list_ports (void)
} }
} }
oom: oom:
closedir (pdDir); closedir(pdDir);
return res; return res;
} }

View file

@ -38,31 +38,31 @@ struct serial_port_windows {
}; };
serial_port serial_port
uart_open (const char *pcPortName) uart_open(const char *pcPortName)
{ {
char acPortName[255]; char acPortName[255];
struct serial_port_windows *sp = malloc (sizeof (struct serial_port_windows)); struct serial_port_windows *sp = malloc(sizeof(struct serial_port_windows));
// Copy the input "com?" to "\\.\COM?" format // Copy the input "com?" to "\\.\COM?" format
sprintf (acPortName, "\\\\.\\%s", pcPortName); sprintf(acPortName, "\\\\.\\%s", pcPortName);
_strupr (acPortName); _strupr(acPortName);
// Try to open the serial port // Try to open the serial port
sp->hPort = CreateFileA (acPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); sp->hPort = CreateFileA(acPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (sp->hPort == INVALID_HANDLE_VALUE) { if (sp->hPort == INVALID_HANDLE_VALUE) {
uart_close (sp); uart_close(sp);
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
} }
// Prepare the device control // Prepare the device control
memset (&sp->dcb, 0, sizeof (DCB)); memset(&sp->dcb, 0, sizeof(DCB));
sp->dcb.DCBlength = sizeof (DCB); sp->dcb.DCBlength = sizeof(DCB);
if (!BuildCommDCBA ("baud=9600 data=8 parity=N stop=1", &sp->dcb)) { if (!BuildCommDCBA("baud=9600 data=8 parity=N stop=1", &sp->dcb)) {
uart_close (sp); uart_close(sp);
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
} }
// Update the active serial port // Update the active serial port
if (!SetCommState (sp->hPort, &sp->dcb)) { if (!SetCommState(sp->hPort, &sp->dcb)) {
uart_close (sp); uart_close(sp);
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
} }
@ -72,37 +72,37 @@ uart_open (const char *pcPortName)
sp->ct.WriteTotalTimeoutMultiplier = 30; sp->ct.WriteTotalTimeoutMultiplier = 30;
sp->ct.WriteTotalTimeoutConstant = 0; sp->ct.WriteTotalTimeoutConstant = 0;
if (!SetCommTimeouts (sp->hPort, &sp->ct)) { if (!SetCommTimeouts(sp->hPort, &sp->ct)) {
uart_close (sp); uart_close(sp);
return INVALID_SERIAL_PORT; return INVALID_SERIAL_PORT;
} }
PurgeComm (sp->hPort, PURGE_RXABORT | PURGE_RXCLEAR); PurgeComm(sp->hPort, PURGE_RXABORT | PURGE_RXCLEAR);
return sp; return sp;
} }
void void
uart_close (const serial_port sp) uart_close(const serial_port sp)
{ {
if (((struct serial_port_windows *) sp)->hPort != INVALID_HANDLE_VALUE) { if (((struct serial_port_windows *) sp)->hPort != INVALID_HANDLE_VALUE) {
CloseHandle (((struct serial_port_windows *) sp)->hPort); CloseHandle(((struct serial_port_windows *) sp)->hPort);
} }
free (sp); free(sp);
} }
void void
uart_flush_input (const serial_port sp) uart_flush_input(const serial_port sp)
{ {
PurgeComm(((struct serial_port_windows *) sp)->hPort, PURGE_RXABORT | PURGE_RXCLEAR); PurgeComm(((struct serial_port_windows *) sp)->hPort, PURGE_RXABORT | PURGE_RXCLEAR);
} }
void void
uart_set_speed (serial_port sp, const uint32_t uiPortSpeed) uart_set_speed(serial_port sp, const uint32_t uiPortSpeed)
{ {
struct serial_port_windows *spw; struct serial_port_windows *spw;
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Serial port speed requested to be set to %d bauds.", uiPortSpeed); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Serial port speed requested to be set to %d bauds.", uiPortSpeed);
// Set port speed (Input and Output) // Set port speed (Input and Output)
switch (uiPortSpeed) { switch (uiPortSpeed) {
case 9600: case 9600:
@ -114,32 +114,32 @@ uart_set_speed (serial_port sp, const uint32_t uiPortSpeed)
case 460800: case 460800:
break; break;
default: default:
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set serial port speed to %d bauds. Speed value must be one of these constants: 9600 (default), 19200, 38400, 57600, 115200, 230400 or 460800.", uiPortSpeed); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set serial port speed to %d bauds. Speed value must be one of these constants: 9600 (default), 19200, 38400, 57600, 115200, 230400 or 460800.", uiPortSpeed);
return; return;
}; };
spw = (struct serial_port_windows *) sp; spw = (struct serial_port_windows *) sp;
// Set baud rate // Set baud rate
spw->dcb.BaudRate = uiPortSpeed; spw->dcb.BaudRate = uiPortSpeed;
if (!SetCommState (spw->hPort, &spw->dcb)) { if (!SetCommState(spw->hPort, &spw->dcb)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to apply new speed settings."); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to apply new speed settings.");
return; return;
} }
PurgeComm (spw->hPort, PURGE_RXABORT | PURGE_RXCLEAR); PurgeComm(spw->hPort, PURGE_RXABORT | PURGE_RXCLEAR);
} }
uint32_t uint32_t
uart_get_speed (const serial_port sp) uart_get_speed(const serial_port sp)
{ {
const struct serial_port_windows *spw = (struct serial_port_windows *) sp; const struct serial_port_windows *spw = (struct serial_port_windows *) sp;
if (!GetCommState (spw->hPort, (serial_port) & spw->dcb)) if (!GetCommState(spw->hPort, (serial_port) & spw->dcb))
return spw->dcb.BaudRate; return spw->dcb.BaudRate;
return 0; return 0;
} }
int int
uart_receive (serial_port sp, uint8_t * pbtRx, const size_t szRx, void * abort_p, int timeout) uart_receive(serial_port sp, uint8_t * pbtRx, const size_t szRx, void * abort_p, int timeout)
{ {
DWORD dwBytesToGet = (DWORD)szRx; DWORD dwBytesToGet = (DWORD)szRx;
DWORD dwBytesReceived = 0; DWORD dwBytesReceived = 0;
@ -155,26 +155,26 @@ uart_receive (serial_port sp, uint8_t * pbtRx, const size_t szRx, void * abort_p
timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = timeout_ms; timeouts.WriteTotalTimeoutConstant = timeout_ms;
if (!SetCommTimeouts (((struct serial_port_windows *) sp)->hPort, &timeouts)) { if (!SetCommTimeouts(((struct serial_port_windows *) sp)->hPort, &timeouts)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to apply new timeout settings."); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to apply new timeout settings.");
return NFC_EIO; return NFC_EIO;
} }
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Timeouts are set to %u ms", timeout_ms); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Timeouts are set to %u ms", timeout_ms);
// TODO Enhance the reception method // TODO Enhance the reception method
// - According to MSDN, it could be better to implement nfc_abort_command() mecanism using Cancello() // - According to MSDN, it could be better to implement nfc_abort_command() mecanism using Cancello()
volatile bool * abort_flag_p = (volatile bool *)abort_p; volatile bool * abort_flag_p = (volatile bool *)abort_p;
do { do {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "ReadFile"); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "ReadFile");
res = ReadFile (((struct serial_port_windows *) sp)->hPort, pbtRx + dwTotalBytesReceived, res = ReadFile(((struct serial_port_windows *) sp)->hPort, pbtRx + dwTotalBytesReceived,
dwBytesToGet, dwBytesToGet,
&dwBytesReceived, NULL); &dwBytesReceived, NULL);
dwTotalBytesReceived += dwBytesReceived; dwTotalBytesReceived += dwBytesReceived;
if (!res) { if (!res) {
DWORD err = GetLastError(); DWORD err = GetLastError();
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "ReadFile error: %u", err); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "ReadFile error: %u", err);
return NFC_EIO; return NFC_EIO;
} else if (dwBytesReceived == 0) { } else if (dwBytesReceived == 0) {
return NFC_ETIMEOUT; return NFC_ETIMEOUT;
@ -188,13 +188,13 @@ uart_receive (serial_port sp, uint8_t * pbtRx, const size_t szRx, void * abort_p
return NFC_EOPABORTED; return NFC_EOPABORTED;
} }
} while (((DWORD)szRx) > dwTotalBytesReceived); } while (((DWORD)szRx) > dwTotalBytesReceived);
LOG_HEX ("RX", pbtRx, szRx); LOG_HEX("RX", pbtRx, szRx);
return (dwTotalBytesReceived == (DWORD) szRx) ? 0 : NFC_EIO; return (dwTotalBytesReceived == (DWORD) szRx) ? 0 : NFC_EIO;
} }
int int
uart_send (serial_port sp, const uint8_t * pbtTx, const size_t szTx, int timeout) uart_send(serial_port sp, const uint8_t * pbtTx, const size_t szTx, int timeout)
{ {
DWORD dwTxLen = 0; DWORD dwTxLen = 0;
@ -205,13 +205,13 @@ uart_send (serial_port sp, const uint8_t * pbtTx, const size_t szTx, int timeout
timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = timeout; timeouts.WriteTotalTimeoutConstant = timeout;
if (!SetCommTimeouts (((struct serial_port_windows *) sp)->hPort, &timeouts)) { if (!SetCommTimeouts(((struct serial_port_windows *) sp)->hPort, &timeouts)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to apply new timeout settings."); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to apply new timeout settings.");
return NFC_EIO; return NFC_EIO;
} }
LOG_HEX ("TX", pbtTx, szTx); LOG_HEX("TX", pbtTx, szTx);
if (!WriteFile (((struct serial_port_windows *) sp)->hPort, pbtTx, szTx, &dwTxLen, NULL)) { if (!WriteFile(((struct serial_port_windows *) sp)->hPort, pbtTx, szTx, &dwTxLen, NULL)) {
return NFC_EIO; return NFC_EIO;
} }
if (!dwTxLen) if (!dwTxLen)
@ -236,7 +236,7 @@ BOOL is_port_available(int nPort)
// Try to guess what we should use. // Try to guess what we should use.
#define MAX_SERIAL_PORT_WIN 255 #define MAX_SERIAL_PORT_WIN 255
char ** char **
uart_list_ports (void) uart_list_ports(void)
{ {
char **availablePorts = malloc((1 + MAX_SERIAL_PORT_WIN) * sizeof(char*)); char **availablePorts = malloc((1 + MAX_SERIAL_PORT_WIN) * sizeof(char*));
int curIndex = 0; int curIndex = 0;

View file

@ -144,49 +144,49 @@ typedef enum {
static const pn53x_command pn53x_commands[] = { static const pn53x_command pn53x_commands[] = {
// Miscellaneous // Miscellaneous
PNCMD( Diagnose, PN531 | PN532 | PN533 | RCS360 ), PNCMD(Diagnose, PN531 | PN532 | PN533 | RCS360),
PNCMD( GetFirmwareVersion, PN531 | PN532 | PN533 | RCS360 ), PNCMD(GetFirmwareVersion, PN531 | PN532 | PN533 | RCS360),
PNCMD( GetGeneralStatus, PN531 | PN532 | PN533 | RCS360 ), PNCMD(GetGeneralStatus, PN531 | PN532 | PN533 | RCS360),
PNCMD( ReadRegister, PN531 | PN532 | PN533 | RCS360 ), PNCMD(ReadRegister, PN531 | PN532 | PN533 | RCS360),
PNCMD( WriteRegister, PN531 | PN532 | PN533 | RCS360 ), PNCMD(WriteRegister, PN531 | PN532 | PN533 | RCS360),
PNCMD( ReadGPIO, PN531 | PN532 | PN533 ), PNCMD(ReadGPIO, PN531 | PN532 | PN533),
PNCMD( WriteGPIO, PN531 | PN532 | PN533 ), PNCMD(WriteGPIO, PN531 | PN532 | PN533),
PNCMD( SetSerialBaudRate, PN531 | PN532 | PN533 ), PNCMD(SetSerialBaudRate, PN531 | PN532 | PN533),
PNCMD( SetParameters, PN531 | PN532 | PN533 | RCS360 ), PNCMD(SetParameters, PN531 | PN532 | PN533 | RCS360),
PNCMD( SAMConfiguration, PN531 | PN532 ), PNCMD(SAMConfiguration, PN531 | PN532),
PNCMD( PowerDown, PN531 | PN532 ), PNCMD(PowerDown, PN531 | PN532),
PNCMD( AlparCommandForTDA, PN533 | RCS360 ), // Has another usage on RC-S360... PNCMD(AlparCommandForTDA, PN533 | RCS360), // Has another usage on RC-S360...
// RF communication // RF communication
PNCMD( RFConfiguration, PN531 | PN532 | PN533 | RCS360 ), PNCMD(RFConfiguration, PN531 | PN532 | PN533 | RCS360),
PNCMD( RFRegulationTest, PN531 | PN532 | PN533 ), PNCMD(RFRegulationTest, PN531 | PN532 | PN533),
// Initiator // Initiator
PNCMD( InJumpForDEP, PN531 | PN532 | PN533 | RCS360 ), PNCMD(InJumpForDEP, PN531 | PN532 | PN533 | RCS360),
PNCMD( InJumpForPSL, PN531 | PN532 | PN533 ), PNCMD(InJumpForPSL, PN531 | PN532 | PN533),
PNCMD( InListPassiveTarget, PN531 | PN532 | PN533 | RCS360 ), PNCMD(InListPassiveTarget, PN531 | PN532 | PN533 | RCS360),
PNCMD( InATR, PN531 | PN532 | PN533 ), PNCMD(InATR, PN531 | PN532 | PN533),
PNCMD( InPSL, PN531 | PN532 | PN533 ), PNCMD(InPSL, PN531 | PN532 | PN533),
PNCMD( InDataExchange, PN531 | PN532 | PN533 ), PNCMD(InDataExchange, PN531 | PN532 | PN533),
PNCMD( InCommunicateThru, PN531 | PN532 | PN533 | RCS360 ), PNCMD(InCommunicateThru, PN531 | PN532 | PN533 | RCS360),
PNCMD( InQuartetByteExchange, PN533 ), PNCMD(InQuartetByteExchange, PN533),
PNCMD( InDeselect, PN531 | PN532 | PN533 | RCS360 ), PNCMD(InDeselect, PN531 | PN532 | PN533 | RCS360),
PNCMD( InRelease, PN531 | PN532 | PN533 | RCS360 ), PNCMD(InRelease, PN531 | PN532 | PN533 | RCS360),
PNCMD( InSelect, PN531 | PN532 | PN533 ), PNCMD(InSelect, PN531 | PN532 | PN533),
PNCMD( InAutoPoll, PN532 ), PNCMD(InAutoPoll, PN532),
PNCMD( InActivateDeactivatePaypass, PN533 ), PNCMD(InActivateDeactivatePaypass, PN533),
// Target // Target
PNCMD( TgInitAsTarget, PN531 | PN532 | PN533 ), PNCMD(TgInitAsTarget, PN531 | PN532 | PN533),
PNCMD( TgSetGeneralBytes, PN531 | PN532 | PN533 ), PNCMD(TgSetGeneralBytes, PN531 | PN532 | PN533),
PNCMD( TgGetData, PN531 | PN532 | PN533 ), PNCMD(TgGetData, PN531 | PN532 | PN533),
PNCMD( TgSetData, PN531 | PN532 | PN533 ), PNCMD(TgSetData, PN531 | PN532 | PN533),
PNCMD( TgSetDataSecure, PN533 ), PNCMD(TgSetDataSecure, PN533),
PNCMD( TgSetMetaData, PN531 | PN532 | PN533 ), PNCMD(TgSetMetaData, PN531 | PN532 | PN533),
PNCMD( TgSetMetaDataSecure, PN533 ), PNCMD(TgSetMetaDataSecure, PN533),
PNCMD( TgGetInitiatorCommand, PN531 | PN532 | PN533 ), PNCMD(TgGetInitiatorCommand, PN531 | PN532 | PN533),
PNCMD( TgResponseToInitiator, PN531 | PN532 | PN533 ), PNCMD(TgResponseToInitiator, PN531 | PN532 | PN533),
PNCMD( TgGetTargetStatus, PN531 | PN532 | PN533 ), PNCMD(TgGetTargetStatus, PN531 | PN532 | PN533),
}; };
// SFR part // SFR part
@ -330,76 +330,76 @@ typedef struct {
#ifdef LOGGING #ifdef LOGGING
static const pn53x_register pn53x_registers[] = { static const pn53x_register pn53x_registers[] = {
PNREG (PN53X_REG_CIU_Mode, "Defines general modes for transmitting and receiving"), PNREG(PN53X_REG_CIU_Mode, "Defines general modes for transmitting and receiving"),
PNREG (PN53X_REG_CIU_TxMode, "Defines the transmission data rate and framing during transmission"), PNREG(PN53X_REG_CIU_TxMode, "Defines the transmission data rate and framing during transmission"),
PNREG (PN53X_REG_CIU_RxMode, "Defines the transmission data rate and framing during receiving"), PNREG(PN53X_REG_CIU_RxMode, "Defines the transmission data rate and framing during receiving"),
PNREG (PN53X_REG_CIU_TxControl, "Controls the logical behaviour of the antenna driver pins TX1 and TX2"), PNREG(PN53X_REG_CIU_TxControl, "Controls the logical behaviour of the antenna driver pins TX1 and TX2"),
PNREG (PN53X_REG_CIU_TxAuto, "Controls the settings of the antenna driver"), PNREG(PN53X_REG_CIU_TxAuto, "Controls the settings of the antenna driver"),
PNREG (PN53X_REG_CIU_TxSel, "Selects the internal sources for the antenna driver"), PNREG(PN53X_REG_CIU_TxSel, "Selects the internal sources for the antenna driver"),
PNREG (PN53X_REG_CIU_RxSel, "Selects internal receiver settings"), PNREG(PN53X_REG_CIU_RxSel, "Selects internal receiver settings"),
PNREG (PN53X_REG_CIU_RxThreshold, "Selects thresholds for the bit decoder"), PNREG(PN53X_REG_CIU_RxThreshold, "Selects thresholds for the bit decoder"),
PNREG (PN53X_REG_CIU_Demod, "Defines demodulator settings"), PNREG(PN53X_REG_CIU_Demod, "Defines demodulator settings"),
PNREG (PN53X_REG_CIU_FelNFC1, "Defines the length of the valid range for the received frame"), PNREG(PN53X_REG_CIU_FelNFC1, "Defines the length of the valid range for the received frame"),
PNREG (PN53X_REG_CIU_FelNFC2, "Defines the length of the valid range for the received frame"), PNREG(PN53X_REG_CIU_FelNFC2, "Defines the length of the valid range for the received frame"),
PNREG (PN53X_REG_CIU_MifNFC, "Controls the communication in ISO/IEC 14443/MIFARE and NFC target mode at 106 kbit/s"), PNREG(PN53X_REG_CIU_MifNFC, "Controls the communication in ISO/IEC 14443/MIFARE and NFC target mode at 106 kbit/s"),
PNREG (PN53X_REG_CIU_ManualRCV, "Allows manual fine tuning of the internal receiver"), PNREG(PN53X_REG_CIU_ManualRCV, "Allows manual fine tuning of the internal receiver"),
PNREG (PN53X_REG_CIU_TypeB, "Configure the ISO/IEC 14443 type B"), PNREG(PN53X_REG_CIU_TypeB, "Configure the ISO/IEC 14443 type B"),
// PNREG (PN53X_REG_-, "Reserved"), // PNREG (PN53X_REG_-, "Reserved"),
// PNREG (PN53X_REG_-, "Reserved"), // PNREG (PN53X_REG_-, "Reserved"),
PNREG (PN53X_REG_CIU_CRCResultMSB, "Shows the actual MSB values of the CRC calculation"), PNREG(PN53X_REG_CIU_CRCResultMSB, "Shows the actual MSB values of the CRC calculation"),
PNREG (PN53X_REG_CIU_CRCResultLSB, "Shows the actual LSB values of the CRC calculation"), PNREG(PN53X_REG_CIU_CRCResultLSB, "Shows the actual LSB values of the CRC calculation"),
PNREG (PN53X_REG_CIU_GsNOFF, "Selects the conductance of the antenna driver pins TX1 and TX2 for load modulation when own RF field is switched OFF"), PNREG(PN53X_REG_CIU_GsNOFF, "Selects the conductance of the antenna driver pins TX1 and TX2 for load modulation when own RF field is switched OFF"),
PNREG (PN53X_REG_CIU_ModWidth, "Controls the setting of the width of the Miller pause"), PNREG(PN53X_REG_CIU_ModWidth, "Controls the setting of the width of the Miller pause"),
PNREG (PN53X_REG_CIU_TxBitPhase, "Bit synchronization at 106 kbit/s"), PNREG(PN53X_REG_CIU_TxBitPhase, "Bit synchronization at 106 kbit/s"),
PNREG (PN53X_REG_CIU_RFCfg, "Configures the receiver gain and RF level"), PNREG(PN53X_REG_CIU_RFCfg, "Configures the receiver gain and RF level"),
PNREG (PN53X_REG_CIU_GsNOn, "Selects the conductance of the antenna driver pins TX1 and TX2 for modulation, when own RF field is switched ON"), PNREG(PN53X_REG_CIU_GsNOn, "Selects the conductance of the antenna driver pins TX1 and TX2 for modulation, when own RF field is switched ON"),
PNREG (PN53X_REG_CIU_CWGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when not in modulation phase"), PNREG(PN53X_REG_CIU_CWGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when not in modulation phase"),
PNREG (PN53X_REG_CIU_ModGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when in modulation phase"), PNREG(PN53X_REG_CIU_ModGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when in modulation phase"),
PNREG (PN53X_REG_CIU_TMode, "Defines settings for the internal timer"), PNREG(PN53X_REG_CIU_TMode, "Defines settings for the internal timer"),
PNREG (PN53X_REG_CIU_TPrescaler, "Defines settings for the internal timer"), PNREG(PN53X_REG_CIU_TPrescaler, "Defines settings for the internal timer"),
PNREG (PN53X_REG_CIU_TReloadVal_hi, "Describes the 16-bit long timer reload value (Higher 8 bits)"), PNREG(PN53X_REG_CIU_TReloadVal_hi, "Describes the 16-bit long timer reload value (Higher 8 bits)"),
PNREG (PN53X_REG_CIU_TReloadVal_lo, "Describes the 16-bit long timer reload value (Lower 8 bits)"), PNREG(PN53X_REG_CIU_TReloadVal_lo, "Describes the 16-bit long timer reload value (Lower 8 bits)"),
PNREG (PN53X_REG_CIU_TCounterVal_hi, "Describes the 16-bit long timer actual value (Higher 8 bits)"), PNREG(PN53X_REG_CIU_TCounterVal_hi, "Describes the 16-bit long timer actual value (Higher 8 bits)"),
PNREG (PN53X_REG_CIU_TCounterVal_lo, "Describes the 16-bit long timer actual value (Lower 8 bits)"), PNREG(PN53X_REG_CIU_TCounterVal_lo, "Describes the 16-bit long timer actual value (Lower 8 bits)"),
// PNREG (PN53X_REG_-, "Reserved"), // PNREG (PN53X_REG_-, "Reserved"),
PNREG (PN53X_REG_CIU_TestSel1, "General test signals configuration"), PNREG(PN53X_REG_CIU_TestSel1, "General test signals configuration"),
PNREG (PN53X_REG_CIU_TestSel2, "General test signals configuration and PRBS control"), PNREG(PN53X_REG_CIU_TestSel2, "General test signals configuration and PRBS control"),
PNREG (PN53X_REG_CIU_TestPinEn, "Enables test signals output on pins."), PNREG(PN53X_REG_CIU_TestPinEn, "Enables test signals output on pins."),
PNREG (PN53X_REG_CIU_TestPinValue, "Defines the values for the 8-bit parallel bus when it is used as I/O bus"), PNREG(PN53X_REG_CIU_TestPinValue, "Defines the values for the 8-bit parallel bus when it is used as I/O bus"),
PNREG (PN53X_REG_CIU_TestBus, "Shows the status of the internal test bus"), PNREG(PN53X_REG_CIU_TestBus, "Shows the status of the internal test bus"),
PNREG (PN53X_REG_CIU_AutoTest, "Controls the digital self-test"), PNREG(PN53X_REG_CIU_AutoTest, "Controls the digital self-test"),
PNREG (PN53X_REG_CIU_Version, "Shows the CIU version"), PNREG(PN53X_REG_CIU_Version, "Shows the CIU version"),
PNREG (PN53X_REG_CIU_AnalogTest, "Controls the pins AUX1 and AUX2"), PNREG(PN53X_REG_CIU_AnalogTest, "Controls the pins AUX1 and AUX2"),
PNREG (PN53X_REG_CIU_TestDAC1, "Defines the test value for the TestDAC1"), PNREG(PN53X_REG_CIU_TestDAC1, "Defines the test value for the TestDAC1"),
PNREG (PN53X_REG_CIU_TestDAC2, "Defines the test value for the TestDAC2"), PNREG(PN53X_REG_CIU_TestDAC2, "Defines the test value for the TestDAC2"),
PNREG (PN53X_REG_CIU_TestADC, "Show the actual value of ADC I and Q"), PNREG(PN53X_REG_CIU_TestADC, "Show the actual value of ADC I and Q"),
// PNREG (PN53X_REG_-, "Reserved for tests"), // PNREG (PN53X_REG_-, "Reserved for tests"),
// PNREG (PN53X_REG_-, "Reserved for tests"), // PNREG (PN53X_REG_-, "Reserved for tests"),
// PNREG (PN53X_REG_-, "Reserved for tests"), // PNREG (PN53X_REG_-, "Reserved for tests"),
PNREG (PN53X_REG_CIU_RFlevelDet, "Power down of the RF level detector"), PNREG(PN53X_REG_CIU_RFlevelDet, "Power down of the RF level detector"),
PNREG (PN53X_REG_CIU_SIC_CLK_en, "Enables the use of secure IC clock on P34 / SIC_CLK"), PNREG(PN53X_REG_CIU_SIC_CLK_en, "Enables the use of secure IC clock on P34 / SIC_CLK"),
PNREG (PN53X_REG_CIU_Command, "Starts and stops the command execution"), PNREG(PN53X_REG_CIU_Command, "Starts and stops the command execution"),
PNREG (PN53X_REG_CIU_CommIEn, "Control bits to enable and disable the passing of interrupt requests"), PNREG(PN53X_REG_CIU_CommIEn, "Control bits to enable and disable the passing of interrupt requests"),
PNREG (PN53X_REG_CIU_DivIEn, "Controls bits to enable and disable the passing of interrupt requests"), PNREG(PN53X_REG_CIU_DivIEn, "Controls bits to enable and disable the passing of interrupt requests"),
PNREG (PN53X_REG_CIU_CommIrq, "Contains common CIU interrupt request flags"), PNREG(PN53X_REG_CIU_CommIrq, "Contains common CIU interrupt request flags"),
PNREG (PN53X_REG_CIU_DivIrq, "Contains miscellaneous interrupt request flags"), PNREG(PN53X_REG_CIU_DivIrq, "Contains miscellaneous interrupt request flags"),
PNREG (PN53X_REG_CIU_Error, "Error flags showing the error status of the last command executed"), PNREG(PN53X_REG_CIU_Error, "Error flags showing the error status of the last command executed"),
PNREG (PN53X_REG_CIU_Status1, "Contains status flags of the CRC, Interrupt Request System and FIFO buffer"), PNREG(PN53X_REG_CIU_Status1, "Contains status flags of the CRC, Interrupt Request System and FIFO buffer"),
PNREG (PN53X_REG_CIU_Status2, "Contain status flags of the receiver, transmitter and Data Mode Detector"), PNREG(PN53X_REG_CIU_Status2, "Contain status flags of the receiver, transmitter and Data Mode Detector"),
PNREG (PN53X_REG_CIU_FIFOData, "In- and output of 64 byte FIFO buffer"), PNREG(PN53X_REG_CIU_FIFOData, "In- and output of 64 byte FIFO buffer"),
PNREG (PN53X_REG_CIU_FIFOLevel, "Indicates the number of bytes stored in the FIFO"), PNREG(PN53X_REG_CIU_FIFOLevel, "Indicates the number of bytes stored in the FIFO"),
PNREG (PN53X_REG_CIU_WaterLevel, "Defines the thresholds for FIFO under- and overflow warning"), PNREG(PN53X_REG_CIU_WaterLevel, "Defines the thresholds for FIFO under- and overflow warning"),
PNREG (PN53X_REG_CIU_Control, "Contains miscellaneous control bits"), PNREG(PN53X_REG_CIU_Control, "Contains miscellaneous control bits"),
PNREG (PN53X_REG_CIU_BitFraming, "Adjustments for bit oriented frames"), PNREG(PN53X_REG_CIU_BitFraming, "Adjustments for bit oriented frames"),
PNREG (PN53X_REG_CIU_Coll, "Defines the first bit collision detected on the RF interface"), PNREG(PN53X_REG_CIU_Coll, "Defines the first bit collision detected on the RF interface"),
// SFR // SFR
PNREG (PN53X_SFR_P3CFGA, "Port 3 configuration"), PNREG(PN53X_SFR_P3CFGA, "Port 3 configuration"),
PNREG (PN53X_SFR_P3CFGB, "Port 3 configuration"), PNREG(PN53X_SFR_P3CFGB, "Port 3 configuration"),
PNREG (PN53X_SFR_P3, "Port 3 value"), PNREG(PN53X_SFR_P3, "Port 3 value"),
PNREG (PN53X_SFR_P7CFGA, "Port 7 configuration"), PNREG(PN53X_SFR_P7CFGA, "Port 7 configuration"),
PNREG (PN53X_SFR_P7CFGB, "Port 7 configuration"), PNREG(PN53X_SFR_P7CFGB, "Port 7 configuration"),
PNREG (PN53X_SFR_P7, "Port 7 value"), PNREG(PN53X_SFR_P7, "Port 7 value"),
}; };
#endif #endif

File diff suppressed because it is too large Load diff

View file

@ -292,102 +292,102 @@ extern const uint8_t pn53x_ack_frame[6];
extern const uint8_t pn53x_nack_frame[6]; extern const uint8_t pn53x_nack_frame[6];
int pn53x_init(struct nfc_device *pnd); int pn53x_init(struct nfc_device *pnd);
int pn53x_transceive (struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_transceive(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRxLen, int timeout);
int pn53x_set_parameters (struct nfc_device *pnd, const uint8_t ui8Value, const bool bEnable); int pn53x_set_parameters(struct nfc_device *pnd, const uint8_t ui8Value, const bool bEnable);
int pn53x_set_tx_bits (struct nfc_device *pnd, const uint8_t ui8Bits); int pn53x_set_tx_bits(struct nfc_device *pnd, const uint8_t ui8Bits);
int pn53x_wrap_frame (const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtFrame); int pn53x_wrap_frame(const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtFrame);
int pn53x_unwrap_frame (const uint8_t *pbtFrame, const size_t szFrameBits, uint8_t *pbtRx, uint8_t *pbtRxPar); int pn53x_unwrap_frame(const uint8_t *pbtFrame, const size_t szFrameBits, uint8_t *pbtRx, uint8_t *pbtRxPar);
int pn53x_decode_target_data (const uint8_t *pbtRawData, size_t szRawData, int pn53x_decode_target_data(const uint8_t *pbtRawData, size_t szRawData,
pn53x_type chip_type, nfc_modulation_type nmt, pn53x_type chip_type, nfc_modulation_type nmt,
nfc_target_info *pnti); nfc_target_info *pnti);
int pn53x_read_register (struct nfc_device *pnd, uint16_t ui16Reg, uint8_t *ui8Value); int pn53x_read_register(struct nfc_device *pnd, uint16_t ui16Reg, uint8_t *ui8Value);
int pn53x_write_register (struct nfc_device *pnd, uint16_t ui16Reg, uint8_t ui8SymbolMask, uint8_t ui8Value); int pn53x_write_register(struct nfc_device *pnd, uint16_t ui16Reg, uint8_t ui8SymbolMask, uint8_t ui8Value);
int pn53x_decode_firmware_version (struct nfc_device *pnd); int pn53x_decode_firmware_version(struct nfc_device *pnd);
int pn53x_set_property_int (struct nfc_device *pnd, const nfc_property property, const int value); int pn53x_set_property_int(struct nfc_device *pnd, const nfc_property property, const int value);
int pn53x_set_property_bool (struct nfc_device *pnd, const nfc_property property, const bool bEnable); int pn53x_set_property_bool(struct nfc_device *pnd, const nfc_property property, const bool bEnable);
int pn53x_check_communication (struct nfc_device *pnd); int pn53x_check_communication(struct nfc_device *pnd);
int pn53x_idle (struct nfc_device *pnd); int pn53x_idle(struct nfc_device *pnd);
// NFC device as Initiator functions // NFC device as Initiator functions
int pn53x_initiator_init (struct nfc_device *pnd); int pn53x_initiator_init(struct nfc_device *pnd);
int pn53x_initiator_select_passive_target (struct nfc_device *pnd, int pn53x_initiator_select_passive_target(struct nfc_device *pnd,
const nfc_modulation nm, const nfc_modulation nm,
const uint8_t *pbtInitData, const size_t szInitData, const uint8_t *pbtInitData, const size_t szInitData,
nfc_target *pnt); nfc_target *pnt);
int pn53x_initiator_poll_target (struct nfc_device *pnd, int pn53x_initiator_poll_target(struct nfc_device *pnd,
const nfc_modulation *pnmModulations, const size_t szModulations, const nfc_modulation *pnmModulations, const size_t szModulations,
const uint8_t uiPollNr, const uint8_t uiPeriod, const uint8_t uiPollNr, const uint8_t uiPeriod,
nfc_target *pnt); nfc_target *pnt);
int pn53x_initiator_select_dep_target (struct nfc_device *pnd, int pn53x_initiator_select_dep_target(struct nfc_device *pnd,
const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_mode ndm, const nfc_baud_rate nbr,
const nfc_dep_info *pndiInitiator, const nfc_dep_info *pndiInitiator,
nfc_target *pnt, nfc_target *pnt,
const int timeout); const int timeout);
int pn53x_initiator_transceive_bits (struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, int pn53x_initiator_transceive_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits,
const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar); const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar);
int pn53x_initiator_transceive_bytes (struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int pn53x_initiator_transceive_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx,
uint8_t *pbtRx, const size_t szRx, int timeout); uint8_t *pbtRx, const size_t szRx, int timeout);
int pn53x_initiator_transceive_bits_timed (struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, int pn53x_initiator_transceive_bits_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits,
const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles); const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles);
int pn53x_initiator_transceive_bytes_timed (struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int pn53x_initiator_transceive_bytes_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx,
uint8_t *pbtRx, uint32_t *cycles); uint8_t *pbtRx, uint32_t *cycles);
int pn53x_initiator_deselect_target (struct nfc_device *pnd); int pn53x_initiator_deselect_target(struct nfc_device *pnd);
int pn53x_initiator_target_is_present (struct nfc_device *pnd, const nfc_target nt); int pn53x_initiator_target_is_present(struct nfc_device *pnd, const nfc_target nt);
// NFC device as Target functions // NFC device as Target functions
int pn53x_target_init (struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_target_init(struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRxLen, int timeout);
int pn53x_target_receive_bits (struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar); int pn53x_target_receive_bits(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar);
int pn53x_target_receive_bytes (struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_target_receive_bytes(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout);
int pn53x_target_send_bits (struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar); int pn53x_target_send_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar);
int pn53x_target_send_bytes (struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout); int pn53x_target_send_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout);
// Error handling functions // Error handling functions
const char *pn53x_strerror (const struct nfc_device *pnd); const char *pn53x_strerror(const struct nfc_device *pnd);
// C wrappers for PN53x commands // C wrappers for PN53x commands
int pn53x_SetParameters (struct nfc_device *pnd, const uint8_t ui8Value); int pn53x_SetParameters(struct nfc_device *pnd, const uint8_t ui8Value);
int pn53x_SAMConfiguration (struct nfc_device *pnd, const pn532_sam_mode mode, int timeout); int pn53x_SAMConfiguration(struct nfc_device *pnd, const pn532_sam_mode mode, int timeout);
int pn53x_PowerDown (struct nfc_device *pnd); int pn53x_PowerDown(struct nfc_device *pnd);
int pn53x_InListPassiveTarget (struct nfc_device *pnd, const pn53x_modulation pmInitModulation, int pn53x_InListPassiveTarget(struct nfc_device *pnd, const pn53x_modulation pmInitModulation,
const uint8_t szMaxTargets, const uint8_t *pbtInitiatorData, const uint8_t szMaxTargets, const uint8_t *pbtInitiatorData,
const size_t szInitiatorDataLen, uint8_t *pbtTargetsData, size_t *pszTargetsData, const size_t szInitiatorDataLen, uint8_t *pbtTargetsData, size_t *pszTargetsData,
int timeout); int timeout);
int pn53x_InDeselect (struct nfc_device *pnd, const uint8_t ui8Target); int pn53x_InDeselect(struct nfc_device *pnd, const uint8_t ui8Target);
int pn53x_InRelease (struct nfc_device *pnd, const uint8_t ui8Target); int pn53x_InRelease(struct nfc_device *pnd, const uint8_t ui8Target);
int pn53x_InAutoPoll (struct nfc_device *pnd, const pn53x_target_type *ppttTargetTypes, const size_t szTargetTypes, int pn53x_InAutoPoll(struct nfc_device *pnd, const pn53x_target_type *ppttTargetTypes, const size_t szTargetTypes,
const uint8_t btPollNr, const uint8_t btPeriod, nfc_target *pntTargets, const uint8_t btPollNr, const uint8_t btPeriod, nfc_target *pntTargets,
const int timeout); const int timeout);
int pn53x_InJumpForDEP (struct nfc_device *pnd, int pn53x_InJumpForDEP(struct nfc_device *pnd,
const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_mode ndm, const nfc_baud_rate nbr,
const uint8_t *pbtPassiveInitiatorData, const uint8_t *pbtPassiveInitiatorData,
const uint8_t *pbtNFCID3i, const uint8_t *pbtNFCID3i,
const uint8_t *pbtGB, const size_t szGB, const uint8_t *pbtGB, const size_t szGB,
nfc_target *pnt, nfc_target *pnt,
const int timeout); const int timeout);
int pn53x_TgInitAsTarget (struct nfc_device *pnd, pn53x_target_mode ptm, int pn53x_TgInitAsTarget(struct nfc_device *pnd, pn53x_target_mode ptm,
const uint8_t *pbtMifareParams, const uint8_t *pbtMifareParams,
const uint8_t *pbtTkt, size_t szTkt, const uint8_t *pbtTkt, size_t szTkt,
const uint8_t *pbtFeliCaParams, const uint8_t *pbtFeliCaParams,
const uint8_t *pbtNFCID3t, const uint8_t *pbtGB, const size_t szGB, const uint8_t *pbtNFCID3t, const uint8_t *pbtGB, const size_t szGB,
uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtModeByte, int timeout); uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtModeByte, int timeout);
// RFConfiguration // RFConfiguration
int pn53x_RFConfiguration__RF_field (struct nfc_device *pnd, bool bEnable); int pn53x_RFConfiguration__RF_field(struct nfc_device *pnd, bool bEnable);
int pn53x_RFConfiguration__Various_timings (struct nfc_device *pnd, const uint8_t fATR_RES_Timeout, const uint8_t fRetryTimeout); int pn53x_RFConfiguration__Various_timings(struct nfc_device *pnd, const uint8_t fATR_RES_Timeout, const uint8_t fRetryTimeout);
int pn53x_RFConfiguration__MaxRtyCOM (struct nfc_device *pnd, const uint8_t MaxRtyCOM); int pn53x_RFConfiguration__MaxRtyCOM(struct nfc_device *pnd, const uint8_t MaxRtyCOM);
int pn53x_RFConfiguration__MaxRetries (struct nfc_device *pnd, const uint8_t MxRtyATR, const uint8_t MxRtyPSL, const uint8_t MxRtyPassiveActivation); int pn53x_RFConfiguration__MaxRetries(struct nfc_device *pnd, const uint8_t MxRtyATR, const uint8_t MxRtyPSL, const uint8_t MxRtyPassiveActivation);
// Misc // Misc
int pn53x_check_ack_frame (struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen); int pn53x_check_ack_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen);
int pn53x_check_error_frame (struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen); int pn53x_check_error_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen);
int pn53x_build_frame (uint8_t *pbtFrame, size_t *pszFrame, const uint8_t *pbtData, const size_t szData); int pn53x_build_frame(uint8_t *pbtFrame, size_t *pszFrame, const uint8_t *pbtData, const size_t szData);
int pn53x_get_supported_modulation (nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt); int pn53x_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt);
int pn53x_get_supported_baud_rate (nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); int pn53x_get_supported_baud_rate(nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br);
int pn53x_get_information_about (nfc_device *pnd, char *buf, size_t buflen); int pn53x_get_information_about(nfc_device *pnd, char *buf, size_t buflen);
void pn53x_data_new (struct nfc_device *pnd, const struct pn53x_io *io); void pn53x_data_new(struct nfc_device *pnd, const struct pn53x_io *io);
void pn53x_data_free (struct nfc_device *pnd); void pn53x_data_free(struct nfc_device *pnd);
#endif // __NFC_CHIPS_PN53X_H__ #endif // __NFC_CHIPS_PN53X_H__

View file

@ -83,7 +83,7 @@
const struct pn53x_io acr122_pcsc_io; const struct pn53x_io acr122_pcsc_io;
char *acr122_pcsc_firmware (nfc_device *pnd); char *acr122_pcsc_firmware(nfc_device *pnd);
const char *supported_devices[] = { const char *supported_devices[] = {
"ACS ACR122", // ACR122U & Touchatag, last version "ACS ACR122", // ACR122U & Touchatag, last version
@ -106,10 +106,10 @@ static SCARDCONTEXT _SCardContext;
static int _iSCardContextRefCount = 0; static int _iSCardContextRefCount = 0;
static SCARDCONTEXT * static SCARDCONTEXT *
acr122_pcsc_get_scardcontext (void) acr122_pcsc_get_scardcontext(void)
{ {
if (_iSCardContextRefCount == 0) { if (_iSCardContextRefCount == 0) {
if (SCardEstablishContext (SCARD_SCOPE_USER, NULL, NULL, &_SCardContext) != SCARD_S_SUCCESS) if (SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &_SCardContext) != SCARD_S_SUCCESS)
return NULL; return NULL;
} }
_iSCardContextRefCount++; _iSCardContextRefCount++;
@ -118,12 +118,12 @@ acr122_pcsc_get_scardcontext (void)
} }
static void static void
acr122_pcsc_free_scardcontext (void) acr122_pcsc_free_scardcontext(void)
{ {
if (_iSCardContextRefCount) { if (_iSCardContextRefCount) {
_iSCardContextRefCount--; _iSCardContextRefCount--;
if (!_iSCardContextRefCount) { if (!_iSCardContextRefCount) {
SCardReleaseContext (_SCardContext); SCardReleaseContext(_SCardContext);
} }
} }
} }
@ -140,28 +140,28 @@ acr122_pcsc_free_scardcontext (void)
* @return true if succeeded, false otherwise. * @return true if succeeded, false otherwise.
*/ */
bool bool
acr122_pcsc_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound) acr122_pcsc_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound)
{ {
size_t szPos = 0; size_t szPos = 0;
char acDeviceNames[256 + 64 * PCSC_MAX_DEVICES]; char acDeviceNames[256 + 64 * PCSC_MAX_DEVICES];
size_t szDeviceNamesLen = sizeof (acDeviceNames); size_t szDeviceNamesLen = sizeof(acDeviceNames);
SCARDCONTEXT *pscc; SCARDCONTEXT *pscc;
bool bSupported; bool bSupported;
int i; int i;
// Clear the reader list // Clear the reader list
memset (acDeviceNames, '\0', szDeviceNamesLen); memset(acDeviceNames, '\0', szDeviceNamesLen);
*pszDeviceFound = 0; *pszDeviceFound = 0;
// Test if context succeeded // Test if context succeeded
if (!(pscc = acr122_pcsc_get_scardcontext ())) { if (!(pscc = acr122_pcsc_get_scardcontext())) {
log_put (LOG_CATEGORY, NFC_PRIORITY_WARN, "%s", "PCSC context not found (make sure PCSC daemon is running)."); log_put(LOG_CATEGORY, NFC_PRIORITY_WARN, "%s", "PCSC context not found (make sure PCSC daemon is running).");
return false; return false;
} }
// Retrieve the string array of all available pcsc readers // Retrieve the string array of all available pcsc readers
DWORD dwDeviceNamesLen = szDeviceNamesLen; DWORD dwDeviceNamesLen = szDeviceNamesLen;
if (SCardListReaders (*pscc, NULL, acDeviceNames, &dwDeviceNamesLen) != SCARD_S_SUCCESS) if (SCardListReaders(*pscc, NULL, acDeviceNames, &dwDeviceNamesLen) != SCARD_S_SUCCESS)
return false; return false;
while ((acDeviceNames[szPos] != '\0') && ((*pszDeviceFound) < connstrings_len)) { while ((acDeviceNames[szPos] != '\0') && ((*pszDeviceFound) < connstrings_len)) {
@ -170,22 +170,22 @@ acr122_pcsc_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t
bSupported = false; bSupported = false;
for (i = 0; supported_devices[i] && !bSupported; i++) { for (i = 0; supported_devices[i] && !bSupported; i++) {
int l = strlen (supported_devices[i]); int l = strlen(supported_devices[i]);
bSupported = 0 == strncmp (supported_devices[i], acDeviceNames + szPos, l); bSupported = 0 == strncmp(supported_devices[i], acDeviceNames + szPos, l);
} }
if (bSupported) { if (bSupported) {
// Supported ACR122 device found // Supported ACR122 device found
snprintf (connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s", ACR122_PCSC_DRIVER_NAME, acDeviceNames + szPos); snprintf(connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s", ACR122_PCSC_DRIVER_NAME, acDeviceNames + szPos);
(*pszDeviceFound)++; (*pszDeviceFound)++;
} else { } else {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "PCSC device [%s] is not NFC capable or not supported by libnfc.", acDeviceNames + szPos); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "PCSC device [%s] is not NFC capable or not supported by libnfc.", acDeviceNames + szPos);
} }
// Find next device name position // Find next device name position
while (acDeviceNames[szPos++] != '\0'); while (acDeviceNames[szPos++] != '\0');
} }
acr122_pcsc_free_scardcontext (); acr122_pcsc_free_scardcontext();
return true; return true;
} }
@ -195,48 +195,48 @@ struct acr122_pcsc_descriptor {
}; };
static int static int
acr122_pcsc_connstring_decode (const nfc_connstring connstring, struct acr122_pcsc_descriptor *desc) acr122_pcsc_connstring_decode(const nfc_connstring connstring, struct acr122_pcsc_descriptor *desc)
{ {
char *cs = malloc (strlen (connstring) + 1); char *cs = malloc(strlen(connstring) + 1);
if (!cs) { if (!cs) {
perror ("malloc"); perror("malloc");
return -1; return -1;
} }
strcpy (cs, connstring); strcpy(cs, connstring);
const char *driver_name = strtok (cs, ":"); const char *driver_name = strtok(cs, ":");
if (!driver_name) { if (!driver_name) {
// Parse error // Parse error
free (cs); free(cs);
return -1; return -1;
} }
if (0 != strcmp (driver_name, ACR122_PCSC_DRIVER_NAME)) { if (0 != strcmp(driver_name, ACR122_PCSC_DRIVER_NAME)) {
// Driver name does not match. // Driver name does not match.
free (cs); free(cs);
return 0; return 0;
} }
const char *device_name = strtok (NULL, ":"); const char *device_name = strtok(NULL, ":");
if (!device_name) { if (!device_name) {
// Only driver name was specified (or parsing error) // Only driver name was specified (or parsing error)
free (cs); free(cs);
return 1; return 1;
} }
strncpy (desc->pcsc_device_name, device_name, sizeof(desc->pcsc_device_name) - 1); strncpy(desc->pcsc_device_name, device_name, sizeof(desc->pcsc_device_name) - 1);
desc->pcsc_device_name[sizeof(desc->pcsc_device_name) - 1] = '\0'; desc->pcsc_device_name[sizeof(desc->pcsc_device_name) - 1] = '\0';
free (cs); free(cs);
return 2; return 2;
free (cs); free(cs);
return 3; return 3;
} }
nfc_device * nfc_device *
acr122_pcsc_open (const nfc_connstring connstring) acr122_pcsc_open(const nfc_connstring connstring)
{ {
struct acr122_pcsc_descriptor ndd; struct acr122_pcsc_descriptor ndd;
int connstring_decode_level = acr122_pcsc_connstring_decode (connstring, &ndd); int connstring_decode_level = acr122_pcsc_connstring_decode(connstring, &ndd);
if (connstring_decode_level < 1) { if (connstring_decode_level < 1) {
return NULL; return NULL;
@ -249,7 +249,7 @@ acr122_pcsc_open (const nfc_connstring connstring)
acr122_pcsc_probe(&fullconnstring, 1, &szDeviceFound); acr122_pcsc_probe(&fullconnstring, 1, &szDeviceFound);
if (szDeviceFound < 1) if (szDeviceFound < 1)
return NULL; return NULL;
connstring_decode_level = acr122_pcsc_connstring_decode (fullconnstring, &ndd); connstring_decode_level = acr122_pcsc_connstring_decode(fullconnstring, &ndd);
if (connstring_decode_level < 2) { if (connstring_decode_level < 2) {
return NULL; return NULL;
} }
@ -259,82 +259,82 @@ acr122_pcsc_open (const nfc_connstring connstring)
if (strlen(ndd.pcsc_device_name) < 5) { // We can assume it's a reader ID as pcsc_name always ends with "NN NN" if (strlen(ndd.pcsc_device_name) < 5) { // We can assume it's a reader ID as pcsc_name always ends with "NN NN"
// Device was not specified, only ID, retrieve it // Device was not specified, only ID, retrieve it
size_t index; size_t index;
if (sscanf (ndd.pcsc_device_name, "%lu", &index) != 1) if (sscanf(ndd.pcsc_device_name, "%lu", &index) != 1)
return NULL; return NULL;
nfc_connstring *ncs = malloc (sizeof (nfc_connstring) * (index + 1)); nfc_connstring *ncs = malloc(sizeof(nfc_connstring) * (index + 1));
size_t szDeviceFound; size_t szDeviceFound;
acr122_pcsc_probe(ncs, index + 1, &szDeviceFound); acr122_pcsc_probe(ncs, index + 1, &szDeviceFound);
if (szDeviceFound < index + 1) if (szDeviceFound < index + 1)
return NULL; return NULL;
strncpy(fullconnstring, ncs[index], sizeof(nfc_connstring)); strncpy(fullconnstring, ncs[index], sizeof(nfc_connstring));
free(ncs); free(ncs);
connstring_decode_level = acr122_pcsc_connstring_decode (fullconnstring, &ndd); connstring_decode_level = acr122_pcsc_connstring_decode(fullconnstring, &ndd);
if (connstring_decode_level < 2) { if (connstring_decode_level < 2) {
return NULL; return NULL;
} }
} }
char *pcFirmware; char *pcFirmware;
nfc_device *pnd = nfc_device_new (fullconnstring); nfc_device *pnd = nfc_device_new(fullconnstring);
pnd->driver_data = malloc (sizeof (struct acr122_pcsc_data)); pnd->driver_data = malloc(sizeof(struct acr122_pcsc_data));
// Alloc and init chip's data // Alloc and init chip's data
pn53x_data_new (pnd, &acr122_pcsc_io); pn53x_data_new(pnd, &acr122_pcsc_io);
SCARDCONTEXT *pscc; SCARDCONTEXT *pscc;
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Attempt to open %s", ndd.pcsc_device_name); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Attempt to open %s", ndd.pcsc_device_name);
// Test if context succeeded // Test if context succeeded
if (!(pscc = acr122_pcsc_get_scardcontext ())) if (!(pscc = acr122_pcsc_get_scardcontext()))
goto error; goto error;
// Test if we were able to connect to the "emulator" card // Test if we were able to connect to the "emulator" card
if (SCardConnect (*pscc, ndd.pcsc_device_name, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &(DRIVER_DATA (pnd)->hCard), (void *) & (DRIVER_DATA (pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { if (SCardConnect(*pscc, ndd.pcsc_device_name, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &(DRIVER_DATA(pnd)->hCard), (void *) & (DRIVER_DATA(pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) {
// Connect to ACR122 firmware version >2.0 // Connect to ACR122 firmware version >2.0
if (SCardConnect (*pscc, ndd.pcsc_device_name, SCARD_SHARE_DIRECT, 0, &(DRIVER_DATA (pnd)->hCard), (void *) & (DRIVER_DATA (pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { if (SCardConnect(*pscc, ndd.pcsc_device_name, SCARD_SHARE_DIRECT, 0, &(DRIVER_DATA(pnd)->hCard), (void *) & (DRIVER_DATA(pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) {
// We can not connect to this device. // We can not connect to this device.
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "PCSC connect failed"); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "PCSC connect failed");
goto error; goto error;
} }
} }
// Configure I/O settings for card communication // Configure I/O settings for card communication
DRIVER_DATA (pnd)->ioCard.cbPciLength = sizeof (SCARD_IO_REQUEST); DRIVER_DATA(pnd)->ioCard.cbPciLength = sizeof(SCARD_IO_REQUEST);
// Retrieve the current firmware version // Retrieve the current firmware version
pcFirmware = acr122_pcsc_firmware (pnd); pcFirmware = acr122_pcsc_firmware(pnd);
if (strstr (pcFirmware, FIRMWARE_TEXT) != NULL) { if (strstr(pcFirmware, FIRMWARE_TEXT) != NULL) {
// Done, we found the reader we are looking for // Done, we found the reader we are looking for
snprintf (pnd->name, sizeof (pnd->name), "%s / %s", ndd.pcsc_device_name, pcFirmware); snprintf(pnd->name, sizeof(pnd->name), "%s / %s", ndd.pcsc_device_name, pcFirmware);
// 50: empirical tuning on Touchatag // 50: empirical tuning on Touchatag
// 46: empirical tuning on ACR122U // 46: empirical tuning on ACR122U
CHIP_DATA (pnd)->timer_correction = 50; CHIP_DATA(pnd)->timer_correction = 50;
pnd->driver = &acr122_pcsc_driver; pnd->driver = &acr122_pcsc_driver;
pn53x_init (pnd); pn53x_init(pnd);
return pnd; return pnd;
} }
error: error:
nfc_device_free (pnd); nfc_device_free(pnd);
return NULL; return NULL;
} }
void void
acr122_pcsc_close (nfc_device *pnd) acr122_pcsc_close(nfc_device *pnd)
{ {
SCardDisconnect (DRIVER_DATA (pnd)->hCard, SCARD_LEAVE_CARD); SCardDisconnect(DRIVER_DATA(pnd)->hCard, SCARD_LEAVE_CARD);
acr122_pcsc_free_scardcontext (); acr122_pcsc_free_scardcontext();
pn53x_data_free (pnd); pn53x_data_free(pnd);
nfc_device_free (pnd); nfc_device_free(pnd);
} }
int int
acr122_pcsc_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) acr122_pcsc_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout)
{ {
// FIXME: timeout is not handled // FIXME: timeout is not handled
(void) timeout; (void) timeout;
@ -348,14 +348,14 @@ acr122_pcsc_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData,
// Prepare and transmit the send buffer // Prepare and transmit the send buffer
const size_t szTxBuf = szData + 6; const size_t szTxBuf = szData + 6;
uint8_t abtTxBuf[ACR122_PCSC_WRAP_LEN + ACR122_PCSC_COMMAND_LEN] = { 0xFF, 0x00, 0x00, 0x00, szData + 1, 0xD4 }; uint8_t abtTxBuf[ACR122_PCSC_WRAP_LEN + ACR122_PCSC_COMMAND_LEN] = { 0xFF, 0x00, 0x00, 0x00, szData + 1, 0xD4 };
memcpy (abtTxBuf + 6, pbtData, szData); memcpy(abtTxBuf + 6, pbtData, szData);
LOG_HEX ("TX", abtTxBuf, szTxBuf); LOG_HEX("TX", abtTxBuf, szTxBuf);
DRIVER_DATA (pnd)->szRx = 0; DRIVER_DATA(pnd)->szRx = 0;
DWORD dwRxLen = sizeof (DRIVER_DATA (pnd)->abtRx); DWORD dwRxLen = sizeof(DRIVER_DATA(pnd)->abtRx);
if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) {
/* /*
* In this communication mode, we directly have the response from the * In this communication mode, we directly have the response from the
* PN532. Save it in the driver data structure so that it can be retrieved * PN532. Save it in the driver data structure so that it can be retrieved
@ -367,7 +367,7 @@ acr122_pcsc_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData,
* This state is generaly reached when the ACR122 has no target in it's * This state is generaly reached when the ACR122 has no target in it's
* field. * field.
*/ */
if (SCardControl (DRIVER_DATA (pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtTxBuf, szTxBuf, DRIVER_DATA (pnd)->abtRx, ACR122_PCSC_RESPONSE_LEN, &dwRxLen) != SCARD_S_SUCCESS) { if (SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtTxBuf, szTxBuf, DRIVER_DATA(pnd)->abtRx, ACR122_PCSC_RESPONSE_LEN, &dwRxLen) != SCARD_S_SUCCESS) {
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -376,13 +376,13 @@ acr122_pcsc_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData,
* In T=0 mode, we receive an acknoledge from the MCU, in T=1 mode, we * In T=0 mode, we receive an acknoledge from the MCU, in T=1 mode, we
* receive the response from the PN532. * receive the response from the PN532.
*/ */
if (SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtTxBuf, szTxBuf, NULL, DRIVER_DATA (pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { if (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtTxBuf, szTxBuf, NULL, DRIVER_DATA(pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) {
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
} }
if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) {
/* /*
* Check the MCU response * Check the MCU response
*/ */
@ -393,19 +393,19 @@ acr122_pcsc_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData,
return pnd->last_error; return pnd->last_error;
} }
// Check if the operation was successful, so an answer is available // Check if the operation was successful, so an answer is available
if (DRIVER_DATA (pnd)->abtRx[0] == SCARD_OPERATION_ERROR) { if (DRIVER_DATA(pnd)->abtRx[0] == SCARD_OPERATION_ERROR) {
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
} else { } else {
DRIVER_DATA (pnd)->szRx = dwRxLen; DRIVER_DATA(pnd)->szRx = dwRxLen;
} }
return NFC_SUCCESS; return NFC_SUCCESS;
} }
int int
acr122_pcsc_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout) acr122_pcsc_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout)
{ {
// FIXME: timeout is not handled // FIXME: timeout is not handled
(void) timeout; (void) timeout;
@ -413,53 +413,53 @@ acr122_pcsc_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int
int len; int len;
uint8_t abtRxCmd[5] = { 0xFF, 0xC0, 0x00, 0x00 }; uint8_t abtRxCmd[5] = { 0xFF, 0xC0, 0x00, 0x00 };
if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) {
/* /*
* Retrieve the PN532 response. * Retrieve the PN532 response.
*/ */
DWORD dwRxLen = sizeof (DRIVER_DATA (pnd)->abtRx); DWORD dwRxLen = sizeof(DRIVER_DATA(pnd)->abtRx);
abtRxCmd[4] = DRIVER_DATA (pnd)->abtRx[1]; abtRxCmd[4] = DRIVER_DATA(pnd)->abtRx[1];
if (SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtRxCmd, sizeof (abtRxCmd), NULL, DRIVER_DATA (pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { if (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtRxCmd, sizeof(abtRxCmd), NULL, DRIVER_DATA(pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) {
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
DRIVER_DATA (pnd)->szRx = dwRxLen; DRIVER_DATA(pnd)->szRx = dwRxLen;
} else { } else {
/* /*
* We already have the PN532 answer, it was saved by acr122_pcsc_send(). * We already have the PN532 answer, it was saved by acr122_pcsc_send().
*/ */
} }
LOG_HEX ("RX", DRIVER_DATA (pnd)->abtRx, DRIVER_DATA (pnd)->szRx); LOG_HEX("RX", DRIVER_DATA(pnd)->abtRx, DRIVER_DATA(pnd)->szRx);
// Make sure we have an emulated answer that fits the return buffer // Make sure we have an emulated answer that fits the return buffer
if (DRIVER_DATA (pnd)->szRx < 4 || (DRIVER_DATA (pnd)->szRx - 4) > szData) { if (DRIVER_DATA(pnd)->szRx < 4 || (DRIVER_DATA(pnd)->szRx - 4) > szData) {
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
// Wipe out the 4 APDU emulation bytes: D5 4B .. .. .. 90 00 // Wipe out the 4 APDU emulation bytes: D5 4B .. .. .. 90 00
len = DRIVER_DATA (pnd)->szRx - 4; len = DRIVER_DATA(pnd)->szRx - 4;
memcpy (pbtData, DRIVER_DATA (pnd)->abtRx + 2, len); memcpy(pbtData, DRIVER_DATA(pnd)->abtRx + 2, len);
return len; return len;
} }
char * char *
acr122_pcsc_firmware (nfc_device *pnd) acr122_pcsc_firmware(nfc_device *pnd)
{ {
uint8_t abtGetFw[5] = { 0xFF, 0x00, 0x48, 0x00, 0x00 }; uint8_t abtGetFw[5] = { 0xFF, 0x00, 0x48, 0x00, 0x00 };
uint32_t uiResult; uint32_t uiResult;
static char abtFw[11]; static char abtFw[11];
DWORD dwFwLen = sizeof (abtFw); DWORD dwFwLen = sizeof(abtFw);
memset (abtFw, 0x00, sizeof (abtFw)); memset(abtFw, 0x00, sizeof(abtFw));
if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) {
uiResult = SCardControl (DRIVER_DATA (pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtGetFw, sizeof (abtGetFw), (uint8_t *) abtFw, dwFwLen - 1, &dwFwLen); uiResult = SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtGetFw, sizeof(abtGetFw), (uint8_t *) abtFw, dwFwLen - 1, &dwFwLen);
} else { } else {
uiResult = SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtGetFw, sizeof (abtGetFw), NULL, (uint8_t *) abtFw, &dwFwLen); uiResult = SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtGetFw, sizeof(abtGetFw), NULL, (uint8_t *) abtFw, &dwFwLen);
} }
if (uiResult != SCARD_S_SUCCESS) { if (uiResult != SCARD_S_SUCCESS) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "No ACR122 firmware received, Error: %08x", uiResult); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "No ACR122 firmware received, Error: %08x", uiResult);
} }
return abtFw; return abtFw;
@ -467,16 +467,16 @@ acr122_pcsc_firmware (nfc_device *pnd)
#if 0 #if 0
bool bool
acr122_pcsc_led_red (nfc_device *pnd, bool bOn) acr122_pcsc_led_red(nfc_device *pnd, bool bOn)
{ {
uint8_t abtLed[9] = { 0xFF, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x00 }; uint8_t abtLed[9] = { 0xFF, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x00 };
uint8_t abtBuf[2]; uint8_t abtBuf[2];
DWORD dwBufLen = sizeof (abtBuf); DWORD dwBufLen = sizeof(abtBuf);
(void) bOn; (void) bOn;
if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) {
return (SCardControl (DRIVER_DATA (pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtLed, sizeof (abtLed), abtBuf, dwBufLen, &dwBufLen) == SCARD_S_SUCCESS); return (SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtLed, sizeof(abtLed), abtBuf, dwBufLen, &dwBufLen) == SCARD_S_SUCCESS);
} else { } else {
return (SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtLed, sizeof (abtLed), NULL, abtBuf, &dwBufLen) == SCARD_S_SUCCESS); return (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtLed, sizeof(abtLed), NULL, abtBuf, &dwBufLen) == SCARD_S_SUCCESS);
} }
} }
#endif #endif

View file

@ -28,13 +28,13 @@
# include <nfc/nfc-types.h> # include <nfc/nfc-types.h>
bool acr122_pcsc_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound); bool acr122_pcsc_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound);
// Functions used by developer to handle connection to this device // Functions used by developer to handle connection to this device
nfc_device *acr122_pcsc_open (const nfc_connstring connstring); nfc_device *acr122_pcsc_open(const nfc_connstring connstring);
int acr122_pcsc_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); int acr122_pcsc_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout);
int acr122_pcsc_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout); int acr122_pcsc_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout);
void acr122_pcsc_close (nfc_device *pnd); void acr122_pcsc_close(nfc_device *pnd);
extern const struct nfc_driver acr122_pcsc_driver; extern const struct nfc_driver acr122_pcsc_driver;

View file

@ -99,20 +99,20 @@ struct acr122_usb_data {
}; };
const struct pn53x_io acr122_usb_io; const struct pn53x_io acr122_usb_io;
bool acr122_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len); bool acr122_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len);
int acr122_usb_init (nfc_device *pnd); int acr122_usb_init(nfc_device *pnd);
int acr122_usb_ack (nfc_device *pnd); int acr122_usb_ack(nfc_device *pnd);
static int static int
acr122_usb_bulk_read (struct acr122_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout) acr122_usb_bulk_read(struct acr122_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout)
{ {
int res = usb_bulk_read (data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout); int res = usb_bulk_read(data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout);
if (res > 0) { if (res > 0) {
LOG_HEX ("RX", abtRx, res); LOG_HEX("RX", abtRx, res);
} else if (res < 0) { } else if (res < 0) {
if (res != -USB_TIMEDOUT) { if (res != -USB_TIMEDOUT) {
res = NFC_EIO; res = NFC_EIO;
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror(res));
} else { } else {
res = NFC_ETIMEOUT; res = NFC_ETIMEOUT;
} }
@ -121,17 +121,17 @@ acr122_usb_bulk_read (struct acr122_usb_data *data, uint8_t abtRx[], const size_
} }
static int static int
acr122_usb_bulk_write (struct acr122_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout) acr122_usb_bulk_write(struct acr122_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout)
{ {
LOG_HEX ("TX", abtTx, szTx); LOG_HEX("TX", abtTx, szTx);
int res = usb_bulk_write (data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout); int res = usb_bulk_write(data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout);
if (res > 0) { if (res > 0) {
// HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details
if ((res % data->uiMaxPacketSize) == 0) { if ((res % data->uiMaxPacketSize) == 0) {
usb_bulk_write (data->pudh, data->uiEndPointOut, "\0", 0, timeout); usb_bulk_write(data->pudh, data->uiEndPointOut, "\0", 0, timeout);
} }
} else if (res < 0) { } else if (res < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror(res));
if (res == -USB_TIMEDOUT) { if (res == -USB_TIMEDOUT) {
res = NFC_ETIMEOUT; res = NFC_ETIMEOUT;
} else { } else {
@ -154,9 +154,9 @@ const struct acr122_usb_supported_device acr122_usb_supported_devices[] = {
}; };
static acr122_usb_model static acr122_usb_model
acr122_usb_get_device_model (uint16_t vendor_id, uint16_t product_id) acr122_usb_get_device_model(uint16_t vendor_id, uint16_t product_id)
{ {
for (size_t n = 0; n < sizeof (acr122_usb_supported_devices) / sizeof (struct acr122_usb_supported_device); n++) { for (size_t n = 0; n < sizeof(acr122_usb_supported_devices) / sizeof(struct acr122_usb_supported_device); n++) {
if ((vendor_id == acr122_usb_supported_devices[n].vendor_id) && if ((vendor_id == acr122_usb_supported_devices[n].vendor_id) &&
(product_id == acr122_usb_supported_devices[n].product_id)) (product_id == acr122_usb_supported_devices[n].product_id))
return acr122_usb_supported_devices[n].model; return acr122_usb_supported_devices[n].model;
@ -167,7 +167,7 @@ acr122_usb_get_device_model (uint16_t vendor_id, uint16_t product_id)
// Find transfer endpoints for bulk transfers // Find transfer endpoints for bulk transfers
static void static void
acr122_usb_get_end_points (struct usb_device *dev, struct acr122_usb_data *data) acr122_usb_get_end_points(struct usb_device *dev, struct acr122_usb_data *data)
{ {
uint32_t uiIndex; uint32_t uiIndex;
uint32_t uiEndPoint; uint32_t uiEndPoint;
@ -196,23 +196,23 @@ acr122_usb_get_end_points (struct usb_device *dev, struct acr122_usb_data *data)
} }
bool bool
acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound) acr122_usb_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound)
{ {
usb_init (); usb_init();
int res; int res;
// usb_find_busses will find all of the busses on the system. Returns the // usb_find_busses will find all of the busses on the system. Returns the
// number of changes since previous call to this function (total of new // number of changes since previous call to this function (total of new
// busses and busses removed). // busses and busses removed).
if ((res = usb_find_busses () < 0)) { if ((res = usb_find_busses() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror(res));
return false; return false;
} }
// usb_find_devices will find all of the devices on each bus. This should be // usb_find_devices will find all of the devices on each bus. This should be
// called after usb_find_busses. Returns the number of changes since the // called after usb_find_busses. Returns the number of changes since the
// previous call to this function (total of new device and devices removed). // previous call to this function (total of new device and devices removed).
if ((res = usb_find_devices () < 0)) { if ((res = usb_find_devices() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror(res));
return false; return false;
} }
@ -220,11 +220,11 @@ acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *
uint32_t uiBusIndex = 0; uint32_t uiBusIndex = 0;
struct usb_bus *bus; struct usb_bus *bus;
for (bus = usb_get_busses (); bus; bus = bus->next) { for (bus = usb_get_busses(); bus; bus = bus->next) {
struct usb_device *dev; struct usb_device *dev;
for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) { for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) {
for (size_t n = 0; n < sizeof (acr122_usb_supported_devices) / sizeof (struct acr122_usb_supported_device); n++) { for (size_t n = 0; n < sizeof(acr122_usb_supported_devices) / sizeof(struct acr122_usb_supported_device); n++) {
if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) &&
(acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) {
// Make sure there are 2 endpoints available // Make sure there are 2 endpoints available
@ -238,13 +238,13 @@ acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *
continue; continue;
} }
usb_dev_handle *udev = usb_open (dev); usb_dev_handle *udev = usb_open(dev);
// Set configuration // Set configuration
// acr122_usb_get_usb_device_name (dev, udev, pnddDevices[*pszDeviceFound].acDevice, sizeof (pnddDevices[*pszDeviceFound].acDevice)); // acr122_usb_get_usb_device_name (dev, udev, pnddDevices[*pszDeviceFound].acDevice, sizeof (pnddDevices[*pszDeviceFound].acDevice));
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "device found: Bus %s Device %s", bus->dirname, dev->filename); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "device found: Bus %s Device %s", bus->dirname, dev->filename);
usb_close (udev); usb_close(udev);
snprintf (connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%s", ACR122_USB_DRIVER_NAME, bus->dirname, dev->filename); snprintf(connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%s", ACR122_USB_DRIVER_NAME, bus->dirname, dev->filename);
(*pszDeviceFound)++; (*pszDeviceFound)++;
// Test if we reach the maximum "wanted" devices // Test if we reach the maximum "wanted" devices
if ((*pszDeviceFound) == connstrings_len) { if ((*pszDeviceFound) == connstrings_len) {
@ -264,51 +264,51 @@ struct acr122_usb_descriptor {
}; };
static int static int
acr122_usb_connstring_decode (const nfc_connstring connstring, struct acr122_usb_descriptor *desc) acr122_usb_connstring_decode(const nfc_connstring connstring, struct acr122_usb_descriptor *desc)
{ {
int n = strlen (connstring) + 1; int n = strlen(connstring) + 1;
char *driver_name = malloc (n); char *driver_name = malloc(n);
char *dirname = malloc (n); char *dirname = malloc(n);
char *filename = malloc (n); char *filename = malloc(n);
driver_name[0] = '\0'; driver_name[0] = '\0';
int res = sscanf (connstring, "%[^:]:%[^:]:%[^:]", driver_name, dirname, filename); int res = sscanf(connstring, "%[^:]:%[^:]:%[^:]", driver_name, dirname, filename);
if (!res || (0 != strcmp (driver_name, ACR122_USB_DRIVER_NAME))) { if (!res || (0 != strcmp(driver_name, ACR122_USB_DRIVER_NAME))) {
// Driver name does not match. // Driver name does not match.
res = 0; res = 0;
} else { } else {
desc->dirname = strdup (dirname); desc->dirname = strdup(dirname);
desc->filename = strdup (filename); desc->filename = strdup(filename);
} }
free (driver_name); free(driver_name);
free (dirname); free(dirname);
free (filename); free(filename);
return res; return res;
} }
bool bool
acr122_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len) acr122_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len)
{ {
*buffer = '\0'; *buffer = '\0';
if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) { if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) {
if (udev) { if (udev) {
usb_get_string_simple (udev, dev->descriptor.iManufacturer, buffer, len); usb_get_string_simple(udev, dev->descriptor.iManufacturer, buffer, len);
if (strlen (buffer) > 0) if (strlen(buffer) > 0)
strcpy (buffer + strlen (buffer), " / "); strcpy(buffer + strlen(buffer), " / ");
usb_get_string_simple (udev, dev->descriptor.iProduct, buffer + strlen (buffer), len - strlen (buffer)); usb_get_string_simple(udev, dev->descriptor.iProduct, buffer + strlen(buffer), len - strlen(buffer));
} }
} }
if (!*buffer) { if (!*buffer) {
for (size_t n = 0; n < sizeof (acr122_usb_supported_devices) / sizeof (struct acr122_usb_supported_device); n++) { for (size_t n = 0; n < sizeof(acr122_usb_supported_devices) / sizeof(struct acr122_usb_supported_device); n++) {
if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) &&
(acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) {
strncpy (buffer, acr122_usb_supported_devices[n].name, len); strncpy(buffer, acr122_usb_supported_devices[n].name, len);
return true; return true;
} }
} }
@ -318,12 +318,12 @@ acr122_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, ch
} }
static nfc_device * static nfc_device *
acr122_usb_open (const nfc_connstring connstring) acr122_usb_open(const nfc_connstring connstring)
{ {
nfc_device *pnd = NULL; nfc_device *pnd = NULL;
struct acr122_usb_descriptor desc = { NULL, NULL }; struct acr122_usb_descriptor desc = { NULL, NULL };
int connstring_decode_level = acr122_usb_connstring_decode (connstring, &desc); int connstring_decode_level = acr122_usb_connstring_decode(connstring, &desc);
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring);
if (connstring_decode_level < 1) { if (connstring_decode_level < 1) {
goto free_mem; goto free_mem;
} }
@ -336,88 +336,88 @@ acr122_usb_open (const nfc_connstring connstring)
struct usb_bus *bus; struct usb_bus *bus;
struct usb_device *dev; struct usb_device *dev;
usb_init (); usb_init();
int res; int res;
// usb_find_busses will find all of the busses on the system. Returns the // usb_find_busses will find all of the busses on the system. Returns the
// number of changes since previous call to this function (total of new // number of changes since previous call to this function (total of new
// busses and busses removed). // busses and busses removed).
if ((res = usb_find_busses () < 0)) { if ((res = usb_find_busses() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror(res));
goto free_mem; goto free_mem;
} }
// usb_find_devices will find all of the devices on each bus. This should be // usb_find_devices will find all of the devices on each bus. This should be
// called after usb_find_busses. Returns the number of changes since the // called after usb_find_busses. Returns the number of changes since the
// previous call to this function (total of new device and devices removed). // previous call to this function (total of new device and devices removed).
if ((res = usb_find_devices () < 0)) { if ((res = usb_find_devices() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror(res));
goto free_mem; goto free_mem;
} }
for (bus = usb_get_busses (); bus; bus = bus->next) { for (bus = usb_get_busses(); bus; bus = bus->next) {
if (connstring_decode_level > 1) { if (connstring_decode_level > 1) {
// A specific bus have been specified // A specific bus have been specified
if (0 != strcmp (bus->dirname, desc.dirname)) if (0 != strcmp(bus->dirname, desc.dirname))
continue; continue;
} }
for (dev = bus->devices; dev; dev = dev->next) { for (dev = bus->devices; dev; dev = dev->next) {
if (connstring_decode_level > 2) { if (connstring_decode_level > 2) {
// A specific dev have been specified // A specific dev have been specified
if (0 != strcmp (dev->filename, desc.filename)) if (0 != strcmp(dev->filename, desc.filename))
continue; continue;
} }
// Open the USB device // Open the USB device
data.pudh = usb_open (dev); data.pudh = usb_open(dev);
// Reset device // Reset device
usb_reset (data.pudh); usb_reset(data.pudh);
// Retrieve end points // Retrieve end points
acr122_usb_get_end_points (dev, &data); acr122_usb_get_end_points(dev, &data);
// Claim interface // Claim interface
res = usb_claim_interface (data.pudh, 0); res = usb_claim_interface(data.pudh, 0);
if (res < 0) { if (res < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror(res));
usb_close (data.pudh); usb_close(data.pudh);
// we failed to use the specified device // we failed to use the specified device
goto free_mem; goto free_mem;
} }
res = usb_set_altinterface (data.pudh, 0); res = usb_set_altinterface(data.pudh, 0);
if (res < 0) { if (res < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set alternate setting on USB interface (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set alternate setting on USB interface (%s)", _usb_strerror(res));
usb_close (data.pudh); usb_close(data.pudh);
// we failed to use the specified device // we failed to use the specified device
goto free_mem; goto free_mem;
} }
data.model = acr122_usb_get_device_model (dev->descriptor.idVendor, dev->descriptor.idProduct); data.model = acr122_usb_get_device_model(dev->descriptor.idVendor, dev->descriptor.idProduct);
// Allocate memory for the device info and specification, fill it and return the info // Allocate memory for the device info and specification, fill it and return the info
pnd = nfc_device_new (connstring); pnd = nfc_device_new(connstring);
acr122_usb_get_usb_device_name (dev, data.pudh, pnd->name, sizeof (pnd->name)); acr122_usb_get_usb_device_name(dev, data.pudh, pnd->name, sizeof(pnd->name));
pnd->driver_data = malloc(sizeof(struct acr122_usb_data)); pnd->driver_data = malloc(sizeof(struct acr122_usb_data));
*DRIVER_DATA (pnd) = data; *DRIVER_DATA(pnd) = data;
// Alloc and init chip's data // Alloc and init chip's data
pn53x_data_new (pnd, &acr122_usb_io); pn53x_data_new(pnd, &acr122_usb_io);
switch (DRIVER_DATA (pnd)->model) { switch (DRIVER_DATA(pnd)->model) {
// empirical tuning // empirical tuning
case ACR122: case ACR122:
CHIP_DATA (pnd)->timer_correction = 46; CHIP_DATA(pnd)->timer_correction = 46;
break; break;
case TOUCHATAG: case TOUCHATAG:
CHIP_DATA (pnd)->timer_correction = 50; CHIP_DATA(pnd)->timer_correction = 50;
break; break;
case UNKNOWN: case UNKNOWN:
break; break;
} }
pnd->driver = &acr122_usb_driver; pnd->driver = &acr122_usb_driver;
if (acr122_usb_init (pnd) < 0) { if (acr122_usb_init(pnd) < 0) {
usb_close (data.pudh); usb_close(data.pudh);
goto error; goto error;
} }
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
goto free_mem; goto free_mem;
} }
} }
@ -426,31 +426,31 @@ acr122_usb_open (const nfc_connstring connstring)
error: error:
// Free allocated structure on error. // Free allocated structure on error.
nfc_device_free (pnd); nfc_device_free(pnd);
pnd = NULL; pnd = NULL;
free_mem: free_mem:
free (desc.dirname); free(desc.dirname);
free (desc.filename); free(desc.filename);
return pnd; return pnd;
} }
static void static void
acr122_usb_close (nfc_device *pnd) acr122_usb_close(nfc_device *pnd)
{ {
acr122_usb_ack (pnd); acr122_usb_ack(pnd);
pn53x_idle (pnd); pn53x_idle(pnd);
int res; int res;
if ((res = usb_release_interface (DRIVER_DATA (pnd)->pudh, 0)) < 0) { if ((res = usb_release_interface(DRIVER_DATA(pnd)->pudh, 0)) < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror(res));
} }
if ((res = usb_close (DRIVER_DATA (pnd)->pudh)) < 0) { if ((res = usb_close(DRIVER_DATA(pnd)->pudh)) < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror(res));
} }
pn53x_data_free (pnd); pn53x_data_free(pnd);
nfc_device_free (pnd); nfc_device_free(pnd);
} }
/* /*
@ -505,7 +505,7 @@ RDR_to_PC_DataBlock SW: more data: 8 bytes
// FIXME ACR122_USB_BUFFER_LEN don't have the correct lenght value // FIXME ACR122_USB_BUFFER_LEN don't have the correct lenght value
#define ACR122_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) #define ACR122_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD)
static int static int
acr122_build_frame_from_apdu (uint8_t **frame, const uint8_t *apdu, const size_t apdu_len) acr122_build_frame_from_apdu(uint8_t **frame, const uint8_t *apdu, const size_t apdu_len)
{ {
static uint8_t abtFrame[ACR122_USB_BUFFER_LEN] = { static uint8_t abtFrame[ACR122_USB_BUFFER_LEN] = {
0x6b, // PC_to_RDR_Escape 0x6b, // PC_to_RDR_Escape
@ -516,13 +516,13 @@ acr122_build_frame_from_apdu (uint8_t **frame, const uint8_t *apdu, const size_t
return NFC_EINVARG; return NFC_EINVARG;
abtFrame[1] = apdu_len; abtFrame[1] = apdu_len;
memcpy (abtFrame + 10, apdu, apdu_len); memcpy(abtFrame + 10, apdu, apdu_len);
*frame = abtFrame; *frame = abtFrame;
return (apdu_len + 10); return (apdu_len + 10);
} }
static int static int
acr122_build_frame_from_tama (uint8_t **frame, const uint8_t *tama, const size_t tama_len) acr122_build_frame_from_tama(uint8_t **frame, const uint8_t *tama, const size_t tama_len)
{ {
static uint8_t abtFrame[ACR122_USB_BUFFER_LEN] = { static uint8_t abtFrame[ACR122_USB_BUFFER_LEN] = {
0x6b, // PC_to_RDR_Escape 0x6b, // PC_to_RDR_Escape
@ -538,22 +538,22 @@ acr122_build_frame_from_tama (uint8_t **frame, const uint8_t *tama, const size_t
abtFrame[1] = tama_len + 6; abtFrame[1] = tama_len + 6;
abtFrame[14] = tama_len + 1; abtFrame[14] = tama_len + 1;
memcpy (abtFrame + 16, tama, tama_len); memcpy(abtFrame + 16, tama, tama_len);
*frame = abtFrame; *frame = abtFrame;
return (tama_len + 16); return (tama_len + 16);
} }
int int
acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) acr122_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout)
{ {
uint8_t *frame; uint8_t *frame;
int res; int res;
if ((res = acr122_build_frame_from_tama (&frame, pbtData, szData)) < 0) { if ((res = acr122_build_frame_from_tama(&frame, pbtData, szData)) < 0) {
pnd->last_error = NFC_EINVARG; pnd->last_error = NFC_EINVARG;
return pnd->last_error; return pnd->last_error;
} }
if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), frame, res, timeout)) < 0) { if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), frame, res, timeout)) < 0) {
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
@ -562,7 +562,7 @@ acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, c
#define USB_TIMEOUT_PER_PASS 200 #define USB_TIMEOUT_PER_PASS 200
int int
acr122_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) acr122_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout)
{ {
off_t offset = 0; off_t offset = 0;
@ -589,12 +589,12 @@ read:
} }
} }
res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), usb_timeout); res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), usb_timeout);
if (res == NFC_ETIMEOUT) { if (res == NFC_ETIMEOUT) {
if (DRIVER_DATA (pnd)->abort_flag) { if (DRIVER_DATA(pnd)->abort_flag) {
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
acr122_usb_ack (pnd); acr122_usb_ack(pnd);
pnd->last_error = NFC_EOPABORTED; pnd->last_error = NFC_EOPABORTED;
return pnd->last_error; return pnd->last_error;
} else { } else {
@ -610,7 +610,7 @@ read:
} }
if (abtRxBuf[offset] != 0x83) { if (abtRxBuf[offset] != 0x83) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame header mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame header mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -618,21 +618,21 @@ read:
size_t len = abtRxBuf[offset++]; size_t len = abtRxBuf[offset++];
if (len < 4) { if (len < 4) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Too small reply"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Too small reply");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
len -= 4; len -= 4;
if (len > szDataLen) { if (len > szDataLen) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len);
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
const uint8_t acr122_preamble[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x81, 0x00 }; const uint8_t acr122_preamble[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x81, 0x00 };
if (0 != (memcmp (abtRxBuf + offset, acr122_preamble, sizeof(acr122_preamble)))) { if (0 != (memcmp(abtRxBuf + offset, acr122_preamble, sizeof(acr122_preamble)))) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -640,44 +640,44 @@ read:
// TFI + PD0 (CC+1) // TFI + PD0 (CC+1)
if (abtRxBuf[offset] != 0xD5) { if (abtRxBuf[offset] != 0xD5) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
offset += 1; offset += 1;
if (abtRxBuf[offset] != CHIP_DATA (pnd)->last_command + 1) { if (abtRxBuf[offset] != CHIP_DATA(pnd)->last_command + 1) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
offset += 1; offset += 1;
memcpy (pbtData, abtRxBuf + offset, len); memcpy(pbtData, abtRxBuf + offset, len);
offset += len; offset += len;
return len; return len;
} }
int int
acr122_usb_ack (nfc_device *pnd) acr122_usb_ack(nfc_device *pnd)
{ {
(void) pnd; (void) pnd;
int res = 0; int res = 0;
uint8_t acr122_ack_frame[] = { GetFirmwareVersion }; // We can't send a PN532's ACK frame, so we use a normal command to cancel current command uint8_t acr122_ack_frame[] = { GetFirmwareVersion }; // We can't send a PN532's ACK frame, so we use a normal command to cancel current command
log_put (LOG_CATEGORY, NFC_PRIORITY_DEBUG, "%s", "ACR122 Abort"); log_put(LOG_CATEGORY, NFC_PRIORITY_DEBUG, "%s", "ACR122 Abort");
uint8_t *frame; uint8_t *frame;
if ((res = acr122_build_frame_from_tama (&frame, acr122_ack_frame, sizeof (acr122_ack_frame))) < 0) if ((res = acr122_build_frame_from_tama(&frame, acr122_ack_frame, sizeof(acr122_ack_frame))) < 0)
return res; return res;
res = acr122_usb_bulk_write (DRIVER_DATA (pnd), frame, res, 1000); res = acr122_usb_bulk_write(DRIVER_DATA(pnd), frame, res, 1000);
uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN]; uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN];
res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), 1000); res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), 1000);
return res; return res;
} }
int int
acr122_usb_init (nfc_device *pnd) acr122_usb_init(nfc_device *pnd)
{ {
int res = 0; int res = 0;
uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN]; uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN];
@ -705,7 +705,7 @@ acr122_usb_init (nfc_device *pnd)
return res; return res;
*/ */
if ((res = pn53x_set_property_int (pnd, NP_TIMEOUT_COMMAND, 1000)) < 0) if ((res = pn53x_set_property_int(pnd, NP_TIMEOUT_COMMAND, 1000)) < 0)
return res; return res;
uint8_t acr122u_set_picc_operating_parameters_off_frame[] = { uint8_t acr122u_set_picc_operating_parameters_off_frame[] = {
@ -717,24 +717,24 @@ acr122_usb_init (nfc_device *pnd)
}; };
uint8_t *frame; uint8_t *frame;
log_put (LOG_CATEGORY, NFC_PRIORITY_DEBUG, "%s", "ACR122 PICC Operating Parameters"); log_put(LOG_CATEGORY, NFC_PRIORITY_DEBUG, "%s", "ACR122 PICC Operating Parameters");
if ((res = acr122_build_frame_from_apdu (&frame, acr122u_set_picc_operating_parameters_off_frame, sizeof(acr122u_set_picc_operating_parameters_off_frame))) < 0) if ((res = acr122_build_frame_from_apdu(&frame, acr122u_set_picc_operating_parameters_off_frame, sizeof(acr122u_set_picc_operating_parameters_off_frame))) < 0)
return res; return res;
if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), frame, res, 1000)) < 0) if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), frame, res, 1000)) < 0)
return res; return res;
if ((res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), 1000)) < 0) if ((res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), 1000)) < 0)
return res; return res;
if ((res = pn53x_init (pnd)) < 0) if ((res = pn53x_init(pnd)) < 0)
return res; return res;
return NFC_SUCCESS; return NFC_SUCCESS;
} }
static int static int
acr122_usb_abort_command (nfc_device *pnd) acr122_usb_abort_command(nfc_device *pnd)
{ {
DRIVER_DATA (pnd)->abort_flag = true; DRIVER_DATA(pnd)->abort_flag = true;
return NFC_SUCCESS; return NFC_SUCCESS;
} }

View file

@ -29,11 +29,11 @@
# include <nfc/nfc-types.h> # include <nfc/nfc-types.h>
bool acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound); bool acr122_usb_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound);
nfc_device *acr122_usb_connect (const nfc_connstring connstring); nfc_device *acr122_usb_connect(const nfc_connstring connstring);
int acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); int acr122_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout);
int acr122_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout); int acr122_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout);
void acr122_usb_disconnect (nfc_device *pnd); void acr122_usb_disconnect(nfc_device *pnd);
extern const struct nfc_driver acr122_usb_driver; extern const struct nfc_driver acr122_usb_driver;

View file

@ -270,7 +270,7 @@ acr122s_recv_frame(nfc_device *pnd, uint8_t *frame, size_t frame_size, void *abo
return ret; return ret;
struct xfr_block_res *res = (struct xfr_block_res *) &frame[1]; struct xfr_block_res *res = (struct xfr_block_res *) &frame[1];
if ((uint8_t) (res->seq + 1) != DRIVER_DATA(pnd)->seq) { if ((uint8_t)(res->seq + 1) != DRIVER_DATA(pnd)->seq) {
log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Invalid response sequence number."); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Invalid response sequence number.");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
@ -418,51 +418,51 @@ struct acr122s_descriptor {
}; };
static int static int
acr122s_connstring_decode (const nfc_connstring connstring, struct acr122s_descriptor *desc) acr122s_connstring_decode(const nfc_connstring connstring, struct acr122s_descriptor *desc)
{ {
char *cs = malloc (strlen (connstring) + 1); char *cs = malloc(strlen(connstring) + 1);
if (!cs) { if (!cs) {
perror ("malloc"); perror("malloc");
return -1; return -1;
} }
strcpy (cs, connstring); strcpy(cs, connstring);
const char *driver_name = strtok (cs, ":"); const char *driver_name = strtok(cs, ":");
if (!driver_name) { if (!driver_name) {
// Parse error // Parse error
free (cs); free(cs);
return -1; return -1;
} }
if (0 != strcmp (driver_name, ACR122S_DRIVER_NAME)) { if (0 != strcmp(driver_name, ACR122S_DRIVER_NAME)) {
// Driver name does not match. // Driver name does not match.
free (cs); free(cs);
return 0; return 0;
} }
const char *port = strtok (NULL, ":"); const char *port = strtok(NULL, ":");
if (!port) { if (!port) {
// Only driver name was specified (or parsing error) // Only driver name was specified (or parsing error)
free (cs); free(cs);
return 1; return 1;
} }
strncpy (desc->port, port, sizeof(desc->port) - 1); strncpy(desc->port, port, sizeof(desc->port) - 1);
desc->port[sizeof(desc->port) - 1] = '\0'; desc->port[sizeof(desc->port) - 1] = '\0';
const char *speed_s = strtok (NULL, ":"); const char *speed_s = strtok(NULL, ":");
if (!speed_s) { if (!speed_s) {
// speed not specified (or parsing error) // speed not specified (or parsing error)
free (cs); free(cs);
return 2; return 2;
} }
unsigned long speed; unsigned long speed;
if (sscanf (speed_s, "%lu", &speed) != 1) { if (sscanf(speed_s, "%lu", &speed) != 1) {
// speed_s is not a number // speed_s is not a number
free (cs); free(cs);
return 2; return 2;
} }
desc->speed = speed; desc->speed = speed;
free (cs); free(cs);
return 3; return 3;
} }
@ -482,26 +482,26 @@ acr122s_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszD
*pszDeviceFound = 0; *pszDeviceFound = 0;
serial_port sp; serial_port sp;
char **acPorts = uart_list_ports (); char **acPorts = uart_list_ports();
const char *acPort; const char *acPort;
int iDevice = 0; int iDevice = 0;
while ((acPort = acPorts[iDevice++])) { while ((acPort = acPorts[iDevice++])) {
sp = uart_open (acPort); sp = uart_open(acPort);
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Trying to find ACR122S device on serial port: %s at %d bauds.", acPort, ACR122S_DEFAULT_SPEED); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Trying to find ACR122S device on serial port: %s at %d bauds.", acPort, ACR122S_DEFAULT_SPEED);
if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) {
// We need to flush input to be sure first reply does not comes from older byte transceive // We need to flush input to be sure first reply does not comes from older byte transceive
uart_flush_input (sp); uart_flush_input(sp);
uart_set_speed (sp, ACR122S_DEFAULT_SPEED); uart_set_speed(sp, ACR122S_DEFAULT_SPEED);
nfc_connstring connstring; nfc_connstring connstring;
snprintf (connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ACR122S_DRIVER_NAME, acPort, ACR122S_DEFAULT_SPEED); snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ACR122S_DRIVER_NAME, acPort, ACR122S_DEFAULT_SPEED);
nfc_device *pnd = nfc_device_new (connstring); nfc_device *pnd = nfc_device_new(connstring);
pnd->driver = &acr122s_driver; pnd->driver = &acr122s_driver;
pnd->driver_data = malloc(sizeof(struct acr122s_data)); pnd->driver_data = malloc(sizeof(struct acr122s_data));
DRIVER_DATA (pnd)->port = sp; DRIVER_DATA(pnd)->port = sp;
DRIVER_DATA(pnd)->seq = 0; DRIVER_DATA(pnd)->seq = 0;
#ifndef WIN32 #ifndef WIN32
@ -528,7 +528,7 @@ acr122s_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszD
continue; continue;
// ACR122S reader is found // ACR122S reader is found
memcpy (connstrings[*pszDeviceFound], connstring, sizeof(nfc_connstring)); memcpy(connstrings[*pszDeviceFound], connstring, sizeof(nfc_connstring));
(*pszDeviceFound)++; (*pszDeviceFound)++;
// Test if we reach the maximum "wanted" devices // Test if we reach the maximum "wanted" devices
@ -538,9 +538,9 @@ acr122s_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszD
} }
iDevice = 0; iDevice = 0;
while ((acPort = acPorts[iDevice++])) { while ((acPort = acPorts[iDevice++])) {
free ((void*)acPort); free((void*)acPort);
} }
free (acPorts); free(acPorts);
#endif /* SERIAL_AUTOPROBE_ENABLED */ #endif /* SERIAL_AUTOPROBE_ENABLED */
return true; return true;
} }
@ -551,7 +551,7 @@ acr122s_open(const nfc_connstring connstring)
serial_port sp; serial_port sp;
nfc_device *pnd; nfc_device *pnd;
struct acr122s_descriptor ndd; struct acr122s_descriptor ndd;
int connstring_decode_level = acr122s_connstring_decode (connstring, &ndd); int connstring_decode_level = acr122s_connstring_decode(connstring, &ndd);
if (connstring_decode_level < 2) { if (connstring_decode_level < 2) {
return NULL; return NULL;
@ -633,15 +633,15 @@ acr122s_open(const nfc_connstring connstring)
} }
void void
acr122s_close (nfc_device *pnd) acr122s_close(nfc_device *pnd)
{ {
acr122s_deactivate_sam(pnd); acr122s_deactivate_sam(pnd);
uart_close(DRIVER_DATA(pnd)->port); uart_close(DRIVER_DATA(pnd)->port);
#ifndef WIN32 #ifndef WIN32
// Release file descriptors used for abort mecanism // Release file descriptors used for abort mecanism
close (DRIVER_DATA(pnd)->abort_fds[0]); close(DRIVER_DATA(pnd)->abort_fds[0]);
close (DRIVER_DATA(pnd)->abort_fds[1]); close(DRIVER_DATA(pnd)->abort_fds[1]);
#endif #endif
pn53x_data_free(pnd); pn53x_data_free(pnd);
@ -691,7 +691,7 @@ acr122s_receive(nfc_device *pnd, uint8_t *buf, size_t buf_len, int timeout)
size_t data_len = FRAME_SIZE(tmp) - 17; size_t data_len = FRAME_SIZE(tmp) - 17;
if (data_len > buf_len) { if (data_len > buf_len) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Receive buffer too small. (buf_len: %zu, data_len: %zu)", buf_len, data_len); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Receive buffer too small. (buf_len: %zu, data_len: %zu)", buf_len, data_len);
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -707,7 +707,7 @@ acr122s_abort_command(nfc_device *pnd)
#ifndef WIN32 #ifndef WIN32
close(DRIVER_DATA(pnd)->abort_fds[0]); close(DRIVER_DATA(pnd)->abort_fds[0]);
close(DRIVER_DATA(pnd)->abort_fds[1]); close(DRIVER_DATA(pnd)->abort_fds[1]);
if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0 ) { if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0) {
return NFC_ESOFT; return NFC_ESOFT;
} }
#else #else

View file

@ -87,11 +87,11 @@ static const uint8_t arygon_error_none[] = "FF000000\x0d\x0a";
static const uint8_t arygon_error_incomplete_command[] = "FF0C0000\x0d\x0a"; static const uint8_t arygon_error_incomplete_command[] = "FF0C0000\x0d\x0a";
static const uint8_t arygon_error_unknown_mode[] = "FF060000\x0d\x0a"; static const uint8_t arygon_error_unknown_mode[] = "FF060000\x0d\x0a";
int arygon_reset_tama (nfc_device *pnd); int arygon_reset_tama(nfc_device *pnd);
void arygon_firmware (nfc_device *pnd, char *str); void arygon_firmware(nfc_device *pnd, char *str);
bool bool
arygon_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound) arygon_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound)
{ {
/** @note: Due to UART bus we can't know if its really an ARYGON without /** @note: Due to UART bus we can't know if its really an ARYGON without
* sending some commands. But using this way to probe devices, we can * sending some commands. But using this way to probe devices, we can
@ -100,53 +100,53 @@ arygon_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszD
(void) connstrings; (void) connstrings;
(void) connstrings_len; (void) connstrings_len;
*pszDeviceFound = 0; *pszDeviceFound = 0;
log_put (LOG_CATEGORY, NFC_PRIORITY_INFO, "%s", "Serial auto-probing have been disabled at compile time. Skipping autoprobe."); log_put(LOG_CATEGORY, NFC_PRIORITY_INFO, "%s", "Serial auto-probing have been disabled at compile time. Skipping autoprobe.");
return false; return false;
#else /* SERIAL_AUTOPROBE_ENABLED */ #else /* SERIAL_AUTOPROBE_ENABLED */
*pszDeviceFound = 0; *pszDeviceFound = 0;
serial_port sp; serial_port sp;
char **acPorts = uart_list_ports (); char **acPorts = uart_list_ports();
const char *acPort; const char *acPort;
int iDevice = 0; int iDevice = 0;
while ((acPort = acPorts[iDevice++])) { while ((acPort = acPorts[iDevice++])) {
sp = uart_open (acPort); sp = uart_open(acPort);
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Trying to find ARYGON device on serial port: %s at %d bauds.", acPort, ARYGON_DEFAULT_SPEED); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Trying to find ARYGON device on serial port: %s at %d bauds.", acPort, ARYGON_DEFAULT_SPEED);
if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) {
// We need to flush input to be sure first reply does not comes from older byte transceive // We need to flush input to be sure first reply does not comes from older byte transceive
uart_flush_input (sp); uart_flush_input(sp);
uart_set_speed (sp, ARYGON_DEFAULT_SPEED); uart_set_speed(sp, ARYGON_DEFAULT_SPEED);
nfc_connstring connstring; nfc_connstring connstring;
snprintf (connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ARYGON_DRIVER_NAME, acPort, ARYGON_DEFAULT_SPEED); snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ARYGON_DRIVER_NAME, acPort, ARYGON_DEFAULT_SPEED);
nfc_device *pnd = nfc_device_new (connstring); nfc_device *pnd = nfc_device_new(connstring);
pnd->driver = &arygon_driver; pnd->driver = &arygon_driver;
pnd->driver_data = malloc(sizeof(struct arygon_data)); pnd->driver_data = malloc(sizeof(struct arygon_data));
DRIVER_DATA (pnd)->port = sp; DRIVER_DATA(pnd)->port = sp;
// Alloc and init chip's data // Alloc and init chip's data
pn53x_data_new (pnd, &arygon_tama_io); pn53x_data_new(pnd, &arygon_tama_io);
#ifndef WIN32 #ifndef WIN32
// pipe-based abort mecanism // pipe-based abort mecanism
pipe (DRIVER_DATA (pnd)->iAbortFds); pipe(DRIVER_DATA(pnd)->iAbortFds);
#else #else
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
#endif #endif
int res = arygon_reset_tama (pnd); int res = arygon_reset_tama(pnd);
pn53x_data_free (pnd); pn53x_data_free(pnd);
nfc_device_free (pnd); nfc_device_free(pnd);
uart_close (sp); uart_close(sp);
if(res < 0) { if (res < 0) {
continue; continue;
} }
// ARYGON reader is found // ARYGON reader is found
memcpy (connstrings[*pszDeviceFound], connstring, sizeof(nfc_connstring)); memcpy(connstrings[*pszDeviceFound], connstring, sizeof(nfc_connstring));
(*pszDeviceFound)++; (*pszDeviceFound)++;
// Test if we reach the maximum "wanted" devices // Test if we reach the maximum "wanted" devices
@ -156,9 +156,9 @@ arygon_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszD
} }
iDevice = 0; iDevice = 0;
while ((acPort = acPorts[iDevice++])) { while ((acPort = acPorts[iDevice++])) {
free ((void*)acPort); free((void*)acPort);
} }
free (acPorts); free(acPorts);
#endif /* SERIAL_AUTOPROBE_ENABLED */ #endif /* SERIAL_AUTOPROBE_ENABLED */
return true; return true;
} }
@ -169,59 +169,59 @@ struct arygon_descriptor {
}; };
static int static int
arygon_connstring_decode (const nfc_connstring connstring, struct arygon_descriptor *desc) arygon_connstring_decode(const nfc_connstring connstring, struct arygon_descriptor *desc)
{ {
char *cs = malloc (strlen (connstring) + 1); char *cs = malloc(strlen(connstring) + 1);
if (!cs) { if (!cs) {
perror ("malloc"); perror("malloc");
return -1; return -1;
} }
strcpy (cs, connstring); strcpy(cs, connstring);
const char *driver_name = strtok (cs, ":"); const char *driver_name = strtok(cs, ":");
if (!driver_name) { if (!driver_name) {
// Parse error // Parse error
free (cs); free(cs);
return -1; return -1;
} }
if (0 != strcmp (driver_name, ARYGON_DRIVER_NAME)) { if (0 != strcmp(driver_name, ARYGON_DRIVER_NAME)) {
// Driver name does not match. // Driver name does not match.
free (cs); free(cs);
return 0; return 0;
} }
const char *port = strtok (NULL, ":"); const char *port = strtok(NULL, ":");
if (!port) { if (!port) {
// Only driver name was specified (or parsing error) // Only driver name was specified (or parsing error)
free (cs); free(cs);
return 1; return 1;
} }
strncpy (desc->port, port, sizeof(desc->port) - 1); strncpy(desc->port, port, sizeof(desc->port) - 1);
desc->port[sizeof(desc->port) - 1] = '\0'; desc->port[sizeof(desc->port) - 1] = '\0';
const char *speed_s = strtok (NULL, ":"); const char *speed_s = strtok(NULL, ":");
if (!speed_s) { if (!speed_s) {
// speed not specified (or parsing error) // speed not specified (or parsing error)
free (cs); free(cs);
return 2; return 2;
} }
unsigned long speed; unsigned long speed;
if (sscanf (speed_s, "%lu", &speed) != 1) { if (sscanf(speed_s, "%lu", &speed) != 1) {
// speed_s is not a number // speed_s is not a number
free (cs); free(cs);
return 2; return 2;
} }
desc->speed = speed; desc->speed = speed;
free (cs); free(cs);
return 3; return 3;
} }
nfc_device * nfc_device *
arygon_open (const nfc_connstring connstring) arygon_open(const nfc_connstring connstring)
{ {
struct arygon_descriptor ndd; struct arygon_descriptor ndd;
int connstring_decode_level = arygon_connstring_decode (connstring, &ndd); int connstring_decode_level = arygon_connstring_decode(connstring, &ndd);
if (connstring_decode_level < 2) { if (connstring_decode_level < 2) {
return NULL; return NULL;
@ -232,123 +232,123 @@ arygon_open (const nfc_connstring connstring)
serial_port sp; serial_port sp;
nfc_device *pnd = NULL; nfc_device *pnd = NULL;
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Attempt to open: %s at %d bauds.", ndd.port, ndd.speed); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Attempt to open: %s at %d bauds.", ndd.port, ndd.speed);
sp = uart_open (ndd.port); sp = uart_open(ndd.port);
if (sp == INVALID_SERIAL_PORT) if (sp == INVALID_SERIAL_PORT)
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port);
if (sp == CLAIMED_SERIAL_PORT) if (sp == CLAIMED_SERIAL_PORT)
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port);
if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT)) if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT))
return NULL; return NULL;
// We need to flush input to be sure first reply does not comes from older byte transceive // We need to flush input to be sure first reply does not comes from older byte transceive
uart_flush_input (sp); uart_flush_input(sp);
uart_set_speed (sp, ndd.speed); uart_set_speed(sp, ndd.speed);
// We have a connection // We have a connection
pnd = nfc_device_new (connstring); pnd = nfc_device_new(connstring);
snprintf (pnd->name, sizeof (pnd->name), "%s:%s", ARYGON_DRIVER_NAME, ndd.port); snprintf(pnd->name, sizeof(pnd->name), "%s:%s", ARYGON_DRIVER_NAME, ndd.port);
pnd->driver_data = malloc(sizeof(struct arygon_data)); pnd->driver_data = malloc(sizeof(struct arygon_data));
DRIVER_DATA (pnd)->port = sp; DRIVER_DATA(pnd)->port = sp;
// Alloc and init chip's data // Alloc and init chip's data
pn53x_data_new (pnd, &arygon_tama_io); pn53x_data_new(pnd, &arygon_tama_io);
// The PN53x chip opened to ARYGON MCU doesn't seems to be in LowVBat mode // The PN53x chip opened to ARYGON MCU doesn't seems to be in LowVBat mode
CHIP_DATA (pnd)->power_mode = NORMAL; CHIP_DATA(pnd)->power_mode = NORMAL;
// empirical tuning // empirical tuning
CHIP_DATA (pnd)->timer_correction = 46; CHIP_DATA(pnd)->timer_correction = 46;
pnd->driver = &arygon_driver; pnd->driver = &arygon_driver;
#ifndef WIN32 #ifndef WIN32
// pipe-based abort mecanism // pipe-based abort mecanism
if (pipe (DRIVER_DATA (pnd)->iAbortFds) < 0) { if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) {
return NULL; return NULL;
} }
#else #else
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
#endif #endif
// Check communication using "Reset TAMA" command // Check communication using "Reset TAMA" command
if (arygon_reset_tama(pnd) < 0) { if (arygon_reset_tama(pnd) < 0) {
arygon_close (pnd); arygon_close(pnd);
return NULL; return NULL;
} }
char arygon_firmware_version[10]; char arygon_firmware_version[10];
arygon_firmware (pnd, arygon_firmware_version); arygon_firmware(pnd, arygon_firmware_version);
char *pcName; char *pcName;
pcName = strdup (pnd->name); pcName = strdup(pnd->name);
snprintf (pnd->name, sizeof (pnd->name), "%s %s", pcName, arygon_firmware_version); snprintf(pnd->name, sizeof(pnd->name), "%s %s", pcName, arygon_firmware_version);
free (pcName); free(pcName);
pn53x_init(pnd); pn53x_init(pnd);
return pnd; return pnd;
} }
void void
arygon_close (nfc_device *pnd) arygon_close(nfc_device *pnd)
{ {
// Release UART port // Release UART port
uart_close (DRIVER_DATA (pnd)->port); uart_close(DRIVER_DATA(pnd)->port);
#ifndef WIN32 #ifndef WIN32
// Release file descriptors used for abort mecanism // Release file descriptors used for abort mecanism
close (DRIVER_DATA (pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[0]);
close (DRIVER_DATA (pnd)->iAbortFds[1]); close(DRIVER_DATA(pnd)->iAbortFds[1]);
#endif #endif
pn53x_data_free (pnd); pn53x_data_free(pnd);
nfc_device_free (pnd); nfc_device_free(pnd);
} }
#define ARYGON_TX_BUFFER_LEN (PN53x_NORMAL_FRAME__DATA_MAX_LEN + PN53x_NORMAL_FRAME__OVERHEAD + 1) #define ARYGON_TX_BUFFER_LEN (PN53x_NORMAL_FRAME__DATA_MAX_LEN + PN53x_NORMAL_FRAME__OVERHEAD + 1)
#define ARYGON_RX_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) #define ARYGON_RX_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD)
int int
arygon_tama_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) arygon_tama_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout)
{ {
int res = 0; int res = 0;
// Before sending anything, we need to discard from any junk bytes // Before sending anything, we need to discard from any junk bytes
uart_flush_input (DRIVER_DATA(pnd)->port); uart_flush_input(DRIVER_DATA(pnd)->port);
uint8_t abtFrame[ARYGON_TX_BUFFER_LEN] = { DEV_ARYGON_PROTOCOL_TAMA, 0x00, 0x00, 0xff }; // Every packet must start with "0x32 0x00 0x00 0xff" uint8_t abtFrame[ARYGON_TX_BUFFER_LEN] = { DEV_ARYGON_PROTOCOL_TAMA, 0x00, 0x00, 0xff }; // Every packet must start with "0x32 0x00 0x00 0xff"
size_t szFrame = 0; size_t szFrame = 0;
if (szData > PN53x_NORMAL_FRAME__DATA_MAX_LEN) { if (szData > PN53x_NORMAL_FRAME__DATA_MAX_LEN) {
// ARYGON Reader with PN532 equipped does not support extended frame (bug in ARYGON firmware?) // ARYGON Reader with PN532 equipped does not support extended frame (bug in ARYGON firmware?)
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "ARYGON device does not support more than %d bytes as payload (requested: %zd)", PN53x_NORMAL_FRAME__DATA_MAX_LEN, szData); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "ARYGON device does not support more than %d bytes as payload (requested: %zd)", PN53x_NORMAL_FRAME__DATA_MAX_LEN, szData);
pnd->last_error = NFC_EDEVNOTSUPP; pnd->last_error = NFC_EDEVNOTSUPP;
return pnd->last_error; return pnd->last_error;
} }
if ((res = pn53x_build_frame (abtFrame + 1, &szFrame, pbtData, szData)) < 0) { if ((res = pn53x_build_frame(abtFrame + 1, &szFrame, pbtData, szData)) < 0) {
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
if ((res = uart_send (DRIVER_DATA (pnd)->port, abtFrame, szFrame + 1, timeout)) != 0) { if ((res = uart_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame + 1, timeout)) != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)");
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
uint8_t abtRxBuf[6]; uint8_t abtRxBuf[6];
if ((res = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, sizeof (abtRxBuf), 0, timeout)) != 0) { if ((res = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, sizeof(abtRxBuf), 0, timeout)) != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to read ACK"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to read ACK");
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
if (pn53x_check_ack_frame (pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) {
// The PN53x is running the sent command // The PN53x is running the sent command
} else if (0 == memcmp(arygon_error_unknown_mode, abtRxBuf, sizeof(abtRxBuf))) { } else if (0 == memcmp(arygon_error_unknown_mode, abtRxBuf, sizeof(abtRxBuf))) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Bad frame format."); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Bad frame format.");
// We have already read 6 bytes and arygon_error_unknown_mode is 10 bytes long // We have already read 6 bytes and arygon_error_unknown_mode is 10 bytes long
// so we have to read 4 remaining bytes to be synchronized at the next receiving pass. // so we have to read 4 remaining bytes to be synchronized at the next receiving pass.
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 4, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 4, 0, timeout);
return pnd->last_error; return pnd->last_error;
} else { } else {
return pnd->last_error; return pnd->last_error;
@ -357,34 +357,34 @@ arygon_tama_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData,
} }
static int static int
arygon_abort (nfc_device *pnd) arygon_abort(nfc_device *pnd)
{ {
// Send a valid TAMA packet to wakup the PN53x (we will not have an answer, according to Arygon manual) // Send a valid TAMA packet to wakup the PN53x (we will not have an answer, according to Arygon manual)
uint8_t dummy[] = { 0x32, 0x00, 0x00, 0xff, 0x09, 0xf7, 0xd4, 0x00, 0x00, 0x6c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0xbe, 0x00 }; uint8_t dummy[] = { 0x32, 0x00, 0x00, 0xff, 0x09, 0xf7, 0xd4, 0x00, 0x00, 0x6c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0xbe, 0x00 };
uart_send (DRIVER_DATA (pnd)->port, dummy, sizeof (dummy), 0); uart_send(DRIVER_DATA(pnd)->port, dummy, sizeof(dummy), 0);
// Using Arygon device we can't send ACK frame to abort the running command // Using Arygon device we can't send ACK frame to abort the running command
return pn53x_check_communication (pnd); return pn53x_check_communication(pnd);
} }
int int
arygon_tama_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) arygon_tama_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout)
{ {
uint8_t abtRxBuf[5]; uint8_t abtRxBuf[5];
size_t len; size_t len;
void *abort_p = NULL; void *abort_p = NULL;
#ifndef WIN32 #ifndef WIN32
abort_p = &(DRIVER_DATA (pnd)->iAbortFds[1]); abort_p = &(DRIVER_DATA(pnd)->iAbortFds[1]);
#else #else
abort_p = (void*) & (DRIVER_DATA (pnd)->abort_flag); abort_p = (void*) & (DRIVER_DATA(pnd)->abort_flag);
#endif #endif
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 5, abort_p, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 5, abort_p, timeout);
if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { if (abort_p && (NFC_EOPABORTED == pnd->last_error)) {
arygon_abort (pnd); arygon_abort(pnd);
/* last_error got reset by arygon_abort() */ /* last_error got reset by arygon_abort() */
pnd->last_error = NFC_EOPABORTED; pnd->last_error = NFC_EOPABORTED;
@ -392,32 +392,32 @@ arygon_tama_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen,
} }
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
return pnd->last_error; return pnd->last_error;
} }
const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff };
if (0 != (memcmp (abtRxBuf, pn53x_preamble, 3))) { if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) {
// Error frame // Error frame
uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 3, 0, timeout); uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout);
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { } else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) {
// Extended frame // Extended frame
// ARYGON devices does not support extended frame sending // ARYGON devices does not support extended frame sending
abort (); abort();
} else { } else {
// Normal frame // Normal frame
if (256 != (abtRxBuf[3] + abtRxBuf[4])) { if (256 != (abtRxBuf[3] + abtRxBuf[4])) {
// TODO: Retry // TODO: Retry
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -427,58 +427,58 @@ arygon_tama_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen,
} }
if (len > szDataLen) { if (len > szDataLen) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len);
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
// TFI + PD0 (CC+1) // TFI + PD0 (CC+1)
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 2, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout);
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
return pnd->last_error; return pnd->last_error;
} }
if (abtRxBuf[0] != 0xD5) { if (abtRxBuf[0] != 0xD5) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
if (abtRxBuf[1] != CHIP_DATA (pnd)->last_command + 1) { if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
if (len) { if (len) {
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, pbtData, len, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, pbtData, len, 0, timeout);
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
return pnd->last_error; return pnd->last_error;
} }
} }
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 2, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout);
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
return pnd->last_error; return pnd->last_error;
} }
uint8_t btDCS = (256 - 0xD5); uint8_t btDCS = (256 - 0xD5);
btDCS -= CHIP_DATA (pnd)->last_command + 1; btDCS -= CHIP_DATA(pnd)->last_command + 1;
for (size_t szPos = 0; szPos < len; szPos++) { for (size_t szPos = 0; szPos < len; szPos++) {
btDCS -= pbtData[szPos]; btDCS -= pbtData[szPos];
} }
if (btDCS != abtRxBuf[0]) { if (btDCS != abtRxBuf[0]) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
if (0x00 != abtRxBuf[1]) { if (0x00 != abtRxBuf[1]) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -487,53 +487,53 @@ arygon_tama_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen,
} }
void void
arygon_firmware (nfc_device *pnd, char *str) arygon_firmware(nfc_device *pnd, char *str)
{ {
const uint8_t arygon_firmware_version_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'v' }; const uint8_t arygon_firmware_version_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'v' };
uint8_t abtRx[16]; uint8_t abtRx[16];
size_t szRx = sizeof(abtRx); size_t szRx = sizeof(abtRx);
int res = uart_send (DRIVER_DATA (pnd)->port, arygon_firmware_version_cmd, sizeof (arygon_firmware_version_cmd), 0); int res = uart_send(DRIVER_DATA(pnd)->port, arygon_firmware_version_cmd, sizeof(arygon_firmware_version_cmd), 0);
if (res != 0) { if (res != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Unable to send ARYGON firmware command."); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Unable to send ARYGON firmware command.");
return; return;
} }
res = uart_receive (DRIVER_DATA (pnd)->port, abtRx, szRx, 0, 0); res = uart_receive(DRIVER_DATA(pnd)->port, abtRx, szRx, 0, 0);
if (res != 0) { if (res != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Unable to retrieve ARYGON firmware version."); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "Unable to retrieve ARYGON firmware version.");
return; return;
} }
if ( 0 == memcmp (abtRx, arygon_error_none, 6)) { if (0 == memcmp(abtRx, arygon_error_none, 6)) {
uint8_t *p = abtRx + 6; uint8_t *p = abtRx + 6;
unsigned int szData; unsigned int szData;
sscanf ((const char*)p, "%02x%s", &szData, p); sscanf((const char*)p, "%02x%s", &szData, p);
memcpy (str, p, szData); memcpy(str, p, szData);
*(str + szData) = '\0'; *(str + szData) = '\0';
} }
} }
int int
arygon_reset_tama (nfc_device *pnd) arygon_reset_tama(nfc_device *pnd)
{ {
const uint8_t arygon_reset_tama_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'r' }; const uint8_t arygon_reset_tama_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'r' };
uint8_t abtRx[10]; // Attempted response is 10 bytes long uint8_t abtRx[10]; // Attempted response is 10 bytes long
size_t szRx = sizeof(abtRx); size_t szRx = sizeof(abtRx);
int res; int res;
uart_send (DRIVER_DATA (pnd)->port, arygon_reset_tama_cmd, sizeof (arygon_reset_tama_cmd), 500); uart_send(DRIVER_DATA(pnd)->port, arygon_reset_tama_cmd, sizeof(arygon_reset_tama_cmd), 500);
// Two reply are possible from ARYGON device: arygon_error_none (ie. in case the byte is well-sent) // Two reply are possible from ARYGON device: arygon_error_none (ie. in case the byte is well-sent)
// or arygon_error_unknown_mode (ie. in case of the first byte was bad-transmitted) // or arygon_error_unknown_mode (ie. in case of the first byte was bad-transmitted)
res = uart_receive (DRIVER_DATA (pnd)->port, abtRx, szRx, 0, 1000); res = uart_receive(DRIVER_DATA(pnd)->port, abtRx, szRx, 0, 1000);
if (res != 0) { if (res != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "No reply to 'reset TAMA' command."); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "No reply to 'reset TAMA' command.");
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
if (0 != memcmp (abtRx, arygon_error_none, sizeof (arygon_error_none) - 1)) { if (0 != memcmp(abtRx, arygon_error_none, sizeof(arygon_error_none) - 1)) {
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -542,16 +542,16 @@ arygon_reset_tama (nfc_device *pnd)
} }
static int static int
arygon_abort_command (nfc_device *pnd) arygon_abort_command(nfc_device *pnd)
{ {
if (pnd) { if (pnd) {
#ifndef WIN32 #ifndef WIN32
close (DRIVER_DATA (pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[0]);
if (pipe (DRIVER_DATA (pnd)->iAbortFds) < 0) { if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) {
return NFC_ESOFT; return NFC_ESOFT;
} }
#else #else
DRIVER_DATA (pnd)->abort_flag = true; DRIVER_DATA(pnd)->abort_flag = true;
#endif #endif
} }
return NFC_SUCCESS; return NFC_SUCCESS;

View file

@ -30,13 +30,13 @@
# include <nfc/nfc-types.h> # include <nfc/nfc-types.h>
bool arygon_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound); bool arygon_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound);
nfc_device *arygon_open (const nfc_connstring connstring); nfc_device *arygon_open(const nfc_connstring connstring);
void arygon_close (nfc_device *pnd); void arygon_close(nfc_device *pnd);
int arygon_tama_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); int arygon_tama_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout);
int arygon_tama_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDat, int timeouta); int arygon_tama_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDat, int timeouta);
extern const struct nfc_driver arygon_driver; extern const struct nfc_driver arygon_driver;

View file

@ -48,8 +48,8 @@
#define PN532_UART_DRIVER_NAME "pn532_uart" #define PN532_UART_DRIVER_NAME "pn532_uart"
#define LOG_CATEGORY "libnfc.driver.pn532_uart" #define LOG_CATEGORY "libnfc.driver.pn532_uart"
int pn532_uart_ack (nfc_device *pnd); int pn532_uart_ack(nfc_device *pnd);
int pn532_uart_wakeup (nfc_device *pnd); int pn532_uart_wakeup(nfc_device *pnd);
const struct pn53x_io pn532_uart_io; const struct pn53x_io pn532_uart_io;
@ -65,7 +65,7 @@ struct pn532_uart_data {
#define DRIVER_DATA(pnd) ((struct pn532_uart_data*)(pnd->driver_data)) #define DRIVER_DATA(pnd) ((struct pn532_uart_data*)(pnd->driver_data))
bool bool
pn532_uart_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound) pn532_uart_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound)
{ {
/** @note: Due to UART bus we can't know if its really a pn532 without /** @note: Due to UART bus we can't know if its really a pn532 without
* sending some PN53x commands. But using this way to probe devices, we can * sending some PN53x commands. But using this way to probe devices, we can
@ -74,57 +74,57 @@ pn532_uart_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *
(void) connstrings; (void) connstrings;
(void) connstrings_len; (void) connstrings_len;
*pszDeviceFound = 0; *pszDeviceFound = 0;
log_put (LOG_CATEGORY, NFC_PRIORITY_INFO, "%s", "Serial auto-probing have been disabled at compile time. Skipping autoprobe."); log_put(LOG_CATEGORY, NFC_PRIORITY_INFO, "%s", "Serial auto-probing have been disabled at compile time. Skipping autoprobe.");
return false; return false;
#else /* SERIAL_AUTOPROBE_ENABLED */ #else /* SERIAL_AUTOPROBE_ENABLED */
*pszDeviceFound = 0; *pszDeviceFound = 0;
serial_port sp; serial_port sp;
char **acPorts = uart_list_ports (); char **acPorts = uart_list_ports();
const char *acPort; const char *acPort;
int iDevice = 0; int iDevice = 0;
while ((acPort = acPorts[iDevice++])) { while ((acPort = acPorts[iDevice++])) {
sp = uart_open (acPort); sp = uart_open(acPort);
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Trying to find PN532 device on serial port: %s at %d bauds.", acPort, PN532_UART_DEFAULT_SPEED); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Trying to find PN532 device on serial port: %s at %d bauds.", acPort, PN532_UART_DEFAULT_SPEED);
if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) {
// We need to flush input to be sure first reply does not comes from older byte transceive // We need to flush input to be sure first reply does not comes from older byte transceive
uart_flush_input (sp); uart_flush_input(sp);
// Serial port claimed but we need to check if a PN532_UART is opened. // Serial port claimed but we need to check if a PN532_UART is opened.
uart_set_speed (sp, PN532_UART_DEFAULT_SPEED); uart_set_speed(sp, PN532_UART_DEFAULT_SPEED);
nfc_connstring connstring; nfc_connstring connstring;
snprintf (connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, PN532_UART_DRIVER_NAME, acPort, PN532_UART_DEFAULT_SPEED); snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, PN532_UART_DRIVER_NAME, acPort, PN532_UART_DEFAULT_SPEED);
nfc_device *pnd = nfc_device_new (connstring); nfc_device *pnd = nfc_device_new(connstring);
pnd->driver = &pn532_uart_driver; pnd->driver = &pn532_uart_driver;
pnd->driver_data = malloc(sizeof(struct pn532_uart_data)); pnd->driver_data = malloc(sizeof(struct pn532_uart_data));
DRIVER_DATA (pnd)->port = sp; DRIVER_DATA(pnd)->port = sp;
// Alloc and init chip's data // Alloc and init chip's data
pn53x_data_new (pnd, &pn532_uart_io); pn53x_data_new(pnd, &pn532_uart_io);
// SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532
CHIP_DATA (pnd)->type = PN532; CHIP_DATA(pnd)->type = PN532;
// This device starts in LowVBat power mode // This device starts in LowVBat power mode
CHIP_DATA (pnd)->power_mode = LOWVBAT; CHIP_DATA(pnd)->power_mode = LOWVBAT;
#ifndef WIN32 #ifndef WIN32
// pipe-based abort mecanism // pipe-based abort mecanism
pipe (DRIVER_DATA (pnd)->iAbortFds); pipe(DRIVER_DATA(pnd)->iAbortFds);
#else #else
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
#endif #endif
// Check communication using "Diagnose" command, with "Communication test" (0x00) // Check communication using "Diagnose" command, with "Communication test" (0x00)
int res = pn53x_check_communication (pnd); int res = pn53x_check_communication(pnd);
pn53x_data_free (pnd); pn53x_data_free(pnd);
nfc_device_free (pnd); nfc_device_free(pnd);
uart_close (sp); uart_close(sp);
if(res < 0) { if (res < 0) {
continue; continue;
} }
memcpy (connstrings[*pszDeviceFound], connstring, sizeof (nfc_connstring)); memcpy(connstrings[*pszDeviceFound], connstring, sizeof(nfc_connstring));
(*pszDeviceFound)++; (*pszDeviceFound)++;
// Test if we reach the maximum "wanted" devices // Test if we reach the maximum "wanted" devices
@ -134,9 +134,9 @@ pn532_uart_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *
} }
iDevice = 0; iDevice = 0;
while ((acPort = acPorts[iDevice++])) { while ((acPort = acPorts[iDevice++])) {
free ((void*)acPort); free((void*)acPort);
} }
free (acPorts); free(acPorts);
#endif /* SERIAL_AUTOPROBE_ENABLED */ #endif /* SERIAL_AUTOPROBE_ENABLED */
return true; return true;
} }
@ -147,59 +147,59 @@ struct pn532_uart_descriptor {
}; };
static int static int
pn532_connstring_decode (const nfc_connstring connstring, struct pn532_uart_descriptor *desc) pn532_connstring_decode(const nfc_connstring connstring, struct pn532_uart_descriptor *desc)
{ {
char *cs = malloc (strlen (connstring) + 1); char *cs = malloc(strlen(connstring) + 1);
if (!cs) { if (!cs) {
perror ("malloc"); perror("malloc");
return -1; return -1;
} }
strcpy (cs, connstring); strcpy(cs, connstring);
const char *driver_name = strtok (cs, ":"); const char *driver_name = strtok(cs, ":");
if (!driver_name) { if (!driver_name) {
// Parse error // Parse error
free (cs); free(cs);
return -1; return -1;
} }
if (0 != strcmp (driver_name, PN532_UART_DRIVER_NAME)) { if (0 != strcmp(driver_name, PN532_UART_DRIVER_NAME)) {
// Driver name does not match. // Driver name does not match.
free (cs); free(cs);
return 0; return 0;
} }
const char *port = strtok (NULL, ":"); const char *port = strtok(NULL, ":");
if (!port) { if (!port) {
// Only driver name was specified (or parsing error) // Only driver name was specified (or parsing error)
free (cs); free(cs);
return 1; return 1;
} }
strncpy (desc->port, port, sizeof(desc->port) - 1); strncpy(desc->port, port, sizeof(desc->port) - 1);
desc->port[sizeof(desc->port) - 1] = '\0'; desc->port[sizeof(desc->port) - 1] = '\0';
const char *speed_s = strtok (NULL, ":"); const char *speed_s = strtok(NULL, ":");
if (!speed_s) { if (!speed_s) {
// speed not specified (or parsing error) // speed not specified (or parsing error)
free (cs); free(cs);
return 2; return 2;
} }
unsigned long speed; unsigned long speed;
if (sscanf (speed_s, "%lu", &speed) != 1) { if (sscanf(speed_s, "%lu", &speed) != 1) {
// speed_s is not a number // speed_s is not a number
free (cs); free(cs);
return 2; return 2;
} }
desc->speed = speed; desc->speed = speed;
free (cs); free(cs);
return 3; return 3;
} }
nfc_device * nfc_device *
pn532_uart_open (const nfc_connstring connstring) pn532_uart_open(const nfc_connstring connstring)
{ {
struct pn532_uart_descriptor ndd; struct pn532_uart_descriptor ndd;
int connstring_decode_level = pn532_connstring_decode (connstring, &ndd); int connstring_decode_level = pn532_connstring_decode(connstring, &ndd);
if (connstring_decode_level < 2) { if (connstring_decode_level < 2) {
return NULL; return NULL;
@ -210,31 +210,31 @@ pn532_uart_open (const nfc_connstring connstring)
serial_port sp; serial_port sp;
nfc_device *pnd = NULL; nfc_device *pnd = NULL;
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Attempt to open: %s at %d bauds.", ndd.port, ndd.speed); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Attempt to open: %s at %d bauds.", ndd.port, ndd.speed);
sp = uart_open (ndd.port); sp = uart_open(ndd.port);
if (sp == INVALID_SERIAL_PORT) if (sp == INVALID_SERIAL_PORT)
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port);
if (sp == CLAIMED_SERIAL_PORT) if (sp == CLAIMED_SERIAL_PORT)
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port);
if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT)) if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT))
return NULL; return NULL;
// We need to flush input to be sure first reply does not comes from older byte transceive // We need to flush input to be sure first reply does not comes from older byte transceive
uart_flush_input (sp); uart_flush_input(sp);
uart_set_speed (sp, ndd.speed); uart_set_speed(sp, ndd.speed);
// We have a connection // We have a connection
pnd = nfc_device_new (connstring); pnd = nfc_device_new(connstring);
snprintf (pnd->name, sizeof (pnd->name), "%s:%s", PN532_UART_DRIVER_NAME, ndd.port); snprintf(pnd->name, sizeof(pnd->name), "%s:%s", PN532_UART_DRIVER_NAME, ndd.port);
pnd->driver_data = malloc(sizeof(struct pn532_uart_data)); pnd->driver_data = malloc(sizeof(struct pn532_uart_data));
DRIVER_DATA (pnd)->port = sp; DRIVER_DATA(pnd)->port = sp;
// Alloc and init chip's data // Alloc and init chip's data
pn53x_data_new (pnd, &pn532_uart_io); pn53x_data_new(pnd, &pn532_uart_io);
// SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532
CHIP_DATA (pnd)->type = PN532; CHIP_DATA(pnd)->type = PN532;
// This device starts in LowVBat mode // This device starts in LowVBat mode
CHIP_DATA(pnd)->power_mode = LOWVBAT; CHIP_DATA(pnd)->power_mode = LOWVBAT;
@ -244,15 +244,15 @@ pn532_uart_open (const nfc_connstring connstring)
#ifndef WIN32 #ifndef WIN32
// pipe-based abort mecanism // pipe-based abort mecanism
pipe (DRIVER_DATA (pnd)->iAbortFds); pipe(DRIVER_DATA(pnd)->iAbortFds);
#else #else
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
#endif #endif
// Check communication using "Diagnose" command, with "Communication test" (0x00) // Check communication using "Diagnose" command, with "Communication test" (0x00)
if (pn53x_check_communication (pnd) < 0) { if (pn53x_check_communication(pnd) < 0) {
nfc_perror (pnd, "pn53x_check_communication"); nfc_perror(pnd, "pn53x_check_communication");
pn532_uart_close (pnd); pn532_uart_close(pnd);
return NULL; return NULL;
} }
@ -261,38 +261,38 @@ pn532_uart_open (const nfc_connstring connstring)
} }
void void
pn532_uart_close (nfc_device *pnd) pn532_uart_close(nfc_device *pnd)
{ {
// Release UART port // Release UART port
uart_close (DRIVER_DATA(pnd)->port); uart_close(DRIVER_DATA(pnd)->port);
#ifndef WIN32 #ifndef WIN32
// Release file descriptors used for abort mecanism // Release file descriptors used for abort mecanism
close (DRIVER_DATA (pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[0]);
close (DRIVER_DATA (pnd)->iAbortFds[1]); close(DRIVER_DATA(pnd)->iAbortFds[1]);
#endif #endif
pn53x_data_free (pnd); pn53x_data_free(pnd);
nfc_device_free (pnd); nfc_device_free(pnd);
} }
int int
pn532_uart_wakeup (nfc_device *pnd) pn532_uart_wakeup(nfc_device *pnd)
{ {
/* High Speed Unit (HSU) wake up consist to send 0x55 and wait a "long" delay for PN532 being wakeup. */ /* High Speed Unit (HSU) wake up consist to send 0x55 and wait a "long" delay for PN532 being wakeup. */
const uint8_t pn532_wakeup_preamble[] = { 0x55, 0x55, 0x00, 0x00, 0x00 }; const uint8_t pn532_wakeup_preamble[] = { 0x55, 0x55, 0x00, 0x00, 0x00 };
int res = uart_send (DRIVER_DATA(pnd)->port, pn532_wakeup_preamble, sizeof (pn532_wakeup_preamble), 0); int res = uart_send(DRIVER_DATA(pnd)->port, pn532_wakeup_preamble, sizeof(pn532_wakeup_preamble), 0);
CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 should now be awake CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 should now be awake
return res; return res;
} }
#define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) #define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD)
int int
pn532_uart_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) pn532_uart_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout)
{ {
int res = 0; int res = 0;
// Before sending anything, we need to discard from any junk bytes // Before sending anything, we need to discard from any junk bytes
uart_flush_input (DRIVER_DATA(pnd)->port); uart_flush_input(DRIVER_DATA(pnd)->port);
switch (CHIP_DATA(pnd)->power_mode) { switch (CHIP_DATA(pnd)->power_mode) {
case LOWVBAT: { case LOWVBAT: {
@ -301,7 +301,7 @@ pn532_uart_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, i
return res; return res;
} }
// According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command // According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command
if ((res = pn53x_SAMConfiguration (pnd, 0x01, 1000)) < 0) { if ((res = pn53x_SAMConfiguration(pnd, 0x01, 1000)) < 0) {
return res; return res;
} }
} }
@ -320,27 +320,27 @@ pn532_uart_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, i
uint8_t abtFrame[PN532_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" uint8_t abtFrame[PN532_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff"
size_t szFrame = 0; size_t szFrame = 0;
if ((res = pn53x_build_frame (abtFrame, &szFrame, pbtData, szData)) < 0) { if ((res = pn53x_build_frame(abtFrame, &szFrame, pbtData, szData)) < 0) {
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
res = uart_send (DRIVER_DATA(pnd)->port, abtFrame, szFrame, timeout); res = uart_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame, timeout);
if (res != 0) { if (res != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)");
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
uint8_t abtRxBuf[6]; uint8_t abtRxBuf[6];
res = uart_receive (DRIVER_DATA(pnd)->port, abtRxBuf, 6, 0, timeout); res = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 6, 0, timeout);
if (res != 0) { if (res != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to read ACK"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to read ACK");
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
if (pn53x_check_ack_frame (pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) {
// The PN53x is running the sent command // The PN53x is running the sent command
} else { } else {
return pnd->last_error; return pnd->last_error;
@ -349,22 +349,22 @@ pn532_uart_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, i
} }
int int
pn532_uart_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) pn532_uart_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout)
{ {
uint8_t abtRxBuf[5]; uint8_t abtRxBuf[5];
size_t len; size_t len;
void *abort_p = NULL; void *abort_p = NULL;
#ifndef WIN32 #ifndef WIN32
abort_p = &(DRIVER_DATA (pnd)->iAbortFds[1]); abort_p = &(DRIVER_DATA(pnd)->iAbortFds[1]);
#else #else
abort_p = (void*) & (DRIVER_DATA (pnd)->abort_flag); abort_p = (void*) & (DRIVER_DATA(pnd)->abort_flag);
#endif #endif
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 5, abort_p, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 5, abort_p, timeout);
if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { if (abort_p && (NFC_EOPABORTED == pnd->last_error)) {
return pn532_uart_ack (pnd); return pn532_uart_ack(pnd);
} }
if (pnd->last_error < 0) { if (pnd->last_error < 0) {
@ -372,29 +372,29 @@ pn532_uart_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, i
} }
const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff };
if (0 != (memcmp (abtRxBuf, pn53x_preamble, 3))) { if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) {
// Error frame // Error frame
uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 3, 0, timeout); uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout);
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { } else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) {
// Extended frame // Extended frame
pnd->last_error = uart_receive (DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout);
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
goto error; goto error;
} }
// (abtRxBuf[0] << 8) + abtRxBuf[1] (LEN) include TFI + (CC+1) // (abtRxBuf[0] << 8) + abtRxBuf[1] (LEN) include TFI + (CC+1)
len = (abtRxBuf[0] << 8) + abtRxBuf[1] - 2; len = (abtRxBuf[0] << 8) + abtRxBuf[1] - 2;
if (((abtRxBuf[0] + abtRxBuf[1] + abtRxBuf[2]) % 256) != 0) { if (((abtRxBuf[0] + abtRxBuf[1] + abtRxBuf[2]) % 256) != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
@ -402,7 +402,7 @@ pn532_uart_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, i
// Normal frame // Normal frame
if (256 != (abtRxBuf[3] + abtRxBuf[4])) { if (256 != (abtRxBuf[3] + abtRxBuf[4])) {
// TODO: Retry // TODO: Retry
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
@ -412,70 +412,70 @@ pn532_uart_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, i
} }
if (len > szDataLen) { if (len > szDataLen) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len);
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
// TFI + PD0 (CC+1) // TFI + PD0 (CC+1)
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 2, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout);
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
goto error; goto error;
} }
if (abtRxBuf[0] != 0xD5) { if (abtRxBuf[0] != 0xD5) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
if (abtRxBuf[1] != CHIP_DATA (pnd)->last_command + 1) { if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
if (len) { if (len) {
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, pbtData, len, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, pbtData, len, 0, timeout);
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
goto error; goto error;
} }
} }
pnd->last_error = uart_receive (DRIVER_DATA (pnd)->port, abtRxBuf, 2, 0, timeout); pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout);
if (pnd->last_error != 0) { if (pnd->last_error != 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)");
goto error; goto error;
} }
uint8_t btDCS = (256 - 0xD5); uint8_t btDCS = (256 - 0xD5);
btDCS -= CHIP_DATA (pnd)->last_command + 1; btDCS -= CHIP_DATA(pnd)->last_command + 1;
for (size_t szPos = 0; szPos < len; szPos++) { for (size_t szPos = 0; szPos < len; szPos++) {
btDCS -= pbtData[szPos]; btDCS -= pbtData[szPos];
} }
if (btDCS != abtRxBuf[0]) { if (btDCS != abtRxBuf[0]) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
if (0x00 != abtRxBuf[1]) { if (0x00 != abtRxBuf[1]) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
goto error; goto error;
} }
// The PN53x command is done and we successfully received the reply // The PN53x command is done and we successfully received the reply
return len; return len;
error: error:
uart_flush_input (DRIVER_DATA (pnd)->port); uart_flush_input(DRIVER_DATA(pnd)->port);
return pnd->last_error; return pnd->last_error;
} }
int int
pn532_uart_ack (nfc_device *pnd) pn532_uart_ack(nfc_device *pnd)
{ {
int res = 0; int res = 0;
if (POWERDOWN == CHIP_DATA(pnd)->power_mode) { if (POWERDOWN == CHIP_DATA(pnd)->power_mode) {
@ -483,18 +483,18 @@ pn532_uart_ack (nfc_device *pnd)
return res; return res;
} }
} }
return (uart_send (DRIVER_DATA(pnd)->port, pn53x_ack_frame, sizeof (pn53x_ack_frame), 0)); return (uart_send(DRIVER_DATA(pnd)->port, pn53x_ack_frame, sizeof(pn53x_ack_frame), 0));
} }
static int static int
pn532_uart_abort_command (nfc_device *pnd) pn532_uart_abort_command(nfc_device *pnd)
{ {
if (pnd) { if (pnd) {
#ifndef WIN32 #ifndef WIN32
close (DRIVER_DATA (pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[0]);
pipe (DRIVER_DATA (pnd)->iAbortFds); pipe(DRIVER_DATA(pnd)->iAbortFds);
#else #else
DRIVER_DATA (pnd)->abort_flag = true; DRIVER_DATA(pnd)->abort_flag = true;
#endif #endif
} }
return NFC_SUCCESS; return NFC_SUCCESS;

View file

@ -29,12 +29,12 @@
# include <nfc/nfc-types.h> # include <nfc/nfc-types.h>
bool pn532_uart_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound); bool pn532_uart_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound);
nfc_device *pn532_uart_open (const nfc_connstring connstring); nfc_device *pn532_uart_open(const nfc_connstring connstring);
void pn532_uart_close (nfc_device *pnd); void pn532_uart_close(nfc_device *pnd);
int pn532_uart_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); int pn532_uart_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout);
int pn532_uart_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout); int pn532_uart_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout);
extern const struct nfc_driver pn532_uart_driver; extern const struct nfc_driver pn532_uart_driver;

View file

@ -86,34 +86,34 @@ struct pn53x_usb_data {
}; };
const struct pn53x_io pn53x_usb_io; const struct pn53x_io pn53x_usb_io;
bool pn53x_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len); bool pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len);
int pn53x_usb_init (nfc_device *pnd); int pn53x_usb_init(nfc_device *pnd);
static int static int
pn53x_usb_bulk_read (struct pn53x_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout) pn53x_usb_bulk_read(struct pn53x_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout)
{ {
int res = usb_bulk_read (data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout); int res = usb_bulk_read(data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout);
if (res > 0) { if (res > 0) {
LOG_HEX ("RX", abtRx, res); LOG_HEX("RX", abtRx, res);
} else if (res < 0) { } else if (res < 0) {
if (res != -USB_TIMEDOUT) if (res != -USB_TIMEDOUT)
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror(res));
} }
return res; return res;
} }
static int static int
pn53x_usb_bulk_write (struct pn53x_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout) pn53x_usb_bulk_write(struct pn53x_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout)
{ {
LOG_HEX ("TX", abtTx, szTx); LOG_HEX("TX", abtTx, szTx);
int res = usb_bulk_write (data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout); int res = usb_bulk_write(data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout);
if (res > 0) { if (res > 0) {
// HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details
if ((res % data->uiMaxPacketSize) == 0) { if ((res % data->uiMaxPacketSize) == 0) {
usb_bulk_write (data->pudh, data->uiEndPointOut, "\0", 0, timeout); usb_bulk_write(data->pudh, data->uiEndPointOut, "\0", 0, timeout);
} }
} else { } else {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror(res));
} }
return res; return res;
} }
@ -135,9 +135,9 @@ const struct pn53x_usb_supported_device pn53x_usb_supported_devices[] = {
}; };
static pn53x_usb_model static pn53x_usb_model
pn53x_usb_get_device_model (uint16_t vendor_id, uint16_t product_id) pn53x_usb_get_device_model(uint16_t vendor_id, uint16_t product_id)
{ {
for (size_t n = 0; n < sizeof (pn53x_usb_supported_devices) / sizeof (struct pn53x_usb_supported_device); n++) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) {
if ((vendor_id == pn53x_usb_supported_devices[n].vendor_id) && if ((vendor_id == pn53x_usb_supported_devices[n].vendor_id) &&
(product_id == pn53x_usb_supported_devices[n].product_id)) (product_id == pn53x_usb_supported_devices[n].product_id))
return pn53x_usb_supported_devices[n].model; return pn53x_usb_supported_devices[n].model;
@ -146,11 +146,11 @@ pn53x_usb_get_device_model (uint16_t vendor_id, uint16_t product_id)
return UNKNOWN; return UNKNOWN;
} }
int pn53x_usb_ack (nfc_device *pnd); int pn53x_usb_ack(nfc_device *pnd);
// Find transfer endpoints for bulk transfers // Find transfer endpoints for bulk transfers
static void static void
pn53x_usb_get_end_points (struct usb_device *dev, struct pn53x_usb_data *data) pn53x_usb_get_end_points(struct usb_device *dev, struct pn53x_usb_data *data)
{ {
uint32_t uiIndex; uint32_t uiIndex;
uint32_t uiEndPoint; uint32_t uiEndPoint;
@ -179,23 +179,23 @@ pn53x_usb_get_end_points (struct usb_device *dev, struct pn53x_usb_data *data)
} }
bool bool
pn53x_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound) pn53x_usb_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound)
{ {
usb_init (); usb_init();
int res; int res;
// usb_find_busses will find all of the busses on the system. Returns the // usb_find_busses will find all of the busses on the system. Returns the
// number of changes since previous call to this function (total of new // number of changes since previous call to this function (total of new
// busses and busses removed). // busses and busses removed).
if ((res = usb_find_busses () < 0)) { if ((res = usb_find_busses() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror(res));
return false; return false;
} }
// usb_find_devices will find all of the devices on each bus. This should be // usb_find_devices will find all of the devices on each bus. This should be
// called after usb_find_busses. Returns the number of changes since the // called after usb_find_busses. Returns the number of changes since the
// previous call to this function (total of new device and devices removed). // previous call to this function (total of new device and devices removed).
if ((res = usb_find_devices () < 0)) { if ((res = usb_find_devices() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror(res));
return false; return false;
} }
@ -203,11 +203,11 @@ pn53x_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *p
uint32_t uiBusIndex = 0; uint32_t uiBusIndex = 0;
struct usb_bus *bus; struct usb_bus *bus;
for (bus = usb_get_busses (); bus; bus = bus->next) { for (bus = usb_get_busses(); bus; bus = bus->next) {
struct usb_device *dev; struct usb_device *dev;
for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) { for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) {
for (size_t n = 0; n < sizeof (pn53x_usb_supported_devices) / sizeof (struct pn53x_usb_supported_device); n++) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) {
if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) &&
(pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) {
// Make sure there are 2 endpoints available // Make sure there are 2 endpoints available
@ -221,21 +221,21 @@ pn53x_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *p
continue; continue;
} }
usb_dev_handle *udev = usb_open (dev); usb_dev_handle *udev = usb_open(dev);
// Set configuration // Set configuration
res = usb_set_configuration (udev, 1); res = usb_set_configuration(udev, 1);
if (res < 0) { if (res < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res));
usb_close (udev); usb_close(udev);
// we failed to use the device // we failed to use the device
continue; continue;
} }
// pn53x_usb_get_usb_device_name (dev, udev, pnddDevices[*pszDeviceFound].acDevice, sizeof (pnddDevices[*pszDeviceFound].acDevice)); // pn53x_usb_get_usb_device_name (dev, udev, pnddDevices[*pszDeviceFound].acDevice, sizeof (pnddDevices[*pszDeviceFound].acDevice));
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "device found: Bus %s Device %s", bus->dirname, dev->filename); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "device found: Bus %s Device %s", bus->dirname, dev->filename);
usb_close (udev); usb_close(udev);
snprintf (connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%s", PN53X_USB_DRIVER_NAME, bus->dirname, dev->filename); snprintf(connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%s", PN53X_USB_DRIVER_NAME, bus->dirname, dev->filename);
(*pszDeviceFound)++; (*pszDeviceFound)++;
// Test if we reach the maximum "wanted" devices // Test if we reach the maximum "wanted" devices
if ((*pszDeviceFound) == connstrings_len) { if ((*pszDeviceFound) == connstrings_len) {
@ -255,51 +255,51 @@ struct pn53x_usb_descriptor {
}; };
static int static int
pn53x_usb_connstring_decode (const nfc_connstring connstring, struct pn53x_usb_descriptor *desc) pn53x_usb_connstring_decode(const nfc_connstring connstring, struct pn53x_usb_descriptor *desc)
{ {
int n = strlen (connstring) + 1; int n = strlen(connstring) + 1;
char *driver_name = malloc (n); char *driver_name = malloc(n);
char *dirname = malloc (n); char *dirname = malloc(n);
char *filename = malloc (n); char *filename = malloc(n);
driver_name[0] = '\0'; driver_name[0] = '\0';
int res = sscanf (connstring, "%[^:]:%[^:]:%[^:]", driver_name, dirname, filename); int res = sscanf(connstring, "%[^:]:%[^:]:%[^:]", driver_name, dirname, filename);
if (!res || (0 != strcmp (driver_name, PN53X_USB_DRIVER_NAME))) { if (!res || (0 != strcmp(driver_name, PN53X_USB_DRIVER_NAME))) {
// Driver name does not match. // Driver name does not match.
res = 0; res = 0;
} else { } else {
desc->dirname = strdup (dirname); desc->dirname = strdup(dirname);
desc->filename = strdup (filename); desc->filename = strdup(filename);
} }
free (driver_name); free(driver_name);
free (dirname); free(dirname);
free (filename); free(filename);
return res; return res;
} }
bool bool
pn53x_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len) pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len)
{ {
*buffer = '\0'; *buffer = '\0';
if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) { if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) {
if (udev) { if (udev) {
usb_get_string_simple (udev, dev->descriptor.iManufacturer, buffer, len); usb_get_string_simple(udev, dev->descriptor.iManufacturer, buffer, len);
if (strlen (buffer) > 0) if (strlen(buffer) > 0)
strcpy (buffer + strlen (buffer), " / "); strcpy(buffer + strlen(buffer), " / ");
usb_get_string_simple (udev, dev->descriptor.iProduct, buffer + strlen (buffer), len - strlen (buffer)); usb_get_string_simple(udev, dev->descriptor.iProduct, buffer + strlen(buffer), len - strlen(buffer));
} }
} }
if (!*buffer) { if (!*buffer) {
for (size_t n = 0; n < sizeof (pn53x_usb_supported_devices) / sizeof (struct pn53x_usb_supported_device); n++) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) {
if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) &&
(pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) {
strncpy (buffer, pn53x_usb_supported_devices[n].name, len); strncpy(buffer, pn53x_usb_supported_devices[n].name, len);
return true; return true;
} }
} }
@ -309,12 +309,12 @@ pn53x_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, cha
} }
nfc_device * nfc_device *
pn53x_usb_open (const nfc_connstring connstring) pn53x_usb_open(const nfc_connstring connstring)
{ {
nfc_device *pnd = NULL; nfc_device *pnd = NULL;
struct pn53x_usb_descriptor desc = { NULL, NULL }; struct pn53x_usb_descriptor desc = { NULL, NULL };
int connstring_decode_level = pn53x_usb_connstring_decode (connstring, &desc); int connstring_decode_level = pn53x_usb_connstring_decode(connstring, &desc);
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring);
if (connstring_decode_level < 1) { if (connstring_decode_level < 1) {
goto free_mem; goto free_mem;
} }
@ -327,102 +327,102 @@ pn53x_usb_open (const nfc_connstring connstring)
struct usb_bus *bus; struct usb_bus *bus;
struct usb_device *dev; struct usb_device *dev;
usb_init (); usb_init();
int res; int res;
// usb_find_busses will find all of the busses on the system. Returns the // usb_find_busses will find all of the busses on the system. Returns the
// number of changes since previous call to this function (total of new // number of changes since previous call to this function (total of new
// busses and busses removed). // busses and busses removed).
if ((res = usb_find_busses () < 0)) { if ((res = usb_find_busses() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror(res));
goto free_mem; goto free_mem;
} }
// usb_find_devices will find all of the devices on each bus. This should be // usb_find_devices will find all of the devices on each bus. This should be
// called after usb_find_busses. Returns the number of changes since the // called after usb_find_busses. Returns the number of changes since the
// previous call to this function (total of new device and devices removed). // previous call to this function (total of new device and devices removed).
if ((res = usb_find_devices () < 0)) { if ((res = usb_find_devices() < 0)) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror(res));
goto free_mem; goto free_mem;
} }
for (bus = usb_get_busses (); bus; bus = bus->next) { for (bus = usb_get_busses(); bus; bus = bus->next) {
if (connstring_decode_level > 1) { if (connstring_decode_level > 1) {
// A specific bus have been specified // A specific bus have been specified
if (0 != strcmp (bus->dirname, desc.dirname)) if (0 != strcmp(bus->dirname, desc.dirname))
continue; continue;
} }
for (dev = bus->devices; dev; dev = dev->next) { for (dev = bus->devices; dev; dev = dev->next) {
if (connstring_decode_level > 2) { if (connstring_decode_level > 2) {
// A specific dev have been specified // A specific dev have been specified
if (0 != strcmp (dev->filename, desc.filename)) if (0 != strcmp(dev->filename, desc.filename))
continue; continue;
} }
// Open the USB device // Open the USB device
data.pudh = usb_open (dev); data.pudh = usb_open(dev);
// Retrieve end points // Retrieve end points
pn53x_usb_get_end_points (dev, &data); pn53x_usb_get_end_points(dev, &data);
// Set configuration // Set configuration
res = usb_set_configuration (data.pudh, 1); res = usb_set_configuration(data.pudh, 1);
if (res < 0) { if (res < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res));
if (EPERM == -res) { if (EPERM == -res) {
log_put (LOG_CATEGORY, NFC_PRIORITY_WARN, "Please double check USB permissions for device %04x:%04x", dev->descriptor.idVendor, dev->descriptor.idProduct); log_put(LOG_CATEGORY, NFC_PRIORITY_WARN, "Please double check USB permissions for device %04x:%04x", dev->descriptor.idVendor, dev->descriptor.idProduct);
} }
usb_close (data.pudh); usb_close(data.pudh);
// we failed to use the specified device // we failed to use the specified device
goto free_mem; goto free_mem;
} }
res = usb_claim_interface (data.pudh, 0); res = usb_claim_interface(data.pudh, 0);
if (res < 0) { if (res < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror(res));
usb_close (data.pudh); usb_close(data.pudh);
// we failed to use the specified device // we failed to use the specified device
goto free_mem; goto free_mem;
} }
data.model = pn53x_usb_get_device_model (dev->descriptor.idVendor, dev->descriptor.idProduct); data.model = pn53x_usb_get_device_model(dev->descriptor.idVendor, dev->descriptor.idProduct);
// Allocate memory for the device info and specification, fill it and return the info // Allocate memory for the device info and specification, fill it and return the info
pnd = nfc_device_new (connstring); pnd = nfc_device_new(connstring);
pn53x_usb_get_usb_device_name (dev, data.pudh, pnd->name, sizeof (pnd->name)); pn53x_usb_get_usb_device_name(dev, data.pudh, pnd->name, sizeof(pnd->name));
pnd->driver_data = malloc(sizeof(struct pn53x_usb_data)); pnd->driver_data = malloc(sizeof(struct pn53x_usb_data));
*DRIVER_DATA (pnd) = data; *DRIVER_DATA(pnd) = data;
// Alloc and init chip's data // Alloc and init chip's data
pn53x_data_new (pnd, &pn53x_usb_io); pn53x_data_new(pnd, &pn53x_usb_io);
switch (DRIVER_DATA (pnd)->model) { switch (DRIVER_DATA(pnd)->model) {
// empirical tuning // empirical tuning
case ASK_LOGO: case ASK_LOGO:
CHIP_DATA (pnd)->timer_correction = 50; CHIP_DATA(pnd)->timer_correction = 50;
break; break;
case SCM_SCL3711: case SCM_SCL3711:
case NXP_PN533: case NXP_PN533:
CHIP_DATA (pnd)->timer_correction = 46; CHIP_DATA(pnd)->timer_correction = 46;
break; break;
case NXP_PN531: case NXP_PN531:
CHIP_DATA (pnd)->timer_correction = 50; CHIP_DATA(pnd)->timer_correction = 50;
break; break;
case SONY_PN531: case SONY_PN531:
CHIP_DATA (pnd)->timer_correction = 54; CHIP_DATA(pnd)->timer_correction = 54;
break; break;
case SONY_RCS360: case SONY_RCS360:
case UNKNOWN: case UNKNOWN:
CHIP_DATA (pnd)->timer_correction = 0; // TODO: allow user to know if timed functions are available CHIP_DATA(pnd)->timer_correction = 0; // TODO: allow user to know if timed functions are available
break; break;
} }
pnd->driver = &pn53x_usb_driver; pnd->driver = &pn53x_usb_driver;
// HACK1: Send first an ACK as Abort command, to reset chip before talking to it: // HACK1: Send first an ACK as Abort command, to reset chip before talking to it:
pn53x_usb_ack (pnd); pn53x_usb_ack(pnd);
// HACK2: Then send a GetFirmware command to resync USB toggle bit between host & device // HACK2: Then send a GetFirmware command to resync USB toggle bit between host & device
// in case host used set_configuration and expects the device to have reset its toggle bit, which PN53x doesn't do // in case host used set_configuration and expects the device to have reset its toggle bit, which PN53x doesn't do
if (pn53x_usb_init (pnd) < 0) { if (pn53x_usb_init(pnd) < 0) {
usb_close (data.pudh); usb_close(data.pudh);
goto error; goto error;
} }
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
goto free_mem; goto free_mem;
} }
} }
@ -431,64 +431,64 @@ pn53x_usb_open (const nfc_connstring connstring)
error: error:
// Free allocated structure on error. // Free allocated structure on error.
nfc_device_free (pnd); nfc_device_free(pnd);
pnd = NULL; pnd = NULL;
free_mem: free_mem:
free (desc.dirname); free(desc.dirname);
free (desc.filename); free(desc.filename);
return pnd; return pnd;
} }
void void
pn53x_usb_close (nfc_device *pnd) pn53x_usb_close(nfc_device *pnd)
{ {
pn53x_usb_ack (pnd); pn53x_usb_ack(pnd);
pn53x_idle (pnd); pn53x_idle(pnd);
if (DRIVER_DATA (pnd)->model == ASK_LOGO) { if (DRIVER_DATA(pnd)->model == ASK_LOGO) {
/* Set P30, P31, P32, P33, P35 to logic 1 and P34 to 0 logic */ /* Set P30, P31, P32, P33, P35 to logic 1 and P34 to 0 logic */
/* ie. Switch all LEDs off and turn off progressive field */ /* ie. Switch all LEDs off and turn off progressive field */
pn53x_write_register (pnd, PN53X_SFR_P3, 0xFF, _BV (P30) | _BV (P31) | _BV (P32) | _BV (P33) | _BV (P35)); pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P32) | _BV(P33) | _BV(P35));
} }
int res; int res;
if ((res = usb_release_interface (DRIVER_DATA (pnd)->pudh, 0)) < 0) { if ((res = usb_release_interface(DRIVER_DATA(pnd)->pudh, 0)) < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror(res));
} }
if ((res = usb_close (DRIVER_DATA (pnd)->pudh)) < 0) { if ((res = usb_close(DRIVER_DATA(pnd)->pudh)) < 0) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror (res)); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror(res));
} }
pn53x_data_free (pnd); pn53x_data_free(pnd);
nfc_device_free (pnd); nfc_device_free(pnd);
} }
#define PN53X_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) #define PN53X_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD)
int int
pn53x_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) pn53x_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout)
{ {
uint8_t abtFrame[PN53X_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" uint8_t abtFrame[PN53X_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff"
size_t szFrame = 0; size_t szFrame = 0;
int res = 0; int res = 0;
pn53x_build_frame (abtFrame, &szFrame, pbtData, szData); pn53x_build_frame(abtFrame, &szFrame, pbtData, szData);
if ((res = pn53x_usb_bulk_write (DRIVER_DATA (pnd), abtFrame, szFrame, timeout)) < 0) { if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), abtFrame, szFrame, timeout)) < 0) {
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN];
if ((res = pn53x_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), timeout)) < 0) { if ((res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), timeout)) < 0) {
// try to interrupt current device state // try to interrupt current device state
pn53x_usb_ack(pnd); pn53x_usb_ack(pnd);
pnd->last_error = res; pnd->last_error = res;
return pnd->last_error; return pnd->last_error;
} }
if (pn53x_check_ack_frame (pnd, abtRxBuf, res) == 0) { if (pn53x_check_ack_frame(pnd, abtRxBuf, res) == 0) {
// The PN53x is running the sent command // The PN53x is running the sent command
} else { } else {
// For some reasons (eg. send another command while a previous one is // For some reasons (eg. send another command while a previous one is
@ -498,7 +498,7 @@ pn53x_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, co
// pn53x_usb_receive()) will be able to retreive the correct response // pn53x_usb_receive()) will be able to retreive the correct response
// packet. // packet.
// FIXME Sony reader is also affected by this bug but NACK is not supported // FIXME Sony reader is also affected by this bug but NACK is not supported
if ((res = pn53x_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout)) < 0) { if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout)) < 0) {
pnd->last_error = res; pnd->last_error = res;
// try to interrupt current device state // try to interrupt current device state
pn53x_usb_ack(pnd); pn53x_usb_ack(pnd);
@ -511,7 +511,7 @@ pn53x_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, co
#define USB_TIMEOUT_PER_PASS 200 #define USB_TIMEOUT_PER_PASS 200
int int
pn53x_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) pn53x_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout)
{ {
size_t len; size_t len;
off_t offset = 0; off_t offset = 0;
@ -539,12 +539,12 @@ read:
} }
} }
res = pn53x_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), usb_timeout); res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), usb_timeout);
if (res == -USB_TIMEDOUT) { if (res == -USB_TIMEDOUT) {
if (DRIVER_DATA (pnd)->abort_flag) { if (DRIVER_DATA(pnd)->abort_flag) {
DRIVER_DATA (pnd)->abort_flag = false; DRIVER_DATA(pnd)->abort_flag = false;
pn53x_usb_ack (pnd); pn53x_usb_ack(pnd);
pnd->last_error = NFC_EOPABORTED; pnd->last_error = NFC_EOPABORTED;
return pnd->last_error; return pnd->last_error;
} else { } else {
@ -560,8 +560,8 @@ read:
} }
const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff };
if (0 != (memcmp (abtRxBuf, pn53x_preamble, 3))) { if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -569,7 +569,7 @@ read:
if ((0x01 == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { if ((0x01 == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) {
// Error frame // Error frame
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} else if ((0xff == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { } else if ((0xff == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) {
@ -580,7 +580,7 @@ read:
len = (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] - 2; len = (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] - 2;
if (((abtRxBuf[offset] + abtRxBuf[offset + 1] + abtRxBuf[offset + 2]) % 256) != 0) { if (((abtRxBuf[offset] + abtRxBuf[offset + 1] + abtRxBuf[offset + 2]) % 256) != 0) {
// TODO: Retry // TODO: Retry
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -589,7 +589,7 @@ read:
// Normal frame // Normal frame
if (256 != (abtRxBuf[offset] + abtRxBuf[offset + 1])) { if (256 != (abtRxBuf[offset] + abtRxBuf[offset + 1])) {
// TODO: Retry // TODO: Retry
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -600,44 +600,44 @@ read:
} }
if (len > szDataLen) { if (len > szDataLen) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len);
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
// TFI + PD0 (CC+1) // TFI + PD0 (CC+1)
if (abtRxBuf[offset] != 0xD5) { if (abtRxBuf[offset] != 0xD5) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
offset += 1; offset += 1;
if (abtRxBuf[offset] != CHIP_DATA (pnd)->last_command + 1) { if (abtRxBuf[offset] != CHIP_DATA(pnd)->last_command + 1) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
offset += 1; offset += 1;
memcpy (pbtData, abtRxBuf + offset, len); memcpy(pbtData, abtRxBuf + offset, len);
offset += len; offset += len;
uint8_t btDCS = (256 - 0xD5); uint8_t btDCS = (256 - 0xD5);
btDCS -= CHIP_DATA (pnd)->last_command + 1; btDCS -= CHIP_DATA(pnd)->last_command + 1;
for (size_t szPos = 0; szPos < len; szPos++) { for (size_t szPos = 0; szPos < len; szPos++) {
btDCS -= pbtData[szPos]; btDCS -= pbtData[szPos];
} }
if (btDCS != abtRxBuf[offset]) { if (btDCS != abtRxBuf[offset]) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
offset += 1; offset += 1;
if (0x00 != abtRxBuf[offset]) { if (0x00 != abtRxBuf[offset]) {
log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); log_put(LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch");
pnd->last_error = NFC_EIO; pnd->last_error = NFC_EIO;
return pnd->last_error; return pnd->last_error;
} }
@ -647,42 +647,42 @@ read:
} }
int int
pn53x_usb_ack (nfc_device *pnd) pn53x_usb_ack(nfc_device *pnd)
{ {
return pn53x_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *) pn53x_ack_frame, sizeof (pn53x_ack_frame), 0); return pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *) pn53x_ack_frame, sizeof(pn53x_ack_frame), 0);
} }
int int
pn53x_usb_init (nfc_device *pnd) pn53x_usb_init(nfc_device *pnd)
{ {
int res = 0; int res = 0;
// Sometimes PN53x USB doesn't reply ACK one the first frame, so we need to send a dummy one... // Sometimes PN53x USB doesn't reply ACK one the first frame, so we need to send a dummy one...
//pn53x_check_communication (pnd); // Sony RC-S360 doesn't support this command for now so let's use a get_firmware_version instead: //pn53x_check_communication (pnd); // Sony RC-S360 doesn't support this command for now so let's use a get_firmware_version instead:
const uint8_t abtCmd[] = { GetFirmwareVersion }; const uint8_t abtCmd[] = { GetFirmwareVersion };
pn53x_transceive (pnd, abtCmd, sizeof (abtCmd), NULL, 0, 0); pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 0);
// ...and we don't care about error // ...and we don't care about error
pnd->last_error = 0; pnd->last_error = 0;
if (SONY_RCS360 == DRIVER_DATA (pnd)->model) { if (SONY_RCS360 == DRIVER_DATA(pnd)->model) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "SONY RC-S360 initialization."); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "SONY RC-S360 initialization.");
const uint8_t abtCmd2[] = { 0x18, 0x01 }; const uint8_t abtCmd2[] = { 0x18, 0x01 };
pn53x_transceive (pnd, abtCmd2, sizeof (abtCmd2), NULL, 0, 0); pn53x_transceive(pnd, abtCmd2, sizeof(abtCmd2), NULL, 0, 0);
pn53x_usb_ack (pnd); pn53x_usb_ack(pnd);
} }
if ((res = pn53x_init (pnd)) < 0) if ((res = pn53x_init(pnd)) < 0)
return res; return res;
if (ASK_LOGO == DRIVER_DATA (pnd)->model) { if (ASK_LOGO == DRIVER_DATA(pnd)->model) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "ASK LoGO initialization."); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "ASK LoGO initialization.");
/* Internal registers */ /* Internal registers */
/* Disable 100mA current limit, Power on Secure IC (SVDD) */ /* Disable 100mA current limit, Power on Secure IC (SVDD) */
pn53x_write_register (pnd, PN53X_REG_Control_switch_rng, 0xFF, SYMBOL_CURLIMOFF | SYMBOL_SIC_SWITCH_EN | SYMBOL_RANDOM_DATAREADY); pn53x_write_register(pnd, PN53X_REG_Control_switch_rng, 0xFF, SYMBOL_CURLIMOFF | SYMBOL_SIC_SWITCH_EN | SYMBOL_RANDOM_DATAREADY);
/* Select the signal to be output on SIGOUT: Modulation signal (envelope) from the internal coder */ /* Select the signal to be output on SIGOUT: Modulation signal (envelope) from the internal coder */
pn53x_write_register (pnd, PN53X_REG_CIU_TxSel, 0xFF, 0x14); pn53x_write_register(pnd, PN53X_REG_CIU_TxSel, 0xFF, 0x14);
/* SFR Registers */ /* SFR Registers */
/* Setup push-pulls for pins from P30 to P35 */ /* Setup push-pulls for pins from P30 to P35 */
pn53x_write_register (pnd, PN53X_SFR_P3CFGB, 0xFF, 0x37); pn53x_write_register(pnd, PN53X_SFR_P3CFGB, 0xFF, 0x37);
/* /*
On ASK LoGO hardware: On ASK LoGO hardware:
@ -704,32 +704,32 @@ pn53x_usb_init (nfc_device *pnd)
/* Set P30, P31, P33, P35 to logic 1 and P32, P34 to 0 logic */ /* Set P30, P31, P33, P35 to logic 1 and P32, P34 to 0 logic */
/* ie. Switch LED1 on and turn off progressive field */ /* ie. Switch LED1 on and turn off progressive field */
pn53x_write_register (pnd, PN53X_SFR_P3, 0xFF, _BV (P30) | _BV (P31) | _BV (P33) | _BV (P35)); pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P33) | _BV(P35));
} }
return NFC_SUCCESS; return NFC_SUCCESS;
} }
static int static int
pn53x_usb_set_property_bool (nfc_device *pnd, const nfc_property property, const bool bEnable) pn53x_usb_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable)
{ {
int res = 0; int res = 0;
if ((res = pn53x_set_property_bool (pnd, property, bEnable)) < 0) if ((res = pn53x_set_property_bool(pnd, property, bEnable)) < 0)
return res; return res;
switch (DRIVER_DATA (pnd)->model) { switch (DRIVER_DATA(pnd)->model) {
case ASK_LOGO: case ASK_LOGO:
if (NP_ACTIVATE_FIELD == property) { if (NP_ACTIVATE_FIELD == property) {
/* Switch on/off LED2 and Progressive Field GPIO according to ACTIVATE_FIELD option */ /* Switch on/off LED2 and Progressive Field GPIO according to ACTIVATE_FIELD option */
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Switch progressive field %s", bEnable ? "On" : "Off"); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Switch progressive field %s", bEnable ? "On" : "Off");
if ((res = pn53x_write_register (pnd, PN53X_SFR_P3, _BV(P31) | _BV(P34), bEnable ? _BV (P34) : _BV (P31))) < 0) if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P31) | _BV(P34), bEnable ? _BV(P34) : _BV(P31))) < 0)
return NFC_ECHIP; return NFC_ECHIP;
} }
break; break;
case SCM_SCL3711: case SCM_SCL3711:
if (NP_ACTIVATE_FIELD == property) { if (NP_ACTIVATE_FIELD == property) {
// Switch on/off LED according to ACTIVATE_FIELD option // Switch on/off LED according to ACTIVATE_FIELD option
if ((res = pn53x_write_register (pnd, PN53X_SFR_P3, _BV (P32), bEnable ? 0 : _BV (P32))) < 0) if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P32), bEnable ? 0 : _BV(P32))) < 0)
return res; return res;
} }
break; break;
@ -745,9 +745,9 @@ pn53x_usb_set_property_bool (nfc_device *pnd, const nfc_property property, const
} }
static int static int
pn53x_usb_abort_command (nfc_device *pnd) pn53x_usb_abort_command(nfc_device *pnd)
{ {
DRIVER_DATA (pnd)->abort_flag = true; DRIVER_DATA(pnd)->abort_flag = true;
return NFC_SUCCESS; return NFC_SUCCESS;
} }

View file

@ -31,11 +31,11 @@
#include "nfc-internal.h" #include "nfc-internal.h"
bool pn53x_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound); bool pn53x_usb_probe(nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound);
nfc_device *pn53x_usb_open (const nfc_connstring connstring); nfc_device *pn53x_usb_open(const nfc_connstring connstring);
int pn53x_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); int pn53x_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout);
int pn53x_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout); int pn53x_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout);
void pn53x_usb_close (nfc_device *pnd); void pn53x_usb_close(nfc_device *pnd);
extern const struct nfc_driver pn53x_usb_driver; extern const struct nfc_driver pn53x_usb_driver;

View file

@ -38,20 +38,20 @@
* *
*/ */
void void
iso14443a_crc (uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc) iso14443a_crc(uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc)
{ {
uint8_t bt; uint8_t bt;
uint32_t wCrc = 0x6363; uint32_t wCrc = 0x6363;
do { do {
bt = *pbtData++; bt = *pbtData++;
bt = (bt ^ (uint8_t) (wCrc & 0x00FF)); bt = (bt ^(uint8_t)(wCrc & 0x00FF));
bt = (bt ^ (bt << 4)); bt = (bt ^(bt << 4));
wCrc = (wCrc >> 8) ^ ((uint32_t) bt << 8) ^ ((uint32_t) bt << 3) ^ ((uint32_t) bt >> 4); wCrc = (wCrc >> 8) ^((uint32_t) bt << 8) ^((uint32_t) bt << 3) ^((uint32_t) bt >> 4);
} while (--szLen); } while (--szLen);
*pbtCrc++ = (uint8_t) (wCrc & 0xFF); *pbtCrc++ = (uint8_t)(wCrc & 0xFF);
*pbtCrc = (uint8_t) ((wCrc >> 8) & 0xFF); *pbtCrc = (uint8_t)((wCrc >> 8) & 0xFF);
} }
/** /**
@ -59,9 +59,9 @@ iso14443a_crc (uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc)
* *
*/ */
void void
iso14443a_crc_append (uint8_t *pbtData, size_t szLen) iso14443a_crc_append(uint8_t *pbtData, size_t szLen)
{ {
iso14443a_crc (pbtData, szLen, pbtData + szLen); iso14443a_crc(pbtData, szLen, pbtData + szLen);
} }
/** /**
@ -69,7 +69,7 @@ iso14443a_crc_append (uint8_t *pbtData, size_t szLen)
* @see ISO/IEC 14443-4 (5.2.7 Historical bytes) * @see ISO/IEC 14443-4 (5.2.7 Historical bytes)
*/ */
uint8_t * uint8_t *
iso14443a_locate_historical_bytes (uint8_t *pbtAts, size_t szAts, size_t *pszTk) iso14443a_locate_historical_bytes(uint8_t *pbtAts, size_t szAts, size_t *pszTk)
{ {
if (szAts) { if (szAts) {
size_t offset = 1; size_t offset = 1;
@ -96,26 +96,26 @@ iso14443a_locate_historical_bytes (uint8_t *pbtAts, size_t szAts, size_t *pszTk)
* @see ISO/IEC 14443-3 (6.4.4 UID contents and cascade levels) * @see ISO/IEC 14443-3 (6.4.4 UID contents and cascade levels)
*/ */
void void
iso14443_cascade_uid (const uint8_t abtUID[], const size_t szUID, uint8_t *pbtCascadedUID, size_t *pszCascadedUID) iso14443_cascade_uid(const uint8_t abtUID[], const size_t szUID, uint8_t *pbtCascadedUID, size_t *pszCascadedUID)
{ {
switch (szUID) { switch (szUID) {
case 7: case 7:
pbtCascadedUID[0] = 0x88; pbtCascadedUID[0] = 0x88;
memcpy (pbtCascadedUID + 1, abtUID, 7); memcpy(pbtCascadedUID + 1, abtUID, 7);
*pszCascadedUID = 8; *pszCascadedUID = 8;
break; break;
case 10: case 10:
pbtCascadedUID[0] = 0x88; pbtCascadedUID[0] = 0x88;
memcpy (pbtCascadedUID + 1, abtUID, 3); memcpy(pbtCascadedUID + 1, abtUID, 3);
pbtCascadedUID[4] = 0x88; pbtCascadedUID[4] = 0x88;
memcpy (pbtCascadedUID + 5, abtUID + 3, 7); memcpy(pbtCascadedUID + 5, abtUID + 3, 7);
*pszCascadedUID = 12; *pszCascadedUID = 12;
break; break;
case 4: case 4:
default: default:
memcpy (pbtCascadedUID, abtUID, szUID); memcpy(pbtCascadedUID, abtUID, szUID);
*pszCascadedUID = szUID; *pszCascadedUID = szUID;
break; break;
} }

View file

@ -27,7 +27,7 @@
static uint8_t __log_init_counter = 0; static uint8_t __log_init_counter = 0;
int int
log_init (void) log_init(void)
{ {
int res = 0; int res = 0;
@ -41,7 +41,7 @@ log_init (void)
} }
int int
log_fini (void) log_fini(void)
{ {
int res = 0; int res = 0;
if (__log_init_counter >= 1) { if (__log_init_counter >= 1) {
@ -56,12 +56,12 @@ log_fini (void)
} }
void void
log_put (const char *category, const char *priority, const char *format, ...) log_put(const char *category, const char *priority, const char *format, ...)
{ {
va_list va; va_list va;
va_start (va, format); va_start(va, format);
fprintf (stderr, "%s\t%s\t", priority, category); fprintf(stderr, "%s\t%s\t", priority, category);
vfprintf (stderr, format, va); vfprintf(stderr, format, va);
fprintf (stderr, "\n"); fprintf(stderr, "\n");
va_end (va); va_end(va);
} }

View file

@ -34,9 +34,9 @@
// User want debug features // User want debug features
#define LOGGING 1 #define LOGGING 1
int log_init (void); int log_init(void);
int log_fini (void); int log_fini(void);
void log_put (const char *category, const char *priority, const char *format, ...) void log_put(const char *category, const char *priority, const char *format, ...)
# if __has_attribute_format # if __has_attribute_format
__attribute__((format(printf, 3, 4))) __attribute__((format(printf, 3, 4)))
# endif # endif

View file

@ -54,13 +54,13 @@ static const uint8_t ByteMirror[256] = {
}; };
uint8_t uint8_t
mirror (uint8_t bt) mirror(uint8_t bt)
{ {
return ByteMirror[bt]; return ByteMirror[bt];
} }
static void static void
mirror_bytes (uint8_t *pbts, size_t szLen) mirror_bytes(uint8_t *pbts, size_t szLen)
{ {
size_t szByteNr; size_t szByteNr;
@ -71,15 +71,15 @@ mirror_bytes (uint8_t *pbts, size_t szLen)
} }
uint32_t uint32_t
mirror32 (uint32_t ui32Bits) mirror32(uint32_t ui32Bits)
{ {
mirror_bytes ((uint8_t *) & ui32Bits, 4); mirror_bytes((uint8_t *) & ui32Bits, 4);
return ui32Bits; return ui32Bits;
} }
uint64_t uint64_t
mirror64 (uint64_t ui64Bits) mirror64(uint64_t ui64Bits)
{ {
mirror_bytes ((uint8_t *) & ui64Bits, 8); mirror_bytes((uint8_t *) & ui64Bits, 8);
return ui64Bits; return ui64Bits;
} }

View file

@ -29,9 +29,9 @@
# include <nfc/nfc-types.h> # include <nfc/nfc-types.h>
uint8_t mirror (uint8_t bt); uint8_t mirror(uint8_t bt);
uint32_t mirror32 (uint32_t ui32Bits); uint32_t mirror32(uint32_t ui32Bits);
uint64_t mirror64 (uint64_t ui64Bits); uint64_t mirror64(uint64_t ui64Bits);
void mirror_uint8_ts (uint8_t *pbts, size_t szLen); void mirror_uint8_ts(uint8_t *pbts, size_t szLen);
#endif // _LIBNFC_MIRROR_SUBR_H_ #endif // _LIBNFC_MIRROR_SUBR_H_

View file

@ -34,12 +34,12 @@
#include "nfc-internal.h" #include "nfc-internal.h"
nfc_device * nfc_device *
nfc_device_new (const nfc_connstring connstring) nfc_device_new(const nfc_connstring connstring)
{ {
nfc_device *res = malloc (sizeof (*res)); nfc_device *res = malloc(sizeof(*res));
if (!res) { if (!res) {
err (EXIT_FAILURE, "nfc_device_new: malloc"); err(EXIT_FAILURE, "nfc_device_new: malloc");
} }
// Variables initiatialization // Variables initiatialization
@ -51,7 +51,7 @@ nfc_device_new (const nfc_connstring connstring)
res->bEasyFraming = false; res->bEasyFraming = false;
res->bAutoIso14443_4 = false; res->bAutoIso14443_4 = false;
res->last_error = 0; res->last_error = 0;
memcpy (res->connstring, connstring, sizeof (res->connstring)); memcpy(res->connstring, connstring, sizeof(res->connstring));
res->driver_data = NULL; res->driver_data = NULL;
res->chip_data = NULL; res->chip_data = NULL;
@ -59,10 +59,10 @@ nfc_device_new (const nfc_connstring connstring)
} }
void void
nfc_device_free (nfc_device *dev) nfc_device_free(nfc_device *dev)
{ {
if (dev) { if (dev) {
free (dev->driver_data); free(dev->driver_data);
free (dev); free(dev);
} }
} }

View file

@ -28,20 +28,20 @@
#include "iso7816.h" #include "iso7816.h"
int int
nfc_emulate_target (nfc_device *pnd, struct nfc_emulator *emulator) nfc_emulate_target(nfc_device *pnd, struct nfc_emulator *emulator)
{ {
uint8_t abtRx[ISO7816_SHORT_R_APDU_MAX_LEN]; uint8_t abtRx[ISO7816_SHORT_R_APDU_MAX_LEN];
uint8_t abtTx[ISO7816_SHORT_C_APDU_MAX_LEN]; uint8_t abtTx[ISO7816_SHORT_C_APDU_MAX_LEN];
int res; int res;
if ((res = nfc_target_init (pnd, emulator->target, abtRx, sizeof(abtRx), 0)) < 0) { if ((res = nfc_target_init(pnd, emulator->target, abtRx, sizeof(abtRx), 0)) < 0) {
return res; return res;
} }
size_t szRx = res; size_t szRx = res;
int io_res = res; int io_res = res;
while (io_res >= 0) { while (io_res >= 0) {
io_res = emulator->state_machine->io (emulator, abtRx, szRx, abtTx, sizeof (abtTx)); io_res = emulator->state_machine->io(emulator, abtRx, szRx, abtTx, sizeof(abtTx));
if (io_res > 0) { if (io_res > 0) {
if ((res = nfc_target_send_bytes(pnd, abtTx, io_res, 0)) < 0) { if ((res = nfc_target_send_bytes(pnd, abtTx, io_res, 0)) < 0) {
return res; return res;

View file

@ -26,7 +26,7 @@
#include "nfc-internal.h" #include "nfc-internal.h"
void void
prepare_initiator_data (const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t * pszInitiatorData) prepare_initiator_data(const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t * pszInitiatorData)
{ {
switch (nm.nmt) { switch (nm.nmt) {
case NMT_ISO14443B: { case NMT_ISO14443B: {

View file

@ -136,35 +136,35 @@
struct nfc_driver { struct nfc_driver {
const char *name; const char *name;
bool (*probe)(nfc_connstring connstrings[], size_t connstrings_len, size_t * pszDeviceFound); bool (*probe)(nfc_connstring connstrings[], size_t connstrings_len, size_t * pszDeviceFound);
struct nfc_device *(*open) (const nfc_connstring connstring); struct nfc_device *(*open)(const nfc_connstring connstring);
void (*close) (struct nfc_device *pnd); void (*close)(struct nfc_device *pnd);
const char *(*strerror) (const struct nfc_device *pnd); const char *(*strerror)(const struct nfc_device *pnd);
int (*initiator_init) (struct nfc_device *pnd); int (*initiator_init)(struct nfc_device *pnd);
int (*initiator_select_passive_target) (struct nfc_device *pnd, const nfc_modulation nm, const uint8_t * pbtInitData, const size_t szInitData, nfc_target * pnt); int (*initiator_select_passive_target)(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t * pbtInitData, const size_t szInitData, nfc_target * pnt);
int (*initiator_poll_target) (struct nfc_device *pnd, const nfc_modulation * pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t btPeriod, nfc_target * pnt); int (*initiator_poll_target)(struct nfc_device *pnd, const nfc_modulation * pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t btPeriod, nfc_target * pnt);
int (*initiator_select_dep_target) (struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info * pndiInitiator, nfc_target * pnt, const int timeout); int (*initiator_select_dep_target)(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info * pndiInitiator, nfc_target * pnt, const int timeout);
int (*initiator_deselect_target) (struct nfc_device *pnd); int (*initiator_deselect_target)(struct nfc_device *pnd);
int (*initiator_transceive_bytes) (struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTx, uint8_t * pbtRx, const size_t szRx, int timeout); int (*initiator_transceive_bytes)(struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTx, uint8_t * pbtRx, const size_t szRx, int timeout);
int (*initiator_transceive_bits) (struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTxBits, const uint8_t * pbtTxPar, uint8_t * pbtRx, uint8_t * pbtRxPar); int (*initiator_transceive_bits)(struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTxBits, const uint8_t * pbtTxPar, uint8_t * pbtRx, uint8_t * pbtRxPar);
int (*initiator_transceive_bytes_timed) (struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTx, uint8_t * pbtRx, uint32_t * cycles); int (*initiator_transceive_bytes_timed)(struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTx, uint8_t * pbtRx, uint32_t * cycles);
int (*initiator_transceive_bits_timed) (struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTxBits, const uint8_t * pbtTxPar, uint8_t * pbtRx, uint8_t * pbtRxPar, uint32_t * cycles); int (*initiator_transceive_bits_timed)(struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTxBits, const uint8_t * pbtTxPar, uint8_t * pbtRx, uint8_t * pbtRxPar, uint32_t * cycles);
int (*initiator_target_is_present) (struct nfc_device *pnd, const nfc_target nt); int (*initiator_target_is_present)(struct nfc_device *pnd, const nfc_target nt);
int (*target_init) (struct nfc_device *pnd, nfc_target * pnt, uint8_t * pbtRx, const size_t szRx, int timeout); int (*target_init)(struct nfc_device *pnd, nfc_target * pnt, uint8_t * pbtRx, const size_t szRx, int timeout);
int (*target_send_bytes) (struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTx, int timeout); int (*target_send_bytes)(struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTx, int timeout);
int (*target_receive_bytes) (struct nfc_device *pnd, uint8_t * pbtRx, const size_t szRxLen, int timeout); int (*target_receive_bytes)(struct nfc_device *pnd, uint8_t * pbtRx, const size_t szRxLen, int timeout);
int (*target_send_bits) (struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTxBits, const uint8_t * pbtTxPar); int (*target_send_bits)(struct nfc_device *pnd, const uint8_t * pbtTx, const size_t szTxBits, const uint8_t * pbtTxPar);
int (*target_receive_bits) (struct nfc_device *pnd, uint8_t * pbtRx, const size_t szRxLen, uint8_t * pbtRxPar); int (*target_receive_bits)(struct nfc_device *pnd, uint8_t * pbtRx, const size_t szRxLen, uint8_t * pbtRxPar);
int (*device_set_property_bool) (struct nfc_device *pnd, const nfc_property property, const bool bEnable); int (*device_set_property_bool)(struct nfc_device *pnd, const nfc_property property, const bool bEnable);
int (*device_set_property_int) (struct nfc_device *pnd, const nfc_property property, const int value); int (*device_set_property_int)(struct nfc_device *pnd, const nfc_property property, const int value);
int (*get_supported_modulation) (struct nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt); int (*get_supported_modulation)(struct nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt);
int (*get_supported_baud_rate) (struct nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); int (*get_supported_baud_rate)(struct nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br);
int (*device_get_information_about) (struct nfc_device *pnd, char *buf, size_t buflen); int (*device_get_information_about)(struct nfc_device *pnd, char *buf, size_t buflen);
int (*abort_command) (struct nfc_device *pnd); int (*abort_command)(struct nfc_device *pnd);
int (*idle) (struct nfc_device *pnd); int (*idle)(struct nfc_device *pnd);
}; };
# define DEVICE_NAME_LENGTH 256 # define DEVICE_NAME_LENGTH 256
@ -198,11 +198,11 @@ struct nfc_device {
int last_error; int last_error;
}; };
nfc_device *nfc_device_new (const nfc_connstring connstring); nfc_device *nfc_device_new(const nfc_connstring connstring);
void nfc_device_free (nfc_device *dev); void nfc_device_free(nfc_device *dev);
void iso14443_cascade_uid (const uint8_t abtUID[], const size_t szUID, uint8_t * pbtCascadedUID, size_t * pszCascadedUID); void iso14443_cascade_uid(const uint8_t abtUID[], const size_t szUID, uint8_t * pbtCascadedUID, size_t * pszCascadedUID);
void prepare_initiator_data (const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t * pszInitiatorData); void prepare_initiator_data(const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t * pszInitiatorData);
#endif // __NFC_INTERNAL_H__ #endif // __NFC_INTERNAL_H__

View file

@ -111,7 +111,7 @@ void
nfc_init(nfc_context *context) nfc_init(nfc_context *context)
{ {
(void) context; (void) context;
log_init (); log_init();
} }
/** @ingroup lib /** @ingroup lib
@ -123,7 +123,7 @@ void
nfc_exit(nfc_context *context) nfc_exit(nfc_context *context)
{ {
(void) context; (void) context;
log_fini (); log_fini();
} }
/** @ingroup dev /** @ingroup dev
@ -141,20 +141,20 @@ nfc_exit(nfc_context *context)
* set with incorrect value. * set with incorrect value.
*/ */
bool bool
nfc_get_default_device (nfc_connstring *connstring) nfc_get_default_device(nfc_connstring *connstring)
{ {
char *env_default_connstring = getenv ("LIBNFC_DEFAULT_DEVICE"); char *env_default_connstring = getenv("LIBNFC_DEFAULT_DEVICE");
if (NULL == env_default_connstring) { if (NULL == env_default_connstring) {
// LIBNFC_DEFAULT_DEVICE is not set, we fallback on probing for the first available device // LIBNFC_DEFAULT_DEVICE is not set, we fallback on probing for the first available device
nfc_connstring listed_cs[1]; nfc_connstring listed_cs[1];
size_t szDeviceFound = nfc_list_devices (NULL, listed_cs, 1); size_t szDeviceFound = nfc_list_devices(NULL, listed_cs, 1);
if (szDeviceFound) { if (szDeviceFound) {
strncpy (*connstring, listed_cs[0], sizeof(nfc_connstring)); strncpy(*connstring, listed_cs[0], sizeof(nfc_connstring));
} else { } else {
return false; return false;
} }
} else { } else {
strncpy (*connstring, env_default_connstring, sizeof(nfc_connstring)); strncpy(*connstring, env_default_connstring, sizeof(nfc_connstring));
} }
return true; return true;
} }
@ -177,19 +177,19 @@ nfc_get_default_device (nfc_connstring *connstring)
* optionally followed by manual tuning of the parameters if the default parameters are not suiting your goals. * optionally followed by manual tuning of the parameters if the default parameters are not suiting your goals.
*/ */
nfc_device * nfc_device *
nfc_open (nfc_context *context, const nfc_connstring connstring) nfc_open(nfc_context *context, const nfc_connstring connstring)
{ {
(void) context; (void) context;
nfc_device *pnd = NULL; nfc_device *pnd = NULL;
nfc_connstring ncs; nfc_connstring ncs;
if (connstring == NULL) { if (connstring == NULL) {
if (!nfc_get_default_device (&ncs)) { if (!nfc_get_default_device(&ncs)) {
log_fini (); log_fini();
return NULL; return NULL;
} }
} else { } else {
strncpy (ncs, connstring, sizeof (nfc_connstring)); strncpy(ncs, connstring, sizeof(nfc_connstring));
} }
// Search through the device list for an available device // Search through the device list for an available device
@ -197,27 +197,27 @@ nfc_open (nfc_context *context, const nfc_connstring connstring)
const struct nfc_driver **pndr = nfc_drivers; const struct nfc_driver **pndr = nfc_drivers;
while ((ndr = *pndr)) { while ((ndr = *pndr)) {
// Specific device is requested: using device description // Specific device is requested: using device description
if (0 != strncmp (ndr->name, ncs, strlen(ndr->name))) { if (0 != strncmp(ndr->name, ncs, strlen(ndr->name))) {
pndr++; pndr++;
continue; continue;
} }
pnd = ndr->open (ncs); pnd = ndr->open(ncs);
// Test if the opening was successful // Test if the opening was successful
if (pnd == NULL) { if (pnd == NULL) {
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Unable to open \"%s\".", ncs); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "Unable to open \"%s\".", ncs);
log_fini (); log_fini();
return pnd; return pnd;
} }
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "\"%s\" (%s) has been claimed.", pnd->name, pnd->connstring); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "\"%s\" (%s) has been claimed.", pnd->name, pnd->connstring);
log_fini (); log_fini();
return pnd; return pnd;
} }
// Too bad, no driver can decode connstring // Too bad, no driver can decode connstring
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "No driver available to handle \"%s\".", ncs); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "No driver available to handle \"%s\".", ncs);
log_fini (); log_fini();
return NULL; return NULL;
} }
@ -228,13 +228,13 @@ nfc_open (nfc_context *context, const nfc_connstring connstring)
* Initiator's selected tag is closed and the device, including allocated \a nfc_device struct, is released. * Initiator's selected tag is closed and the device, including allocated \a nfc_device struct, is released.
*/ */
void void
nfc_close (nfc_device *pnd) nfc_close(nfc_device *pnd)
{ {
if (pnd) { if (pnd) {
// Go in idle mode // Go in idle mode
nfc_idle (pnd); nfc_idle(pnd);
// Close, clean up and release the device // Close, clean up and release the device
pnd->driver->close (pnd); pnd->driver->close(pnd);
} }
} }
@ -248,7 +248,7 @@ nfc_close (nfc_device *pnd)
* *
*/ */
size_t size_t
nfc_list_devices (nfc_context *context, nfc_connstring connstrings[] , size_t szDevices) nfc_list_devices(nfc_context *context, nfc_connstring connstrings[] , size_t szDevices)
{ {
size_t szN; size_t szN;
size_t szDeviceFound = 0; size_t szDeviceFound = 0;
@ -259,15 +259,15 @@ nfc_list_devices (nfc_context *context, nfc_connstring connstrings[] , size_t sz
while ((ndr = *pndr)) { while ((ndr = *pndr)) {
szN = 0; szN = 0;
if (ndr->probe (connstrings + (szDeviceFound), szDevices - (szDeviceFound), &szN)) { if (ndr->probe(connstrings + (szDeviceFound), szDevices - (szDeviceFound), &szN)) {
szDeviceFound += szN; szDeviceFound += szN;
log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%ld device(s) found using %s driver", (unsigned long) szN, ndr->name); log_put(LOG_CATEGORY, NFC_PRIORITY_TRACE, "%ld device(s) found using %s driver", (unsigned long) szN, ndr->name);
if (szDeviceFound == szDevices) if (szDeviceFound == szDevices)
break; break;
} }
pndr++; pndr++;
} }
log_fini (); log_fini();
return szDeviceFound; return szDeviceFound;
} }
@ -283,9 +283,9 @@ nfc_list_devices (nfc_context *context, nfc_connstring connstrings[] , size_t sz
* @see nfc_property enum values * @see nfc_property enum values
*/ */
int int
nfc_device_set_property_int (nfc_device *pnd, const nfc_property property, const int value) nfc_device_set_property_int(nfc_device *pnd, const nfc_property property, const int value)
{ {
HAL (device_set_property_int, pnd, property, value); HAL(device_set_property_int, pnd, property, value);
} }
@ -302,9 +302,9 @@ nfc_device_set_property_int (nfc_device *pnd, const nfc_property property, const
* accept). * accept).
*/ */
int int
nfc_device_set_property_bool (nfc_device *pnd, const nfc_property property, const bool bEnable) nfc_device_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable)
{ {
HAL (device_set_property_bool, pnd, property, bEnable); HAL(device_set_property_bool, pnd, property, bEnable);
} }
/** @ingroup initiator /** @ingroup initiator
@ -328,46 +328,46 @@ nfc_device_set_property_bool (nfc_device *pnd, const nfc_property property, cons
* - RF field is shortly dropped (if it was enabled) then activated again * - RF field is shortly dropped (if it was enabled) then activated again
*/ */
int int
nfc_initiator_init (nfc_device *pnd) nfc_initiator_init(nfc_device *pnd)
{ {
int res = 0; int res = 0;
// Drop the field for a while // Drop the field for a while
if ((res = nfc_device_set_property_bool (pnd, NP_ACTIVATE_FIELD, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0)
return res; return res;
// Enable field so more power consuming cards can power themselves up // Enable field so more power consuming cards can power themselves up
if ((res = nfc_device_set_property_bool (pnd, NP_ACTIVATE_FIELD, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, true)) < 0)
return res; return res;
// Let the device try forever to find a target/tag // Let the device try forever to find a target/tag
if ((res = nfc_device_set_property_bool (pnd, NP_INFINITE_SELECT, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0)
return res; return res;
// Activate auto ISO14443-4 switching by default // Activate auto ISO14443-4 switching by default
if ((res = nfc_device_set_property_bool (pnd, NP_AUTO_ISO14443_4, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, true)) < 0)
return res; return res;
// Force 14443-A mode // Force 14443-A mode
if ((res = nfc_device_set_property_bool (pnd, NP_FORCE_ISO14443_A, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_ISO14443_A, true)) < 0)
return res; return res;
// Force speed at 106kbps // Force speed at 106kbps
if ((res = nfc_device_set_property_bool (pnd, NP_FORCE_SPEED_106, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_SPEED_106, true)) < 0)
return res; return res;
// Disallow invalid frame // Disallow invalid frame
if ((res = nfc_device_set_property_bool (pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0)
return res; return res;
// Disallow multiple frames // Disallow multiple frames
if ((res = nfc_device_set_property_bool (pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0)
return res; return res;
// Make sure we reset the CRC and parity to chip handling. // Make sure we reset the CRC and parity to chip handling.
if ((res = nfc_device_set_property_bool (pnd, NP_HANDLE_CRC, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0)
return res; return res;
if ((res = nfc_device_set_property_bool (pnd, NP_HANDLE_PARITY, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, true)) < 0)
return res; return res;
// Activate "easy framing" feature by default // Activate "easy framing" feature by default
if ((res = nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0)
return res; return res;
// Deactivate the CRYPTO1 cipher, it may could cause problems when still active // Deactivate the CRYPTO1 cipher, it may could cause problems when still active
if ((res = nfc_device_set_property_bool (pnd, NP_ACTIVATE_CRYPTO1, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_CRYPTO1, false)) < 0)
return res; return res;
HAL (initiator_init, pnd); HAL(initiator_init, pnd);
} }
/** @ingroup initiator /** @ingroup initiator
@ -391,17 +391,17 @@ nfc_initiator_init (nfc_device *pnd)
* the initial modulation and speed (106, 212 or 424 kbps) should be supplied. * the initial modulation and speed (106, 212 or 424 kbps) should be supplied.
*/ */
int int
nfc_initiator_select_passive_target (nfc_device *pnd, nfc_initiator_select_passive_target(nfc_device *pnd,
const nfc_modulation nm, const nfc_modulation nm,
const uint8_t *pbtInitData, const size_t szInitData, const uint8_t *pbtInitData, const size_t szInitData,
nfc_target *pnt) nfc_target *pnt)
{ {
uint8_t abtInit[MAX(12, szInitData)]; uint8_t abtInit[MAX(12, szInitData)];
size_t szInit; size_t szInit;
switch (nm.nmt) { switch (nm.nmt) {
case NMT_ISO14443A: case NMT_ISO14443A:
iso14443_cascade_uid (pbtInitData, szInitData, abtInit, &szInit); iso14443_cascade_uid(pbtInitData, szInitData, abtInit, &szInit);
break; break;
case NMT_JEWEL: case NMT_JEWEL:
@ -411,12 +411,12 @@ nfc_initiator_select_passive_target (nfc_device *pnd,
case NMT_ISO14443B2CT: case NMT_ISO14443B2CT:
case NMT_FELICA: case NMT_FELICA:
case NMT_DEP: case NMT_DEP:
memcpy (abtInit, pbtInitData, szInitData); memcpy(abtInit, pbtInitData, szInitData);
szInit = szInitData; szInit = szInitData;
break; break;
} }
HAL (initiator_select_passive_target, pnd, nm, abtInit, szInit, pnt); HAL(initiator_select_passive_target, pnd, nm, abtInit, szInit, pnt);
} }
/** @ingroup initiator /** @ingroup initiator
@ -436,9 +436,9 @@ nfc_initiator_select_passive_target (nfc_device *pnd,
* should be supplied. * should be supplied.
*/ */
int int
nfc_initiator_list_passive_targets (nfc_device *pnd, nfc_initiator_list_passive_targets(nfc_device *pnd,
const nfc_modulation nm, const nfc_modulation nm,
nfc_target ant[], const size_t szTargets) nfc_target ant[], const size_t szTargets)
{ {
nfc_target nt; nfc_target nt;
size_t szTargetFound = 0; size_t szTargetFound = 0;
@ -449,14 +449,14 @@ nfc_initiator_list_passive_targets (nfc_device *pnd,
pnd->last_error = 0; pnd->last_error = 0;
// Let the reader only try once to find a tag // Let the reader only try once to find a tag
if ((res = nfc_device_set_property_bool (pnd, NP_INFINITE_SELECT, false)) < 0) { if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false)) < 0) {
return res; return res;
} }
prepare_initiator_data (nm, &pbtInitData, &szInitDataLen); prepare_initiator_data(nm, &pbtInitData, &szInitDataLen);
while (nfc_initiator_select_passive_target (pnd, nm, pbtInitData, szInitDataLen, &nt) > 0) { while (nfc_initiator_select_passive_target(pnd, nm, pbtInitData, szInitDataLen, &nt) > 0) {
nfc_initiator_deselect_target (pnd); nfc_initiator_deselect_target(pnd);
if (szTargets == szTargetFound) { if (szTargets == szTargetFound) {
break; break;
} }
@ -464,14 +464,14 @@ nfc_initiator_list_passive_targets (nfc_device *pnd,
bool seen = false; bool seen = false;
// Check if we've already seen this tag // Check if we've already seen this tag
for (i = 0; i < szTargetFound; i++) { for (i = 0; i < szTargetFound; i++) {
if (memcmp(&(ant[i]), &nt, sizeof (nfc_target)) == 0) { if (memcmp(&(ant[i]), &nt, sizeof(nfc_target)) == 0) {
seen = true; seen = true;
} }
} }
if (seen) { if (seen) {
break; break;
} }
memcpy (&(ant[szTargetFound]), &nt, sizeof (nfc_target)); memcpy(&(ant[szTargetFound]), &nt, sizeof(nfc_target));
szTargetFound++; szTargetFound++;
// deselect has no effect on FeliCa and Jewel cards so we'll stop after one... // deselect has no effect on FeliCa and Jewel cards so we'll stop after one...
// ISO/IEC 14443 B' cards are polled at 100% probability so it's not possible to detect correctly two cards at the same time // ISO/IEC 14443 B' cards are polled at 100% probability so it's not possible to detect correctly two cards at the same time
@ -496,12 +496,12 @@ nfc_initiator_list_passive_targets (nfc_device *pnd,
* @param[out] pnt pointer on \a nfc_target (over)writable struct * @param[out] pnt pointer on \a nfc_target (over)writable struct
*/ */
int int
nfc_initiator_poll_target (nfc_device *pnd, nfc_initiator_poll_target(nfc_device *pnd,
const nfc_modulation *pnmModulations, const size_t szModulations, const nfc_modulation *pnmModulations, const size_t szModulations,
const uint8_t uiPollNr, const uint8_t uiPeriod, const uint8_t uiPollNr, const uint8_t uiPeriod,
nfc_target *pnt) nfc_target *pnt)
{ {
HAL (initiator_poll_target, pnd, pnmModulations, szModulations, uiPollNr, uiPeriod, pnt); HAL(initiator_poll_target, pnd, pnmModulations, szModulations, uiPollNr, uiPeriod, pnt);
} }
@ -523,11 +523,11 @@ nfc_initiator_poll_target (nfc_device *pnd,
* @note \a nfc_dep_info will be returned when the target was acquired successfully. * @note \a nfc_dep_info will be returned when the target was acquired successfully.
*/ */
int int
nfc_initiator_select_dep_target (nfc_device *pnd, nfc_initiator_select_dep_target(nfc_device *pnd,
const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_mode ndm, const nfc_baud_rate nbr,
const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout) const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout)
{ {
HAL (initiator_select_dep_target, pnd, ndm, nbr, pndiInitiator, pnt, timeout); HAL(initiator_select_dep_target, pnd, ndm, nbr, pndiInitiator, pnt, timeout);
} }
/** @ingroup initiator /** @ingroup initiator
@ -548,19 +548,19 @@ nfc_initiator_select_dep_target (nfc_device *pnd,
* @note \a nfc_dep_info will be returned when the target was acquired successfully. * @note \a nfc_dep_info will be returned when the target was acquired successfully.
*/ */
int int
nfc_initiator_poll_dep_target (struct nfc_device *pnd, nfc_initiator_poll_dep_target(struct nfc_device *pnd,
const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_mode ndm, const nfc_baud_rate nbr,
const nfc_dep_info *pndiInitiator, const nfc_dep_info *pndiInitiator,
nfc_target *pnt, nfc_target *pnt,
const int timeout) const int timeout)
{ {
const int period = 300; const int period = 300;
int remaining_time = timeout; int remaining_time = timeout;
int res; int res;
if ((res = nfc_device_set_property_bool (pnd, NP_INFINITE_SELECT, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0)
return res; return res;
while (remaining_time > 0) { while (remaining_time > 0) {
if ((res = nfc_initiator_select_dep_target (pnd, ndm, nbr, pndiInitiator, pnt, period)) < 0) { if ((res = nfc_initiator_select_dep_target(pnd, ndm, nbr, pndiInitiator, pnt, period)) < 0) {
if (res != NFC_ETIMEOUT) if (res != NFC_ETIMEOUT)
return res; return res;
} }
@ -584,9 +584,9 @@ nfc_initiator_poll_dep_target (struct nfc_device *pnd,
* the next tag until the correct tag is found. * the next tag until the correct tag is found.
*/ */
int int
nfc_initiator_deselect_target (nfc_device *pnd) nfc_initiator_deselect_target(nfc_device *pnd)
{ {
HAL (initiator_deselect_target, pnd); HAL(initiator_deselect_target, pnd);
} }
/** @ingroup initiator /** @ingroup initiator
@ -616,10 +616,10 @@ nfc_initiator_deselect_target (nfc_device *pnd)
* @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value).
*/ */
int int
nfc_initiator_transceive_bytes (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, nfc_initiator_transceive_bytes(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx,
const size_t szRx, int timeout) const size_t szRx, int timeout)
{ {
HAL (initiator_transceive_bytes, pnd, pbtTx, szTx, pbtRx, szRx, timeout) HAL(initiator_transceive_bytes, pnd, pbtTx, szTx, pbtRx, szRx, timeout)
} }
/** @ingroup initiator /** @ingroup initiator
@ -658,10 +658,10 @@ nfc_initiator_transceive_bytes (nfc_device *pnd, const uint8_t *pbtTx, const siz
* CRC bytes. Using this feature you are able to simulate these frames. * CRC bytes. Using this feature you are able to simulate these frames.
*/ */
int int
nfc_initiator_transceive_bits (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, nfc_initiator_transceive_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar,
uint8_t *pbtRx, uint8_t *pbtRxPar) uint8_t *pbtRx, uint8_t *pbtRxPar)
{ {
HAL (initiator_transceive_bits, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar); HAL(initiator_transceive_bits, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar);
} }
/** @ingroup initiator /** @ingroup initiator
@ -685,9 +685,9 @@ nfc_initiator_transceive_bits (nfc_device *pnd, const uint8_t *pbtTx, const size
* @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value).
*/ */
int int
nfc_initiator_transceive_bytes_timed (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, uint32_t *cycles) nfc_initiator_transceive_bytes_timed(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, uint32_t *cycles)
{ {
HAL (initiator_transceive_bytes_timed, pnd, pbtTx, szTx, pbtRx, cycles); HAL(initiator_transceive_bytes_timed, pnd, pbtTx, szTx, pbtRx, cycles);
} }
/** @ingroup initiator /** @ingroup initiator
@ -699,9 +699,9 @@ nfc_initiator_transceive_bytes_timed (nfc_device *pnd, const uint8_t *pbtTx, con
* @warning To run the test, one or more commands will be sent to target * @warning To run the test, one or more commands will be sent to target
*/ */
int int
nfc_initiator_target_is_present (nfc_device *pnd, const nfc_target nt) nfc_initiator_target_is_present(nfc_device *pnd, const nfc_target nt)
{ {
HAL (initiator_target_is_present, pnd, nt); HAL(initiator_target_is_present, pnd, nt);
} }
/** @ingroup initiator /** @ingroup initiator
@ -726,10 +726,10 @@ nfc_initiator_target_is_present (nfc_device *pnd, const nfc_target nt)
* @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value).
*/ */
int int
nfc_initiator_transceive_bits_timed (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, nfc_initiator_transceive_bits_timed(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar,
uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles) uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles)
{ {
HAL (initiator_transceive_bits_timed, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar, cycles); HAL(initiator_transceive_bits_timed, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar, cycles);
} }
/** @ingroup target /** @ingroup target
@ -763,34 +763,34 @@ nfc_initiator_transceive_bits_timed (nfc_device *pnd, const uint8_t *pbtTx, cons
* receive functions can be used. * receive functions can be used.
*/ */
int int
nfc_target_init (nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout) nfc_target_init(nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout)
{ {
int res = 0; int res = 0;
// Disallow invalid frame // Disallow invalid frame
if ((res = nfc_device_set_property_bool (pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0)
return res; return res;
// Disallow multiple frames // Disallow multiple frames
if ((res = nfc_device_set_property_bool (pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0)
return res; return res;
// Make sure we reset the CRC and parity to chip handling. // Make sure we reset the CRC and parity to chip handling.
if ((res = nfc_device_set_property_bool (pnd, NP_HANDLE_CRC, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0)
return res; return res;
if ((res = nfc_device_set_property_bool (pnd, NP_HANDLE_PARITY, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, true)) < 0)
return res; return res;
// Activate auto ISO14443-4 switching by default // Activate auto ISO14443-4 switching by default
if ((res = nfc_device_set_property_bool (pnd, NP_AUTO_ISO14443_4, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, true)) < 0)
return res; return res;
// Activate "easy framing" feature by default // Activate "easy framing" feature by default
if ((res = nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, true)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0)
return res; return res;
// Deactivate the CRYPTO1 cipher, it may could cause problems when still active // Deactivate the CRYPTO1 cipher, it may could cause problems when still active
if ((res = nfc_device_set_property_bool (pnd, NP_ACTIVATE_CRYPTO1, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_CRYPTO1, false)) < 0)
return res; return res;
// Drop explicitely the field // Drop explicitely the field
if ((res = nfc_device_set_property_bool (pnd, NP_ACTIVATE_FIELD, false)) < 0) if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0)
return res; return res;
HAL (target_init, pnd, pnt, pbtRx, szRx, timeout); HAL(target_init, pnd, pnt, pbtRx, szRx, timeout);
} }
/** @ingroup dev /** @ingroup dev
@ -804,9 +804,9 @@ nfc_target_init (nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t
* In target mode, the emulation is stoped (no target available from external initiator) and the device is set to low power mode (if avaible). * In target mode, the emulation is stoped (no target available from external initiator) and the device is set to low power mode (if avaible).
*/ */
int int
nfc_idle (nfc_device *pnd) nfc_idle(nfc_device *pnd)
{ {
HAL (idle, pnd); HAL(idle, pnd);
} }
/** @ingroup dev /** @ingroup dev
@ -821,9 +821,9 @@ nfc_idle (nfc_device *pnd)
* @note The blocking function (ie. nfc_target_init()) will failed with DEABORT error. * @note The blocking function (ie. nfc_target_init()) will failed with DEABORT error.
*/ */
int int
nfc_abort_command (nfc_device *pnd) nfc_abort_command(nfc_device *pnd)
{ {
HAL (abort_command, pnd); HAL(abort_command, pnd);
} }
/** @ingroup target /** @ingroup target
@ -842,9 +842,9 @@ nfc_abort_command (nfc_device *pnd)
* If timeout is a null pointer, the function blocks indefinitely (until an error is raised or function is completed). * If timeout is a null pointer, the function blocks indefinitely (until an error is raised or function is completed).
*/ */
int int
nfc_target_send_bytes (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout) nfc_target_send_bytes(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout)
{ {
HAL (target_send_bytes, pnd, pbtTx, szTx, timeout); HAL(target_send_bytes, pnd, pbtTx, szTx, timeout);
} }
/** @ingroup target /** @ingroup target
@ -862,9 +862,9 @@ nfc_target_send_bytes (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx,
* If timeout equals to -1, the default timeout will be used * If timeout equals to -1, the default timeout will be used
*/ */
int int
nfc_target_receive_bytes (nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, int timeout) nfc_target_receive_bytes(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, int timeout)
{ {
HAL (target_receive_bytes, pnd, pbtRx, szRx, timeout); HAL(target_receive_bytes, pnd, pbtRx, szRx, timeout);
} }
/** @ingroup target /** @ingroup target
@ -879,9 +879,9 @@ nfc_target_receive_bytes (nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, in
* using the specified NFC device (configured as \e target). * using the specified NFC device (configured as \e target).
*/ */
int int
nfc_target_send_bits (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar) nfc_target_send_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar)
{ {
HAL (target_send_bits, pnd, pbtTx, szTxBits, pbtTxPar); HAL(target_send_bits, pnd, pbtTx, szTxBits, pbtTxPar);
} }
/** @ingroup target /** @ingroup target
@ -901,9 +901,9 @@ nfc_target_send_bits (nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBi
* frames. * frames.
*/ */
int int
nfc_target_receive_bits (nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar) nfc_target_receive_bits(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar)
{ {
HAL (target_receive_bits, pnd, pbtRx, szRx, pbtRxPar); HAL(target_receive_bits, pnd, pbtRx, szRx, pbtRxPar);
} }
static struct sErrorMessage { static struct sErrorMessage {
@ -932,11 +932,11 @@ static struct sErrorMessage {
* @param pnd \a nfc_device struct pointer that represent currently used device * @param pnd \a nfc_device struct pointer that represent currently used device
*/ */
const char * const char *
nfc_strerror (const nfc_device *pnd) nfc_strerror(const nfc_device *pnd)
{ {
const char *pcRes = "Unknown error"; const char *pcRes = "Unknown error";
size_t i; size_t i;
for (i = 0; i < (sizeof (sErrorMessages) / sizeof (struct sErrorMessage)); i++) { for (i = 0; i < (sizeof(sErrorMessages) / sizeof(struct sErrorMessage)); i++) {
if (sErrorMessages[i].iErrorCode == pnd->last_error) { if (sErrorMessages[i].iErrorCode == pnd->last_error) {
pcRes = sErrorMessages[i].pcErrorMsg; pcRes = sErrorMessages[i].pcErrorMsg;
break; break;
@ -955,9 +955,9 @@ nfc_strerror (const nfc_device *pnd)
* @param szBufLen size of buffer * @param szBufLen size of buffer
*/ */
int int
nfc_strerror_r (const nfc_device *pnd, char *pcStrErrBuf, size_t szBufLen) nfc_strerror_r(const nfc_device *pnd, char *pcStrErrBuf, size_t szBufLen)
{ {
return (snprintf (pcStrErrBuf, szBufLen, "%s", nfc_strerror (pnd)) < 0) ? -1 : 0; return (snprintf(pcStrErrBuf, szBufLen, "%s", nfc_strerror(pnd)) < 0) ? -1 : 0;
} }
/** @ingroup error /** @ingroup error
@ -967,9 +967,9 @@ nfc_strerror_r (const nfc_device *pnd, char *pcStrErrBuf, size_t szBufLen)
* @param pcString a string * @param pcString a string
*/ */
void void
nfc_perror (const nfc_device *pnd, const char *pcString) nfc_perror(const nfc_device *pnd, const char *pcString)
{ {
fprintf (stderr, "%s: %s\n", pcString, nfc_strerror (pnd)); fprintf(stderr, "%s: %s\n", pcString, nfc_strerror(pnd));
} }
/** @ingroup error /** @ingroup error
@ -979,7 +979,7 @@ nfc_perror (const nfc_device *pnd, const char *pcString)
* @param pnd \a nfc_device struct pointer that represent currently used device * @param pnd \a nfc_device struct pointer that represent currently used device
*/ */
int int
nfc_device_get_last_error (const nfc_device *pnd) nfc_device_get_last_error(const nfc_device *pnd)
{ {
return pnd->last_error; return pnd->last_error;
} }
@ -993,7 +993,7 @@ nfc_device_get_last_error (const nfc_device *pnd)
* @param pnd \a nfc_device struct pointer that represent currently used device * @param pnd \a nfc_device struct pointer that represent currently used device
*/ */
const char * const char *
nfc_device_get_name (nfc_device *pnd) nfc_device_get_name(nfc_device *pnd)
{ {
return pnd->name; return pnd->name;
} }
@ -1005,7 +1005,7 @@ nfc_device_get_name (nfc_device *pnd)
* @param pnd \a nfc_device struct pointer that represent currently used device * @param pnd \a nfc_device struct pointer that represent currently used device
*/ */
const char * const char *
nfc_device_get_connstring (nfc_device *pnd) nfc_device_get_connstring(nfc_device *pnd)
{ {
return pnd->connstring; return pnd->connstring;
} }
@ -1019,9 +1019,9 @@ nfc_device_get_connstring (nfc_device *pnd)
* *
*/ */
int int
nfc_device_get_supported_modulation (nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt) nfc_device_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt)
{ {
HAL (get_supported_modulation, pnd, mode, supported_mt); HAL(get_supported_modulation, pnd, mode, supported_mt);
} }
/** @ingroup data /** @ingroup data
@ -1033,9 +1033,9 @@ nfc_device_get_supported_modulation (nfc_device *pnd, const nfc_mode mode, const
* *
*/ */
int int
nfc_device_get_supported_baud_rate (nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br) nfc_device_get_supported_baud_rate(nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br)
{ {
HAL (get_supported_baud_rate, pnd, nmt, supported_br); HAL(get_supported_baud_rate, pnd, nmt, supported_br);
} }
/* Misc. functions */ /* Misc. functions */
@ -1047,7 +1047,7 @@ nfc_device_get_supported_baud_rate (nfc_device *pnd, const nfc_modulation_type n
* @param pnd \a nfc_device struct pointer that represent currently used device * @param pnd \a nfc_device struct pointer that represent currently used device
*/ */
const char * const char *
nfc_version (void) nfc_version(void)
{ {
#ifdef SVN_REVISION #ifdef SVN_REVISION
return PACKAGE_VERSION " (r" SVN_REVISION ")"; return PACKAGE_VERSION " (r" SVN_REVISION ")";
@ -1064,9 +1064,9 @@ nfc_version (void)
* @param buflen buf length * @param buflen buf length
*/ */
int int
nfc_device_get_information_about (nfc_device *pnd, char *buf, size_t buflen) nfc_device_get_information_about(nfc_device *pnd, char *buf, size_t buflen)
{ {
HAL (device_get_information_about, pnd, buf, buflen); HAL(device_get_information_about, pnd, buf, buflen);
} }
/** @ingroup string-converter /** @ingroup string-converter
@ -1075,9 +1075,9 @@ nfc_device_get_information_about (nfc_device *pnd, char *buf, size_t buflen)
* @param \a nfc_baud_rate to convert * @param \a nfc_baud_rate to convert
*/ */
const char * const char *
str_nfc_baud_rate (const nfc_baud_rate nbr) str_nfc_baud_rate(const nfc_baud_rate nbr)
{ {
switch(nbr) { switch (nbr) {
case NBR_UNDEFINED: case NBR_UNDEFINED:
return "undefined baud rate"; return "undefined baud rate";
break; break;
@ -1104,9 +1104,9 @@ str_nfc_baud_rate (const nfc_baud_rate nbr)
* @param \a nfc_modulation_type to convert * @param \a nfc_modulation_type to convert
*/ */
const char * const char *
str_nfc_modulation_type (const nfc_modulation_type nmt) str_nfc_modulation_type(const nfc_modulation_type nmt)
{ {
switch(nmt) { switch (nmt) {
case NMT_ISO14443A: case NMT_ISO14443A:
return "ISO/IEC 14443A"; return "ISO/IEC 14443A";
break; break;

View file

@ -11,45 +11,45 @@
* inconsistent state after use. * inconsistent state after use.
*/ */
void void
test_access_storm (void) test_access_storm(void)
{ {
int n = NTESTS; int n = NTESTS;
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
int res = 0; int res = 0;
nfc_init (NULL); nfc_init(NULL);
size_t ref_device_count = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t ref_device_count = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
if (!ref_device_count) if (!ref_device_count)
cut_omit ("No NFC device found"); cut_omit("No NFC device found");
while (n) { while (n) {
size_t i; size_t i;
size_t device_count = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t device_count = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
cut_assert_equal_int (ref_device_count, device_count, cut_message ("device count")); cut_assert_equal_int(ref_device_count, device_count, cut_message("device count"));
for (i = 0; i < device_count; i++) { for (i = 0; i < device_count; i++) {
nfc_device *device; nfc_device *device;
nfc_target ant[MAX_TARGET_COUNT]; nfc_target ant[MAX_TARGET_COUNT];
device = nfc_open (NULL, connstrings[i]); device = nfc_open(NULL, connstrings[i]);
cut_assert_not_null (device, cut_message ("nfc_open")); cut_assert_not_null(device, cut_message("nfc_open"));
res = nfc_initiator_init(device); res = nfc_initiator_init(device);
cut_assert_equal_int (0, res, cut_message ("nfc_initiator_init")); cut_assert_equal_int(0, res, cut_message("nfc_initiator_init"));
const nfc_modulation nm = { const nfc_modulation nm = {
.nmt = NMT_ISO14443A, .nmt = NMT_ISO14443A,
.nbr = NBR_106, .nbr = NBR_106,
}; };
res = nfc_initiator_list_passive_targets(device, nm, ant, MAX_TARGET_COUNT); res = nfc_initiator_list_passive_targets(device, nm, ant, MAX_TARGET_COUNT);
cut_assert_operator_int (res, >= , 0, cut_message ("nfc_initiator_list_passive_targets")); cut_assert_operator_int(res, >= , 0, cut_message("nfc_initiator_list_passive_targets"));
nfc_close (device); nfc_close(device);
} }
n--; n--;
} }
nfc_exit (NULL); nfc_exit(NULL);
} }

View file

@ -15,35 +15,35 @@ nfc_device *devices[2];
intptr_t result[2]; intptr_t result[2];
void void
abort_test_by_keypress (int sig) abort_test_by_keypress(int sig)
{ {
(void) sig; (void) sig;
printf ("\033[0;1;31mSIGINT\033[0m"); printf("\033[0;1;31mSIGINT\033[0m");
nfc_abort_command (devices[INITIATOR]); nfc_abort_command(devices[INITIATOR]);
nfc_abort_command (devices[TARGET]); nfc_abort_command(devices[TARGET]);
} }
void void
cut_setup (void) cut_setup(void)
{ {
size_t n = nfc_list_devices (NULL, connstrings, 2); size_t n = nfc_list_devices(NULL, connstrings, 2);
if (n < 2) { if (n < 2) {
cut_omit ("At least two NFC devices must be plugged-in to run this test"); cut_omit("At least two NFC devices must be plugged-in to run this test");
} }
nfc_init (NULL); nfc_init(NULL);
devices[TARGET] = nfc_open (NULL, connstrings[TARGET]); devices[TARGET] = nfc_open(NULL, connstrings[TARGET]);
devices[INITIATOR] = nfc_open (NULL, connstrings[INITIATOR]); devices[INITIATOR] = nfc_open(NULL, connstrings[INITIATOR]);
signal (SIGINT, abort_test_by_keypress); signal(SIGINT, abort_test_by_keypress);
} }
void void
cut_teardown (void) cut_teardown(void)
{ {
nfc_close (devices[TARGET]); nfc_close(devices[TARGET]);
nfc_close (devices[INITIATOR]); nfc_close(devices[INITIATOR]);
nfc_exit (NULL); nfc_exit(NULL);
} }
struct thread_data { struct thread_data {
@ -53,13 +53,13 @@ struct thread_data {
}; };
void * void *
target_thread (void *arg) target_thread(void *arg)
{ {
intptr_t thread_res = 0; intptr_t thread_res = 0;
nfc_device *device = ((struct thread_data *) arg)->device; nfc_device *device = ((struct thread_data *) arg)->device;
cut_set_current_test_context (((struct thread_data *) arg)->cut_test_context); cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context);
printf ("=========== TARGET %s =========\n", nfc_device_get_name (device)); printf("=========== TARGET %s =========\n", nfc_device_get_name(device));
nfc_target nt = { nfc_target nt = {
.nm = { .nm = {
.nmt = NMT_DEP, .nmt = NMT_DEP,
@ -82,79 +82,79 @@ target_thread (void *arg)
}; };
uint8_t abtRx[1024]; uint8_t abtRx[1024];
size_t szRx = sizeof (abtRx); size_t szRx = sizeof(abtRx);
int res = nfc_target_init (device, &nt, abtRx, sizeof (abtRx), 0); int res = nfc_target_init(device, &nt, abtRx, sizeof(abtRx), 0);
cut_assert_operator_int (res, > , 0, cut_message ("Can't initialize NFC device as target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_target_receive_bytes (device, abtRx, sizeof (abtRx), 500); res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't receive bytes from initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device)));
szRx = (size_t) res; szRx = (size_t) res;
const uint8_t abtAttRx[] = "Hello DEP target!"; const uint8_t abtAttRx[] = "Hello DEP target!";
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
const uint8_t abtTx[] = "Hello DEP initiator!"; const uint8_t abtTx[] = "Hello DEP initiator!";
res = nfc_target_send_bytes (device, abtTx, sizeof(abtTx), 500); res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't send bytes to initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device)));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
return (void *) thread_res; return (void *) thread_res;
} }
void * void *
initiator_thread (void *arg) initiator_thread(void *arg)
{ {
intptr_t thread_res = 0; intptr_t thread_res = 0;
nfc_device *device = ((struct thread_data *) arg)->device; nfc_device *device = ((struct thread_data *) arg)->device;
cut_set_current_test_context (((struct thread_data *) arg)->cut_test_context); cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context);
nfc_baud_rate nbr = (((struct thread_data *) arg)->nbr); nfc_baud_rate nbr = (((struct thread_data *) arg)->nbr);
/* /*
* Wait some time for the other thread to initialise NFC device as target * Wait some time for the other thread to initialise NFC device as target
*/ */
sleep (1); sleep(1);
printf ("=========== INITIATOR %s =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(device));
int res = nfc_initiator_init (device); int res = nfc_initiator_init(device);
cut_assert_equal_int (0, res, cut_message ("Can't initialize NFC device as initiator: %s", nfc_strerror (device))); cut_assert_equal_int(0, res, cut_message("Can't initialize NFC device as initiator: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
nfc_target nt; nfc_target nt;
// Active mode // Active mode
printf ("=========== INITIATOR %s (Active mode / %s Kbps) =========\n", nfc_device_get_name (device), str_nfc_baud_rate(nbr)); printf("=========== INITIATOR %s (Active mode / %s Kbps) =========\n", nfc_device_get_name(device), str_nfc_baud_rate(nbr));
res = nfc_initiator_select_dep_target (device, NDM_ACTIVE, nbr, NULL, &nt, 1000); res = nfc_initiator_select_dep_target(device, NDM_ACTIVE, nbr, NULL, &nt, 1000);
cut_assert_operator_int (res, > , 0, cut_message ("Can't select any DEP target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device)));
cut_assert_equal_int (NMT_DEP, nt.nm.nmt, cut_message ("Invalid target modulation")); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation"));
cut_assert_equal_int (nbr, nt.nm.nbr, cut_message ("Invalid target baud rate")); cut_assert_equal_int(nbr, nt.nm.nbr, cut_message("Invalid target baud rate"));
cut_assert_equal_memory ("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message ("Invalid target NFCID3")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3"));
cut_assert_equal_int (NDM_ACTIVE, nt.nti.ndi.ndm, cut_message ("Invalid target DEP mode")); cut_assert_equal_int(NDM_ACTIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode"));
cut_assert_equal_memory ("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message ("Invalid target general bytes")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
const uint8_t abtTx[] = "Hello DEP target!"; const uint8_t abtTx[] = "Hello DEP target!";
uint8_t abtRx[1024]; uint8_t abtRx[1024];
size_t szRx = sizeof (abtRx); size_t szRx = sizeof(abtRx);
res = nfc_initiator_transceive_bytes (device, abtTx, sizeof (abtTx), abtRx, &szRx, 5000); res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, &szRx, 5000);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't transceive bytes to target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device)));
const uint8_t abtAttRx[] = "Hello DEP initiator!"; const uint8_t abtAttRx[] = "Hello DEP initiator!";
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_initiator_deselect_target (device); res = nfc_initiator_deselect_target(device);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't deselect target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
return (void *) thread_res; return (void *) thread_res;
} }
void void
test_dep (void) test_dep(void)
{ {
int res; int res;
nfc_baud_rate nbrs[3] = { NBR_106, NBR_212, NBR_424}; nfc_baud_rate nbrs[3] = { NBR_106, NBR_212, NBR_424};
CutTestContext *test_context = cut_get_current_test_context (); CutTestContext *test_context = cut_get_current_test_context();
struct thread_data target_data = { struct thread_data target_data = {
.device = devices[TARGET], .device = devices[TARGET],
.cut_test_context = test_context, .cut_test_context = test_context,
@ -168,18 +168,18 @@ test_dep (void)
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
initiator_data.nbr = nbrs[i]; initiator_data.nbr = nbrs[i];
if ((res = pthread_create (&(threads[TARGET]), NULL, target_thread, &target_data))) if ((res = pthread_create(&(threads[TARGET]), NULL, target_thread, &target_data)))
cut_fail ("pthread_create() returned %d", res); cut_fail("pthread_create() returned %d", res);
if ((res = pthread_create (&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data))) if ((res = pthread_create(&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data)))
cut_fail ("pthread_create() returned %d", res); cut_fail("pthread_create() returned %d", res);
if ((res = pthread_join (threads[INITIATOR], (void *) &result[INITIATOR]))) if ((res = pthread_join(threads[INITIATOR], (void *) &result[INITIATOR])))
cut_fail ("pthread_join() returned %d", res); cut_fail("pthread_join() returned %d", res);
if ((res = pthread_join (threads[TARGET], (void *) &result[TARGET]))) if ((res = pthread_join(threads[TARGET], (void *) &result[TARGET])))
cut_fail ("pthread_join() returned %d", res); cut_fail("pthread_join() returned %d", res);
cut_assert_equal_int (0, result[INITIATOR], cut_message ("Unexpected initiator return code")); cut_assert_equal_int(0, result[INITIATOR], cut_message("Unexpected initiator return code"));
cut_assert_equal_int (0, result[TARGET], cut_message ("Unexpected target return code")); cut_assert_equal_int(0, result[TARGET], cut_message("Unexpected target return code"));
} }
} }

View file

@ -14,36 +14,36 @@ nfc_device *devices[2];
intptr_t result[2]; intptr_t result[2];
void void
abort_test_by_keypress (int sig) abort_test_by_keypress(int sig)
{ {
(void) sig; (void) sig;
printf ("\033[0;1;31mSIGINT\033[0m"); printf("\033[0;1;31mSIGINT\033[0m");
nfc_abort_command (devices[INITIATOR]); nfc_abort_command(devices[INITIATOR]);
nfc_abort_command (devices[TARGET]); nfc_abort_command(devices[TARGET]);
} }
void void
cut_setup (void) cut_setup(void)
{ {
size_t n = nfc_list_devices (NULL, connstrings, 2); size_t n = nfc_list_devices(NULL, connstrings, 2);
if (n < 2) { if (n < 2) {
cut_omit ("At least two NFC devices must be plugged-in to run this test"); cut_omit("At least two NFC devices must be plugged-in to run this test");
} }
nfc_init (NULL); nfc_init(NULL);
devices[TARGET] = nfc_open (NULL, connstrings[TARGET]); devices[TARGET] = nfc_open(NULL, connstrings[TARGET]);
devices[INITIATOR] = nfc_open (NULL, connstrings[INITIATOR]); devices[INITIATOR] = nfc_open(NULL, connstrings[INITIATOR]);
signal (SIGINT, abort_test_by_keypress); signal(SIGINT, abort_test_by_keypress);
} }
void void
cut_teardown (void) cut_teardown(void)
{ {
nfc_close (devices[TARGET]); nfc_close(devices[TARGET]);
nfc_close (devices[INITIATOR]); nfc_close(devices[INITIATOR]);
nfc_exit (NULL); nfc_exit(NULL);
} }
struct thread_data { struct thread_data {
@ -52,13 +52,13 @@ struct thread_data {
}; };
void * void *
target_thread (void *arg) target_thread(void *arg)
{ {
intptr_t thread_res = 0; intptr_t thread_res = 0;
nfc_device *device = ((struct thread_data *) arg)->device; nfc_device *device = ((struct thread_data *) arg)->device;
cut_set_current_test_context (((struct thread_data *) arg)->cut_test_context); cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context);
printf ("=========== TARGET %s =========\n", nfc_device_get_name (device)); printf("=========== TARGET %s =========\n", nfc_device_get_name(device));
nfc_target nt = { nfc_target nt = {
.nm = { .nm = {
.nmt = NMT_DEP, .nmt = NMT_DEP,
@ -81,202 +81,202 @@ target_thread (void *arg)
}; };
uint8_t abtRx[1024]; uint8_t abtRx[1024];
size_t szRx = sizeof (abtRx); size_t szRx = sizeof(abtRx);
int res = nfc_target_init (device, &nt, abtRx, szRx, 0); int res = nfc_target_init(device, &nt, abtRx, szRx, 0);
cut_assert_operator_int (res, > , 0, cut_message ("Can't initialize NFC device as target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
// First pass // First pass
res = nfc_target_receive_bytes (device, abtRx, sizeof (abtRx), 500); res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't receive bytes from initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device)));
szRx = (size_t) res; szRx = (size_t) res;
const uint8_t abtAttRx[] = "Hello DEP target!"; const uint8_t abtAttRx[] = "Hello DEP target!";
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
const uint8_t abtTx[] = "Hello DEP initiator!"; const uint8_t abtTx[] = "Hello DEP initiator!";
res = nfc_target_send_bytes (device, abtTx, sizeof(abtTx), 500); res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't send bytes to initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device)));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
// Second pass // Second pass
res = nfc_target_receive_bytes (device, abtRx, sizeof (abtRx), 500); res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't receive bytes from initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device)));
szRx = (size_t) res; szRx = (size_t) res;
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_target_send_bytes (device, abtTx, sizeof(abtTx), 500); res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't send bytes to initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device)));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
// Third pass // Third pass
res = nfc_target_receive_bytes (device, abtRx, sizeof (abtRx), 500); res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't receive bytes from initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device)));
szRx = (size_t) res; szRx = (size_t) res;
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_target_send_bytes (device, abtTx, sizeof(abtTx), 500); res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't send bytes to initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device)));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
// Fourth pass // Fourth pass
res = nfc_target_receive_bytes (device, abtRx, sizeof (abtRx), 500); res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't receive bytes from initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device)));
szRx = (size_t) res; szRx = (size_t) res;
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_target_send_bytes (device, abtTx, sizeof(abtTx), 500); res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't send bytes to initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device)));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
return (void *) thread_res; return (void *) thread_res;
} }
void * void *
initiator_thread (void *arg) initiator_thread(void *arg)
{ {
intptr_t thread_res = 0; intptr_t thread_res = 0;
nfc_device *device = ((struct thread_data *) arg)->device; nfc_device *device = ((struct thread_data *) arg)->device;
cut_set_current_test_context (((struct thread_data *) arg)->cut_test_context); cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context);
/* /*
* Wait some time for the other thread to initialise NFC device as target * Wait some time for the other thread to initialise NFC device as target
*/ */
sleep (1); sleep(1);
printf ("=========== INITIATOR %s =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(device));
int res = nfc_initiator_init (device); int res = nfc_initiator_init(device);
cut_assert_equal_int (0, res, cut_message ("Can't initialize NFC device as initiator: %s", nfc_strerror (device))); cut_assert_equal_int(0, res, cut_message("Can't initialize NFC device as initiator: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
nfc_target nt; nfc_target nt;
// Passive mode / 106Kbps // Passive mode / 106Kbps
printf ("=========== INITIATOR %s (Passive mode / 106Kbps) =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s (Passive mode / 106Kbps) =========\n", nfc_device_get_name(device));
res = nfc_initiator_select_dep_target (device, NDM_PASSIVE, NBR_106, NULL, &nt, 5000); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt, 5000);
cut_assert_operator_int (res, > , 0, cut_message ("Can't select any DEP target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device)));
cut_assert_equal_int (NMT_DEP, nt.nm.nmt, cut_message ("Invalid target modulation")); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation"));
cut_assert_equal_int (NBR_106, nt.nm.nbr, cut_message ("Invalid target baud rate")); cut_assert_equal_int(NBR_106, nt.nm.nbr, cut_message("Invalid target baud rate"));
cut_assert_equal_memory ("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message ("Invalid target NFCID3")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3"));
cut_assert_equal_int (NDM_PASSIVE, nt.nti.ndi.ndm, cut_message ("Invalid target DEP mode")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode"));
cut_assert_equal_memory ("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message ("Invalid target general bytes")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
const uint8_t abtTx[] = "Hello DEP target!"; const uint8_t abtTx[] = "Hello DEP target!";
uint8_t abtRx[1024]; uint8_t abtRx[1024];
size_t szRx = sizeof (abtRx); size_t szRx = sizeof(abtRx);
res = nfc_initiator_transceive_bytes (device, abtTx, sizeof (abtTx), abtRx, &szRx, 500); res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, &szRx, 500);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't transceive bytes to target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device)));
const uint8_t abtAttRx[] = "Hello DEP initiator!"; const uint8_t abtAttRx[] = "Hello DEP initiator!";
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_initiator_deselect_target (device); res = nfc_initiator_deselect_target(device);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't deselect target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
// Passive mode / 212Kbps (second pass) // Passive mode / 212Kbps (second pass)
printf ("=========== INITIATOR %s (Passive mode / 212Kbps) =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s (Passive mode / 212Kbps) =========\n", nfc_device_get_name(device));
res = nfc_initiator_select_dep_target (device, NDM_PASSIVE, NBR_212, NULL, &nt, 1000); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_212, NULL, &nt, 1000);
cut_assert_operator_int (res, > , 0, cut_message ("Can't select any DEP target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device)));
cut_assert_equal_int (NMT_DEP, nt.nm.nmt, cut_message ("Invalid target modulation")); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation"));
cut_assert_equal_int (NBR_212, nt.nm.nbr, cut_message ("Invalid target baud rate")); cut_assert_equal_int(NBR_212, nt.nm.nbr, cut_message("Invalid target baud rate"));
cut_assert_equal_memory ("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message ("Invalid target NFCID3")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3"));
cut_assert_equal_int (NDM_PASSIVE, nt.nti.ndi.ndm, cut_message ("Invalid target DEP mode")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode"));
cut_assert_equal_memory ("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message ("Invalid target general bytes")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
szRx = sizeof (abtRx); szRx = sizeof(abtRx);
res = nfc_initiator_transceive_bytes (device, abtTx, sizeof (abtTx), abtRx, &szRx, 1000); res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, &szRx, 1000);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't transceive bytes to target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device)));
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_initiator_deselect_target (device); res = nfc_initiator_deselect_target(device);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't deselect target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
// Passive mode / 212Kbps // Passive mode / 212Kbps
printf ("=========== INITIATOR %s (Passive mode / 212Kbps, second pass) =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s (Passive mode / 212Kbps, second pass) =========\n", nfc_device_get_name(device));
res = nfc_initiator_select_dep_target (device, NDM_PASSIVE, NBR_212, NULL, &nt, 1000); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_212, NULL, &nt, 1000);
cut_assert_operator_int (res, > , 0, cut_message ("Can't select any DEP target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device)));
cut_assert_equal_int (NMT_DEP, nt.nm.nmt, cut_message ("Invalid target modulation")); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation"));
cut_assert_equal_int (NBR_212, nt.nm.nbr, cut_message ("Invalid target baud rate")); cut_assert_equal_int(NBR_212, nt.nm.nbr, cut_message("Invalid target baud rate"));
cut_assert_equal_memory ("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message ("Invalid target NFCID3")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3"));
cut_assert_equal_int (NDM_PASSIVE, nt.nti.ndi.ndm, cut_message ("Invalid target DEP mode")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode"));
cut_assert_equal_memory ("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message ("Invalid target general bytes")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
szRx = sizeof (abtRx); szRx = sizeof(abtRx);
res = nfc_initiator_transceive_bytes (device, abtTx, sizeof (abtTx), abtRx, &szRx, 5000); res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, &szRx, 5000);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't transceive bytes to target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device)));
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_initiator_deselect_target (device); res = nfc_initiator_deselect_target(device);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't deselect target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
// Passive mode / 424Kbps // Passive mode / 424Kbps
printf ("=========== INITIATOR %s (Passive mode / 424Kbps) =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s (Passive mode / 424Kbps) =========\n", nfc_device_get_name(device));
res = nfc_initiator_select_dep_target (device, NDM_PASSIVE, NBR_424, NULL, &nt, 1000); res = nfc_initiator_select_dep_target(device, NDM_PASSIVE, NBR_424, NULL, &nt, 1000);
cut_assert_operator_int (res, > , 0, cut_message ("Can't select any DEP target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device)));
cut_assert_equal_int (NMT_DEP, nt.nm.nmt, cut_message ("Invalid target modulation")); cut_assert_equal_int(NMT_DEP, nt.nm.nmt, cut_message("Invalid target modulation"));
cut_assert_equal_int (NBR_424, nt.nm.nbr, cut_message ("Invalid target baud rate")); cut_assert_equal_int(NBR_424, nt.nm.nbr, cut_message("Invalid target baud rate"));
cut_assert_equal_memory ("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message ("Invalid target NFCID3")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3"));
cut_assert_equal_int (NDM_PASSIVE, nt.nti.ndi.ndm, cut_message ("Invalid target DEP mode")); cut_assert_equal_int(NDM_PASSIVE, nt.nti.ndi.ndm, cut_message("Invalid target DEP mode"));
cut_assert_equal_memory ("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message ("Invalid target general bytes")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt.nti.ndi.abtGB, nt.nti.ndi.szGB, cut_message("Invalid target general bytes"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
szRx = sizeof (abtRx); szRx = sizeof(abtRx);
res = nfc_initiator_transceive_bytes (device, abtTx, sizeof (abtTx), abtRx, &szRx, 5000); res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, &szRx, 5000);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't transceive bytes to target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device)));
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_initiator_deselect_target (device); res = nfc_initiator_deselect_target(device);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't deselect target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
return (void *) thread_res; return (void *) thread_res;
} }
void void
test_dep (void) test_dep(void)
{ {
int res; int res;
CutTestContext *test_context = cut_get_current_test_context (); CutTestContext *test_context = cut_get_current_test_context();
struct thread_data target_data = { struct thread_data target_data = {
.device = devices[TARGET], .device = devices[TARGET],
.cut_test_context = test_context, .cut_test_context = test_context,
}; };
if ((res = pthread_create (&(threads[TARGET]), NULL, target_thread, &target_data))) if ((res = pthread_create(&(threads[TARGET]), NULL, target_thread, &target_data)))
cut_fail ("pthread_create() returned %d", res); cut_fail("pthread_create() returned %d", res);
struct thread_data initiator_data = { struct thread_data initiator_data = {
.device = devices[INITIATOR], .device = devices[INITIATOR],
.cut_test_context = test_context, .cut_test_context = test_context,
}; };
if ((res = pthread_create (&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data))) if ((res = pthread_create(&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data)))
cut_fail ("pthread_create() returned %d", res); cut_fail("pthread_create() returned %d", res);
if ((res = pthread_join (threads[INITIATOR], (void *) &result[INITIATOR]))) if ((res = pthread_join(threads[INITIATOR], (void *) &result[INITIATOR])))
cut_fail ("pthread_join() returned %d", res); cut_fail("pthread_join() returned %d", res);
if ((res = pthread_join (threads[TARGET], (void *) &result[TARGET]))) if ((res = pthread_join(threads[TARGET], (void *) &result[TARGET])))
cut_fail ("pthread_join() returned %d", res); cut_fail("pthread_join() returned %d", res);
cut_assert_equal_int (0, result[INITIATOR], cut_message ("Unexpected initiator return code")); cut_assert_equal_int(0, result[INITIATOR], cut_message("Unexpected initiator return code"));
cut_assert_equal_int (0, result[TARGET], cut_message ("Unexpected target return code")); cut_assert_equal_int(0, result[TARGET], cut_message("Unexpected target return code"));
} }

View file

@ -12,36 +12,36 @@ nfc_device *first_device, *second_device;
intptr_t result[2]; intptr_t result[2];
void void
abort_test_by_keypress (int sig) abort_test_by_keypress(int sig)
{ {
(void) sig; (void) sig;
printf ("\033[0;1;31mSIGINT\033[0m"); printf("\033[0;1;31mSIGINT\033[0m");
nfc_abort_command (first_device); nfc_abort_command(first_device);
nfc_abort_command (second_device); nfc_abort_command(second_device);
} }
void void
cut_setup (void) cut_setup(void)
{ {
size_t n = nfc_list_devices (NULL, connstrings, 2); size_t n = nfc_list_devices(NULL, connstrings, 2);
if (n < 2) { if (n < 2) {
cut_omit ("At least two NFC devices must be plugged-in to run this test"); cut_omit("At least two NFC devices must be plugged-in to run this test");
} }
nfc_init (NULL); nfc_init(NULL);
second_device = nfc_open (NULL, connstrings[0]); second_device = nfc_open(NULL, connstrings[0]);
first_device = nfc_open (NULL, connstrings[1]); first_device = nfc_open(NULL, connstrings[1]);
signal (SIGINT, abort_test_by_keypress); signal(SIGINT, abort_test_by_keypress);
} }
void void
cut_teardown (void) cut_teardown(void)
{ {
nfc_close (second_device); nfc_close(second_device);
nfc_close (first_device); nfc_close(first_device);
nfc_exit (NULL); nfc_exit(NULL);
} }
struct thread_data { struct thread_data {
@ -50,21 +50,21 @@ struct thread_data {
}; };
void * void *
target_thread (void *arg) target_thread(void *arg)
{ {
intptr_t thread_res = 0; intptr_t thread_res = 0;
nfc_device *device = ((struct thread_data *) arg)->device; nfc_device *device = ((struct thread_data *) arg)->device;
cut_set_current_test_context (((struct thread_data *) arg)->cut_test_context); cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context);
printf ("=========== TARGET %s =========\n", nfc_device_get_name (device)); printf("=========== TARGET %s =========\n", nfc_device_get_name(device));
nfc_target nt; nfc_target nt;
uint8_t abtRx[1024]; uint8_t abtRx[1024];
size_t szRx = sizeof (abtRx); size_t szRx = sizeof(abtRx);
// 1) nfc_target_init should take target in idle mode // 1) nfc_target_init should take target in idle mode
int res = nfc_target_init (device, &nt, abtRx, szRx, 500); int res = nfc_target_init(device, &nt, abtRx, szRx, 500);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't initialize NFC device as target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
// 2) act as target // 2) act as target
@ -89,51 +89,51 @@ target_thread (void *arg)
}, },
}; };
sleep(6); sleep(6);
res = nfc_target_init (device, &nt1, abtRx, szRx, 0); res = nfc_target_init(device, &nt1, abtRx, szRx, 0);
cut_assert_operator_int (res, > , 0, cut_message ("Can't initialize NFC device as target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't initialize NFC device as target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_target_receive_bytes (device, abtRx, sizeof (abtRx), 500); res = nfc_target_receive_bytes(device, abtRx, sizeof(abtRx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't receive bytes from initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't receive bytes from initiator: %s", nfc_strerror(device)));
szRx = (size_t) res; szRx = (size_t) res;
const uint8_t abtAttRx[] = "Hello DEP target!"; const uint8_t abtAttRx[] = "Hello DEP target!";
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
const uint8_t abtTx[] = "Hello DEP initiator!"; const uint8_t abtTx[] = "Hello DEP initiator!";
res = nfc_target_send_bytes (device, abtTx, sizeof(abtTx), 500); res = nfc_target_send_bytes(device, abtTx, sizeof(abtTx), 500);
cut_assert_operator_int (res, > , 0, cut_message ("Can't send bytes to initiator: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't send bytes to initiator: %s", nfc_strerror(device)));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
// 3) idle mode // 3) idle mode
sleep (1); sleep(1);
nfc_idle (device); nfc_idle(device);
return (void *) thread_res; return (void *) thread_res;
} }
void * void *
initiator_thread (void *arg) initiator_thread(void *arg)
{ {
intptr_t thread_res = 0; intptr_t thread_res = 0;
nfc_device *device = ((struct thread_data *) arg)->device; nfc_device *device = ((struct thread_data *) arg)->device;
cut_set_current_test_context (((struct thread_data *) arg)->cut_test_context); cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context);
/* /*
* Wait some time for the other thread to initialise NFC device as target * Wait some time for the other thread to initialise NFC device as target
*/ */
sleep (5); sleep(5);
printf ("=========== INITIATOR %s =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(device));
int res = nfc_initiator_init (device); int res = nfc_initiator_init(device);
cut_assert_equal_int (0, res, cut_message ("Can't initialize NFC device as initiator: %s", nfc_strerror (device))); cut_assert_equal_int(0, res, cut_message("Can't initialize NFC device as initiator: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
// 1) As other device should be in idle mode, nfc_initiator_poll_dep_target should return 0 // 1) As other device should be in idle mode, nfc_initiator_poll_dep_target should return 0
nfc_target nt; nfc_target nt;
res = nfc_initiator_poll_dep_target (device, NDM_PASSIVE, NBR_106, NULL, &nt, 1000); res = nfc_initiator_poll_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt, 1000);
cut_assert_equal_int (0, res, cut_message ("Problem with nfc_idle")); cut_assert_equal_int(0, res, cut_message("Problem with nfc_idle"));
if (res != 0) { thread_res = -1; return (void*) thread_res; } if (res != 0) { thread_res = -1; return (void*) thread_res; }
@ -141,45 +141,45 @@ initiator_thread (void *arg)
nfc_target nt1; nfc_target nt1;
// Passive mode / 106Kbps // Passive mode / 106Kbps
printf ("=========== INITIATOR %s (Passive mode / 106Kbps) =========\n", nfc_device_get_name (device)); printf("=========== INITIATOR %s (Passive mode / 106Kbps) =========\n", nfc_device_get_name(device));
res = nfc_initiator_poll_dep_target (device, NDM_PASSIVE, NBR_106, NULL, &nt1, 5000); res = nfc_initiator_poll_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt1, 5000);
cut_assert_operator_int (res, > , 0, cut_message ("Can't select any DEP target: %s", nfc_strerror (device))); cut_assert_operator_int(res, > , 0, cut_message("Can't select any DEP target: %s", nfc_strerror(device)));
cut_assert_equal_int (NMT_DEP, nt1.nm.nmt, cut_message ("Invalid target modulation")); cut_assert_equal_int(NMT_DEP, nt1.nm.nmt, cut_message("Invalid target modulation"));
cut_assert_equal_int (NBR_106, nt1.nm.nbr, cut_message ("Invalid target baud rate")); cut_assert_equal_int(NBR_106, nt1.nm.nbr, cut_message("Invalid target baud rate"));
cut_assert_equal_memory ("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt1.nti.ndi.abtNFCID3, 10, cut_message ("Invalid target NFCID3")); cut_assert_equal_memory("\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA", 10, nt1.nti.ndi.abtNFCID3, 10, cut_message("Invalid target NFCID3"));
cut_assert_equal_int (NDM_PASSIVE, nt1.nti.ndi.ndm, cut_message ("Invalid target DEP mode")); cut_assert_equal_int(NDM_PASSIVE, nt1.nti.ndi.ndm, cut_message("Invalid target DEP mode"));
cut_assert_equal_memory ("\x12\x34\x56\x78", 4, nt1.nti.ndi.abtGB, nt1.nti.ndi.szGB, cut_message ("Invalid target general bytes")); cut_assert_equal_memory("\x12\x34\x56\x78", 4, nt1.nti.ndi.abtGB, nt1.nti.ndi.szGB, cut_message("Invalid target general bytes"));
if (res <= 0) { thread_res = -1; return (void*) thread_res; } if (res <= 0) { thread_res = -1; return (void*) thread_res; }
const uint8_t abtTx[] = "Hello DEP target!"; const uint8_t abtTx[] = "Hello DEP target!";
uint8_t abtRx[1024]; uint8_t abtRx[1024];
size_t szRx = sizeof (abtRx); size_t szRx = sizeof(abtRx);
res = nfc_initiator_transceive_bytes (device, abtTx, sizeof (abtTx), abtRx, &szRx, 500); res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, &szRx, 500);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't transceive bytes to target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't transceive bytes to target: %s", nfc_strerror(device)));
const uint8_t abtAttRx[] = "Hello DEP initiator!"; const uint8_t abtAttRx[] = "Hello DEP initiator!";
cut_assert_equal_memory (abtAttRx, sizeof (abtAttRx), abtRx, szRx, cut_message ("Invalid received data")); cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, szRx, cut_message("Invalid received data"));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
res = nfc_initiator_deselect_target (device); res = nfc_initiator_deselect_target(device);
cut_assert_operator_int (res, >= , 0, cut_message ("Can't deselect target: %s", nfc_strerror (device))); cut_assert_operator_int(res, >= , 0, cut_message("Can't deselect target: %s", nfc_strerror(device)));
if (res < 0) { thread_res = -1; return (void*) thread_res; } if (res < 0) { thread_res = -1; return (void*) thread_res; }
// 3) As other device should be in idle mode, nfc_initiator_poll_dep_target should return 0 // 3) As other device should be in idle mode, nfc_initiator_poll_dep_target should return 0
nfc_target nt2; nfc_target nt2;
res = nfc_initiator_poll_dep_target (device, NDM_PASSIVE, NBR_106, NULL, &nt2, 1000); res = nfc_initiator_poll_dep_target(device, NDM_PASSIVE, NBR_106, NULL, &nt2, 1000);
cut_assert_equal_int (0, res, cut_message ("Problem with nfc_idle")); cut_assert_equal_int(0, res, cut_message("Problem with nfc_idle"));
if (res != 0) { thread_res = -1; return (void*) thread_res; } if (res != 0) { thread_res = -1; return (void*) thread_res; }
return (void *) thread_res; return (void *) thread_res;
} }
void void
test_dep_states (void) test_dep_states(void)
{ {
int res; int res;
CutTestContext *test_context = cut_get_current_test_context (); CutTestContext *test_context = cut_get_current_test_context();
struct thread_data target_data = { struct thread_data target_data = {
.device = first_device, .device = first_device,
.cut_test_context = test_context, .cut_test_context = test_context,
@ -191,19 +191,19 @@ test_dep_states (void)
}; };
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
if ((res = pthread_create (&(threads[1]), NULL, target_thread, &target_data))) if ((res = pthread_create(&(threads[1]), NULL, target_thread, &target_data)))
cut_fail ("pthread_create() returned %d", res); cut_fail("pthread_create() returned %d", res);
if ((res = pthread_create (&(threads[0]), NULL, initiator_thread, &initiator_data))) if ((res = pthread_create(&(threads[0]), NULL, initiator_thread, &initiator_data)))
cut_fail ("pthread_create() returned %d", res); cut_fail("pthread_create() returned %d", res);
if ((res = pthread_join (threads[0], (void *) &result[0]))) if ((res = pthread_join(threads[0], (void *) &result[0])))
cut_fail ("pthread_join() returned %d", res); cut_fail("pthread_join() returned %d", res);
if ((res = pthread_join (threads[1], (void *) &result[1]))) if ((res = pthread_join(threads[1], (void *) &result[1])))
cut_fail ("pthread_join() returned %d", res); cut_fail("pthread_join() returned %d", res);
cut_assert_equal_int (0, result[0], cut_message ("Unexpected initiator return code")); cut_assert_equal_int(0, result[0], cut_message("Unexpected initiator return code"));
cut_assert_equal_int (0, result[1], cut_message ("Unexpected target return code")); cut_assert_equal_int(0, result[1], cut_message("Unexpected target return code"));
// initiator --> target, target --> initiator // initiator --> target, target --> initiator
target_data.device = second_device; target_data.device = second_device;

View file

@ -7,42 +7,42 @@
#define MAX_TARGET_COUNT 1 #define MAX_TARGET_COUNT 1
void void
test_register_endianness (void) test_register_endianness(void)
{ {
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
int res = 0; int res = 0;
nfc_init (NULL); nfc_init(NULL);
size_t device_count = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t device_count = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
if (!device_count) if (!device_count)
cut_omit ("No NFC device found"); cut_omit("No NFC device found");
nfc_device *device; nfc_device *device;
device = nfc_open (NULL, connstrings[0]); device = nfc_open(NULL, connstrings[0]);
cut_assert_not_null (device, cut_message ("nfc_open")); cut_assert_not_null(device, cut_message("nfc_open"));
uint8_t value; uint8_t value;
/* Set a 0xAA test value in writable register memory to test register access */ /* Set a 0xAA test value in writable register memory to test register access */
res = pn53x_write_register (device, PN53X_REG_CIU_TxMode, 0xFF, 0xAA); res = pn53x_write_register(device, PN53X_REG_CIU_TxMode, 0xFF, 0xAA);
cut_assert_equal_int (0, res, cut_message ("write register value to 0xAA")); cut_assert_equal_int(0, res, cut_message("write register value to 0xAA"));
/* Get test value from register memory */ /* Get test value from register memory */
res = pn53x_read_register (device, PN53X_REG_CIU_TxMode, &value); res = pn53x_read_register(device, PN53X_REG_CIU_TxMode, &value);
cut_assert_equal_int (0, res, cut_message ("read register value")); cut_assert_equal_int(0, res, cut_message("read register value"));
cut_assert_equal_uint (0xAA, value, cut_message ("check register value")); cut_assert_equal_uint(0xAA, value, cut_message("check register value"));
/* Set a 0x55 test value in writable register memory to test register access */ /* Set a 0x55 test value in writable register memory to test register access */
res = pn53x_write_register (device, PN53X_REG_CIU_TxMode, 0xFF, 0x55); res = pn53x_write_register(device, PN53X_REG_CIU_TxMode, 0xFF, 0x55);
cut_assert_equal_int (0, res, cut_message ("write register value to 0x55")); cut_assert_equal_int(0, res, cut_message("write register value to 0x55"));
/* Get test value from register memory */ /* Get test value from register memory */
res = pn53x_read_register (device, PN53X_REG_CIU_TxMode, &value); res = pn53x_read_register(device, PN53X_REG_CIU_TxMode, &value);
cut_assert_equal_int (0, res, cut_message ("read register value")); cut_assert_equal_int(0, res, cut_message("read register value"));
cut_assert_equal_uint (0x55, value, cut_message ("check register value")); cut_assert_equal_uint(0x55, value, cut_message("check register value"));
nfc_close (device); nfc_close(device);
nfc_exit (NULL); nfc_exit(NULL);
} }

View file

@ -8,32 +8,32 @@
#include "chips/pn53x.h" #include "chips/pn53x.h"
void void
test_register_endianness (void) test_register_endianness(void)
{ {
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
int res = 0; int res = 0;
nfc_init (NULL); nfc_init(NULL);
size_t device_count = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t device_count = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
if (!device_count) if (!device_count)
cut_omit ("No NFC device found"); cut_omit("No NFC device found");
nfc_device *device; nfc_device *device;
device = nfc_open (NULL, connstrings[0]); device = nfc_open(NULL, connstrings[0]);
cut_assert_not_null (device, cut_message ("nfc_open")); cut_assert_not_null(device, cut_message("nfc_open"));
uint8_t value; uint8_t value;
/* Read valid XRAM memory */ /* Read valid XRAM memory */
res = pn53x_read_register (device, 0xF0FF, &value); res = pn53x_read_register(device, 0xF0FF, &value);
cut_assert_equal_int (0, res, cut_message ("read register 0xF0FF")); cut_assert_equal_int(0, res, cut_message("read register 0xF0FF"));
/* Read invalid SFR register */ /* Read invalid SFR register */
res = pn53x_read_register (device, 0xFFF0, &value); res = pn53x_read_register(device, 0xFFF0, &value);
cut_assert_equal_int (0, res, cut_message ("read register 0xFFF0")); cut_assert_equal_int(0, res, cut_message("read register 0xFFF0"));
nfc_close (device); nfc_close(device);
nfc_exit (NULL); nfc_exit(NULL);
} }

View file

@ -51,7 +51,7 @@
* The MIFARE Classic Specification (http://www.nxp.com/acrobat/other/identification/M001053_MF1ICS50_rev5_3.pdf) explains more about this process. * The MIFARE Classic Specification (http://www.nxp.com/acrobat/other/identification/M001053_MF1ICS50_rev5_3.pdf) explains more about this process.
*/ */
bool bool
nfc_initiator_mifare_cmd (nfc_device *pnd, const mifare_cmd mc, const uint8_t ui8Block, mifare_param *pmp) nfc_initiator_mifare_cmd(nfc_device *pnd, const mifare_cmd mc, const uint8_t ui8Block, mifare_param *pmp)
{ {
uint8_t abtRx[265]; uint8_t abtRx[265];
size_t szParamLen; size_t szParamLen;
@ -71,19 +71,19 @@ nfc_initiator_mifare_cmd (nfc_device *pnd, const mifare_cmd mc, const uint8_t ui
// Authenticate command // Authenticate command
case MC_AUTH_A: case MC_AUTH_A:
case MC_AUTH_B: case MC_AUTH_B:
szParamLen = sizeof (struct mifare_param_auth); szParamLen = sizeof(struct mifare_param_auth);
break; break;
// Data command // Data command
case MC_WRITE: case MC_WRITE:
szParamLen = sizeof (struct mifare_param_data); szParamLen = sizeof(struct mifare_param_data);
break; break;
// Value command // Value command
case MC_DECREMENT: case MC_DECREMENT:
case MC_INCREMENT: case MC_INCREMENT:
case MC_TRANSFER: case MC_TRANSFER:
szParamLen = sizeof (struct mifare_param_value); szParamLen = sizeof(struct mifare_param_value);
break; break;
// Please fix your code, you never should reach this statement // Please fix your code, you never should reach this statement
@ -94,24 +94,24 @@ nfc_initiator_mifare_cmd (nfc_device *pnd, const mifare_cmd mc, const uint8_t ui
// When available, copy the parameter bytes // When available, copy the parameter bytes
if (szParamLen) if (szParamLen)
memcpy (abtCmd + 2, (uint8_t *) pmp, szParamLen); memcpy(abtCmd + 2, (uint8_t *) pmp, szParamLen);
// FIXME: Save and restore bEasyFraming // FIXME: Save and restore bEasyFraming
// bEasyFraming = nfc_device_get_property_bool (pnd, NP_EASY_FRAMING, &bEasyFraming); // bEasyFraming = nfc_device_get_property_bool (pnd, NP_EASY_FRAMING, &bEasyFraming);
if (nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, true) < 0) { if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
return false; return false;
} }
// Fire the mifare command // Fire the mifare command
int res; int res;
if ((res = nfc_initiator_transceive_bytes (pnd, abtCmd, 2 + szParamLen, abtRx, sizeof(abtRx), -1)) < 0) { if ((res = nfc_initiator_transceive_bytes(pnd, abtCmd, 2 + szParamLen, abtRx, sizeof(abtRx), -1)) < 0) {
if (res == NFC_ERFTRANS) { if (res == NFC_ERFTRANS) {
// "Invalid received frame", usual means we are // "Invalid received frame", usual means we are
// authenticated on a sector but the requested MIFARE cmd (read, write) // authenticated on a sector but the requested MIFARE cmd (read, write)
// is not permitted by current acces bytes; // is not permitted by current acces bytes;
// So there is nothing to do here. // So there is nothing to do here.
} else { } else {
nfc_perror (pnd, "nfc_initiator_transceive_bytes"); nfc_perror(pnd, "nfc_initiator_transceive_bytes");
} }
// XXX nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, bEasyFraming); // XXX nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, bEasyFraming);
return false; return false;
@ -126,7 +126,7 @@ nfc_initiator_mifare_cmd (nfc_device *pnd, const mifare_cmd mc, const uint8_t ui
// When we have executed a read command, copy the received bytes into the param // When we have executed a read command, copy the received bytes into the param
if (mc == MC_READ) { if (mc == MC_READ) {
if (res == 16) { if (res == 16) {
memcpy (pmp->mpd.abtData, abtRx, 16); memcpy(pmp->mpd.abtData, abtRx, 16);
} else { } else {
return false; return false;
} }

View file

@ -75,7 +75,7 @@ typedef union {
// Reset struct alignment to default // Reset struct alignment to default
# pragma pack() # pragma pack()
bool nfc_initiator_mifare_cmd (nfc_device *pnd, const mifare_cmd mc, const uint8_t ui8Block, mifare_param *pmp); bool nfc_initiator_mifare_cmd(nfc_device *pnd, const mifare_cmd mc, const uint8_t ui8Block, mifare_param *pmp);
// Compiler directive, set struct alignment to 1 uint8_t for compatibility // Compiler directive, set struct alignment to 1 uint8_t for compatibility
# pragma pack(1) # pragma pack(1)

View file

@ -116,7 +116,7 @@ uint8_t nfcforum_capability_container[] = {
#define ISO144434A_RATS 0xE0 #define ISO144434A_RATS 0xE0
static int static int
nfcforum_tag4_io (struct nfc_emulator *emulator, const uint8_t *data_in, const size_t data_in_len, uint8_t *data_out, const size_t data_out_len) nfcforum_tag4_io(struct nfc_emulator *emulator, const uint8_t *data_in, const size_t data_in_len, uint8_t *data_out, const size_t data_out_len)
{ {
int res = 0; int res = 0;
@ -130,11 +130,11 @@ nfcforum_tag4_io (struct nfc_emulator *emulator, const uint8_t *data_in, const s
// Show transmitted command // Show transmitted command
if (!quiet_output) { if (!quiet_output) {
printf (" In: "); printf(" In: ");
print_hex (data_in, data_in_len); print_hex(data_in, data_in_len);
} }
if(data_in_len >= 4) { if (data_in_len >= 4) {
if (data_in[CLA] != 0x00) if (data_in[CLA] != 0x00)
return -ENOTSUP; return -ENOTSUP;
@ -142,7 +142,7 @@ nfcforum_tag4_io (struct nfc_emulator *emulator, const uint8_t *data_in, const s
#define ISO7816_READ_BINARY 0xB0 #define ISO7816_READ_BINARY 0xB0
#define ISO7816_UPDATE_BINARY 0xD6 #define ISO7816_UPDATE_BINARY 0xD6
switch(data_in[INS]) { switch (data_in[INS]) {
case ISO7816_SELECT: case ISO7816_SELECT:
switch (data_in[P1]) { switch (data_in[P1]) {
@ -152,14 +152,14 @@ nfcforum_tag4_io (struct nfc_emulator *emulator, const uint8_t *data_in, const s
const uint8_t ndef_capability_container[] = { 0xE1, 0x03 }; const uint8_t ndef_capability_container[] = { 0xE1, 0x03 };
const uint8_t ndef_file[] = { 0xE1, 0x04 }; const uint8_t ndef_file[] = { 0xE1, 0x04 };
if ((data_in[LC] == sizeof (ndef_capability_container)) && (0 == memcmp (ndef_capability_container, data_in + DATA, data_in[LC]))) { if ((data_in[LC] == sizeof(ndef_capability_container)) && (0 == memcmp(ndef_capability_container, data_in + DATA, data_in[LC]))) {
memcpy (data_out, "\x90\x00", res = 2); memcpy(data_out, "\x90\x00", res = 2);
state_machine_data->current_file = CC_FILE; state_machine_data->current_file = CC_FILE;
} else if ((data_in[LC] == sizeof (ndef_file)) && (0 == memcmp (ndef_file, data_in + DATA, data_in[LC]))) { } else if ((data_in[LC] == sizeof(ndef_file)) && (0 == memcmp(ndef_file, data_in + DATA, data_in[LC]))) {
memcpy (data_out, "\x90\x00", res = 2); memcpy(data_out, "\x90\x00", res = 2);
state_machine_data->current_file = NDEF_FILE; state_machine_data->current_file = NDEF_FILE;
} else { } else {
memcpy (data_out, "\x6a\x00", res = 2); memcpy(data_out, "\x6a\x00", res = 2);
state_machine_data->current_file = NONE; state_machine_data->current_file = NONE;
} }
@ -170,12 +170,12 @@ nfcforum_tag4_io (struct nfc_emulator *emulator, const uint8_t *data_in, const s
const uint8_t ndef_tag_application_name_v1[] = { 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x00 }; const uint8_t ndef_tag_application_name_v1[] = { 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x00 };
const uint8_t ndef_tag_application_name_v2[] = { 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01 }; const uint8_t ndef_tag_application_name_v2[] = { 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01 };
if ((type4v == 1) && (data_in[LC] == sizeof (ndef_tag_application_name_v1)) && (0 == memcmp (ndef_tag_application_name_v1, data_in + DATA, data_in[LC]))) if ((type4v == 1) && (data_in[LC] == sizeof(ndef_tag_application_name_v1)) && (0 == memcmp(ndef_tag_application_name_v1, data_in + DATA, data_in[LC])))
memcpy (data_out, "\x90\x00", res = 2); memcpy(data_out, "\x90\x00", res = 2);
else if ((type4v == 2) && (data_in[LC] == sizeof (ndef_tag_application_name_v2)) && (0 == memcmp (ndef_tag_application_name_v2, data_in + DATA, data_in[LC]))) else if ((type4v == 2) && (data_in[LC] == sizeof(ndef_tag_application_name_v2)) && (0 == memcmp(ndef_tag_application_name_v2, data_in + DATA, data_in[LC])))
memcpy (data_out, "\x90\x00", res = 2); memcpy(data_out, "\x90\x00", res = 2);
else else
memcpy (data_out, "\x6a\x82", res = 2); memcpy(data_out, "\x6a\x82", res = 2);
break; break;
default: default:
@ -189,27 +189,27 @@ nfcforum_tag4_io (struct nfc_emulator *emulator, const uint8_t *data_in, const s
} }
switch (state_machine_data->current_file) { switch (state_machine_data->current_file) {
case NONE: case NONE:
memcpy (data_out, "\x6a\x82", res = 2); memcpy(data_out, "\x6a\x82", res = 2);
break; break;
case CC_FILE: case CC_FILE:
memcpy (data_out, nfcforum_capability_container + (data_in[P1] << 8) + data_in[P2], data_in[LC]); memcpy(data_out, nfcforum_capability_container + (data_in[P1] << 8) + data_in[P2], data_in[LC]);
memcpy (data_out + data_in[LC], "\x90\x00", 2); memcpy(data_out + data_in[LC], "\x90\x00", 2);
res = data_in[LC] + 2; res = data_in[LC] + 2;
break; break;
case NDEF_FILE: case NDEF_FILE:
memcpy (data_out, ndef_data->ndef_file + (data_in[P1] << 8) + data_in[P2], data_in[LC]); memcpy(data_out, ndef_data->ndef_file + (data_in[P1] << 8) + data_in[P2], data_in[LC]);
memcpy (data_out + data_in[LC], "\x90\x00", 2); memcpy(data_out + data_in[LC], "\x90\x00", 2);
res = data_in[LC] + 2; res = data_in[LC] + 2;
break; break;
} }
break; break;
case ISO7816_UPDATE_BINARY: case ISO7816_UPDATE_BINARY:
memcpy (ndef_data->ndef_file + (data_in[P1] << 8) + data_in[P2], data_in + DATA, data_in[LC]); memcpy(ndef_data->ndef_file + (data_in[P1] << 8) + data_in[P2], data_in + DATA, data_in[LC]);
if ((data_in[P1] << 8) + data_in[P2] == 0) { if ((data_in[P1] << 8) + data_in[P2] == 0) {
ndef_data->ndef_file_len = (ndef_data->ndef_file[0] << 8) + ndef_data->ndef_file[1] + 2; ndef_data->ndef_file_len = (ndef_data->ndef_file[0] << 8) + ndef_data->ndef_file[1] + 2;
} }
memcpy (data_out, "\x90\x00", res = 2); memcpy(data_out, "\x90\x00", res = 2);
break; break;
default: // Unknown default: // Unknown
if (!quiet_output) { if (!quiet_output) {
@ -224,34 +224,34 @@ nfcforum_tag4_io (struct nfc_emulator *emulator, const uint8_t *data_in, const s
// Show transmitted command // Show transmitted command
if (!quiet_output) { if (!quiet_output) {
if (res < 0) { if (res < 0) {
ERR ("%s (%d)", strerror (-res), -res); ERR("%s (%d)", strerror(-res), -res);
} else { } else {
printf (" Out: "); printf(" Out: ");
print_hex (data_out, res); print_hex(data_out, res);
} }
} }
return res; return res;
} }
static void stop_emulation (int sig) static void stop_emulation(int sig)
{ {
(void) sig; (void) sig;
if (pnd) if (pnd)
nfc_abort_command (pnd); nfc_abort_command(pnd);
else else
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
static size_t static size_t
ndef_message_load (char *filename, struct nfcforum_tag4_ndef_data *tag_data) ndef_message_load(char *filename, struct nfcforum_tag4_ndef_data *tag_data)
{ {
struct stat sb; struct stat sb;
if (stat (filename, &sb) < 0) if (stat(filename, &sb) < 0)
return 0; return 0;
/* Check file size */ /* Check file size */
if (sb.st_size > 0xFFFF) { if (sb.st_size > 0xFFFF) {
errx (EXIT_FAILURE, "file size too large '%s'", filename); errx(EXIT_FAILURE, "file size too large '%s'", filename);
} }
tag_data->ndef_file_len = sb.st_size + 2; tag_data->ndef_file_len = sb.st_size + 2;
@ -260,41 +260,41 @@ ndef_message_load (char *filename, struct nfcforum_tag4_ndef_data *tag_data)
tag_data->ndef_file[1] = (uint8_t)(sb.st_size); tag_data->ndef_file[1] = (uint8_t)(sb.st_size);
FILE *F; FILE *F;
if (!(F = fopen (filename, "r"))) if (!(F = fopen(filename, "r")))
err (EXIT_FAILURE, "fopen (%s, \"r\")", filename); err(EXIT_FAILURE, "fopen (%s, \"r\")", filename);
if (1 != fread (tag_data->ndef_file + 2, sb.st_size, 1, F)) if (1 != fread(tag_data->ndef_file + 2, sb.st_size, 1, F))
err (EXIT_FAILURE, "Can't read from %s", filename); err(EXIT_FAILURE, "Can't read from %s", filename);
fclose (F); fclose(F);
return sb.st_size; return sb.st_size;
} }
static size_t static size_t
ndef_message_save (char *filename, struct nfcforum_tag4_ndef_data *tag_data) ndef_message_save(char *filename, struct nfcforum_tag4_ndef_data *tag_data)
{ {
FILE *F; FILE *F;
if (!(F = fopen (filename, "w"))) if (!(F = fopen(filename, "w")))
err (EXIT_FAILURE, "fopen (%s, w)", filename); err(EXIT_FAILURE, "fopen (%s, w)", filename);
if (1 != fwrite (tag_data->ndef_file + 2, tag_data->ndef_file_len - 2, 1, F)) { if (1 != fwrite(tag_data->ndef_file + 2, tag_data->ndef_file_len - 2, 1, F)) {
err (EXIT_FAILURE, "fwrite (%d)", (int) tag_data->ndef_file_len - 2); err(EXIT_FAILURE, "fwrite (%d)", (int) tag_data->ndef_file_len - 2);
} }
fclose (F); fclose(F);
return tag_data->ndef_file_len - 2; return tag_data->ndef_file_len - 2;
} }
static void static void
usage (char *progname) usage(char *progname)
{ {
fprintf (stderr, "usage: %s [-1] [infile [outfile]]\n", progname); fprintf(stderr, "usage: %s [-1] [infile [outfile]]\n", progname);
fprintf (stderr, " -1: force Tag Type 4 v1.0 (default is v2.0)\n"); fprintf(stderr, " -1: force Tag Type 4 v1.0 (default is v2.0)\n");
} }
int int
main (int argc, char *argv[]) main(int argc, char *argv[])
{ {
int options = 0; int options = 0;
nfc_target nt = { nfc_target nt = {
@ -342,56 +342,56 @@ main (int argc, char *argv[])
.user_data = &nfcforum_tag4_data, .user_data = &nfcforum_tag4_data,
}; };
if ((argc > (1 + options)) && (0 == strcmp ("-h", argv[1 + options]))) { if ((argc > (1 + options)) && (0 == strcmp("-h", argv[1 + options]))) {
usage (argv[0]); usage(argv[0]);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
if ((argc > (1 + options)) && (0 == strcmp ("-1", argv[1 + options]))) { if ((argc > (1 + options)) && (0 == strcmp("-1", argv[1 + options]))) {
type4v = 1; type4v = 1;
nfcforum_capability_container[2] = 0x10; nfcforum_capability_container[2] = 0x10;
options += 1; options += 1;
} }
if (argc > (3 + options)) { if (argc > (3 + options)) {
usage (argv[0]); usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// If some file is provided load it // If some file is provided load it
if (argc >= (2 + options)) { if (argc >= (2 + options)) {
if (!ndef_message_load (argv[1 + options], &nfcforum_tag4_data)) { if (!ndef_message_load(argv[1 + options], &nfcforum_tag4_data)) {
err (EXIT_FAILURE, "Can't load NDEF file '%s'", argv[1 + options]); err(EXIT_FAILURE, "Can't load NDEF file '%s'", argv[1 + options]);
} }
} }
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC reader // Try to open the NFC reader
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR("Unable to open NFC device"); ERR("Unable to open NFC device");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
signal (SIGINT, stop_emulation); signal(SIGINT, stop_emulation);
printf ("NFC device: %s opened\n", nfc_device_get_name(pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
printf ("Emulating NDEF tag now, please touch it with a second NFC device\n"); printf("Emulating NDEF tag now, please touch it with a second NFC device\n");
if (0 != nfc_emulate_target (pnd, &emulator)) { // contains already nfc_target_init() call if (0 != nfc_emulate_target(pnd, &emulator)) { // contains already nfc_target_init() call
nfc_perror (pnd, "nfc_emulate_target"); nfc_perror(pnd, "nfc_emulate_target");
} }
nfc_close(pnd); nfc_close(pnd);
if (argc == (3 + options)) { if (argc == (3 + options)) {
if (!(ndef_message_save (argv[2 + options], &nfcforum_tag4_data))) { if (!(ndef_message_save(argv[2 + options], &nfcforum_tag4_data))) {
err (EXIT_FAILURE, "Can't save NDEF file '%s'", argv[2 + options]); err(EXIT_FAILURE, "Can't save NDEF file '%s'", argv[2 + options]);
} }
} }
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }

View file

@ -59,14 +59,14 @@
static nfc_device *pnd; static nfc_device *pnd;
static void static void
print_usage (const char* progname) print_usage(const char* progname)
{ {
printf ("usage: %s [-v]\n", progname); printf("usage: %s [-v]\n", progname);
printf (" -v\t verbose display\n"); printf(" -v\t verbose display\n");
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
(void) argc; (void) argc;
const char *acLibnfcVersion; const char *acLibnfcVersion;
@ -74,29 +74,29 @@ main (int argc, const char *argv[])
bool verbose = false; bool verbose = false;
int res = 0; int res = 0;
nfc_init (NULL); nfc_init(NULL);
// Display libnfc version // Display libnfc version
acLibnfcVersion = nfc_version (); acLibnfcVersion = nfc_version();
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
if (argc != 1) { if (argc != 1) {
if ((argc == 2) && (0 == strcmp ("-v", argv[1]))) { if ((argc == 2) && (0 == strcmp("-v", argv[1]))) {
verbose = true; verbose = true;
} else { } else {
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
#ifdef HAVE_LIBUSB #ifdef HAVE_LIBUSB
# ifdef DEBUG # ifdef DEBUG
usb_set_debug (4); usb_set_debug(4);
# endif # endif
#endif #endif
/* Lazy way to open an NFC device */ /* Lazy way to open an NFC device */
#if 0 #if 0
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
#endif #endif
/* If specific device is wanted, i.e. an ARYGON device on /dev/ttyUSB0 */ /* If specific device is wanted, i.e. an ARYGON device on /dev/ttyUSB0 */
@ -105,7 +105,7 @@ main (int argc, const char *argv[])
ndd.pcDriver = "ARYGON"; ndd.pcDriver = "ARYGON";
ndd.pcPort = "/dev/ttyUSB0"; ndd.pcPort = "/dev/ttyUSB0";
ndd.uiSpeed = 115200; ndd.uiSpeed = 115200;
pnd = nfc_open (NULL, &ndd); pnd = nfc_open(NULL, &ndd);
#endif #endif
/* If specific device is wanted, i.e. a SCL3711 on USB */ /* If specific device is wanted, i.e. a SCL3711 on USB */
@ -113,125 +113,125 @@ main (int argc, const char *argv[])
nfc_device_desc_t ndd; nfc_device_desc_t ndd;
ndd.pcDriver = "PN533_USB"; ndd.pcDriver = "PN533_USB";
strcpy(ndd.acDevice, "SCM Micro / SCL3711-NFC&RW"); strcpy(ndd.acDevice, "SCM Micro / SCL3711-NFC&RW");
pnd = nfc_open (NULL, &ndd); pnd = nfc_open(NULL, &ndd);
#endif #endif
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
size_t szDeviceFound = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t szDeviceFound = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
if (szDeviceFound == 0) { if (szDeviceFound == 0) {
printf ("No NFC device found.\n"); printf("No NFC device found.\n");
} }
for (i = 0; i < szDeviceFound; i++) { for (i = 0; i < szDeviceFound; i++) {
nfc_target ant[MAX_TARGET_COUNT]; nfc_target ant[MAX_TARGET_COUNT];
pnd = nfc_open (NULL, connstrings[i]); pnd = nfc_open(NULL, connstrings[i]);
if (pnd == NULL) { if (pnd == NULL) {
ERR ("Unable to open NFC device: %s", connstrings[i]); ERR("Unable to open NFC device: %s", connstrings[i]);
continue; continue;
} }
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC device: %s opened\n", nfc_device_get_name (pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
nfc_modulation nm; nfc_modulation nm;
nm.nmt = NMT_ISO14443A; nm.nmt = NMT_ISO14443A;
nm.nbr = NBR_106; nm.nbr = NBR_106;
// List ISO14443A targets // List ISO14443A targets
if ((res = nfc_initiator_list_passive_targets (pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) {
int n; int n;
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf ("%d ISO14443A passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d ISO14443A passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for (n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_iso14443a_info (ant[n].nti.nai, verbose); print_nfc_iso14443a_info(ant[n].nti.nai, verbose);
printf ("\n"); printf("\n");
} }
} }
nm.nmt = NMT_FELICA; nm.nmt = NMT_FELICA;
nm.nbr = NBR_212; nm.nbr = NBR_212;
// List Felica tags // List Felica tags
if ((res = nfc_initiator_list_passive_targets (pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) {
int n; int n;
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf ("%d Felica (212 kbps) passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d Felica (212 kbps) passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for (n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_felica_info (ant[n].nti.nfi, verbose); print_nfc_felica_info(ant[n].nti.nfi, verbose);
printf ("\n"); printf("\n");
} }
} }
nm.nbr = NBR_424; nm.nbr = NBR_424;
if ((res = nfc_initiator_list_passive_targets (pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) {
int n; int n;
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf ("%d Felica (424 kbps) passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d Felica (424 kbps) passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for (n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_felica_info (ant[n].nti.nfi, verbose); print_nfc_felica_info(ant[n].nti.nfi, verbose);
printf ("\n"); printf("\n");
} }
} }
nm.nmt = NMT_ISO14443B; nm.nmt = NMT_ISO14443B;
nm.nbr = NBR_106; nm.nbr = NBR_106;
// List ISO14443B targets // List ISO14443B targets
if ((res = nfc_initiator_list_passive_targets (pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) {
int n; int n;
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf ("%d ISO14443B passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d ISO14443B passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for (n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_iso14443b_info (ant[n].nti.nbi, verbose); print_nfc_iso14443b_info(ant[n].nti.nbi, verbose);
printf ("\n"); printf("\n");
} }
} }
nm.nmt = NMT_ISO14443BI; nm.nmt = NMT_ISO14443BI;
nm.nbr = NBR_106; nm.nbr = NBR_106;
// List ISO14443B' targets // List ISO14443B' targets
if ((res = nfc_initiator_list_passive_targets (pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) {
int n; int n;
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf ("%d ISO14443B' passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d ISO14443B' passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for (n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_iso14443bi_info (ant[n].nti.nii, verbose); print_nfc_iso14443bi_info(ant[n].nti.nii, verbose);
printf ("\n"); printf("\n");
} }
} }
nm.nmt = NMT_ISO14443B2SR; nm.nmt = NMT_ISO14443B2SR;
nm.nbr = NBR_106; nm.nbr = NBR_106;
// List ISO14443B-2 ST SRx family targets // List ISO14443B-2 ST SRx family targets
if ((res = nfc_initiator_list_passive_targets (pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) {
int n; int n;
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf ("%d ISO14443B-2 ST SRx passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d ISO14443B-2 ST SRx passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for (n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_iso14443b2sr_info (ant[n].nti.nsi, verbose); print_nfc_iso14443b2sr_info(ant[n].nti.nsi, verbose);
printf ("\n"); printf("\n");
} }
} }
nm.nmt = NMT_ISO14443B2CT; nm.nmt = NMT_ISO14443B2CT;
nm.nbr = NBR_106; nm.nbr = NBR_106;
// List ISO14443B-2 ASK CTx family targets // List ISO14443B-2 ASK CTx family targets
if ((res = nfc_initiator_list_passive_targets (pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) {
int n; int n;
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf ("%d ISO14443B-2 ASK CTx passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d ISO14443B-2 ASK CTx passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for (n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_iso14443b2ct_info (ant[n].nti.nci, verbose); print_nfc_iso14443b2ct_info(ant[n].nti.nci, verbose);
printf ("\n"); printf("\n");
} }
} }
@ -243,14 +243,14 @@ main (int argc, const char *argv[])
if (verbose || (res > 0)) { if (verbose || (res > 0)) {
printf("%d Jewel passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); printf("%d Jewel passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":");
} }
for(n = 0; n < res; n++) { for (n = 0; n < res; n++) {
print_nfc_jewel_info (ant[n].nti.nji, verbose); print_nfc_jewel_info(ant[n].nti.nji, verbose);
printf("\n"); printf("\n");
} }
} }
nfc_close (pnd); nfc_close(pnd);
} }
nfc_exit (NULL); nfc_exit(NULL);
return 0; return 0;
} }

View file

@ -77,7 +77,7 @@ static const nfc_modulation nmMifare = {
.nbr = NBR_106, .nbr = NBR_106,
}; };
static size_t num_keys = sizeof (keys) / 6; static size_t num_keys = sizeof(keys) / 6;
#define MAX_FRAME_LEN 264 #define MAX_FRAME_LEN 264
@ -91,51 +91,51 @@ uint8_t abtUnlock1[1] = { 0x40 };
uint8_t abtUnlock2[1] = { 0x43 }; uint8_t abtUnlock2[1] = { 0x43 };
static bool static bool
transmit_bits (const uint8_t *pbtTx, const size_t szTxBits) transmit_bits(const uint8_t *pbtTx, const size_t szTxBits)
{ {
// Show transmitted command // Show transmitted command
printf ("Sent bits: "); printf("Sent bits: ");
print_hex_bits (pbtTx, szTxBits); print_hex_bits(pbtTx, szTxBits);
// Transmit the bit frame command, we don't use the arbitrary parity feature // Transmit the bit frame command, we don't use the arbitrary parity feature
if ((szRxBits = nfc_initiator_transceive_bits (pnd, pbtTx, szTxBits, NULL, abtRx, NULL)) < 0) if ((szRxBits = nfc_initiator_transceive_bits(pnd, pbtTx, szTxBits, NULL, abtRx, NULL)) < 0)
return false; return false;
// Show received answer // Show received answer
printf ("Received bits: "); printf("Received bits: ");
print_hex_bits (abtRx, szRxBits); print_hex_bits(abtRx, szRxBits);
// Succesful transfer // Succesful transfer
return true; return true;
} }
static bool static bool
transmit_bytes (const uint8_t *pbtTx, const size_t szTx) transmit_bytes(const uint8_t *pbtTx, const size_t szTx)
{ {
// Show transmitted command // Show transmitted command
printf ("Sent bits: "); printf("Sent bits: ");
print_hex (pbtTx, szTx); print_hex(pbtTx, szTx);
// Transmit the command bytes // Transmit the command bytes
int res; int res;
if ((res = nfc_initiator_transceive_bytes (pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0) if ((res = nfc_initiator_transceive_bytes(pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0)
return false; return false;
// Show received answer // Show received answer
printf ("Received bits: "); printf("Received bits: ");
print_hex (abtRx, res); print_hex(abtRx, res);
// Succesful transfer // Succesful transfer
return true; return true;
} }
static void static void
print_success_or_failure (bool bFailure, uint32_t *uiBlockCounter) print_success_or_failure(bool bFailure, uint32_t *uiBlockCounter)
{ {
printf ("%c", (bFailure) ? 'x' : '.'); printf("%c", (bFailure) ? 'x' : '.');
if (uiBlockCounter && !bFailure) if (uiBlockCounter && !bFailure)
*uiBlockCounter += (*uiBlockCounter < 128) ? 4 : 16; *uiBlockCounter += (*uiBlockCounter < 128) ? 4 : 16;
} }
static bool static bool
is_first_block (uint32_t uiBlock) is_first_block(uint32_t uiBlock)
{ {
// Test if we are in the small or big sectors // Test if we are in the small or big sectors
if (uiBlock < 128) if (uiBlock < 128)
@ -145,7 +145,7 @@ is_first_block (uint32_t uiBlock)
} }
static bool static bool
is_trailer_block (uint32_t uiBlock) is_trailer_block(uint32_t uiBlock)
{ {
// Test if we are in the small or big sectors // Test if we are in the small or big sectors
if (uiBlock < 128) if (uiBlock < 128)
@ -155,7 +155,7 @@ is_trailer_block (uint32_t uiBlock)
} }
static uint32_t static uint32_t
get_trailer_block (uint32_t uiFirstBlock) get_trailer_block(uint32_t uiFirstBlock)
{ {
// Test if we are in the small or big sectors // Test if we are in the small or big sectors
uint32_t trailer_block = 0; uint32_t trailer_block = 0;
@ -168,14 +168,14 @@ get_trailer_block (uint32_t uiFirstBlock)
} }
static bool static bool
authenticate (uint32_t uiBlock) authenticate(uint32_t uiBlock)
{ {
mifare_cmd mc; mifare_cmd mc;
uint32_t uiTrailerBlock; uint32_t uiTrailerBlock;
size_t key_index; size_t key_index;
// Set the authentication information (uid) // Set the authentication information (uid)
memcpy (mp.mpa.abtUid, nt.nti.nai.abtUid + nt.nti.nai.szUidLen - 4, 4); memcpy(mp.mpa.abtUid, nt.nti.nai.abtUid + nt.nti.nai.szUidLen - 4, 4);
// Should we use key A or B? // Should we use key A or B?
mc = (bUseKeyA) ? MC_AUTH_A : MC_AUTH_B; mc = (bUseKeyA) ? MC_AUTH_A : MC_AUTH_B;
@ -184,29 +184,29 @@ authenticate (uint32_t uiBlock)
if (bUseKeyFile) { if (bUseKeyFile) {
// Locate the trailer (with the keys) used for this sector // Locate the trailer (with the keys) used for this sector
uiTrailerBlock = get_trailer_block (uiBlock); uiTrailerBlock = get_trailer_block(uiBlock);
// Extract the right key from dump file // Extract the right key from dump file
if (bUseKeyA) if (bUseKeyA)
memcpy (mp.mpa.abtKey, mtKeys.amb[uiTrailerBlock].mbt.abtKeyA, 6); memcpy(mp.mpa.abtKey, mtKeys.amb[uiTrailerBlock].mbt.abtKeyA, 6);
else else
memcpy (mp.mpa.abtKey, mtKeys.amb[uiTrailerBlock].mbt.abtKeyB, 6); memcpy(mp.mpa.abtKey, mtKeys.amb[uiTrailerBlock].mbt.abtKeyB, 6);
// Try to authenticate for the current sector // Try to authenticate for the current sector
if (nfc_initiator_mifare_cmd (pnd, mc, uiBlock, &mp)) if (nfc_initiator_mifare_cmd(pnd, mc, uiBlock, &mp))
return true; return true;
} else { } else {
// Try to guess the right key // Try to guess the right key
for (key_index = 0; key_index < num_keys; key_index++) { for (key_index = 0; key_index < num_keys; key_index++) {
memcpy (mp.mpa.abtKey, keys + (key_index * 6), 6); memcpy(mp.mpa.abtKey, keys + (key_index * 6), 6);
if (nfc_initiator_mifare_cmd (pnd, mc, uiBlock, &mp)) { if (nfc_initiator_mifare_cmd(pnd, mc, uiBlock, &mp)) {
if (bUseKeyA) if (bUseKeyA)
memcpy (mtKeys.amb[uiBlock].mbt.abtKeyA, &mp.mpa.abtKey, 6); memcpy(mtKeys.amb[uiBlock].mbt.abtKeyA, &mp.mpa.abtKey, 6);
else else
memcpy (mtKeys.amb[uiBlock].mbt.abtKeyB, &mp.mpa.abtKey, 6); memcpy(mtKeys.amb[uiBlock].mbt.abtKeyB, &mp.mpa.abtKey, 6);
return true; return true;
} }
nfc_initiator_select_passive_target (pnd, nmMifare, nt.nti.nai.abtUid, nt.nti.nai.szUidLen, NULL); nfc_initiator_select_passive_target(pnd, nmMifare, nt.nti.nai.abtUid, nt.nti.nai.szUidLen, NULL);
} }
} }
@ -214,170 +214,170 @@ authenticate (uint32_t uiBlock)
} }
static bool static bool
unlock_card (void) unlock_card(void)
{ {
printf ("Unlocking card\n"); printf("Unlocking card\n");
// Configure the CRC // Configure the CRC
if (nfc_device_set_property_bool (pnd, NP_HANDLE_CRC, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) {
nfc_perror (pnd, "nfc_configure"); nfc_perror(pnd, "nfc_configure");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Use raw send/receive methods // Use raw send/receive methods
if (nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) {
nfc_perror (pnd, "nfc_configure"); nfc_perror(pnd, "nfc_configure");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
iso14443a_crc_append(abtHalt, 2); iso14443a_crc_append(abtHalt, 2);
transmit_bytes (abtHalt, 4); transmit_bytes(abtHalt, 4);
// now send unlock // now send unlock
if (!transmit_bits (abtUnlock1, 7)) { if (!transmit_bits(abtUnlock1, 7)) {
printf("unlock failure!\n"); printf("unlock failure!\n");
return false; return false;
} }
if (!transmit_bytes (abtUnlock2, 1)) { if (!transmit_bytes(abtUnlock2, 1)) {
printf("unlock failure!\n"); printf("unlock failure!\n");
return false; return false;
} }
// reset reader // reset reader
// Configure the CRC // Configure the CRC
if (nfc_device_set_property_bool (pnd, NP_HANDLE_CRC, true) < 0) { if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Switch off raw send/receive methods // Switch off raw send/receive methods
if (nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, true) < 0) { if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
return true; return true;
} }
static bool static bool
read_card (int read_unlocked) read_card(int read_unlocked)
{ {
int32_t iBlock; int32_t iBlock;
bool bFailure = false; bool bFailure = false;
uint32_t uiReadBlocks = 0; uint32_t uiReadBlocks = 0;
if(read_unlocked) if (read_unlocked)
if (!unlock_card()) if (!unlock_card())
return false; return false;
printf ("Reading out %d blocks |", uiBlocks + 1); printf("Reading out %d blocks |", uiBlocks + 1);
// Read the card from end to begin // Read the card from end to begin
for (iBlock = uiBlocks; iBlock >= 0; iBlock--) { for (iBlock = uiBlocks; iBlock >= 0; iBlock--) {
// Authenticate everytime we reach a trailer block // Authenticate everytime we reach a trailer block
if (is_trailer_block (iBlock)) { if (is_trailer_block(iBlock)) {
// Skip this the first time, bFailure it means nothing (yet) // Skip this the first time, bFailure it means nothing (yet)
if (iBlock != uiBlocks) if (iBlock != uiBlocks)
print_success_or_failure (bFailure, &uiReadBlocks); print_success_or_failure(bFailure, &uiReadBlocks);
// Show if the readout went well // Show if the readout went well
if (bFailure) { if (bFailure) {
// When a failure occured we need to redo the anti-collision // When a failure occured we need to redo the anti-collision
if (nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt) < 0) { if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) < 0) {
printf ("!\nError: tag was removed\n"); printf("!\nError: tag was removed\n");
return false; return false;
} }
bFailure = false; bFailure = false;
} }
fflush (stdout); fflush(stdout);
// Try to authenticate for the current sector // Try to authenticate for the current sector
if (!read_unlocked && !authenticate (iBlock)) { if (!read_unlocked && !authenticate(iBlock)) {
printf ("!\nError: authentication failed for block 0x%02x\n", iBlock); printf("!\nError: authentication failed for block 0x%02x\n", iBlock);
return false; return false;
} }
// Try to read out the trailer // Try to read out the trailer
if (nfc_initiator_mifare_cmd (pnd, MC_READ, iBlock, &mp)) { if (nfc_initiator_mifare_cmd(pnd, MC_READ, iBlock, &mp)) {
if(read_unlocked) { if (read_unlocked) {
memcpy (mtDump.amb[iBlock].mbd.abtData, mp.mpd.abtData, 16); memcpy(mtDump.amb[iBlock].mbd.abtData, mp.mpd.abtData, 16);
} else { } else {
// Copy the keys over from our key dump and store the retrieved access bits // Copy the keys over from our key dump and store the retrieved access bits
memcpy (mtDump.amb[iBlock].mbt.abtKeyA, mtKeys.amb[iBlock].mbt.abtKeyA, 6); memcpy(mtDump.amb[iBlock].mbt.abtKeyA, mtKeys.amb[iBlock].mbt.abtKeyA, 6);
memcpy (mtDump.amb[iBlock].mbt.abtAccessBits, mp.mpd.abtData + 6, 4); memcpy(mtDump.amb[iBlock].mbt.abtAccessBits, mp.mpd.abtData + 6, 4);
memcpy (mtDump.amb[iBlock].mbt.abtKeyB, mtKeys.amb[iBlock].mbt.abtKeyB, 6); memcpy(mtDump.amb[iBlock].mbt.abtKeyB, mtKeys.amb[iBlock].mbt.abtKeyB, 6);
} }
} else { } else {
printf ("!\nError: unable to read trailer block 0x%02x\n", iBlock); printf("!\nError: unable to read trailer block 0x%02x\n", iBlock);
} }
} else { } else {
// Make sure a earlier readout did not fail // Make sure a earlier readout did not fail
if (!bFailure) { if (!bFailure) {
// Try to read out the data block // Try to read out the data block
if (nfc_initiator_mifare_cmd (pnd, MC_READ, iBlock, &mp)) { if (nfc_initiator_mifare_cmd(pnd, MC_READ, iBlock, &mp)) {
memcpy (mtDump.amb[iBlock].mbd.abtData, mp.mpd.abtData, 16); memcpy(mtDump.amb[iBlock].mbd.abtData, mp.mpd.abtData, 16);
} else { } else {
bFailure = true; bFailure = true;
printf ("!\nError: unable to read block 0x%02x\n", iBlock); printf("!\nError: unable to read block 0x%02x\n", iBlock);
return false; return false;
} }
} }
} }
} }
print_success_or_failure (bFailure, &uiReadBlocks); print_success_or_failure(bFailure, &uiReadBlocks);
printf ("|\n"); printf("|\n");
printf ("Done, %d of %d blocks read.\n", uiReadBlocks, uiBlocks + 1); printf("Done, %d of %d blocks read.\n", uiReadBlocks, uiBlocks + 1);
fflush (stdout); fflush(stdout);
return true; return true;
} }
static bool static bool
write_card (int write_block_zero) write_card(int write_block_zero)
{ {
uint32_t uiBlock; uint32_t uiBlock;
bool bFailure = false; bool bFailure = false;
uint32_t uiWriteBlocks = 0; uint32_t uiWriteBlocks = 0;
if(write_block_zero) if (write_block_zero)
if (!unlock_card()) if (!unlock_card())
return false; return false;
printf ("Writing %d blocks |", uiBlocks + 1); printf("Writing %d blocks |", uiBlocks + 1);
// Write the card from begin to end; // Write the card from begin to end;
for (uiBlock = 0; uiBlock <= uiBlocks; uiBlock++) { for (uiBlock = 0; uiBlock <= uiBlocks; uiBlock++) {
// Authenticate everytime we reach the first sector of a new block // Authenticate everytime we reach the first sector of a new block
if (is_first_block (uiBlock)) { if (is_first_block(uiBlock)) {
// Skip this the first time, bFailure it means nothing (yet) // Skip this the first time, bFailure it means nothing (yet)
if (uiBlock != 0) if (uiBlock != 0)
print_success_or_failure (bFailure, &uiWriteBlocks); print_success_or_failure(bFailure, &uiWriteBlocks);
// Show if the readout went well // Show if the readout went well
if (bFailure) { if (bFailure) {
// When a failure occured we need to redo the anti-collision // When a failure occured we need to redo the anti-collision
if (nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt) < 0) { if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) < 0) {
printf ("!\nError: tag was removed\n"); printf("!\nError: tag was removed\n");
return false; return false;
} }
bFailure = false; bFailure = false;
} }
fflush (stdout); fflush(stdout);
// Try to authenticate for the current sector // Try to authenticate for the current sector
if (!write_block_zero && !authenticate (uiBlock)) { if (!write_block_zero && !authenticate(uiBlock)) {
printf ("!\nError: authentication failed for block %02x\n", uiBlock); printf("!\nError: authentication failed for block %02x\n", uiBlock);
return false; return false;
} }
} }
if (is_trailer_block (uiBlock)) { if (is_trailer_block(uiBlock)) {
// Copy the keys over from our key dump and store the retrieved access bits // Copy the keys over from our key dump and store the retrieved access bits
memcpy (mp.mpd.abtData, mtDump.amb[uiBlock].mbt.abtKeyA, 6); memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbt.abtKeyA, 6);
memcpy (mp.mpd.abtData + 6, mtDump.amb[uiBlock].mbt.abtAccessBits, 4); memcpy(mp.mpd.abtData + 6, mtDump.amb[uiBlock].mbt.abtAccessBits, 4);
memcpy (mp.mpd.abtData + 10, mtDump.amb[uiBlock].mbt.abtKeyB, 6); memcpy(mp.mpd.abtData + 10, mtDump.amb[uiBlock].mbt.abtKeyB, 6);
// Try to write the trailer // Try to write the trailer
if (nfc_initiator_mifare_cmd (pnd, MC_WRITE, uiBlock, &mp) == false) { if (nfc_initiator_mifare_cmd(pnd, MC_WRITE, uiBlock, &mp) == false) {
printf ("failed to write trailer block %d \n", uiBlock); printf("failed to write trailer block %d \n", uiBlock);
bFailure = true; bFailure = true;
} }
} else { } else {
@ -389,23 +389,23 @@ write_card (int write_block_zero)
// Make sure a earlier write did not fail // Make sure a earlier write did not fail
if (!bFailure) { if (!bFailure) {
// Try to write the data block // Try to write the data block
memcpy (mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData, 16); memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData, 16);
// do not write a block 0 with incorrect BCC - card will be made invalid! // do not write a block 0 with incorrect BCC - card will be made invalid!
if (uiBlock == 0) { if (uiBlock == 0) {
if((mp.mpd.abtData[0] ^ mp.mpd.abtData[1] ^ mp.mpd.abtData[2] ^ mp.mpd.abtData[3] ^ mp.mpd.abtData[4]) != 0x00) { if ((mp.mpd.abtData[0] ^ mp.mpd.abtData[1] ^ mp.mpd.abtData[2] ^ mp.mpd.abtData[3] ^ mp.mpd.abtData[4]) != 0x00) {
printf ("!\nError: incorrect BCC in MFD file!\n"); printf("!\nError: incorrect BCC in MFD file!\n");
return false; return false;
} }
} }
if (!nfc_initiator_mifare_cmd (pnd, MC_WRITE, uiBlock, &mp)) if (!nfc_initiator_mifare_cmd(pnd, MC_WRITE, uiBlock, &mp))
bFailure = true; bFailure = true;
} }
} }
} }
print_success_or_failure (bFailure, &uiWriteBlocks); print_success_or_failure(bFailure, &uiWriteBlocks);
printf ("|\n"); printf("|\n");
printf ("Done, %d of %d blocks written.\n", uiWriteBlocks, uiBlocks + 1); printf("Done, %d of %d blocks written.\n", uiWriteBlocks, uiBlocks + 1);
fflush (stdout); fflush(stdout);
return true; return true;
} }
@ -417,21 +417,21 @@ typedef enum {
} action_t; } action_t;
static void static void
print_usage (const char *pcProgramName) print_usage(const char *pcProgramName)
{ {
printf ("Usage: "); printf("Usage: ");
printf ("%s r|R|w|W a|b <dump.mfd> [<keys.mfd>]\n", pcProgramName); printf("%s r|R|w|W a|b <dump.mfd> [<keys.mfd>]\n", pcProgramName);
printf (" r|R|w|W - Perform read from (r) or unlocked read from (R) or write to (w) or unlocked write to (W) card\n"); printf(" r|R|w|W - Perform read from (r) or unlocked read from (R) or write to (w) or unlocked write to (W) card\n");
printf (" *** note that unlocked write will attempt to overwrite block 0 including UID\n"); printf(" *** note that unlocked write will attempt to overwrite block 0 including UID\n");
printf (" *** unlocked read does not require authentication and will reveal A and B keys\n"); printf(" *** unlocked read does not require authentication and will reveal A and B keys\n");
printf (" *** unlocking only works with special Mifare 1K cards (Chinese clones)\n"); printf(" *** unlocking only works with special Mifare 1K cards (Chinese clones)\n");
printf (" a|b - Use A or B keys for action\n"); printf(" a|b - Use A or B keys for action\n");
printf (" <dump.mfd> - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n"); printf(" <dump.mfd> - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
printf (" <keys.mfd> - MiFare Dump (MFD) that contain the keys (optional)\n"); printf(" <keys.mfd> - MiFare Dump (MFD) that contain the keys (optional)\n");
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
action_t atAction = ACTION_USAGE; action_t atAction = ACTION_USAGE;
uint8_t *pbtUID; uint8_t *pbtUID;
@ -440,107 +440,107 @@ main (int argc, const char *argv[])
int unlock = 0; int unlock = 0;
if (argc < 2) { if (argc < 2) {
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
const char *command = argv[1]; const char *command = argv[1];
if (strcmp (command, "r") == 0 || strcmp (command, "R") == 0) { if (strcmp(command, "r") == 0 || strcmp(command, "R") == 0) {
if (argc < 4) { if (argc < 4) {
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
atAction = ACTION_READ; atAction = ACTION_READ;
if (strcmp (command, "R") == 0) if (strcmp(command, "R") == 0)
unlock = 1; unlock = 1;
bUseKeyA = tolower ((int) ((unsigned char) * (argv[2]))) == 'a'; bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a';
bUseKeyFile = (argc > 4); bUseKeyFile = (argc > 4);
} else if (strcmp (command, "w") == 0 || strcmp (command, "W") == 0) { } else if (strcmp(command, "w") == 0 || strcmp(command, "W") == 0) {
if (argc < 4) { if (argc < 4) {
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
atAction = ACTION_WRITE; atAction = ACTION_WRITE;
if (strcmp (command, "W") == 0) if (strcmp(command, "W") == 0)
unlock = 1; unlock = 1;
bUseKeyA = tolower ((int) ((unsigned char) * (argv[2]))) == 'a'; bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a';
bUseKeyFile = (argc > 4); bUseKeyFile = (argc > 4);
} }
switch (atAction) { switch (atAction) {
case ACTION_USAGE: case ACTION_USAGE:
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
break; break;
case ACTION_READ: case ACTION_READ:
case ACTION_WRITE: case ACTION_WRITE:
if (bUseKeyFile) { if (bUseKeyFile) {
pfKeys = fopen (argv[4], "rb"); pfKeys = fopen(argv[4], "rb");
if (pfKeys == NULL) { if (pfKeys == NULL) {
printf ("Could not open keys file: %s\n", argv[4]); printf("Could not open keys file: %s\n", argv[4]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (fread (&mtKeys, 1, sizeof (mtKeys), pfKeys) != sizeof (mtKeys)) { if (fread(&mtKeys, 1, sizeof(mtKeys), pfKeys) != sizeof(mtKeys)) {
printf ("Could not read keys file: %s\n", argv[4]); printf("Could not read keys file: %s\n", argv[4]);
fclose (pfKeys); fclose(pfKeys);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
fclose (pfKeys); fclose(pfKeys);
} }
if (atAction == ACTION_READ) { if (atAction == ACTION_READ) {
memset (&mtDump, 0x00, sizeof (mtDump)); memset(&mtDump, 0x00, sizeof(mtDump));
} else { } else {
pfDump = fopen (argv[3], "rb"); pfDump = fopen(argv[3], "rb");
if (pfDump == NULL) { if (pfDump == NULL) {
printf ("Could not open dump file: %s\n", argv[3]); printf("Could not open dump file: %s\n", argv[3]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (fread (&mtDump, 1, sizeof (mtDump), pfDump) != sizeof (mtDump)) { if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
printf ("Could not read dump file: %s\n", argv[3]); printf("Could not read dump file: %s\n", argv[3]);
fclose (pfDump); fclose(pfDump);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
fclose (pfDump); fclose(pfDump);
} }
// printf("Successfully opened required files\n"); // printf("Successfully opened required files\n");
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC reader // Try to open the NFC reader
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
printf ("Error opening NFC reader\n"); printf("Error opening NFC reader\n");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
}; };
// Let the reader only try once to find a tag // Let the reader only try once to find a tag
if (nfc_device_set_property_bool (pnd, NP_INFINITE_SELECT, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Disable ISO14443-4 switching in order to read devices that emulate Mifare Classic with ISO14443-4 compliance. // Disable ISO14443-4 switching in order to read devices that emulate Mifare Classic with ISO14443-4 compliance.
nfc_device_set_property_bool (pnd, NP_AUTO_ISO14443_4, false); nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false);
printf ("NFC reader: %s opened\n", nfc_device_get_name (pnd)); printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
// Try to find a MIFARE Classic tag // Try to find a MIFARE Classic tag
if (nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt) < 0) { if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) < 0) {
printf ("Error: no tag was found\n"); printf("Error: no tag was found\n");
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Test if we are dealing with a MIFARE compatible tag // Test if we are dealing with a MIFARE compatible tag
if ((nt.nti.nai.btSak & 0x08) == 0) { if ((nt.nti.nai.btSak & 0x08) == 0) {
printf ("Warning: tag is probably not a MFC!\n"); printf("Warning: tag is probably not a MFC!\n");
} }
// Get the info from the current tag // Get the info from the current tag
@ -548,15 +548,15 @@ main (int argc, const char *argv[])
if (bUseKeyFile) { if (bUseKeyFile) {
uint8_t fileUid[4]; uint8_t fileUid[4];
memcpy (fileUid, mtKeys.amb[0].mbm.abtUID, 4); memcpy(fileUid, mtKeys.amb[0].mbm.abtUID, 4);
// Compare if key dump UID is the same as the current tag UID, at least for the first 4 bytes // Compare if key dump UID is the same as the current tag UID, at least for the first 4 bytes
if (memcmp (pbtUID, fileUid, 4) != 0) { if (memcmp(pbtUID, fileUid, 4) != 0) {
printf ("Expected MIFARE Classic card with UID starting as: %02x%02x%02x%02x\n", printf("Expected MIFARE Classic card with UID starting as: %02x%02x%02x%02x\n",
fileUid[0], fileUid[1], fileUid[2], fileUid[3]); fileUid[0], fileUid[1], fileUid[2], fileUid[3]);
} }
} }
printf ("Found MIFARE Classic card:\n"); printf("Found MIFARE Classic card:\n");
print_nfc_iso14443a_info (nt.nti.nai, false); print_nfc_iso14443a_info(nt.nti.nai, false);
// Guessing size // Guessing size
if ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x02) if ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x02)
@ -569,32 +569,32 @@ main (int argc, const char *argv[])
// 1K // 1K
// TODO: for MFP it is 0x7f (2K) but how to be sure it's a MFP? Try to get RATS? // TODO: for MFP it is 0x7f (2K) but how to be sure it's a MFP? Try to get RATS?
uiBlocks = 0x3f; uiBlocks = 0x3f;
printf ("Guessing size: seems to be a %i-byte card\n", (uiBlocks + 1) * 16); printf("Guessing size: seems to be a %i-byte card\n", (uiBlocks + 1) * 16);
if (atAction == ACTION_READ) { if (atAction == ACTION_READ) {
if (read_card (unlock)) { if (read_card(unlock)) {
printf ("Writing data to file: %s ...", argv[3]); printf("Writing data to file: %s ...", argv[3]);
fflush (stdout); fflush(stdout);
pfDump = fopen (argv[3], "wb"); pfDump = fopen(argv[3], "wb");
if (pfDump == NULL) { if (pfDump == NULL) {
printf ("Could not open dump file: %s\n", argv[3]); printf("Could not open dump file: %s\n", argv[3]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (fwrite (&mtDump, 1, sizeof (mtDump), pfDump) != sizeof (mtDump)) { if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
printf ("\nCould not write to file: %s\n", argv[3]); printf("\nCould not write to file: %s\n", argv[3]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("Done.\n"); printf("Done.\n");
fclose (pfDump); fclose(pfDump);
} }
} else if (atAction == ACTION_WRITE) { } else if (atAction == ACTION_WRITE) {
write_card (unlock); write_card(unlock);
} }
nfc_close (pnd); nfc_close(pnd);
break; break;
}; };
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }

View file

@ -63,45 +63,45 @@ static const nfc_modulation nmMifare = {
}; };
static void static void
print_success_or_failure (bool bFailure, uint32_t * uiCounter) print_success_or_failure(bool bFailure, uint32_t * uiCounter)
{ {
printf ("%c", (bFailure) ? 'x' : '.'); printf("%c", (bFailure) ? 'x' : '.');
if (uiCounter) if (uiCounter)
*uiCounter += (bFailure) ? 0 : 1; *uiCounter += (bFailure) ? 0 : 1;
} }
static bool static bool
read_card (void) read_card(void)
{ {
uint32_t page; uint32_t page;
bool bFailure = false; bool bFailure = false;
uint32_t uiReadedPages = 0; uint32_t uiReadedPages = 0;
printf ("Reading %d pages |", uiBlocks + 1); printf("Reading %d pages |", uiBlocks + 1);
for (page = 0; page <= uiBlocks; page += 4) { for (page = 0; page <= uiBlocks; page += 4) {
// Try to read out the data block // Try to read out the data block
if (nfc_initiator_mifare_cmd (pnd, MC_READ, page, &mp)) { if (nfc_initiator_mifare_cmd(pnd, MC_READ, page, &mp)) {
memcpy (mtDump.amb[page / 4].mbd.abtData, mp.mpd.abtData, 16); memcpy(mtDump.amb[page / 4].mbd.abtData, mp.mpd.abtData, 16);
} else { } else {
bFailure = true; bFailure = true;
break; break;
} }
print_success_or_failure (bFailure, &uiReadedPages); print_success_or_failure(bFailure, &uiReadedPages);
print_success_or_failure (bFailure, &uiReadedPages); print_success_or_failure(bFailure, &uiReadedPages);
print_success_or_failure (bFailure, &uiReadedPages); print_success_or_failure(bFailure, &uiReadedPages);
print_success_or_failure (bFailure, &uiReadedPages); print_success_or_failure(bFailure, &uiReadedPages);
} }
printf ("|\n"); printf("|\n");
printf ("Done, %d of %d pages readed.\n", uiReadedPages, uiBlocks + 1); printf("Done, %d of %d pages readed.\n", uiReadedPages, uiBlocks + 1);
fflush (stdout); fflush(stdout);
return (!bFailure); return (!bFailure);
} }
static bool static bool
write_card (void) write_card(void)
{ {
uint32_t uiBlock = 0; uint32_t uiBlock = 0;
bool bFailure = false; bool bFailure = false;
@ -112,38 +112,38 @@ write_card (void)
bool write_otp; bool write_otp;
bool write_lock; bool write_lock;
printf ("Write OTP bytes ? [yN] "); printf("Write OTP bytes ? [yN] ");
if (!fgets (buffer, BUFSIZ, stdin)) { if (!fgets(buffer, BUFSIZ, stdin)) {
ERR ("Unable to read standard input."); ERR("Unable to read standard input.");
} }
write_otp = ((buffer[0] == 'y') || (buffer[0] == 'Y')); write_otp = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
printf ("Write Lock bytes ? [yN] "); printf("Write Lock bytes ? [yN] ");
if (!fgets (buffer, BUFSIZ, stdin)) { if (!fgets(buffer, BUFSIZ, stdin)) {
ERR ("Unable to read standard input."); ERR("Unable to read standard input.");
} }
write_lock = ((buffer[0] == 'y') || (buffer[0] == 'Y')); write_lock = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
printf ("Writing %d pages |", uiBlocks + 1); printf("Writing %d pages |", uiBlocks + 1);
/* We need to skip 2 first pages. */ /* We need to skip 2 first pages. */
printf ("ss"); printf("ss");
uiSkippedPages = 2; uiSkippedPages = 2;
for (int page = 0x2; page <= 0xF; page++) { for (int page = 0x2; page <= 0xF; page++) {
if ((page == 0x2) && (!write_lock)) { if ((page == 0x2) && (!write_lock)) {
printf ("s"); printf("s");
uiSkippedPages++; uiSkippedPages++;
continue; continue;
} }
if ((page == 0x3) && (!write_otp)) { if ((page == 0x3) && (!write_otp)) {
printf ("s"); printf("s");
uiSkippedPages++; uiSkippedPages++;
continue; continue;
} }
// Show if the readout went well // Show if the readout went well
if (bFailure) { if (bFailure) {
// When a failure occured we need to redo the anti-collision // When a failure occured we need to redo the anti-collision
if (nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt) < 0) { if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) < 0) {
ERR ("tag was removed"); ERR("tag was removed");
return false; return false;
} }
bFailure = false; bFailure = false;
@ -153,123 +153,123 @@ write_card (void)
// page (4 bytes). The Ultralight-specific Write command only // page (4 bytes). The Ultralight-specific Write command only
// writes one page at a time. // writes one page at a time.
uiBlock = page / 4; uiBlock = page / 4;
memcpy (mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData + ((page % 4) * 4), 16); memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData + ((page % 4) * 4), 16);
if (!nfc_initiator_mifare_cmd (pnd, MC_WRITE, page, &mp)) if (!nfc_initiator_mifare_cmd(pnd, MC_WRITE, page, &mp))
bFailure = true; bFailure = true;
print_success_or_failure (bFailure, &uiWritenPages); print_success_or_failure(bFailure, &uiWritenPages);
} }
printf ("|\n"); printf("|\n");
printf ("Done, %d of %d pages written (%d pages skipped).\n", uiWritenPages, uiBlocks + 1, uiSkippedPages); printf("Done, %d of %d pages written (%d pages skipped).\n", uiWritenPages, uiBlocks + 1, uiSkippedPages);
return true; return true;
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
bool bReadAction; bool bReadAction;
FILE *pfDump; FILE *pfDump;
if (argc < 3) { if (argc < 3) {
printf ("\n"); printf("\n");
printf ("%s r|w <dump.mfd>\n", argv[0]); printf("%s r|w <dump.mfd>\n", argv[0]);
printf ("\n"); printf("\n");
printf ("r|w - Perform read from or write to card\n"); printf("r|w - Perform read from or write to card\n");
printf ("<dump.mfd> - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n"); printf("<dump.mfd> - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
printf ("\n"); printf("\n");
return 1; return 1;
} }
DBG ("\nChecking arguments and settings\n"); DBG("\nChecking arguments and settings\n");
bReadAction = tolower ((int) ((unsigned char) * (argv[1])) == 'r'); bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r');
if (bReadAction) { if (bReadAction) {
memset (&mtDump, 0x00, sizeof (mtDump)); memset(&mtDump, 0x00, sizeof(mtDump));
} else { } else {
pfDump = fopen (argv[2], "rb"); pfDump = fopen(argv[2], "rb");
if (pfDump == NULL) { if (pfDump == NULL) {
ERR ("Could not open dump file: %s\n", argv[2]); ERR("Could not open dump file: %s\n", argv[2]);
return 1; return 1;
} }
if (fread (&mtDump, 1, sizeof (mtDump), pfDump) != sizeof (mtDump)) { if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
ERR ("Could not read from dump file: %s\n", argv[2]); ERR("Could not read from dump file: %s\n", argv[2]);
fclose (pfDump); fclose(pfDump);
return 1; return 1;
} }
fclose (pfDump); fclose(pfDump);
} }
DBG ("Successfully opened the dump file\n"); DBG("Successfully opened the dump file\n");
nfc_init (NULL); nfc_init(NULL);
// Try to open the NFC device // Try to open the NFC device
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR ("Error opening NFC device\n"); ERR("Error opening NFC device\n");
return 1; return 1;
} }
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Let the device only try once to find a tag // Let the device only try once to find a tag
if (nfc_device_set_property_bool (pnd, NP_INFINITE_SELECT, false) < 0) { if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC device: %s opened\n", nfc_device_get_name (pnd)); printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
// Try to find a MIFARE Ultralight tag // Try to find a MIFARE Ultralight tag
if (nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt) < 0) { if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) < 0) {
ERR ("no tag was found\n"); ERR("no tag was found\n");
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return 1; return 1;
} }
// Test if we are dealing with a MIFARE compatible tag // Test if we are dealing with a MIFARE compatible tag
if (nt.nti.nai.abtAtqa[1] != 0x44) { if (nt.nti.nai.abtAtqa[1] != 0x44) {
ERR ("tag is not a MIFARE Ultralight card\n"); ERR("tag is not a MIFARE Ultralight card\n");
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
// Get the info from the current tag // Get the info from the current tag
printf ("Found MIFARE Ultralight card with UID: "); printf("Found MIFARE Ultralight card with UID: ");
size_t szPos; size_t szPos;
for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) { for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
printf ("%02x", nt.nti.nai.abtUid[szPos]); printf("%02x", nt.nti.nai.abtUid[szPos]);
} }
printf("\n"); printf("\n");
if (bReadAction) { if (bReadAction) {
if (read_card ()) { if (read_card()) {
printf ("Writing data to file: %s ... ", argv[2]); printf("Writing data to file: %s ... ", argv[2]);
fflush (stdout); fflush(stdout);
pfDump = fopen (argv[2], "wb"); pfDump = fopen(argv[2], "wb");
if (pfDump == NULL) { if (pfDump == NULL) {
printf ("Could not open file: %s\n", argv[2]); printf("Could not open file: %s\n", argv[2]);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (fwrite (&mtDump, 1, sizeof (mtDump), pfDump) != sizeof (mtDump)) { if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
printf ("Could not write to file: %s\n", argv[2]); printf("Could not write to file: %s\n", argv[2]);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
fclose (pfDump); fclose(pfDump);
printf ("Done.\n"); printf("Done.\n");
} }
} else { } else {
write_card (); write_card();
} }
nfc_close (pnd); nfc_close(pnd);
nfc_exit (NULL); nfc_exit(NULL);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View file

@ -60,61 +60,61 @@
static nfc_device *pnd; static nfc_device *pnd;
static void static void
print_usage (const char* progname) print_usage(const char* progname)
{ {
printf ("usage: %s [-v]\n", progname); printf("usage: %s [-v]\n", progname);
printf (" -v\t verbose display\n"); printf(" -v\t verbose display\n");
} }
int int
main (int argc, const char *argv[]) main(int argc, const char *argv[])
{ {
(void) argc; (void) argc;
const char *acLibnfcVersion; const char *acLibnfcVersion;
size_t i; size_t i;
bool verbose = false; bool verbose = false;
nfc_init (NULL); nfc_init(NULL);
// Display libnfc version // Display libnfc version
acLibnfcVersion = nfc_version (); acLibnfcVersion = nfc_version();
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
if (argc != 1) { if (argc != 1) {
if ((argc == 2) && (0 == strcmp ("-v", argv[1]))) { if ((argc == 2) && (0 == strcmp("-v", argv[1]))) {
verbose = true; verbose = true;
} else { } else {
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
#ifdef HAVE_LIBUSB #ifdef HAVE_LIBUSB
# ifdef DEBUG # ifdef DEBUG
usb_set_debug (4); usb_set_debug(4);
# endif # endif
#endif #endif
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
size_t szDeviceFound = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t szDeviceFound = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
int res = EXIT_FAILURE; int res = EXIT_FAILURE;
if (szDeviceFound == 0) { if (szDeviceFound == 0) {
printf ("No NFC device found.\n"); printf("No NFC device found.\n");
goto bye; goto bye;
} }
printf ("%d NFC device(s) found:\n", (int)szDeviceFound); printf("%d NFC device(s) found:\n", (int)szDeviceFound);
char strinfo[1024]; char strinfo[1024];
for (i = 0; i < szDeviceFound; i++) { for (i = 0; i < szDeviceFound; i++) {
pnd = nfc_open (NULL, connstrings[i]); pnd = nfc_open(NULL, connstrings[i]);
if (pnd != NULL) { if (pnd != NULL) {
printf ("- %s:\n %s\n", nfc_device_get_name (pnd), nfc_device_get_connstring (pnd)); printf("- %s:\n %s\n", nfc_device_get_name(pnd), nfc_device_get_connstring(pnd));
if (verbose) { if (verbose) {
if (nfc_device_get_information_about (pnd, strinfo, sizeof(strinfo)) >= 0) { if (nfc_device_get_information_about(pnd, strinfo, sizeof(strinfo)) >= 0) {
printf ("%s", strinfo); printf("%s", strinfo);
} }
} }
nfc_close (pnd); nfc_close(pnd);
} else { } else {
printf("nfc_open failed for %s\n", connstrings[i]); printf("nfc_open failed for %s\n", connstrings[i]);
} }
@ -122,6 +122,6 @@ main (int argc, const char *argv[])
res = EXIT_SUCCESS; res = EXIT_SUCCESS;
bye: bye:
nfc_exit (NULL); nfc_exit(NULL);
return res; return res;
} }

View file

@ -60,18 +60,18 @@ static nfc_device *pnd;
static void static void
print_usage(char *progname) print_usage(char *progname)
{ {
fprintf (stderr, "usage: %s -o FILE\n", progname); fprintf(stderr, "usage: %s -o FILE\n", progname);
fprintf (stderr, "\nOptions:\n"); fprintf(stderr, "\nOptions:\n");
fprintf (stderr, " -o Extract NDEF message if available in FILE\n"); fprintf(stderr, " -o Extract NDEF message if available in FILE\n");
} }
static void stop_select (int sig) static void stop_select(int sig)
{ {
(void) sig; (void) sig;
if (pnd) if (pnd)
nfc_abort_command (pnd); nfc_abort_command(pnd);
else else
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
static void static void
@ -80,13 +80,13 @@ build_felica_frame(const nfc_felica_info nfi, const uint8_t command, const uint8
frame[0] = 1 + 1 + 8 + payload_len; frame[0] = 1 + 1 + 8 + payload_len;
*frame_len = frame[0]; *frame_len = frame[0];
frame[1] = command; frame[1] = command;
memcpy (frame + 2, nfi.abtId, 8); memcpy(frame + 2, nfi.abtId, 8);
memcpy (frame + 10, payload, payload_len); memcpy(frame + 10, payload, payload_len);
} }
#define CHECK 0x06 #define CHECK 0x06
static int static int
nfc_forum_tag_type3_check (nfc_device *dev, const nfc_target nt, const uint16_t block, const uint8_t block_count, uint8_t *data, size_t *data_len) nfc_forum_tag_type3_check(nfc_device *dev, const nfc_target nt, const uint16_t block, const uint8_t block_count, uint8_t *data, size_t *data_len)
{ {
uint8_t payload[1024] = { uint8_t payload[1024] = {
1, // Services 1, // Services
@ -109,11 +109,11 @@ nfc_forum_tag_type3_check (nfc_device *dev, const nfc_target nt, const uint16_t
uint8_t frame[1024]; uint8_t frame[1024];
size_t frame_len = sizeof(frame); size_t frame_len = sizeof(frame);
build_felica_frame (nt.nti.nfi, CHECK, payload, payload_len, frame, &frame_len); build_felica_frame(nt.nti.nfi, CHECK, payload, payload_len, frame, &frame_len);
uint8_t rx[1024]; uint8_t rx[1024];
int res; int res;
if ((res = nfc_initiator_transceive_bytes (dev, frame, frame_len, rx, sizeof(rx), 0)) < 0) { if ((res = nfc_initiator_transceive_bytes(dev, frame, frame_len, rx, sizeof(rx), 0)) < 0) {
return res; return res;
} }
const int res_overhead = 1 + 1 + 8 + 2; // 1+1+8+2: LEN + CMD + NFCID2 + STATUS const int res_overhead = 1 + 1 + 8 + 2; // 1+1+8+2: LEN + CMD + NFCID2 + STATUS
@ -130,7 +130,7 @@ nfc_forum_tag_type3_check (nfc_device *dev, const nfc_target nt, const uint16_t
// Command return does not match // Command return does not match
return -1; return -1;
} }
if (0 != memcmp (&rx[2], nt.nti.nfi.abtId, 8)) { if (0 != memcmp(&rx[2], nt.nti.nfi.abtId, 8)) {
// NFCID2 does not match // NFCID2 does not match
return -1; return -1;
} }
@ -138,12 +138,12 @@ nfc_forum_tag_type3_check (nfc_device *dev, const nfc_target nt, const uint16_t
const uint8_t status_flag2 = rx[11]; const uint8_t status_flag2 = rx[11];
if ((status_flag1) || (status_flag2)) { if ((status_flag1) || (status_flag2)) {
// Felica card's error // Felica card's error
fprintf (stderr, "Status bytes: %02x, %02x\n", status_flag1, status_flag2); fprintf(stderr, "Status bytes: %02x, %02x\n", status_flag1, status_flag2);
return -1; return -1;
} }
// const uint8_t res_block_count = res[12]; // const uint8_t res_block_count = res[12];
*data_len = res - res_overhead + 1; // +1 => block count is stored on 1 byte *data_len = res - res_overhead + 1; // +1 => block count is stored on 1 byte
memcpy (data, &rx[res_overhead + 1], *data_len); memcpy(data, &rx[res_overhead + 1], *data_len);
return *data_len; return *data_len;
} }
@ -155,91 +155,91 @@ main(int argc, char *argv[])
int ch; int ch;
char *ndef_output = NULL; char *ndef_output = NULL;
while ((ch = getopt (argc, argv, "ho:")) != -1) { while ((ch = getopt(argc, argv, "ho:")) != -1) {
switch (ch) { switch (ch) {
case 'h': case 'h':
print_usage(argv[0]); print_usage(argv[0]);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
break; break;
case 'o': case 'o':
ndef_output = optarg; ndef_output = optarg;
break; break;
case '?': case '?':
if (optopt == 'o') if (optopt == 'o')
fprintf (stderr, "Option -%c requires an argument.\n", optopt); fprintf(stderr, "Option -%c requires an argument.\n", optopt);
default: default:
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
if (ndef_output == NULL) { if (ndef_output == NULL) {
print_usage (argv[0]); print_usage(argv[0]);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
FILE* message_stream = NULL; FILE* message_stream = NULL;
FILE* ndef_stream = NULL; FILE* ndef_stream = NULL;
if ((strlen (ndef_output) == 1) && (ndef_output[0] == '-')) { if ((strlen(ndef_output) == 1) && (ndef_output[0] == '-')) {
message_stream = stderr; message_stream = stderr;
ndef_stream = stdout; ndef_stream = stdout;
} else { } else {
message_stream = stdout; message_stream = stdout;
ndef_stream = fopen(ndef_output, "wb"); ndef_stream = fopen(ndef_output, "wb");
if (!ndef_stream) { if (!ndef_stream) {
fprintf (stderr, "Could not open file %s.\n", ndef_output); fprintf(stderr, "Could not open file %s.\n", ndef_output);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
nfc_init (NULL); nfc_init(NULL);
pnd = nfc_open (NULL, NULL); pnd = nfc_open(NULL, NULL);
if (pnd == NULL) { if (pnd == NULL) {
ERR("Unable to open NFC device"); ERR("Unable to open NFC device");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
fprintf (message_stream, "NFC device: %s opened\n", nfc_device_get_name (pnd)); fprintf(message_stream, "NFC device: %s opened\n", nfc_device_get_name(pnd));
nfc_modulation nm = { nfc_modulation nm = {
.nmt = NMT_FELICA, .nmt = NMT_FELICA,
.nbr = NBR_212, .nbr = NBR_212,
}; };
signal (SIGINT, stop_select); signal(SIGINT, stop_select);
nfc_target nt; nfc_target nt;
if (nfc_initiator_init (pnd) < 0) { if (nfc_initiator_init(pnd) < 0) {
nfc_perror (pnd, "nfc_initiator_init"); nfc_perror(pnd, "nfc_initiator_init");
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
fprintf (message_stream, "Place your NFC Forum Tag Type 3 in the field...\n"); fprintf(message_stream, "Place your NFC Forum Tag Type 3 in the field...\n");
int error = EXIT_SUCCESS; int error = EXIT_SUCCESS;
// Polling payload (SENSF_REQ) must be present (see NFC Digital Protol) // Polling payload (SENSF_REQ) must be present (see NFC Digital Protol)
const uint8_t *pbtSensfReq = (uint8_t*)"\x00\xff\xff\x01\x00"; const uint8_t *pbtSensfReq = (uint8_t*)"\x00\xff\xff\x01\x00";
if (nfc_initiator_select_passive_target(pnd, nm, pbtSensfReq, 5, &nt) < 0) { if (nfc_initiator_select_passive_target(pnd, nm, pbtSensfReq, 5, &nt) < 0) {
nfc_perror (pnd, "nfc_initiator_select_passive_target"); nfc_perror(pnd, "nfc_initiator_select_passive_target");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
// Check if System Code equals 0x12fc // Check if System Code equals 0x12fc
const uint8_t abtNfcForumSysCode[] = { 0x12, 0xfc }; const uint8_t abtNfcForumSysCode[] = { 0x12, 0xfc };
if (0 != memcmp (nt.nti.nfi.abtSysCode, abtNfcForumSysCode, 2)) { if (0 != memcmp(nt.nti.nfi.abtSysCode, abtNfcForumSysCode, 2)) {
// Retry with special polling // Retry with special polling
const uint8_t *pbtSensfReqNfcForum = (uint8_t*)"\x00\x12\xfc\x01\x00"; const uint8_t *pbtSensfReqNfcForum = (uint8_t*)"\x00\x12\xfc\x01\x00";
if (nfc_initiator_select_passive_target(pnd, nm, pbtSensfReqNfcForum, 5, &nt) < 0) { if (nfc_initiator_select_passive_target(pnd, nm, pbtSensfReqNfcForum, 5, &nt) < 0) {
nfc_perror (pnd, "nfc_initiator_select_passive_target"); nfc_perror(pnd, "nfc_initiator_select_passive_target");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
// Check again if System Code equals 0x12fc // Check again if System Code equals 0x12fc
if (0 != memcmp (nt.nti.nfi.abtSysCode, abtNfcForumSysCode, 2)) { if (0 != memcmp(nt.nti.nfi.abtSysCode, abtNfcForumSysCode, 2)) {
fprintf (stderr, "Tag is not NFC Forum Tag Type 3 compliant.\n"); fprintf(stderr, "Tag is not NFC Forum Tag Type 3 compliant.\n");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
@ -247,8 +247,8 @@ main(int argc, char *argv[])
//print_nfc_felica_info(nt.nti.nfi, true); //print_nfc_felica_info(nt.nti.nfi, true);
if ((nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, false) < 0) || (nfc_device_set_property_bool (pnd, NP_INFINITE_SELECT, false) < 0)) { if ((nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) || (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0)) {
nfc_perror (pnd, "nfc_device_set_property_bool"); nfc_perror(pnd, "nfc_device_set_property_bool");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
@ -257,21 +257,21 @@ main(int argc, char *argv[])
size_t data_len = sizeof(data); size_t data_len = sizeof(data);
int len; int len;
if (0 >= (len = nfc_forum_tag_type3_check (pnd, nt, 0, 1, data, &data_len))) { if (0 >= (len = nfc_forum_tag_type3_check(pnd, nt, 0, 1, data, &data_len))) {
nfc_perror (pnd, "nfc_forum_tag_type3_check"); nfc_perror(pnd, "nfc_forum_tag_type3_check");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
const int ndef_major_version = (data[0] & 0xf0) >> 4; const int ndef_major_version = (data[0] & 0xf0) >> 4;
const int ndef_minor_version = (data[0] & 0x0f); const int ndef_minor_version = (data[0] & 0x0f);
fprintf (message_stream, "NDEF Mapping version: %d.%d\n", ndef_major_version, ndef_minor_version); fprintf(message_stream, "NDEF Mapping version: %d.%d\n", ndef_major_version, ndef_minor_version);
const int available_block_count = (data[3] << 8) + data[4]; const int available_block_count = (data[3] << 8) + data[4];
fprintf (message_stream, "NFC Forum Tag Type 3 capacity: %d bytes\n", available_block_count * 16); fprintf(message_stream, "NFC Forum Tag Type 3 capacity: %d bytes\n", available_block_count * 16);
uint32_t ndef_data_len = (data[11] << 16) + (data[12] << 8) + data[13]; uint32_t ndef_data_len = (data[11] << 16) + (data[12] << 8) + data[13];
fprintf (message_stream, "NDEF data length: %d bytes\n", ndef_data_len); fprintf(message_stream, "NDEF data length: %d bytes\n", ndef_data_len);
uint16_t ndef_calculated_checksum = 0; uint16_t ndef_calculated_checksum = 0;
for (size_t n = 0; n < 14; n++) for (size_t n = 0; n < 14; n++)
@ -279,13 +279,13 @@ main(int argc, char *argv[])
const uint16_t ndef_checksum = (data[14] << 8) + data[15]; const uint16_t ndef_checksum = (data[14] << 8) + data[15];
if (ndef_calculated_checksum != ndef_checksum) { if (ndef_calculated_checksum != ndef_checksum) {
fprintf (stderr, "NDEF CRC does not match with calculated one\n"); fprintf(stderr, "NDEF CRC does not match with calculated one\n");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
if (!ndef_data_len) { if (!ndef_data_len) {
fprintf (stderr, "Empty NFC Forum Tag Type 3\n"); fprintf(stderr, "Empty NFC Forum Tag Type 3\n");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
@ -296,24 +296,24 @@ main(int argc, char *argv[])
data_len = 0; data_len = 0;
for (uint16_t b = 0; b < (block_count_to_check / block_max_per_check); b += block_max_per_check) { for (uint16_t b = 0; b < (block_count_to_check / block_max_per_check); b += block_max_per_check) {
size_t size = sizeof(data) - data_len; size_t size = sizeof(data) - data_len;
if(!nfc_forum_tag_type3_check (pnd, nt, 1 + b, MIN(block_max_per_check, (block_count_to_check - (b * block_max_per_check))), data + data_len, &size)) { if (!nfc_forum_tag_type3_check(pnd, nt, 1 + b, MIN(block_max_per_check, (block_count_to_check - (b * block_max_per_check))), data + data_len, &size)) {
nfc_perror (pnd, "nfc_forum_tag_type3_check"); nfc_perror(pnd, "nfc_forum_tag_type3_check");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
data_len += size; data_len += size;
} }
if (fwrite (data, 1, data_len, ndef_stream) != data_len) { if (fwrite(data, 1, data_len, ndef_stream) != data_len) {
fprintf (stderr, "Could not write to file.\n"); fprintf(stderr, "Could not write to file.\n");
error = EXIT_FAILURE; error = EXIT_FAILURE;
goto error; goto error;
} }
error: error:
fclose (ndef_stream); fclose(ndef_stream);
if (pnd) { if (pnd) {
nfc_close (pnd); nfc_close(pnd);
} }
nfc_exit (NULL); nfc_exit(NULL);
exit (error); exit(error);
} }

View file

@ -72,50 +72,50 @@ FILE * fd3;
FILE * fd4; FILE * fd4;
static void static void
intr_hdlr (int sig) intr_hdlr(int sig)
{ {
(void) sig; (void) sig;
printf ("\nQuitting...\n"); printf("\nQuitting...\n");
printf ("Please send a last command to the emulator to quit properly.\n"); printf("Please send a last command to the emulator to quit properly.\n");
quitting = true; quitting = true;
return; return;
} }
static void static void
print_usage (char *argv[]) print_usage(char *argv[])
{ {
printf ("Usage: %s [OPTIONS]\n", argv[0]); printf("Usage: %s [OPTIONS]\n", argv[0]);
printf ("Options:\n"); printf("Options:\n");
printf ("\t-h\tHelp. Print this message.\n"); printf("\t-h\tHelp. Print this message.\n");
printf ("\t-q\tQuiet mode. Suppress printing of relayed data (improves timing).\n"); printf("\t-q\tQuiet mode. Suppress printing of relayed data (improves timing).\n");
printf ("\t-t\tTarget mode only (the one on reader side). Data expected from FD3 to FD4.\n"); printf("\t-t\tTarget mode only (the one on reader side). Data expected from FD3 to FD4.\n");
printf ("\t-i\tInitiator mode only (the one on tag side). Data expected from FD3 to FD4.\n"); printf("\t-i\tInitiator mode only (the one on tag side). Data expected from FD3 to FD4.\n");
printf ("\t-n N\tAdds a waiting time of N seconds (integer) in the relay to mimic long distance.\n"); printf("\t-n N\tAdds a waiting time of N seconds (integer) in the relay to mimic long distance.\n");
} }
static bool print_hex_fd4 (const uint8_t *pbtData, const size_t szBytes, const char *pchPrefix) static bool print_hex_fd4(const uint8_t *pbtData, const size_t szBytes, const char *pchPrefix)
{ {
size_t szPos; size_t szPos;
if (szBytes > MAX_FRAME_LEN) { if (szBytes > MAX_FRAME_LEN) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (fprintf (fd4, "#%s %04zx: ", pchPrefix, szBytes) < 0) { if (fprintf(fd4, "#%s %04zx: ", pchPrefix, szBytes) < 0) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
for (szPos = 0; szPos < szBytes; szPos++) { for (szPos = 0; szPos < szBytes; szPos++) {
if (fprintf (fd4, "%02x ", pbtData[szPos]) < 0) { if (fprintf(fd4, "%02x ", pbtData[szPos]) < 0) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
if (fprintf (fd4, "\n") < 0) { if (fprintf(fd4, "\n") < 0) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
fflush(fd4); fflush(fd4);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
static bool scan_hex_fd3 (uint8_t *pbtData, size_t *pszBytes, const char *pchPrefix) static bool scan_hex_fd3(uint8_t *pbtData, size_t *pszBytes, const char *pchPrefix)
{ {
size_t szPos; size_t szPos;
unsigned int uiBytes; unsigned int uiBytes;
@ -123,14 +123,14 @@ static bool scan_hex_fd3 (uint8_t *pbtData, size_t *pszBytes, const char *pchPre
char pchScan[256]; char pchScan[256];
int c; int c;
// Look for our next sync marker // Look for our next sync marker
while ( (c = fgetc(fd3)) != '#') { while ((c = fgetc(fd3)) != '#') {
if (c == EOF) { if (c == EOF) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
strncpy(pchScan, pchPrefix, 250); strncpy(pchScan, pchPrefix, 250);
strcat(pchScan, " %04x:"); strcat(pchScan, " %04x:");
if (fscanf (fd3, pchScan, &uiBytes) < 1) { if (fscanf(fd3, pchScan, &uiBytes) < 1) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
*pszBytes = uiBytes; *pszBytes = uiBytes;
@ -138,7 +138,7 @@ static bool scan_hex_fd3 (uint8_t *pbtData, size_t *pszBytes, const char *pchPre
return EXIT_FAILURE; return EXIT_FAILURE;
} }
for (szPos = 0; szPos < *pszBytes; szPos++) { for (szPos = 0; szPos < *pszBytes; szPos++) {
if (fscanf (fd3, "%02x", &uiData) < 1) { if (fscanf(fd3, "%02x", &uiData) < 1) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
pbtData[szPos] = uiData; pbtData[szPos] = uiData;
@ -147,66 +147,66 @@ static bool scan_hex_fd3 (uint8_t *pbtData, size_t *pszBytes, const char *pchPre
} }
int int
main (int argc, char *argv[]) main(int argc, char *argv[])
{ {
int arg; int arg;
const char *acLibnfcVersion = nfc_version (); const char *acLibnfcVersion = nfc_version();
nfc_target ntRealTarget; nfc_target ntRealTarget;
// Get commandline options // Get commandline options
for (arg = 1; arg < argc; arg++) { for (arg = 1; arg < argc; arg++) {
if (0 == strcmp (argv[arg], "-h")) { if (0 == strcmp(argv[arg], "-h")) {
print_usage (argv); print_usage(argv);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} else if (0 == strcmp (argv[arg], "-q")) { } else if (0 == strcmp(argv[arg], "-q")) {
quiet_output = true; quiet_output = true;
} else if (0 == strcmp (argv[arg], "-t")) { } else if (0 == strcmp(argv[arg], "-t")) {
printf ("INFO: %s\n", "Target mode only."); printf("INFO: %s\n", "Target mode only.");
initiator_only_mode = false; initiator_only_mode = false;
target_only_mode = true; target_only_mode = true;
} else if (0 == strcmp (argv[arg], "-i")) { } else if (0 == strcmp(argv[arg], "-i")) {
printf ("INFO: %s\n", "Initiator mode only."); printf("INFO: %s\n", "Initiator mode only.");
initiator_only_mode = true; initiator_only_mode = true;
target_only_mode = false; target_only_mode = false;
} else if (0 == strcmp (argv[arg], "-n")) { } else if (0 == strcmp(argv[arg], "-n")) {
if (++arg == argc || (sscanf(argv[arg], "%i", &waiting_time) < 1)) { if (++arg == argc || (sscanf(argv[arg], "%i", &waiting_time) < 1)) {
ERR ("Missing or wrong waiting time value: %s.", argv[arg]); ERR("Missing or wrong waiting time value: %s.", argv[arg]);
print_usage (argv); print_usage(argv);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("Waiting time: %i secs.\n", waiting_time); printf("Waiting time: %i secs.\n", waiting_time);
} else { } else {
ERR ("%s is not supported option.", argv[arg]); ERR("%s is not supported option.", argv[arg]);
print_usage (argv); print_usage(argv);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
// Display libnfc version // Display libnfc version
printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
#ifdef WIN32 #ifdef WIN32
signal (SIGINT, (void (__cdecl *) (int)) intr_hdlr); signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr);
#else #else
signal (SIGINT, intr_hdlr); signal(SIGINT, intr_hdlr);
#endif #endif
nfc_init (NULL); nfc_init(NULL);
nfc_connstring connstrings[MAX_DEVICE_COUNT]; nfc_connstring connstrings[MAX_DEVICE_COUNT];
// List available devices // List available devices
size_t szFound = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); size_t szFound = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);
if (initiator_only_mode || target_only_mode) { if (initiator_only_mode || target_only_mode) {
if (szFound < 1) { if (szFound < 1) {
ERR ("No device found"); ERR("No device found");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
fd3 = fdopen(3, "r"); fd3 = fdopen(3, "r");
fd4 = fdopen(4, "w"); fd4 = fdopen(4, "w");
} else { } else {
if (szFound < 2) { if (szFound < 2) {
ERR ("%zd device found but two opened devices are needed to relay NFC.", szFound); ERR("%zd device found but two opened devices are needed to relay NFC.", szFound);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
@ -218,23 +218,23 @@ main (int argc, char *argv[])
// if there is more than one readers opened we open the second reader // if there is more than one readers opened we open the second reader
// (we hope they're always detected in the same order) // (we hope they're always detected in the same order)
if (szFound == 1) { if (szFound == 1) {
pndInitiator = nfc_open (NULL, connstrings[0]); pndInitiator = nfc_open(NULL, connstrings[0]);
} else { } else {
pndInitiator = nfc_open (NULL, connstrings[1]); pndInitiator = nfc_open(NULL, connstrings[1]);
} }
if (!pndInitiator) { if (!pndInitiator) {
printf ("Error opening NFC reader\n"); printf("Error opening NFC reader\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("NFC reader device: %s opened\n", nfc_device_get_name (pndInitiator)); printf("NFC reader device: %s opened\n", nfc_device_get_name(pndInitiator));
if (nfc_initiator_init (pndInitiator) < 0) { if (nfc_initiator_init(pndInitiator) < 0) {
printf ("Error: fail initializing initiator\n"); printf("Error: fail initializing initiator\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Try to find a ISO 14443-4A tag // Try to find a ISO 14443-4A tag
@ -242,48 +242,48 @@ main (int argc, char *argv[])
.nmt = NMT_ISO14443A, .nmt = NMT_ISO14443A,
.nbr = NBR_106, .nbr = NBR_106,
}; };
if (nfc_initiator_select_passive_target (pndInitiator, nm, NULL, 0, &ntRealTarget) < 0) { if (nfc_initiator_select_passive_target(pndInitiator, nm, NULL, 0, &ntRealTarget) < 0) {
printf ("Error: no tag was found\n"); printf("Error: no tag was found\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf("Found tag:\n"); printf("Found tag:\n");
print_nfc_iso14443a_info (ntRealTarget.nti.nai, false); print_nfc_iso14443a_info(ntRealTarget.nti.nai, false);
if (initiator_only_mode) { if (initiator_only_mode) {
if (print_hex_fd4(ntRealTarget.nti.nai.abtUid, ntRealTarget.nti.nai.szUidLen, "UID") != EXIT_SUCCESS) { if (print_hex_fd4(ntRealTarget.nti.nai.abtUid, ntRealTarget.nti.nai.szUidLen, "UID") != EXIT_SUCCESS) {
fprintf (stderr, "Error while printing UID to FD4\n"); fprintf(stderr, "Error while printing UID to FD4\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (print_hex_fd4(ntRealTarget.nti.nai.abtAtqa, 2, "ATQA") != EXIT_SUCCESS) { if (print_hex_fd4(ntRealTarget.nti.nai.abtAtqa, 2, "ATQA") != EXIT_SUCCESS) {
fprintf (stderr, "Error while printing ATQA to FD4\n"); fprintf(stderr, "Error while printing ATQA to FD4\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (print_hex_fd4(&(ntRealTarget.nti.nai.btSak), 1, "SAK") != EXIT_SUCCESS) { if (print_hex_fd4(&(ntRealTarget.nti.nai.btSak), 1, "SAK") != EXIT_SUCCESS) {
fprintf (stderr, "Error while printing SAK to FD4\n"); fprintf(stderr, "Error while printing SAK to FD4\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (print_hex_fd4(ntRealTarget.nti.nai.abtAts, ntRealTarget.nti.nai.szAtsLen, "ATS") != EXIT_SUCCESS) { if (print_hex_fd4(ntRealTarget.nti.nai.abtAts, ntRealTarget.nti.nai.szAtsLen, "ATS") != EXIT_SUCCESS) {
fprintf (stderr, "Error while printing ATS to FD4\n"); fprintf(stderr, "Error while printing ATS to FD4\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
} }
if (initiator_only_mode) { if (initiator_only_mode) {
printf ("Hint: tag <---> *INITIATOR* (relay) <-FD3/FD4-> target (relay) <---> original reader\n\n"); printf("Hint: tag <---> *INITIATOR* (relay) <-FD3/FD4-> target (relay) <---> original reader\n\n");
} else if (target_only_mode) { } else if (target_only_mode) {
printf ("Hint: tag <---> initiator (relay) <-FD3/FD4-> *TARGET* (relay) <---> original reader\n\n"); printf("Hint: tag <---> initiator (relay) <-FD3/FD4-> *TARGET* (relay) <---> original reader\n\n");
} else { } else {
printf ("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n"); printf("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n");
} }
if (!initiator_only_mode) { if (!initiator_only_mode) {
nfc_target ntEmulatedTarget = { nfc_target ntEmulatedTarget = {
@ -295,26 +295,26 @@ main (int argc, char *argv[])
if (target_only_mode) { if (target_only_mode) {
size_t foo; size_t foo;
if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtUid, &(ntEmulatedTarget.nti.nai.szUidLen), "UID") != EXIT_SUCCESS) { if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtUid, &(ntEmulatedTarget.nti.nai.szUidLen), "UID") != EXIT_SUCCESS) {
fprintf (stderr, "Error while scanning UID from FD3\n"); fprintf(stderr, "Error while scanning UID from FD3\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAtqa, &foo, "ATQA") != EXIT_SUCCESS) { if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAtqa, &foo, "ATQA") != EXIT_SUCCESS) {
fprintf (stderr, "Error while scanning ATQA from FD3\n"); fprintf(stderr, "Error while scanning ATQA from FD3\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (scan_hex_fd3(&(ntEmulatedTarget.nti.nai.btSak), &foo, "SAK") != EXIT_SUCCESS) { if (scan_hex_fd3(&(ntEmulatedTarget.nti.nai.btSak), &foo, "SAK") != EXIT_SUCCESS) {
fprintf (stderr, "Error while scanning SAK from FD3\n"); fprintf(stderr, "Error while scanning SAK from FD3\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAts, &(ntEmulatedTarget.nti.nai.szAtsLen), "ATS") != EXIT_SUCCESS) { if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAts, &(ntEmulatedTarget.nti.nai.szAtsLen), "ATS") != EXIT_SUCCESS) {
fprintf (stderr, "Error while scanning ATS from FD3\n"); fprintf(stderr, "Error while scanning ATS from FD3\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} else { } else {
@ -338,7 +338,7 @@ main (int argc, char *argv[])
// Creates ATS and copy max 48 bytes of Tk: // Creates ATS and copy max 48 bytes of Tk:
uint8_t * pbtTk; uint8_t * pbtTk;
size_t szTk; size_t szTk;
pbtTk = iso14443a_locate_historical_bytes (ntEmulatedTarget.nti.nai.abtAts, ntEmulatedTarget.nti.nai.szAtsLen, &szTk); pbtTk = iso14443a_locate_historical_bytes(ntEmulatedTarget.nti.nai.abtAts, ntEmulatedTarget.nti.nai.szAtsLen, &szTk);
szTk = (szTk > 48) ? 48 : szTk; szTk = (szTk > 48) ? 48 : szTk;
uint8_t pbtTkt[48]; uint8_t pbtTkt[48];
memcpy(pbtTkt, pbtTk, szTk); memcpy(pbtTkt, pbtTk, szTk);
@ -350,31 +350,31 @@ main (int argc, char *argv[])
memcpy(&(ntEmulatedTarget.nti.nai.abtAts[4]), pbtTkt, szTk); memcpy(&(ntEmulatedTarget.nti.nai.abtAts[4]), pbtTkt, szTk);
printf("We will emulate:\n"); printf("We will emulate:\n");
print_nfc_iso14443a_info (ntEmulatedTarget.nti.nai, false); print_nfc_iso14443a_info(ntEmulatedTarget.nti.nai, false);
// Try to open the NFC emulator device // Try to open the NFC emulator device
pndTarget = nfc_open (NULL, connstrings[0]); pndTarget = nfc_open(NULL, connstrings[0]);
if (pndTarget == NULL) { if (pndTarget == NULL) {
printf ("Error opening NFC emulator device\n"); printf("Error opening NFC emulator device\n");
if (!target_only_mode) { if (!target_only_mode) {
nfc_close (pndInitiator); nfc_close(pndInitiator);
} }
nfc_exit (NULL); nfc_exit(NULL);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf ("NFC emulator device: %s opened\n", nfc_device_get_name (pndTarget)); printf("NFC emulator device: %s opened\n", nfc_device_get_name(pndTarget));
int res; int res;
if ((res = nfc_target_init (pndTarget, &ntEmulatedTarget, abtCapdu, sizeof(abtCapdu), 0)) < 0) { if ((res = nfc_target_init(pndTarget, &ntEmulatedTarget, abtCapdu, sizeof(abtCapdu), 0)) < 0) {
ERR ("%s", "Initialization of NFC emulator failed"); ERR("%s", "Initialization of NFC emulator failed");
if (!target_only_mode) { if (!target_only_mode) {
nfc_close (pndInitiator); nfc_close(pndInitiator);
} }
nfc_close (pndTarget); nfc_close(pndTarget);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
printf ("%s\n", "Done, relaying frames now!"); printf("%s\n", "Done, relaying frames now!");
} }
while (!quitting) { while (!quitting) {
@ -382,41 +382,41 @@ main (int argc, char *argv[])
int res = 0; int res = 0;
if (!initiator_only_mode) { if (!initiator_only_mode) {
// Receive external reader command through target // Receive external reader command through target
if ((res = nfc_target_receive_bytes(pndTarget, abtCapdu, sizeof (abtCapdu), 0)) < 0) { if ((res = nfc_target_receive_bytes(pndTarget, abtCapdu, sizeof(abtCapdu), 0)) < 0) {
nfc_perror (pndTarget, "nfc_target_receive_bytes"); nfc_perror(pndTarget, "nfc_target_receive_bytes");
if (!target_only_mode) { if (!target_only_mode) {
nfc_close (pndInitiator); nfc_close(pndInitiator);
} }
nfc_close (pndTarget); nfc_close(pndTarget);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
szCapduLen = (size_t) res; szCapduLen = (size_t) res;
if (target_only_mode) { if (target_only_mode) {
if (print_hex_fd4(abtCapdu, szCapduLen, "C-APDU") != EXIT_SUCCESS) { if (print_hex_fd4(abtCapdu, szCapduLen, "C-APDU") != EXIT_SUCCESS) {
fprintf (stderr, "Error while printing C-APDU to FD4\n"); fprintf(stderr, "Error while printing C-APDU to FD4\n");
nfc_close (pndTarget); nfc_close(pndTarget);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
} else { } else {
if (scan_hex_fd3(abtCapdu, &szCapduLen, "C-APDU") != EXIT_SUCCESS) { if (scan_hex_fd3(abtCapdu, &szCapduLen, "C-APDU") != EXIT_SUCCESS) {
fprintf (stderr, "Error while scanning C-APDU from FD3\n"); fprintf(stderr, "Error while scanning C-APDU from FD3\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
// Show transmitted response // Show transmitted response
if (!quiet_output) { if (!quiet_output) {
printf ("Forwarding C-APDU: "); printf("Forwarding C-APDU: ");
print_hex (abtCapdu, szCapduLen); print_hex(abtCapdu, szCapduLen);
} }
if (!target_only_mode) { if (!target_only_mode) {
// Forward the frame to the original tag // Forward the frame to the original tag
if ((res = nfc_initiator_transceive_bytes (pndInitiator, abtCapdu, szCapduLen, abtRapdu, sizeof(abtRapdu), -1) < 0)) { if ((res = nfc_initiator_transceive_bytes(pndInitiator, abtCapdu, szCapduLen, abtRapdu, sizeof(abtRapdu), -1) < 0)) {
ret = false; ret = false;
} else { } else {
szCapduLen = (size_t) res; szCapduLen = (size_t) res;
@ -424,9 +424,9 @@ main (int argc, char *argv[])
} }
} else { } else {
if (scan_hex_fd3(abtRapdu, &szRapduLen, "R-APDU") != EXIT_SUCCESS) { if (scan_hex_fd3(abtRapdu, &szRapduLen, "R-APDU") != EXIT_SUCCESS) {
fprintf (stderr, "Error while scanning R-APDU from FD3\n"); fprintf(stderr, "Error while scanning R-APDU from FD3\n");
nfc_close (pndTarget); nfc_close(pndTarget);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
ret = true; ret = true;
@ -435,34 +435,34 @@ main (int argc, char *argv[])
// Redirect the answer back to the external reader // Redirect the answer back to the external reader
if (waiting_time > 0) { if (waiting_time > 0) {
if (!quiet_output) { if (!quiet_output) {
printf ("Waiting %is to simulate longer relay...\n", waiting_time); printf("Waiting %is to simulate longer relay...\n", waiting_time);
} }
sleep(waiting_time); sleep(waiting_time);
} }
// Show transmitted response // Show transmitted response
if (!quiet_output) { if (!quiet_output) {
printf ("Forwarding R-APDU: "); printf("Forwarding R-APDU: ");
print_hex (abtRapdu, szRapduLen); print_hex(abtRapdu, szRapduLen);
} }
if (!initiator_only_mode) { if (!initiator_only_mode) {
// Transmit the response bytes // Transmit the response bytes
if (nfc_target_send_bytes(pndTarget, abtRapdu, szRapduLen, 0) < 0) { if (nfc_target_send_bytes(pndTarget, abtRapdu, szRapduLen, 0) < 0) {
nfc_perror (pndTarget, "nfc_target_send_bytes"); nfc_perror(pndTarget, "nfc_target_send_bytes");
if (!target_only_mode) { if (!target_only_mode) {
nfc_close (pndInitiator); nfc_close(pndInitiator);
} }
if (!initiator_only_mode) { if (!initiator_only_mode) {
nfc_close (pndTarget); nfc_close(pndTarget);
nfc_exit (NULL); nfc_exit(NULL);
} }
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} else { } else {
if (print_hex_fd4(abtRapdu, szRapduLen, "R-APDU") != EXIT_SUCCESS) { if (print_hex_fd4(abtRapdu, szRapduLen, "R-APDU") != EXIT_SUCCESS) {
fprintf (stderr, "Error while printing R-APDU to FD4\n"); fprintf(stderr, "Error while printing R-APDU to FD4\n");
nfc_close (pndInitiator); nfc_close(pndInitiator);
nfc_exit (NULL); nfc_exit(NULL);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
@ -470,12 +470,12 @@ main (int argc, char *argv[])
} }
if (!target_only_mode) { if (!target_only_mode) {
nfc_close (pndInitiator); nfc_close(pndInitiator);
} }
if (!initiator_only_mode) { if (!initiator_only_mode) {
nfc_close (pndTarget); nfc_close(pndTarget);
} }
nfc_exit (NULL); nfc_exit(NULL);
exit (EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }

View file

@ -126,14 +126,14 @@ struct card_sak const_cs[] = {
}; };
uint8_t uint8_t
oddparity (const uint8_t bt) oddparity(const uint8_t bt)
{ {
// cf http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel // cf http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel
return (0x9669 >> ((bt ^ (bt >> 4)) & 0xF)) & 1; return (0x9669 >> ((bt ^(bt >> 4)) & 0xF)) & 1;
} }
void void
oddparity_bytes_ts (const uint8_t *pbtData, const size_t szLen, uint8_t *pbtPar) oddparity_bytes_ts(const uint8_t *pbtData, const size_t szLen, uint8_t *pbtPar)
{ {
size_t szByteNr; size_t szByteNr;
// Calculate the parity bits for the command // Calculate the parity bits for the command
@ -143,51 +143,51 @@ oddparity_bytes_ts (const uint8_t *pbtData, const size_t szLen, uint8_t *pbtPar)
} }
void void
print_hex (const uint8_t *pbtData, const size_t szBytes) print_hex(const uint8_t *pbtData, const size_t szBytes)
{ {
size_t szPos; size_t szPos;
for (szPos = 0; szPos < szBytes; szPos++) { for (szPos = 0; szPos < szBytes; szPos++) {
printf ("%02x ", pbtData[szPos]); printf("%02x ", pbtData[szPos]);
} }
printf ("\n"); printf("\n");
} }
void void
print_hex_bits (const uint8_t *pbtData, const size_t szBits) print_hex_bits(const uint8_t *pbtData, const size_t szBits)
{ {
uint8_t uRemainder; uint8_t uRemainder;
size_t szPos; size_t szPos;
size_t szBytes = szBits / 8; size_t szBytes = szBits / 8;
for (szPos = 0; szPos < szBytes; szPos++) { for (szPos = 0; szPos < szBytes; szPos++) {
printf ("%02x ", pbtData[szPos]); printf("%02x ", pbtData[szPos]);
} }
uRemainder = szBits % 8; uRemainder = szBits % 8;
// Print the rest bits // Print the rest bits
if (uRemainder != 0) { if (uRemainder != 0) {
if (uRemainder < 5) if (uRemainder < 5)
printf ("%01x (%d bits)", pbtData[szBytes], uRemainder); printf("%01x (%d bits)", pbtData[szBytes], uRemainder);
else else
printf ("%02x (%d bits)", pbtData[szBytes], uRemainder); printf("%02x (%d bits)", pbtData[szBytes], uRemainder);
} }
printf ("\n"); printf("\n");
} }
void void
print_hex_par (const uint8_t *pbtData, const size_t szBits, const uint8_t *pbtDataPar) print_hex_par(const uint8_t *pbtData, const size_t szBits, const uint8_t *pbtDataPar)
{ {
uint8_t uRemainder; uint8_t uRemainder;
size_t szPos; size_t szPos;
size_t szBytes = szBits / 8; size_t szBytes = szBits / 8;
for (szPos = 0; szPos < szBytes; szPos++) { for (szPos = 0; szPos < szBytes; szPos++) {
printf ("%02x", pbtData[szPos]); printf("%02x", pbtData[szPos]);
if (oddparity(pbtData[szPos]) != pbtDataPar[szPos]) { if (oddparity(pbtData[szPos]) != pbtDataPar[szPos]) {
printf ("! "); printf("! ");
} else { } else {
printf (" "); printf(" ");
} }
} }
@ -195,11 +195,11 @@ print_hex_par (const uint8_t *pbtData, const size_t szBits, const uint8_t *pbtDa
// Print the rest bits, these cannot have parity bit // Print the rest bits, these cannot have parity bit
if (uRemainder != 0) { if (uRemainder != 0) {
if (uRemainder < 5) if (uRemainder < 5)
printf ("%01x (%d bits)", pbtData[szBytes], uRemainder); printf("%01x (%d bits)", pbtData[szBytes], uRemainder);
else else
printf ("%02x (%d bits)", pbtData[szBytes], uRemainder); printf("%02x (%d bits)", pbtData[szBytes], uRemainder);
} }
printf ("\n"); printf("\n");
} }
#define SAK_UID_NOT_COMPLETE 0x04 #define SAK_UID_NOT_COMPLETE 0x04
@ -207,10 +207,10 @@ print_hex_par (const uint8_t *pbtData, const size_t szBits, const uint8_t *pbtDa
#define SAK_ISO18092_COMPLIANT 0x40 #define SAK_ISO18092_COMPLIANT 0x40
void void
print_nfc_iso14443a_info (const nfc_iso14443a_info nai, bool verbose) print_nfc_iso14443a_info(const nfc_iso14443a_info nai, bool verbose)
{ {
printf (" ATQA (SENS_RES): "); printf(" ATQA (SENS_RES): ");
print_hex (nai.abtAtqa, 2); print_hex(nai.abtAtqa, 2);
if (verbose) { if (verbose) {
printf("* UID size: "); printf("* UID size: ");
switch ((nai.abtAtqa[1] & 0xc0) >> 6) { switch ((nai.abtAtqa[1] & 0xc0) >> 6) {
@ -241,80 +241,80 @@ print_nfc_iso14443a_info (const nfc_iso14443a_info nai, bool verbose)
break; break;
} }
} }
printf (" UID (NFCID%c): ", (nai.abtUid[0] == 0x08 ? '3' : '1')); printf(" UID (NFCID%c): ", (nai.abtUid[0] == 0x08 ? '3' : '1'));
print_hex (nai.abtUid, nai.szUidLen); print_hex(nai.abtUid, nai.szUidLen);
if (verbose) { if (verbose) {
if (nai.abtUid[0] == 0x08) { if (nai.abtUid[0] == 0x08) {
printf ("* Random UID\n"); printf("* Random UID\n");
} }
} }
printf (" SAK (SEL_RES): "); printf(" SAK (SEL_RES): ");
print_hex (&nai.btSak, 1); print_hex(&nai.btSak, 1);
if (verbose) { if (verbose) {
if (nai.btSak & SAK_UID_NOT_COMPLETE) { if (nai.btSak & SAK_UID_NOT_COMPLETE) {
printf ("* Warning! Cascade bit set: UID not complete\n"); printf("* Warning! Cascade bit set: UID not complete\n");
} }
if (nai.btSak & SAK_ISO14443_4_COMPLIANT) { if (nai.btSak & SAK_ISO14443_4_COMPLIANT) {
printf ("* Compliant with ISO/IEC 14443-4\n"); printf("* Compliant with ISO/IEC 14443-4\n");
} else { } else {
printf ("* Not compliant with ISO/IEC 14443-4\n"); printf("* Not compliant with ISO/IEC 14443-4\n");
} }
if (nai.btSak & SAK_ISO18092_COMPLIANT) { if (nai.btSak & SAK_ISO18092_COMPLIANT) {
printf ("* Compliant with ISO/IEC 18092\n"); printf("* Compliant with ISO/IEC 18092\n");
} else { } else {
printf ("* Not compliant with ISO/IEC 18092\n"); printf("* Not compliant with ISO/IEC 18092\n");
} }
} }
if (nai.szAtsLen) { if (nai.szAtsLen) {
printf (" ATS: "); printf(" ATS: ");
print_hex (nai.abtAts, nai.szAtsLen); print_hex(nai.abtAts, nai.szAtsLen);
} }
if (nai.szAtsLen && verbose) { if (nai.szAtsLen && verbose) {
// Decode ATS according to ISO/IEC 14443-4 (5.2 Answer to select) // Decode ATS according to ISO/IEC 14443-4 (5.2 Answer to select)
const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 }; const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 };
printf ("* Max Frame Size accepted by PICC: %d bytes\n", iMaxFrameSizes[nai.abtAts[0] & 0x0F]); printf("* Max Frame Size accepted by PICC: %d bytes\n", iMaxFrameSizes[nai.abtAts[0] & 0x0F]);
size_t offset = 1; size_t offset = 1;
if (nai.abtAts[0] & 0x10) { // TA(1) present if (nai.abtAts[0] & 0x10) { // TA(1) present
uint8_t TA = nai.abtAts[offset]; uint8_t TA = nai.abtAts[offset];
offset++; offset++;
printf ("* Bit Rate Capability:\n"); printf("* Bit Rate Capability:\n");
if (TA == 0) { if (TA == 0) {
printf (" * PICC supports only 106 kbits/s in both directions\n"); printf(" * PICC supports only 106 kbits/s in both directions\n");
} }
if (TA & 1 << 7) { if (TA & 1 << 7) {
printf (" * Same bitrate in both directions mandatory\n"); printf(" * Same bitrate in both directions mandatory\n");
} }
if (TA & 1 << 4) { if (TA & 1 << 4) {
printf (" * PICC to PCD, DS=2, bitrate 212 kbits/s supported\n"); printf(" * PICC to PCD, DS=2, bitrate 212 kbits/s supported\n");
} }
if (TA & 1 << 5) { if (TA & 1 << 5) {
printf (" * PICC to PCD, DS=4, bitrate 424 kbits/s supported\n"); printf(" * PICC to PCD, DS=4, bitrate 424 kbits/s supported\n");
} }
if (TA & 1 << 6) { if (TA & 1 << 6) {
printf (" * PICC to PCD, DS=8, bitrate 847 kbits/s supported\n"); printf(" * PICC to PCD, DS=8, bitrate 847 kbits/s supported\n");
} }
if (TA & 1 << 0) { if (TA & 1 << 0) {
printf (" * PCD to PICC, DR=2, bitrate 212 kbits/s supported\n"); printf(" * PCD to PICC, DR=2, bitrate 212 kbits/s supported\n");
} }
if (TA & 1 << 1) { if (TA & 1 << 1) {
printf (" * PCD to PICC, DR=4, bitrate 424 kbits/s supported\n"); printf(" * PCD to PICC, DR=4, bitrate 424 kbits/s supported\n");
} }
if (TA & 1 << 2) { if (TA & 1 << 2) {
printf (" * PCD to PICC, DR=8, bitrate 847 kbits/s supported\n"); printf(" * PCD to PICC, DR=8, bitrate 847 kbits/s supported\n");
} }
if (TA & 1 << 3) { if (TA & 1 << 3) {
printf (" * ERROR unknown value\n"); printf(" * ERROR unknown value\n");
} }
} }
if (nai.abtAts[0] & 0x20) { // TB(1) present if (nai.abtAts[0] & 0x20) { // TB(1) present
uint8_t TB = nai.abtAts[offset]; uint8_t TB = nai.abtAts[offset];
offset++; offset++;
printf ("* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((TB & 0xf0) >> 4)) / 13560.0); printf("* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((TB & 0xf0) >> 4)) / 13560.0);
if ((TB & 0x0f) == 0) { if ((TB & 0x0f) == 0) {
printf ("* No Start-up Frame Guard Time required\n"); printf("* No Start-up Frame Guard Time required\n");
} else { } else {
printf ("* Start-up Frame Guard Time: %.4g ms\n", 256.0 * 16.0 * (1 << (TB & 0x0f)) / 13560.0); printf("* Start-up Frame Guard Time: %.4g ms\n", 256.0 * 16.0 * (1 << (TB & 0x0f)) / 13560.0);
} }
} }
if (nai.abtAts[0] & 0x40) { // TC(1) present if (nai.abtAts[0] & 0x40) { // TC(1) present
@ -332,8 +332,8 @@ print_nfc_iso14443a_info (const nfc_iso14443a_info nai, bool verbose)
} }
} }
if (nai.szAtsLen > offset) { if (nai.szAtsLen > offset) {
printf ("* Historical bytes Tk: " ); printf("* Historical bytes Tk: ");
print_hex (nai.abtAts + offset, (nai.szAtsLen - offset)); print_hex(nai.abtAts + offset, (nai.szAtsLen - offset));
uint8_t CIB = nai.abtAts[offset]; uint8_t CIB = nai.abtAts[offset];
offset++; offset++;
if (CIB != 0x00 && CIB != 0x10 && (CIB & 0xf0) != 0x80) { if (CIB != 0x00 && CIB != 0x10 && (CIB & 0xf0) != 0x80) {
@ -542,174 +542,174 @@ print_nfc_iso14443a_info (const nfc_iso14443a_info nai, bool verbose)
} }
void void
print_nfc_felica_info (const nfc_felica_info nfi, bool verbose) print_nfc_felica_info(const nfc_felica_info nfi, bool verbose)
{ {
(void) verbose; (void) verbose;
printf (" ID (NFCID2): "); printf(" ID (NFCID2): ");
print_hex (nfi.abtId, 8); print_hex(nfi.abtId, 8);
printf (" Parameter (PAD): "); printf(" Parameter (PAD): ");
print_hex (nfi.abtPad, 8); print_hex(nfi.abtPad, 8);
printf (" System Code (SC): "); printf(" System Code (SC): ");
print_hex (nfi.abtSysCode, 2); print_hex(nfi.abtSysCode, 2);
} }
void void
print_nfc_jewel_info (const nfc_jewel_info nji, bool verbose) print_nfc_jewel_info(const nfc_jewel_info nji, bool verbose)
{ {
(void) verbose; (void) verbose;
printf (" ATQA (SENS_RES): "); printf(" ATQA (SENS_RES): ");
print_hex (nji.btSensRes, 2); print_hex(nji.btSensRes, 2);
printf (" 4-LSB JEWELID: "); printf(" 4-LSB JEWELID: ");
print_hex (nji.btId, 4); print_hex(nji.btId, 4);
} }
#define PI_ISO14443_4_SUPPORTED 0x01 #define PI_ISO14443_4_SUPPORTED 0x01
#define PI_NAD_SUPPORTED 0x01 #define PI_NAD_SUPPORTED 0x01
#define PI_CID_SUPPORTED 0x02 #define PI_CID_SUPPORTED 0x02
void void
print_nfc_iso14443b_info (const nfc_iso14443b_info nbi, bool verbose) print_nfc_iso14443b_info(const nfc_iso14443b_info nbi, bool verbose)
{ {
const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 }; const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 };
printf (" PUPI: "); printf(" PUPI: ");
print_hex (nbi.abtPupi, 4); print_hex(nbi.abtPupi, 4);
printf (" Application Data: "); printf(" Application Data: ");
print_hex (nbi.abtApplicationData, 4); print_hex(nbi.abtApplicationData, 4);
printf (" Protocol Info: "); printf(" Protocol Info: ");
print_hex (nbi.abtProtocolInfo, 3); print_hex(nbi.abtProtocolInfo, 3);
if (verbose) { if (verbose) {
printf ("* Bit Rate Capability:\n"); printf("* Bit Rate Capability:\n");
if (nbi.abtProtocolInfo[0] == 0) { if (nbi.abtProtocolInfo[0] == 0) {
printf (" * PICC supports only 106 kbits/s in both directions\n"); printf(" * PICC supports only 106 kbits/s in both directions\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 7) { if (nbi.abtProtocolInfo[0] & 1 << 7) {
printf (" * Same bitrate in both directions mandatory\n"); printf(" * Same bitrate in both directions mandatory\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 4) { if (nbi.abtProtocolInfo[0] & 1 << 4) {
printf (" * PICC to PCD, 1etu=64/fc, bitrate 212 kbits/s supported\n"); printf(" * PICC to PCD, 1etu=64/fc, bitrate 212 kbits/s supported\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 5) { if (nbi.abtProtocolInfo[0] & 1 << 5) {
printf (" * PICC to PCD, 1etu=32/fc, bitrate 424 kbits/s supported\n"); printf(" * PICC to PCD, 1etu=32/fc, bitrate 424 kbits/s supported\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 6) { if (nbi.abtProtocolInfo[0] & 1 << 6) {
printf (" * PICC to PCD, 1etu=16/fc, bitrate 847 kbits/s supported\n"); printf(" * PICC to PCD, 1etu=16/fc, bitrate 847 kbits/s supported\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 0) { if (nbi.abtProtocolInfo[0] & 1 << 0) {
printf (" * PCD to PICC, 1etu=64/fc, bitrate 212 kbits/s supported\n"); printf(" * PCD to PICC, 1etu=64/fc, bitrate 212 kbits/s supported\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 1) { if (nbi.abtProtocolInfo[0] & 1 << 1) {
printf (" * PCD to PICC, 1etu=32/fc, bitrate 424 kbits/s supported\n"); printf(" * PCD to PICC, 1etu=32/fc, bitrate 424 kbits/s supported\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 2) { if (nbi.abtProtocolInfo[0] & 1 << 2) {
printf (" * PCD to PICC, 1etu=16/fc, bitrate 847 kbits/s supported\n"); printf(" * PCD to PICC, 1etu=16/fc, bitrate 847 kbits/s supported\n");
} }
if (nbi.abtProtocolInfo[0] & 1 << 3) { if (nbi.abtProtocolInfo[0] & 1 << 3) {
printf (" * ERROR unknown value\n"); printf(" * ERROR unknown value\n");
} }
if( (nbi.abtProtocolInfo[1] & 0xf0) <= 0x80 ) { if ((nbi.abtProtocolInfo[1] & 0xf0) <= 0x80) {
printf ("* Maximum frame sizes: %d bytes\n", iMaxFrameSizes[((nbi.abtProtocolInfo[1] & 0xf0) >> 4)]); printf("* Maximum frame sizes: %d bytes\n", iMaxFrameSizes[((nbi.abtProtocolInfo[1] & 0xf0) >> 4)]);
} }
if((nbi.abtProtocolInfo[1] & 0x0f) == PI_ISO14443_4_SUPPORTED) { if ((nbi.abtProtocolInfo[1] & 0x0f) == PI_ISO14443_4_SUPPORTED) {
printf ("* Protocol types supported: ISO/IEC 14443-4\n"); printf("* Protocol types supported: ISO/IEC 14443-4\n");
} }
printf ("* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((nbi.abtProtocolInfo[2] & 0xf0) >> 4)) / 13560.0); printf("* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((nbi.abtProtocolInfo[2] & 0xf0) >> 4)) / 13560.0);
if((nbi.abtProtocolInfo[2] & (PI_NAD_SUPPORTED | PI_CID_SUPPORTED)) != 0) { if ((nbi.abtProtocolInfo[2] & (PI_NAD_SUPPORTED | PI_CID_SUPPORTED)) != 0) {
printf ("* Frame options supported: "); printf("* Frame options supported: ");
if ((nbi.abtProtocolInfo[2] & PI_NAD_SUPPORTED) != 0) printf ("NAD "); if ((nbi.abtProtocolInfo[2] & PI_NAD_SUPPORTED) != 0) printf("NAD ");
if ((nbi.abtProtocolInfo[2] & PI_CID_SUPPORTED) != 0) printf ("CID "); if ((nbi.abtProtocolInfo[2] & PI_CID_SUPPORTED) != 0) printf("CID ");
printf("\n"); printf("\n");
} }
} }
} }
void void
print_nfc_iso14443bi_info (const nfc_iso14443bi_info nii, bool verbose) print_nfc_iso14443bi_info(const nfc_iso14443bi_info nii, bool verbose)
{ {
printf (" DIV: "); printf(" DIV: ");
print_hex (nii.abtDIV, 4); print_hex(nii.abtDIV, 4);
if (verbose) { if (verbose) {
int version = (nii.btVerLog & 0x1e) >> 1; int version = (nii.btVerLog & 0x1e) >> 1;
printf (" Software Version: "); printf(" Software Version: ");
if (version == 15) { if (version == 15) {
printf ("Undefined\n"); printf("Undefined\n");
} else { } else {
printf ("%i\n", version); printf("%i\n", version);
} }
if ((nii.btVerLog & 0x80) && (nii.btConfig & 0x80)) { if ((nii.btVerLog & 0x80) && (nii.btConfig & 0x80)) {
printf (" Wait Enable: yes"); printf(" Wait Enable: yes");
} }
} }
if ((nii.btVerLog & 0x80) && (nii.btConfig & 0x40)) { if ((nii.btVerLog & 0x80) && (nii.btConfig & 0x40)) {
printf (" ATS: "); printf(" ATS: ");
print_hex (nii.abtAtr, nii.szAtrLen); print_hex(nii.abtAtr, nii.szAtrLen);
} }
} }
void void
print_nfc_iso14443b2sr_info (const nfc_iso14443b2sr_info nsi, bool verbose) print_nfc_iso14443b2sr_info(const nfc_iso14443b2sr_info nsi, bool verbose)
{ {
(void) verbose; (void) verbose;
printf (" UID: "); printf(" UID: ");
print_hex (nsi.abtUID, 8); print_hex(nsi.abtUID, 8);
} }
void void
print_nfc_iso14443b2ct_info (const nfc_iso14443b2ct_info nci, bool verbose) print_nfc_iso14443b2ct_info(const nfc_iso14443b2ct_info nci, bool verbose)
{ {
(void) verbose; (void) verbose;
uint32_t uid; uint32_t uid;
uid = (nci.abtUID[3] << 24) + (nci.abtUID[2] << 16) + (nci.abtUID[1] << 8) + nci.abtUID[0]; uid = (nci.abtUID[3] << 24) + (nci.abtUID[2] << 16) + (nci.abtUID[1] << 8) + nci.abtUID[0];
printf (" UID: "); printf(" UID: ");
print_hex (nci.abtUID, sizeof(nci.abtUID)); print_hex(nci.abtUID, sizeof(nci.abtUID));
printf (" UID (decimal): %010u\n", uid); printf(" UID (decimal): %010u\n", uid);
printf (" Product Code: %02X\n", nci.btProdCode); printf(" Product Code: %02X\n", nci.btProdCode);
printf (" Fab Code: %02X\n", nci.btFabCode); printf(" Fab Code: %02X\n", nci.btFabCode);
} }
void void
print_nfc_dep_info (const nfc_dep_info ndi, bool verbose) print_nfc_dep_info(const nfc_dep_info ndi, bool verbose)
{ {
(void) verbose; (void) verbose;
printf (" NFCID3: "); printf(" NFCID3: ");
print_hex (ndi.abtNFCID3, 10); print_hex(ndi.abtNFCID3, 10);
printf (" BS: %02x\n", ndi.btBS); printf(" BS: %02x\n", ndi.btBS);
printf (" BR: %02x\n", ndi.btBR); printf(" BR: %02x\n", ndi.btBR);
printf (" TO: %02x\n", ndi.btTO); printf(" TO: %02x\n", ndi.btTO);
printf (" PP: %02x\n", ndi.btPP); printf(" PP: %02x\n", ndi.btPP);
if (ndi.szGB) { if (ndi.szGB) {
printf ("General Bytes: "); printf("General Bytes: ");
print_hex (ndi.abtGB, ndi.szGB); print_hex(ndi.abtGB, ndi.szGB);
} }
} }
void void
print_nfc_target (const nfc_target nt, bool verbose) print_nfc_target(const nfc_target nt, bool verbose)
{ {
printf ("%s (%s%s) target:\n", str_nfc_modulation_type(nt.nm.nmt), str_nfc_baud_rate(nt.nm.nbr), (nt.nm.nmt != NMT_DEP) ? "" : (nt.nti.ndi.ndm == NDM_ACTIVE) ? "active mode" : "passive mode"); printf("%s (%s%s) target:\n", str_nfc_modulation_type(nt.nm.nmt), str_nfc_baud_rate(nt.nm.nbr), (nt.nm.nmt != NMT_DEP) ? "" : (nt.nti.ndi.ndm == NDM_ACTIVE) ? "active mode" : "passive mode");
switch(nt.nm.nmt) { switch (nt.nm.nmt) {
case NMT_ISO14443A: case NMT_ISO14443A:
print_nfc_iso14443a_info (nt.nti.nai, verbose); print_nfc_iso14443a_info(nt.nti.nai, verbose);
break; break;
case NMT_JEWEL: case NMT_JEWEL:
print_nfc_jewel_info (nt.nti.nji, verbose); print_nfc_jewel_info(nt.nti.nji, verbose);
break; break;
case NMT_FELICA: case NMT_FELICA:
print_nfc_felica_info (nt.nti.nfi, verbose); print_nfc_felica_info(nt.nti.nfi, verbose);
break; break;
case NMT_ISO14443B: case NMT_ISO14443B:
print_nfc_iso14443b_info (nt.nti.nbi, verbose); print_nfc_iso14443b_info(nt.nti.nbi, verbose);
break; break;
case NMT_ISO14443BI: case NMT_ISO14443BI:
print_nfc_iso14443bi_info (nt.nti.nii, verbose); print_nfc_iso14443bi_info(nt.nti.nii, verbose);
break; break;
case NMT_ISO14443B2SR: case NMT_ISO14443B2SR:
print_nfc_iso14443b2sr_info (nt.nti.nsi, verbose); print_nfc_iso14443b2sr_info(nt.nti.nsi, verbose);
break; break;
case NMT_ISO14443B2CT: case NMT_ISO14443B2CT:
print_nfc_iso14443b2ct_info (nt.nti.nci, verbose); print_nfc_iso14443b2ct_info(nt.nti.nci, verbose);
break; break;
case NMT_DEP: case NMT_DEP:
print_nfc_dep_info (nt.nti.ndi, verbose); print_nfc_dep_info(nt.nti.ndi, verbose);
break; break;
} }
} }

View file

@ -86,22 +86,22 @@
#define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif #endif
uint8_t oddparity (const uint8_t bt); uint8_t oddparity(const uint8_t bt);
void oddparity_bytes_ts (const uint8_t *pbtData, const size_t szLen, uint8_t *pbtPar); void oddparity_bytes_ts(const uint8_t *pbtData, const size_t szLen, uint8_t *pbtPar);
void print_hex (const uint8_t *pbtData, const size_t szLen); void print_hex(const uint8_t *pbtData, const size_t szLen);
void print_hex_bits (const uint8_t *pbtData, const size_t szBits); void print_hex_bits(const uint8_t *pbtData, const size_t szBits);
void print_hex_par (const uint8_t *pbtData, const size_t szBits, const uint8_t *pbtDataPar); void print_hex_par(const uint8_t *pbtData, const size_t szBits, const uint8_t *pbtDataPar);
void print_nfc_iso14443a_info (const nfc_iso14443a_info nai, bool verbose); void print_nfc_iso14443a_info(const nfc_iso14443a_info nai, bool verbose);
void print_nfc_iso14443b_info (const nfc_iso14443b_info nbi, bool verbose); void print_nfc_iso14443b_info(const nfc_iso14443b_info nbi, bool verbose);
void print_nfc_iso14443bi_info (const nfc_iso14443bi_info nii, bool verbose); void print_nfc_iso14443bi_info(const nfc_iso14443bi_info nii, bool verbose);
void print_nfc_iso14443b2sr_info (const nfc_iso14443b2sr_info nsi, bool verbose); void print_nfc_iso14443b2sr_info(const nfc_iso14443b2sr_info nsi, bool verbose);
void print_nfc_iso14443b2ct_info (const nfc_iso14443b2ct_info nci, bool verbose); void print_nfc_iso14443b2ct_info(const nfc_iso14443b2ct_info nci, bool verbose);
void print_nfc_felica_info (const nfc_felica_info nfi, bool verbose); void print_nfc_felica_info(const nfc_felica_info nfi, bool verbose);
void print_nfc_jewel_info (const nfc_jewel_info nji, bool verbose); void print_nfc_jewel_info(const nfc_jewel_info nji, bool verbose);
void print_nfc_dep_info (const nfc_dep_info ndi, bool verbose); void print_nfc_dep_info(const nfc_dep_info ndi, bool verbose);
void print_nfc_target (const nfc_target nt, bool verbose); void print_nfc_target(const nfc_target nt, bool verbose);
#endif #endif