code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#include <cutter.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include "nfc/nfc.h" void test_dep_passive(void); #define INITIATOR 0 #define TARGET 1 pthread_t threads[2]; nfc_context *context; nfc_connstring connstrings[2]; nfc_device *devices[2]; intptr_t result[2]; static void abort_test_by_keypress(int sig) { (void) sig; printf("\033[0;1;31mSIGINT\033[0m"); nfc_abort_command(devices[INITIATOR]); nfc_abort_command(devices[TARGET]); } void cut_setup(void) { nfc_init(&context); size_t n = nfc_list_devices(context, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } devices[TARGET] = nfc_open(context, connstrings[TARGET]); devices[INITIATOR] = nfc_open(context, connstrings[INITIATOR]); signal(SIGINT, abort_test_by_keypress); } void cut_teardown(void) { nfc_close(devices[TARGET]); nfc_close(devices[INITIATOR]); nfc_exit(context); } struct thread_data { nfc_device *device; void *cut_test_context; }; static void * target_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); printf("=========== TARGET %s =========\n", nfc_device_get_name(device)); nfc_target nt = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_PASSIVE, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, }, }; uint8_t abtRx[1024]; size_t szRx = sizeof(abtRx); 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))); if (res < 0) { thread_res = -1; return (void *) thread_res; } // First pass 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))); const uint8_t abtAttRx[] = "Hello DEP target!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP initiator!"; 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))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // Second pass 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_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } 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))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // Third pass 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_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } 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))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // Fourth pass 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_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } 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))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } static void * initiator_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; 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 */ sleep(1); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(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))); if (res < 0) { thread_res = -1; return (void *) thread_res; } nfc_target nt; // Passive mode / 106Kbps 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); 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(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_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")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP target!"; uint8_t abtRx[1024]; res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 500); 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!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(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; } // Passive mode / 212Kbps (second pass) 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); 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(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_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")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 1000); 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, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(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; } // Passive mode / 212Kbps 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); 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(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_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")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 5000); 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, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(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; } // Passive mode / 424Kbps 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); 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(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_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")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 5000); 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, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(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; } return (void *) thread_res; } void test_dep_passive(void) { int res; CutTestContext *test_context = cut_get_current_test_context(); struct thread_data target_data = { .device = devices[TARGET], .cut_test_context = test_context, }; if ((res = pthread_create(&(threads[TARGET]), NULL, target_thread, &target_data))) cut_fail("pthread_create() returned %d", res); struct thread_data initiator_data = { .device = devices[INITIATOR], .cut_test_context = test_context, }; if ((res = pthread_create(&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_join(threads[INITIATOR], (void *) &result[INITIATOR]))) cut_fail("pthread_join() returned %d", res); if ((res = pthread_join(threads[TARGET], (void *) &result[TARGET]))) 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[TARGET], cut_message("Unexpected target return code")); }
zzyjames55-nfc0805
test/test_dep_passive.c
C
lgpl
12,735
# $Id$ AM_CPPFLAGS = $(CUTTER_CFLAGS) $(LIBNFC_CFLAGS) LIBS = $(CUTTER_LIBS) if WITH_CUTTER TESTS = run-test.sh TESTS_ENVIRONMENT = NO_MAKE=yes CUTTER="$(CUTTER)" cutter_unit_test_libs = \ test_access_storm.la \ test_dep_active.la \ test_device_modes_as_dep.la \ test_dep_passive.la \ test_register_access.la \ test_register_endianness.la if WITH_DEBUG noinst_LTLIBRARIES = $(cutter_unit_test_libs) else check_LTLIBRARIES = $(cutter_unit_test_libs) endif AM_LDFLAGS = -module -rpath $(libdir) -avoid-version -no-undefined test_access_storm_la_SOURCES = test_access_storm.c test_access_storm_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_dep_active_la_SOURCES = test_dep_active.c test_dep_active_la_LIBADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la test_device_modes_as_dep_la_SOURCES = test_device_modes_as_dep.c test_device_modes_as_dep_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_dep_passive_la_SOURCES = test_dep_passive.c test_dep_passive_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_register_access_la_SOURCES = test_register_access.c test_register_access_la_LIBADD = $(top_builddir)/libnfc/libnfc.la test_register_endianness_la_SOURCES = test_register_endianness.c test_register_endianness_la_LIBADD = $(top_builddir)/libnfc/libnfc.la echo-cutter: @echo $(CUTTER) EXTRA_DIST = run-test.sh CLEANFILES = *.gcno endif
zzyjames55-nfc0805
test/Makefile.am
Makefile
lgpl
1,405
#include <cutter.h> #include <nfc/nfc.h> #include "chips/pn53x.h" #define MAX_DEVICE_COUNT 1 #define MAX_TARGET_COUNT 1 void test_register_access(void); void test_register_access(void) { nfc_connstring connstrings[MAX_DEVICE_COUNT]; int res = 0; nfc_context *context; nfc_init(&context); size_t device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (!device_count) cut_omit("No NFC device found"); nfc_device *device; device = nfc_open(context, connstrings[0]); cut_assert_not_null(device, cut_message("nfc_open")); uint8_t value; /* Set a 0xAA test value in writable register memory to test register access */ res = pn53x_write_register(device, PN53X_REG_CIU_TxMode, 0xFF, 0xAA); cut_assert_equal_int(0, res, cut_message("write register value to 0xAA")); /* Get test value from register memory */ res = pn53x_read_register(device, PN53X_REG_CIU_TxMode, &value); cut_assert_equal_int(0, res, cut_message("read 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 */ res = pn53x_write_register(device, PN53X_REG_CIU_TxMode, 0xFF, 0x55); cut_assert_equal_int(0, res, cut_message("write register value to 0x55")); /* Get test value from register memory */ res = pn53x_read_register(device, PN53X_REG_CIU_TxMode, &value); cut_assert_equal_int(0, res, cut_message("read register value")); cut_assert_equal_uint(0x55, value, cut_message("check register value")); nfc_close(device); nfc_exit(context); }
zzyjames55-nfc0805
test/test_register_access.c
C
lgpl
1,605
#include <cutter.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include "nfc/nfc.h" #include "../utils/nfc-utils.h" void test_dep_states(void); pthread_t threads[2]; nfc_context *context; nfc_connstring connstrings[2]; nfc_device *first_device, *second_device; intptr_t result[2]; static void abort_test_by_keypress(int sig) { (void) sig; printf("\033[0;1;31mSIGINT\033[0m"); nfc_abort_command(first_device); nfc_abort_command(second_device); } void cut_setup(void) { nfc_init(&context); size_t n = nfc_list_devices(context, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } second_device = nfc_open(context, connstrings[0]); first_device = nfc_open(context, connstrings[1]); signal(SIGINT, abort_test_by_keypress); } void cut_teardown(void) { nfc_close(second_device); nfc_close(first_device); nfc_exit(context); } struct thread_data { nfc_device *device; void *cut_test_context; }; static void * target_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); printf("=========== TARGET %s =========\n", nfc_device_get_name(device)); nfc_target nt; uint8_t abtRx[1024]; // 1) nfc_target_init should take target in idle mode int res = nfc_target_init(device, &nt, abtRx, sizeof(abtRx), 500); 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; } // 2) act as target nfc_target nt1 = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_PASSIVE, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, }, }; sleep(6); res = nfc_target_init(device, &nt1, abtRx, sizeof(abtRx), 0); 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; } 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))); const uint8_t abtAttRx[] = "Hello DEP target!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP initiator!"; 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))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } // 3) idle mode sleep(1); nfc_idle(device); return (void *) thread_res; } static void * initiator_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; 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 */ sleep(5); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(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))); 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 nfc_target nt; 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")); if (res != 0) { thread_res = -1; return (void *) thread_res; } // 2 As other device should be in target mode, nfc_initiator_poll_dep_target should be positive. nfc_target nt1; // Passive mode / 106Kbps 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); 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(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_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")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP target!"; uint8_t abtRx[1024]; res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 500); 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!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(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; } // 3) As other device should be in idle mode, nfc_initiator_poll_dep_target should return 0 nfc_target nt2; 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")); if (res != 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } void test_dep_states(void) { CutTestContext *test_context = cut_get_current_test_context(); struct thread_data target_data = { .device = first_device, .cut_test_context = test_context, }; struct thread_data initiator_data = { .device = second_device, .cut_test_context = test_context, }; for (int i = 0; i < 2; i++) { int res; if ((res = pthread_create(&(threads[1]), NULL, target_thread, &target_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_create(&(threads[0]), NULL, initiator_thread, &initiator_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_join(threads[0], (void *) &result[0]))) cut_fail("pthread_join() returned %d", res); if ((res = pthread_join(threads[1], (void *) &result[1]))) 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[1], cut_message("Unexpected target return code")); // initiator --> target, target --> initiator target_data.device = second_device; initiator_data.device = first_device; } }
zzyjames55-nfc0805
test/test_device_modes_as_dep.c
C
lgpl
7,522
#include <cutter.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include "nfc/nfc.h" #include "../utils/nfc-utils.h" void test_dep_active(void); #define INITIATOR 0 #define TARGET 1 pthread_t threads[2]; nfc_context *context; nfc_connstring connstrings[2]; nfc_device *devices[2]; intptr_t result[2]; static void abort_test_by_keypress(int sig) { (void) sig; printf("\033[0;1;31mSIGINT\033[0m"); nfc_abort_command(devices[INITIATOR]); nfc_abort_command(devices[TARGET]); } void cut_setup(void) { nfc_init(&context); size_t n = nfc_list_devices(context, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } devices[TARGET] = nfc_open(context, connstrings[TARGET]); devices[INITIATOR] = nfc_open(context, connstrings[INITIATOR]); signal(SIGINT, abort_test_by_keypress); } void cut_teardown(void) { nfc_close(devices[TARGET]); nfc_close(devices[INITIATOR]); nfc_exit(context); } struct thread_data { nfc_device *device; void *cut_test_context; nfc_baud_rate nbr; }; static void * target_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); printf("=========== TARGET %s =========\n", nfc_device_get_name(device)); nfc_target nt = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_ACTIVE, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, }, }; uint8_t abtRx[1024]; 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))); if (res < 0) { thread_res = -1; return (void *) thread_res; } 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))); const uint8_t abtAttRx[] = "Hello DEP target!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP initiator!"; 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))); if (res <= 0) { thread_res = -1; return (void *) thread_res; } return (void *) thread_res; } static void * initiator_thread(void *arg) { intptr_t thread_res = 0; nfc_device *device = ((struct thread_data *) arg)->device; cut_set_current_test_context(((struct thread_data *) arg)->cut_test_context); nfc_baud_rate nbr = (((struct thread_data *) arg)->nbr); /* * Wait some time for the other thread to initialise NFC device as target */ sleep(1); printf("=========== INITIATOR %s =========\n", nfc_device_get_name(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))); if (res < 0) { thread_res = -1; return (void *) thread_res; } nfc_target nt; // Active mode 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); 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(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_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")); if (res <= 0) { thread_res = -1; return (void *) thread_res; } const uint8_t abtTx[] = "Hello DEP target!"; uint8_t abtRx[1024]; res = nfc_initiator_transceive_bytes(device, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 5000); 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!"; cut_assert_equal_memory(abtAttRx, sizeof(abtAttRx), abtRx, res, cut_message("Invalid received data (as initiator)")); if (res < 0) { thread_res = -1; return (void *) thread_res; } res = nfc_initiator_deselect_target(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; } return (void *) thread_res; } void test_dep_active(void) { nfc_baud_rate nbrs[3] = { NBR_106, NBR_212, NBR_424}; CutTestContext *test_context = cut_get_current_test_context(); struct thread_data target_data = { .device = devices[TARGET], .cut_test_context = test_context, }; struct thread_data initiator_data = { .device = devices[INITIATOR], .cut_test_context = test_context, }; for (int i = 0; i < 3; i++) { initiator_data.nbr = nbrs[i]; int res; if ((res = pthread_create(&(threads[TARGET]), NULL, target_thread, &target_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_create(&(threads[INITIATOR]), NULL, initiator_thread, &initiator_data))) cut_fail("pthread_create() returned %d", res); if ((res = pthread_join(threads[INITIATOR], (void *) &result[INITIATOR]))) cut_fail("pthread_join() returned %d", res); if ((res = pthread_join(threads[TARGET], (void *) &result[TARGET]))) 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[TARGET], cut_message("Unexpected target return code")); } }
zzyjames55-nfc0805
test/test_dep_active.c
C
lgpl
6,508
#!/bin/sh export BASE_DIR="`dirname $0`" if test -z "$NO_MAKE"; then make -C "$BASE_DIR/../" > /dev/null || exit 1 fi if test -z "$CUTTER"; then CUTTER="`make -s -C "$BASE_DIR" echo-cutter`" fi "$CUTTER" --keep-opening-modules -s "$BASE_DIR" "$@" "$BASE_DIR" # ^^^^^^^^^^^^^^^^^^^^^^ # FIXME: Remove this workaround once cutter has been fixed upstream. # Bug report: # http://sourceforge.net/mailarchive/forum.php?thread_name=20100626123941.GA258%40blogreen.org&forum_name=cutter-users-en
zzyjames55-nfc0805
test/run-test.sh
Shell
lgpl
509
ACLOCAL_AMFLAGS = -I m4 AM_CFLAGS = $(LIBNFC_CFLAGS) SUBDIRS = libnfc utils examples include contrib cmake test pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = libnfc.pc EXTRA_DIST = \ CMakeLists.txt \ Doxyfile \ README-Windows.txt \ libnfc.conf.sample CLEANFILES = Doxygen.log coverage.info libnfc.pc clean-local: clean-local-doc clean-local-coverage .PHONY: clean-local-coverage clean-local-doc doc style clean-local-coverage: -rm -rf coverage clean-local-doc: rm -rf doc doc : Doxyfile @DOXYGEN@ $(builddir)/Doxyfile DISTCHECK_CONFIGURE_FLAGS="--with-drivers=all" style: find . -name "*.[ch]" -exec perl -pi -e 's/[ \t]+$$//' {} \; find . -name "*.[ch]" -exec astyle --formatted --mode=c --suffix=none \ --indent=spaces=2 --indent-switches --indent-preprocessor \ --keep-one-line-blocks --max-instatement-indent=60 \ --brackets=linux --pad-oper --unpad-paren --pad-header \ --align-pointer=name {} \; cppcheck: cppcheck --quiet \ -I include -I libnfc -I libnfc/buses -I libnfc/chips -I libnfc/drivers \ --check-config . cppcheck --quiet --enable=all --std=posix --std=c99 \ -I include -I libnfc -I libnfc/buses -I libnfc/chips -I libnfc/drivers \ -DLOG -D__linux__ \ -DDRIVER_PN53X_USB_ENABLED -DDRIVER_ACR122_PCSC_ENABLED \ -DDRIVER_ACR122_USB_ENABLED -DDRIVER_ACR122S_ENABLED \ -DDRIVER_PN532_UART_ENABLED -DDRIVER_ARYGON_ENABLED \ -DDRIVER_PN532_SPI_ENABLED -DDRIVER_PN532_I2C_ENABLED \ --force --inconclusive .
zzyjames55-nfc0805
Makefile.am
Makefile
lgpl
1,510
#! /bin/sh # Stop script on first error. set -e # Retrieve libnfc version from configure.ac LIBNFC_VERSION=$(grep AC_INIT configure.ac | sed 's/^.*\[libnfc\],\[\(.*\)\],\[.*/\1/g') echo "=== Building release archive for libnfc $LIBNFC_VERSION ===" # Easiest part: GNU/linux, BSD and other POSIX systems. LIBNFC_AUTOTOOLS_ARCHIVE=libnfc-$LIBNFC_VERSION.tar.gz echo ">>> Cleaning sources..." # First, clean what we can rm -f configure config.h config.h.in autoreconf -is --force && ./configure && make distclean git clean -dfX echo "<<< Sources cleaned." if [ ! -f $LIBNFC_AUTOTOOLS_ARCHIVE ]; then echo ">>> Autotooled archive generation..." # Second, generate dist archive (and test it) autoreconf -is --force && ./configure && make distcheck # Finally, clean up make distclean echo "<<< Autotooled archive generated." else echo "--- Autotooled archive (GNU/Linux, BSD, etc.) is already done: skipped." fi # Documentation part echo "=== Building documentation archive for libnfc $LIBNFC_VERSION ===" LIBNFC_DOC_DIR=libnfc-doc-$LIBNFC_VERSION LIBNFC_DOC_ARCHIVE=$LIBNFC_DOC_DIR.zip if [ ! -f $LIBNFC_DOC_ARCHIVE ]; then echo ">>> Documentation archive generation..." if [ -d $LIBNFC_DOC_DIR ]; then rm -rf $LIBNFC_DOC_DIR fi # Build documentation autoreconf -is --force && ./configure --enable-doc && make doc || false # Create archive cp -r doc/html $LIBNFC_DOC_DIR zip -r $LIBNFC_DOC_ARCHIVE $LIBNFC_DOC_DIR # Clean up rm -rf $LIBNFC_DOC_DIR make distclean echo "<<< Documentation archive generated." else echo "--- Documentation archive is already done: skipped." fi
zzyjames55-nfc0805
make_release.sh
Shell
lgpl
1,604
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2010 Emanuele Bertoldi * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file pn53x-sam.c * @brief Configures the NFC device to communicate with a SAM (Secure Access Module). * @note This example requiers a PN532 with SAM connected using S2C interface * @see PN532 User manual */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #include "libnfc/chips/pn53x.h" #define MAX_FRAME_LEN 264 #define TIMEOUT 60 // secs. static void wait_one_minute(void) { int secs = 0; printf("|"); fflush(stdout); while (secs < TIMEOUT) { sleep(1); secs++; printf("."); fflush(stdout); } printf("|\n"); } int main(int argc, const char *argv[]) { (void) argc; (void) argv; nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Display libnfc version const char *acLibnfcVersion = nfc_version(); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); // Open using the first available NFC device nfc_device *pnd; pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("%s", "Unable to open NFC device."); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC device: %s opened\n", nfc_device_get_name(pnd)); // Print the example's menu printf("\nSelect the communication mode:\n"); printf("[1] Virtual card mode.\n"); printf("[2] Wired card mode.\n"); printf("[3] Dual card mode.\n"); printf(">> "); // Take user's choice char input = getchar(); printf("\n"); if ((input < '1') || (input > '3')) { ERR("%s", "Invalid selection."); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } /* * '1' -> "Virtual mode" (0x02) * '2' -> "Wired card" (0x03) * '3' -> "Dual card" (0x04) */ int iMode = input - '0' + 0x01; pn532_sam_mode mode = iMode; // Connect with the SAM switch (mode) { case PSM_VIRTUAL_CARD: { // FIXME Its a private pn53x function if (pn532_SAMConfiguration(pnd, mode, 0) < 0) { nfc_perror(pnd, "pn53x_SAMConfiguration"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("Now the SAM is readable for 1 minute from an external reader.\n"); wait_one_minute(); } break; case PSM_WIRED_CARD: { // Set opened NFC device to initiator mode if (nfc_initiator_init_secure_element(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init_secure_element"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Let the reader only try once to find a tag if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Read the SAM's info const nfc_modulation nmSAM = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; nfc_target nt; int res; if ((res = nfc_initiator_select_passive_target(pnd, nmSAM, NULL, 0, &nt)) < 0) { nfc_perror(pnd, "nfc_initiator_select_passive_target"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } else if (res == 0) { ERR("No SAM found."); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } else if (res == 1) { printf("The following ISO14443A tag (SAM) was found:\n"); print_nfc_target(&nt, true); } else { ERR("%s", "More than one ISO14442 tag found as SAM."); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } } break; case PSM_DUAL_CARD: { // FIXME Its a private pn53x function if (pn532_SAMConfiguration(pnd, mode, 0) < 0) { nfc_perror(pnd, "pn53x_SAMConfiguration"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } uint8_t abtRx[MAX_FRAME_LEN]; nfc_target nt = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_UNDEFINED, }, .nti = { .nai = { .abtAtqa = { 0x04, 0x00 }, .abtUid = { 0x08, 0xad, 0xbe, 0xef }, .btSak = 0x20, .szUidLen = 4, .szAtsLen = 0, }, }, }; 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"); if (nfc_target_init(pnd, &nt, abtRx, sizeof(abtRx), 0) < 0) { nfc_perror(pnd, "nfc_target_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // wait_one_minute (); } break; case PSM_NORMAL: // This should not happend... nothing to do. break; } // Disconnect from the SAM pn532_SAMConfiguration(pnd, PSM_NORMAL, -1); // Close NFC device nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/pn53x-sam.c
C
lgpl
7,063
.TH pn53x-tamashell 1 "September 15, 2010" .SH NAME pn53x-tamashell \- PN53x TAMA communication demonstration shell .SH SYNOPSIS .B pn53x-tamashell .IR [script] .SH DESCRIPTION .B pn53x-tamashell is a simple interactive tool to send so called TAMA commands and receive the answers. TAMA refers to the command set supported by the PN53x family. Messages are binary and the shell expects hexadecimal notation. TAMA commands and responses prefixes (0xD4/0xD5), CRC and any framing above are handled transparently. You can use the shell interactively (with readline support) or you can write your own script file consisting in commands and comments (anything that starts with ";", "#" or "//"). Spaces are ignored and can be used for readability. Shebang is supported, simply start your script with: #!/usr/bin/env \fBpn53x-tamashell\fP .SH COMMANDS \fIp N\fP to introduce a pause of N milliseconds. \fIq\fP or \fICtrl-d\fP to quit. .SH EXAMPLES GetFirmware command is D4 02, so one has just to send the command "02": $ \fBpn53x-tamashell\fP Connected to NFC reader: SCM Micro/SCL3711-NFC&RW - PN533 v2.7 (0x07) > 02 Tx: 02 Rx: 33 02 07 07 > 40 Tx: 40 Rx: Command Not Acceptable > q Bye! Same thing, with a script: $ \fBpn53x-tamashell\fP << EOF // This is a comment 02 // GetFirmware 40 // Command with missing arguments EOF Connected to NFC reader: SCM Micro/SCL3711-NFC&RW - PN533 v2.7 (0x07) > // This is a comment > 02 // GetFirmware Tx: 02 Rx: 33 02 07 07 > 40 // Command with missing arguments Tx: 40 Rx: Command Not Acceptable > Bye! .SH OPTIONS .IR script Script file with tama commands .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .PP This manual page is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/pn53x-tamashell.1
Roff Manpage
lgpl
2,021
SET(EXAMPLES-SOURCES nfc-anticol nfc-dep-initiator nfc-dep-target nfc-emulate-forum-tag2 nfc-emulate-tag nfc-emulate-uid nfc-mfsetuid nfc-poll nfc-relay ) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../libnfc) # Examples FOREACH(source ${EXAMPLES-SOURCES}) SET (TARGETS ${source}.c) IF(WIN32) SET(RC_COMMENT "${PACKAGE_NAME} example") SET(RC_INTERNAL_NAME ${source}) SET(RC_ORIGINAL_NAME ${source}.exe) SET(RC_FILE_TYPE VFT_APP) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/../contrib/win32/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/../windows/${source}.rc @ONLY) LIST(APPEND TARGETS ${CMAKE_CURRENT_BINARY_DIR}/../windows/${source}.rc) ENDIF(WIN32) ADD_EXECUTABLE(${source} ${TARGETS}) TARGET_LINK_LIBRARIES(${source} nfc) TARGET_LINK_LIBRARIES(${source} nfcutils) INSTALL(TARGETS ${source} RUNTIME DESTINATION bin COMPONENT examples) ENDFOREACH(source) #install required libraries IF(WIN32) INCLUDE(InstallRequiredSystemLibraries) CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/cmake/FixBundle.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FixBundle.cmake @ONLY) INSTALL(SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/FixBundle.cmake) ENDIF(WIN32) IF(NOT WIN32) # Manuals for the examples FILE(GLOB manuals "${CMAKE_CURRENT_SOURCE_DIR}/*.1") INSTALL(FILES ${manuals} DESTINATION ${SHARE_INSTALL_PREFIX}/man/man1 COMPONENT manuals) ENDIF(NOT WIN32)
zzyjames55-nfc0805
examples/CMakeLists.txt
CMake
lgpl
1,393
.TH nfc-anticol 1 "June 26, 2009" "libnfc" "libnfc's examples" .SH NAME nfc-anticol \- Demonstration of NFC anti-collision command line tool based on libnfc .SH SYNOPSIS .B nfc-anticol .SH DESCRIPTION .B nfc-anticol is an anti-collision demonstration tool for ISO/IEC 14443-A tags, performed by custom constructed frames. The first frame must be a short frame which is only 7 bits long. Commercial SDK's often don't support a feature to send frames that are not a multiple of 8 bits (1 byte) long. This makes it impossible to do the anti-collision yourself. The developer has to rely on closed proprietary software and should hope it does not contain vulnerabilities during the anti-collision phase. Performing the anti-collision using custom frames could protect against a malicious tag that, for example, violates the standard by sending frames with unsupported lengths. Note that this is only a demonstration tool, which can not handle multiple tags as real life anti-collisions with multiple tags generate "messy" bits which are neither 0 nor 1. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org> .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-anticol.1
Roff Manpage
lgpl
1,536
.TH nfc-poll 1 "June 26, 2009" "libnfc" "libnfc's examples" .SH NAME nfc-poll \- poll first available NFC target .SH SYNOPSIS .B nfc-poll .SH DESCRIPTION .B nfc-poll is a utility for polling any available target (tags but also NFCIP targets) using ISO14443-A, FeliCa, Jewel and ISO14443-B modulations. This tool uses hardware polling feature if available (ie. PN532) or switch back to software polling, it will display available information retrieved from the tag. .SH OPTIONS .TP .B \-v Tells .I nfc-poll to be verbose and display detailed information about the targets shown. This includes SAK decoding and fingerprinting is available. .SH IMPORTANT There are some well-know limits with this example: - Even with NDO_AUTO_14443_4A enabled (default), .B nfc-poll can miss ATS. That due to the way the PN532 use to poll for ISO14443 type A, it will attempt to find ISO14443-4-only targets, then ISO14443-3. If your ISO14443-4 target is present when PN532 looks for ISO14443-4-only, ATS will be retrieved. But if your target enter the field during ISO14443-3, RATS will not be sent and ATS not retrieved. - .B nfc-poll can show up only one card while two are in field. That's due, again, to the way the PN532 poll for targets. It will stop polling when one modulation got a result, so if you have, for example, one ISO14443-3 (eg. Mifare Ultralight) and one ISO14443-4 (eg. Mifare DESFire), it will probably return only the ISO14443-4. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Romuald Conty <romuald@libnfc.org> .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-poll.1
Roff Manpage
lgpl
1,927
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2011 Adam Laurie * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-mfsetuid.c * @brief Set UID of special Mifare cards */ /** * based on nfc-anticol.c */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #define SAK_FLAG_ATS_SUPPORTED 0x20 #define MAX_FRAME_LEN 264 static uint8_t abtRx[MAX_FRAME_LEN]; static int szRxBits; static uint8_t abtRawUid[12]; static uint8_t abtAtqa[2]; static uint8_t abtSak; static uint8_t abtAts[MAX_FRAME_LEN]; static uint8_t szAts = 0; static size_t szCL = 1;//Always start with Cascade Level 1 (CL1) static nfc_device *pnd; bool quiet_output = false; bool iso_ats_supported = false; // ISO14443A Anti-Collision Commands uint8_t abtReqa[1] = { 0x26 }; uint8_t abtSelectAll[2] = { 0x93, 0x20 }; uint8_t abtSelectTag[9] = { 0x93, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t abtRats[4] = { 0xe0, 0x50, 0x00, 0x00 }; uint8_t abtHalt[4] = { 0x50, 0x00, 0x00, 0x00 }; #define CASCADE_BIT 0x04 // special unlock command uint8_t abtUnlock1[1] = { 0x40 }; uint8_t abtUnlock2[1] = { 0x43 }; uint8_t abtWipe[1] = { 0x41 }; uint8_t abtWrite[4] = { 0xa0, 0x00, 0x5f, 0xb1 }; uint8_t abtData[18] = { 0x01, 0x23, 0x45, 0x67, 0x00, 0x08, 0x04, 0x00, 0x46, 0x59, 0x25, 0x58, 0x49, 0x10, 0x23, 0x02, 0x23, 0xeb }; uint8_t abtBlank[18] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x36, 0xCC }; static bool transmit_bits(const uint8_t *pbtTx, const size_t szTxBits) { // Show transmitted command if (!quiet_output) { printf("Sent bits: "); print_hex_bits(pbtTx, szTxBits); } // Transmit the bit frame command, we don't use the arbitrary parity feature if ((szRxBits = nfc_initiator_transceive_bits(pnd, pbtTx, szTxBits, NULL, abtRx, sizeof(abtRx), NULL)) < 0) return false; // Show received answer if (!quiet_output) { printf("Received bits: "); print_hex_bits(abtRx, szRxBits); } // Succesful transfer return true; } static bool transmit_bytes(const uint8_t *pbtTx, const size_t szTx) { // Show transmitted command if (!quiet_output) { printf("Sent bits: "); print_hex(pbtTx, szTx); } int res; // Transmit the command bytes if ((res = nfc_initiator_transceive_bytes(pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0) return false; // Show received answer if (!quiet_output) { printf("Received bits: "); print_hex(abtRx, res); } // Succesful transfer return true; } static void print_usage(char *argv[]) { printf("Usage: %s [OPTIONS] [UID]\n", argv[0]); printf("Options:\n"); printf("\t-h\tHelp. Print this message.\n"); printf("\t-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("\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("\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"); } int main(int argc, char *argv[]) { int arg, i; bool format = false; unsigned int c; char tmp[3] = { 0x00, 0x00, 0x00 }; // Get commandline options for (arg = 1; arg < argc; arg++) { if (0 == strcmp(argv[arg], "-h")) { print_usage(argv); exit(EXIT_SUCCESS); } else if (0 == strcmp(argv[arg], "-f")) { format = true; } else if (0 == strcmp(argv[arg], "-q")) { quiet_output = true; } else if (strlen(argv[arg]) == 8) { for (i = 0 ; i < 4 ; ++i) { memcpy(tmp, argv[arg] + i * 2, 2); sscanf(tmp, "%02x", &c); abtData[i] = (char) c; } abtData[4] = abtData[0] ^ abtData[1] ^ abtData[2] ^ abtData[3]; iso14443a_crc_append(abtData, 16); } else { ERR("%s is not supported option.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } } nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Try to open the NFC reader pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Error opening NFC reader"); nfc_exit(context); exit(EXIT_FAILURE); } // Initialise NFC device as "initiator" if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Configure the CRC if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Use raw send/receive methods if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Disable 14443-4 autoswitching if (nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC reader: %s opened\n", nfc_device_get_name(pnd)); // Send the 7 bits request command specified in ISO 14443A (0x26) if (!transmit_bits(abtReqa, 7)) { printf("Error: No tag available\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } memcpy(abtAtqa, abtRx, 2); // Anti-collision transmit_bytes(abtSelectAll, 2); // Check answer if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { printf("WARNING: BCC check failed!\n"); } // Save the UID CL1 memcpy(abtRawUid, abtRx, 4); //Prepare and send CL1 Select-Command memcpy(abtSelectTag + 2, abtRx, 5); iso14443a_crc_append(abtSelectTag, 7); transmit_bytes(abtSelectTag, 9); abtSak = abtRx[0]; // Test if we are dealing with a CL2 if (abtSak & CASCADE_BIT) { szCL = 2;//or more // Check answer if (abtRawUid[0] != 0x88) { printf("WARNING: Cascade bit set but CT != 0x88!\n"); } } if (szCL == 2) { // We have to do the anti-collision for cascade level 2 // Prepare CL2 commands abtSelectAll[0] = 0x95; // Anti-collision transmit_bytes(abtSelectAll, 2); // Check answer if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { printf("WARNING: BCC check failed!\n"); } // Save UID CL2 memcpy(abtRawUid + 4, abtRx, 4); // Selection abtSelectTag[0] = 0x95; memcpy(abtSelectTag + 2, abtRx, 5); iso14443a_crc_append(abtSelectTag, 7); transmit_bytes(abtSelectTag, 9); abtSak = abtRx[0]; // Test if we are dealing with a CL3 if (abtSak & CASCADE_BIT) { szCL = 3; // Check answer if (abtRawUid[0] != 0x88) { printf("WARNING: Cascade bit set but CT != 0x88!\n"); } } if (szCL == 3) { // We have to do the anti-collision for cascade level 3 // Prepare and send CL3 AC-Command abtSelectAll[0] = 0x97; transmit_bytes(abtSelectAll, 2); // Check answer if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { printf("WARNING: BCC check failed!\n"); } // Save UID CL3 memcpy(abtRawUid + 8, abtRx, 4); // Prepare and send final Select-Command abtSelectTag[0] = 0x97; memcpy(abtSelectTag + 2, abtRx, 5); iso14443a_crc_append(abtSelectTag, 7); transmit_bytes(abtSelectTag, 9); abtSak = abtRx[0]; } } // Request ATS, this only applies to tags that support ISO 14443A-4 if (abtRx[0] & SAK_FLAG_ATS_SUPPORTED) { iso_ats_supported = true; } printf("\nFound tag with\n UID: "); switch (szCL) { case 1: printf("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]); break; case 2: printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]); break; case 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%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]); break; } printf("\n"); 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 printf(" ATS: "); print_hex(abtAts, szAts); } printf("\n"); // now reset UID iso14443a_crc_append(abtHalt, 2); transmit_bytes(abtHalt, 4); transmit_bits(abtUnlock1, 7); if (format) { transmit_bytes(abtWipe, 1); transmit_bytes(abtHalt, 4); transmit_bits(abtUnlock1, 7); } transmit_bytes(abtUnlock2, 1); transmit_bytes(abtWrite, 4); transmit_bytes(abtData, 18); if (format) { for (i = 3 ; i < 64 ; i += 4) { abtWrite[1] = (char) i; iso14443a_crc_append(abtWrite, 2); transmit_bytes(abtWrite, 4); transmit_bytes(abtBlank, 18); } } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-mfsetuid.c
C
lgpl
11,280
SUBDIRS = pn53x-tamashell-scripts bin_PROGRAMS = \ nfc-anticol \ nfc-dep-initiator \ nfc-dep-target \ nfc-emulate-forum-tag2 \ nfc-emulate-tag \ nfc-emulate-uid \ nfc-mfsetuid \ nfc-poll \ nfc-relay \ pn53x-diagnose \ pn53x-sam if POSIX_ONLY_EXAMPLES_ENABLED bin_PROGRAMS += \ pn53x-tamashell endif check_PROGRAMS = \ quick_start_example1 \ quick_start_example2 # set the include path found by configure AM_CPPFLAGS = $(all_includes) $(LIBNFC_CFLAGS) AM_CFLAGS = -I$(top_srcdir)/libnfc -I$(top_srcdir) nfc_poll_SOURCES = nfc-poll.c nfc_poll_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_anticol_SOURCES = nfc-anticol.c nfc_anticol_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_relay_SOURCES = nfc-relay.c nfc_relay_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_emulate_forum_tag2_SOURCES = nfc-emulate-forum-tag2.c nfc_emulate_forum_tag2_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_emulate_tag_SOURCES = nfc-emulate-tag.c nfc_emulate_tag_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_emulate_uid_SOURCES = nfc-emulate-uid.c nfc_emulate_uid_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_dep_target_SOURCES = nfc-dep-target.c nfc_dep_target_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_dep_initiator_SOURCES = nfc-dep-initiator.c nfc_dep_initiator_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la nfc_mfsetuid_SOURCES = nfc-mfsetuid.c nfc_mfsetuid_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la pn53x_diagnose_SOURCES = pn53x-diagnose.c pn53x_diagnose_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la pn53x_sam_SOURCES = pn53x-sam.c pn53x_sam_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la pn53x_tamashell_SOURCES = pn53x-tamashell.c pn53x_tamashell_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la pn53x_tamashell_LDFLAGS = @READLINE_LIBS@ quick_start_example1_SOURCES = doc/quick_start_example1.c quick_start_example1_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la quick_start_example2_SOURCES = doc/quick_start_example2.c quick_start_example2_LDADD = $(top_builddir)/libnfc/libnfc.la \ $(top_builddir)/utils/libnfcutils.la dist_man_MANS = \ nfc-anticol.1 \ nfc-dep-initiator.1 \ nfc-dep-target.1 \ nfc-emulate-tag.1 \ nfc-emulate-uid.1 \ nfc-poll.1 \ nfc-relay.1 \ nfc-mfsetuid.1 \ pn53x-diagnose.1 \ pn53x-sam.1 \ pn53x-tamashell.1 \ nfc-emulate-forum-tag2.1 EXTRA_DIST = CMakeLists.txt
zzyjames55-nfc0805
examples/Makefile.am
Makefile
lgpl
2,905
.TH pn53x-diagnose 1 "June 15, 2010" "libnfc" "libnfc's examples" .SH NAME pn53x-diagnose \- PN53x diagnose tool .SH SYNOPSIS .B pn53x-diagnose .SH DESCRIPTION .B pn53x-diagnose is a utility to diagnose PN531, PN532 and PN533 chips. It runs communication, RAM and ROM tests. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Romuald Conty <romuald@libnfc.org> .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/pn53x-diagnose.1
Roff Manpage
lgpl
762
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-dep-initiator.c * @brief Turns the NFC device into a D.E.P. initiator (see NFCIP-1) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #define MAX_FRAME_LEN 264 static nfc_device *pnd; static nfc_context *context; static void stop_dep_communication(int sig) { (void) sig; if (pnd != NULL) { nfc_abort_command(pnd); } else { nfc_exit(context); exit(EXIT_FAILURE); } } int main(int argc, const char *argv[]) { nfc_target nt; uint8_t abtRx[MAX_FRAME_LEN]; uint8_t abtTx[] = "Hello World!"; if (argc > 1) { printf("Usage: %s\n", argv[0]); exit(EXIT_FAILURE); } nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Unable to open NFC device."); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC device: %s\n opened", nfc_device_get_name(pnd)); signal(SIGINT, stop_dep_communication); if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (nfc_initiator_select_dep_target(pnd, NDM_PASSIVE, NBR_212, NULL, &nt, 1000) < 0) { nfc_perror(pnd, "nfc_initiator_select_dep_target"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } print_nfc_target(&nt, false); printf("Sending: %s\n", abtTx); int res; if ((res = nfc_initiator_transceive_bytes(pnd, abtTx, sizeof(abtTx), abtRx, sizeof(abtRx), 0)) < 0) { nfc_perror(pnd, "nfc_initiator_transceive_bytes"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } abtRx[res] = 0; printf("Received: %s\n", abtRx); if (nfc_initiator_deselect_target(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_deselect_target"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-dep-initiator.c
C
lgpl
3,925
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file pn53x-diagnose.c * @brief Small application to diagnose PN53x using dedicated commands */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <err.h> #include <stdlib.h> #include <string.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #include "libnfc/chips/pn53x.h" #define MAX_DEVICE_COUNT 16 int main(int argc, const char *argv[]) { size_t i; nfc_device *pnd = NULL; const char *acLibnfcVersion; bool result; uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); const uint8_t pncmd_diagnose_communication_line_test[] = { Diagnose, 0x00, 0x06, 'l', 'i', 'b', 'n', 'f', 'c' }; const uint8_t pncmd_diagnose_rom_test[] = { Diagnose, 0x01 }; const uint8_t pncmd_diagnose_ram_test[] = { Diagnose, 0x02 }; if (argc > 1) { printf("Usage: %s", argv[0]); exit(EXIT_FAILURE); } nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Display libnfc version acLibnfcVersion = nfc_version(); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); nfc_connstring connstrings[MAX_DEVICE_COUNT]; size_t szFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (szFound == 0) { printf("No NFC device found.\n"); } for (i = 0; i < szFound; i++) { int res = 0; pnd = nfc_open(context, connstrings[i]); if (pnd == NULL) { ERR("%s", "Unable to open NFC device."); nfc_exit(context); exit(EXIT_FAILURE); } 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); if (res > 0) { szRx = (size_t) res; // 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) || (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"); } else { 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); if (res > 0) { szRx = (size_t) res; result = ((szRx == 1) && (abtRx[0] == 0x00)); printf(" ROM test: %s\n", result ? "OK" : "Failed"); } else { nfc_perror(pnd, "pn53x_transceive: cannot diagnose ROM"); } res = pn53x_transceive(pnd, pncmd_diagnose_ram_test, sizeof(pncmd_diagnose_ram_test), abtRx, szRx, 0); if (res > 0) { szRx = (size_t) res; result = ((szRx == 1) && (abtRx[0] == 0x00)); printf(" RAM test: %s\n", result ? "OK" : "Failed"); } else { nfc_perror(pnd, "pn53x_transceive: cannot diagnose RAM"); } } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/pn53x-diagnose.c
C
lgpl
4,938
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-emulate-uid.c * @brief Emulates a tag which which have a "really" custom UID * * NFC devices are able to emulate passive tags but manufacturers restrict the * customization of UID. With PN53x, UID is only 4-byte long and the first * byte of emulated UID is hard-wired to 0x08 which is the standard way to say * this is a random UID. This example shows how to emulate a fully customized * UID by "manually" replying to anti-collision process sent by the initiator. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <signal.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #define MAX_FRAME_LEN 264 static uint8_t abtRecv[MAX_FRAME_LEN]; static int szRecvBits; static nfc_device *pnd; static nfc_context *context; // ISO14443A Anti-Collision response uint8_t abtAtqa[2] = { 0x04, 0x00 }; uint8_t abtUidBcc[5] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x22 }; uint8_t abtSak[9] = { 0x08, 0xb6, 0xdd }; static void intr_hdlr(int sig) { (void) sig; if (pnd != NULL) { printf("\nAborting current command...\n"); nfc_abort_command(pnd); } } static void print_usage(char *argv[]) { printf("Usage: %s [OPTIONS] [UID]\n", argv[0]); printf("Options:\n"); printf("\t-h\tHelp. Print this message.\n"); printf("\t-q\tQuiet mode. Silent output: received and sent frames will not be shown (improves timing).\n"); printf("\n"); printf("\t[UID]\tUID to emulate, specified as 8 HEX digits (default is DEADBEEF).\n"); } int main(int argc, char *argv[]) { uint8_t *pbtTx = NULL; size_t szTxBits; bool quiet_output = false; int arg, i; // Get commandline options for (arg = 1; arg < argc; arg++) { if (0 == strcmp(argv[arg], "-h")) { print_usage(argv); exit(EXIT_SUCCESS); } else if (0 == strcmp(argv[arg], "-q")) { printf("Quiet mode.\n"); quiet_output = true; } else if ((arg == argc - 1) && (strlen(argv[arg]) == 8)) { // See if UID was specified as HEX string uint8_t abtTmp[3] = { 0x00, 0x00, 0x00 }; printf("[+] Using UID: %s\n", argv[arg]); abtUidBcc[4] = 0x00; for (i = 0; i < 4; ++i) { memcpy(abtTmp, argv[arg] + i * 2, 2); abtUidBcc[i] = (uint8_t) strtol((char *) abtTmp, NULL, 16); abtUidBcc[4] ^= abtUidBcc[i]; } } else { ERR("%s is not supported option.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } } #ifdef WIN32 signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr); #else signal(SIGINT, intr_hdlr); #endif nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Try to open the NFC device pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Unable to open NFC device"); nfc_exit(context); exit(EXIT_FAILURE); } printf("\n"); 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("[+] 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"); // 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 = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_UNDEFINED, }, .nti = { .nai = { .abtAtqa = { 0x04, 0x00 }, .abtUid = { 0x08, 0xad, 0xbe, 0xef }, .btSak = 0x20, .szUidLen = 4, .szAtsLen = 0, }, }, }; if ((szRecvBits = nfc_target_init(pnd, &nt, abtRecv, sizeof(abtRecv), 0)) < 0) { nfc_perror(pnd, "nfc_target_init"); ERR("Could not come out of auto-emulation, no command was received"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("[+] Received initiator command: "); print_hex_bits(abtRecv, (size_t) szRecvBits); 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)) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("[+] Done, the emulated tag is initialized with UID: %02X%02X%02X%02X\n\n", abtUidBcc[0], abtUidBcc[1], abtUidBcc[2], abtUidBcc[3]); while (true) { // Test if we received a frame if ((szRecvBits = nfc_target_receive_bits(pnd, abtRecv, sizeof(abtRecv), 0)) > 0) { // Prepare the command to send back for the anti-collision request switch (szRecvBits) { case 7: // Request or Wakeup pbtTx = abtAtqa; szTxBits = 16; // New anti-collsion session started if (!quiet_output) printf("\n"); break; case 16: // Select All pbtTx = abtUidBcc; szTxBits = 40; break; case 72: // Select Tag pbtTx = abtSak; szTxBits = 24; break; default: // unknown length? szTxBits = 0; break; } if (!quiet_output) { printf("R: "); print_hex_bits(abtRecv, (size_t) szRecvBits); } // Test if we know how to respond if (szTxBits) { // Send and print the command to the screen if (nfc_target_send_bits(pnd, pbtTx, szTxBits, NULL) < 0) { nfc_perror(pnd, "nfc_target_send_bits"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (!quiet_output) { printf("T: "); print_hex_bits(pbtTx, szTxBits); } } } } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-emulate-uid.c
C
lgpl
7,805
.Dd September 19, 2012 .Dt NFC-EMULATE-FORUM-TAG2 1 URM .Sh NAME .Nm nfc-emulate-forum-tag2 .Nd NFC Forum tag type 2 emulation command line demonstration tool .Sh SYNOPSIS .Nm .Sh DESCRIPTION .Nm is a demonstration tool that emulates a NFC-Forum Tag Type 2 with NDEF content. .Pp Some devices compliant with NFC-Forum Tag Type 2 can be used with this example, in read mode only. .Sh IMPORTANT This example has been developed using PN533 USB hardware as target and Google Nexus S phone as initiator. .Pp This is know to NOT work with Nokia 6212 Classic and could fail with several NFC Forum compliant devices due to the following reasons: .Pp - The emulated target has only a 4-byte UID while most devices assume a Tag Type 2 has always a 7-byte UID (as a real Mifare Ultralight tag); .Pp - The chip is emulating an ISO/IEC 14443-3 tag, without any hardware helper. If the initiator have too strict timeouts for software-based emulation (which is usually the case), this example will fail. This is not a bug and we can't do anything using this hardware (PN531/PN533). .Pp ACR122 devices (like touchatag, etc.) can be used by this example, but if something goes wrong, you will have to unplug/replug your device. This is not a .Em libnfc's bug, this problem is due to ACR122's internal MCU in front of NFC chip (PN532). .Sh BUGS Please report any bugs on the .Em libnfc issue tracker at: .Em http://code.google.com/p/libnfc/issues .Sh LICENCE .Em libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .Em libnfc-utils and .Em libnfc-examples are covered by the BSD 2-Clause license. .Sh AUTHORS .An Roel Verdult Aq roel@libnfc.org .An Romain Tartière Aq romain@libnfc.org .An Romuald Conty Aq romuald@libnfc.org .Pp This manual page was written by Romuald Conty. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-emulate-forum-tag2.1
Roff Manpage
lgpl
1,860
.TH nfc-dep-target 1 "October 8, 2010" "libnfc" "libnfc's examples" .SH NAME nfc-dep-target \- Demonstration tool to send/received data as D.E.P. target .SH SYNOPSIS .B nfc-dep-target .SH DESCRIPTION .B nfc-dep-target is a demonstration tool for putting NFC device in D.E.P. target mode. This example will listen for a D.E.P. initiator and exchange a simple "Hello" data with initiator. Note: this example is designed to work with a D.E.P. initiator driven by \fBnfc-dep-initiator\fP. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org>, .br Romuald Conty <romuald@libnfc.org>. .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-dep-target.1
Roff Manpage
lgpl
1,012
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-relay.c * @brief Relay example using two devices. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <signal.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #define MAX_FRAME_LEN 264 #define MAX_DEVICE_COUNT 2 static uint8_t abtReaderRx[MAX_FRAME_LEN]; static uint8_t abtReaderRxPar[MAX_FRAME_LEN]; static int szReaderRxBits; static uint8_t abtTagRx[MAX_FRAME_LEN]; static uint8_t abtTagRxPar[MAX_FRAME_LEN]; static int szTagRxBits; static nfc_device *pndReader; static nfc_device *pndTag; static bool quitting = false; static void intr_hdlr(int sig) { (void) sig; printf("\nQuitting...\n"); quitting = true; return; } static void print_usage(char *argv[]) { printf("Usage: %s [OPTIONS]\n", argv[0]); printf("Options:\n"); printf("\t-h\tHelp. Print this message.\n"); printf("\t-q\tQuiet mode. Suppress output of READER and EMULATOR data (improves timing).\n"); } int main(int argc, char *argv[]) { int arg; bool quiet_output = false; const char *acLibnfcVersion = nfc_version(); // Get commandline options for (arg = 1; arg < argc; arg++) { if (0 == strcmp(argv[arg], "-h")) { print_usage(argv); exit(EXIT_SUCCESS); } else if (0 == strcmp(argv[arg], "-q")) { quiet_output = true; } else { ERR("%s is not supported option.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } } // Display libnfc version printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); #ifdef WIN32 signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr); #else signal(SIGINT, intr_hdlr); #endif nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } nfc_connstring connstrings[MAX_DEVICE_COUNT]; // List available devices size_t szFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (szFound < 2) { ERR("%" PRIdPTR " device found but two opened devices are needed to relay NFC.", szFound); nfc_exit(context); exit(EXIT_FAILURE); } // Try to open the NFC emulator device pndTag = nfc_open(context, connstrings[0]); if (pndTag == NULL) { ERR("Error opening NFC emulator device"); nfc_exit(context); exit(EXIT_FAILURE); } printf("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n"); 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("[+] 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"); nfc_target nt = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_UNDEFINED, }, .nti = { .nai = { .abtAtqa = { 0x04, 0x00 }, .abtUid = { 0x08, 0xad, 0xbe, 0xef }, .btSak = 0x20, .szUidLen = 4, .szAtsLen = 0, }, }, }; if ((szReaderRxBits = nfc_target_init(pndTag, &nt, abtReaderRx, sizeof(abtReaderRx), 0)) < 0) { ERR("%s", "Initialization of NFC emulator failed"); nfc_close(pndTag); nfc_exit(context); exit(EXIT_FAILURE); } printf("%s", "Configuring emulator settings..."); 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_perror(pndTag, "nfc_device_set_property_bool"); nfc_close(pndTag); nfc_exit(context); exit(EXIT_FAILURE); } printf("%s", "Done, emulated tag is initialized"); // Try to open the NFC reader pndReader = nfc_open(context, connstrings[1]); if (pndReader == NULL) { printf("Error opening NFC reader device\n"); nfc_close(pndTag); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC reader device: %s opened", nfc_device_get_name(pndReader)); printf("%s", "Configuring NFC reader settings..."); if (nfc_initiator_init(pndReader) < 0) { nfc_perror(pndReader, "nfc_initiator_init"); nfc_close(pndTag); nfc_close(pndReader); nfc_exit(context); exit(EXIT_FAILURE); } 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_ACCEPT_INVALID_FRAMES, true)) < 0) { nfc_perror(pndReader, "nfc_device_set_property_bool"); nfc_close(pndTag); nfc_close(pndReader); nfc_exit(context); exit(EXIT_FAILURE); } printf("%s", "Done, relaying frames now!"); while (!quitting) { // Test if we received a frame from the reader 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 if (szReaderRxBits == 7 && abtReaderRx[0] == 0x26) { // Drop down field for a very short time (original tag will reboot) if (nfc_device_set_property_bool(pndReader, NP_ACTIVATE_FIELD, false) < 0) { nfc_perror(pndReader, "nfc_device_set_property_bool"); nfc_close(pndTag); nfc_close(pndReader); nfc_exit(context); exit(EXIT_FAILURE); } if (!quiet_output) printf("\n"); if (nfc_device_set_property_bool(pndReader, NP_ACTIVATE_FIELD, true) < 0) { nfc_perror(pndReader, "nfc_device_set_property_bool"); nfc_close(pndTag); nfc_close(pndReader); nfc_exit(context); exit(EXIT_FAILURE); } } // Print the reader frame to the screen if (!quiet_output) { printf("R: "); print_hex_par(abtReaderRx, (size_t) szReaderRxBits, abtReaderRxPar); } // Forward the frame to the original tag if ((szTagRxBits = nfc_initiator_transceive_bits (pndReader, abtReaderRx, (size_t) szReaderRxBits, abtReaderRxPar, abtTagRx, sizeof(abtTagRx), abtTagRxPar)) > 0) { // Redirect the answer back to the reader if (nfc_target_send_bits(pndTag, abtTagRx, szTagRxBits, abtTagRxPar) < 0) { nfc_perror(pndTag, "nfc_target_send_bits"); nfc_close(pndTag); nfc_close(pndReader); nfc_exit(context); exit(EXIT_FAILURE); } // Print the tag frame to the screen if (!quiet_output) { printf("T: "); print_hex_par(abtTagRx, szTagRxBits, abtTagRxPar); } } } } nfc_close(pndTag); nfc_close(pndReader); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-relay.c
C
lgpl
8,675
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file pn53x-tamashell.c * @brief Configures the NFC device to communicate with a SAM (Secure Access Module). */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H # include <stdio.h> #if defined(HAVE_READLINE) # include <readline/readline.h> # include <readline/history.h> #endif //HAVE_READLINE #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #ifndef _WIN32 # include <time.h> # define msleep(x) do { \ struct timespec xsleep; \ xsleep.tv_sec = x / 1000; \ xsleep.tv_nsec = (x - xsleep.tv_sec * 1000) * 1000 * 1000; \ nanosleep(&xsleep, NULL); \ } while (0) #else # include <winbase.h> # define msleep Sleep #endif #include <nfc/nfc.h> #include "utils/nfc-utils.h" #include "libnfc/chips/pn53x.h" #define MAX_FRAME_LEN 264 int main(int argc, const char *argv[]) { nfc_device *pnd; uint8_t abtRx[MAX_FRAME_LEN]; uint8_t abtTx[MAX_FRAME_LEN]; size_t szRx = sizeof(abtRx); size_t szTx; FILE *input = NULL; if (argc >= 2) { if ((input = fopen(argv[1], "r")) == NULL) { ERR("%s", "Cannot open file."); exit(EXIT_FAILURE); } } nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Try to open the NFC reader pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("%s", "Unable to open NFC device."); if (input != NULL) { fclose(input); } nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC reader: %s opened\n", nfc_device_get_name(pnd)); if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); if (input != NULL) { fclose(input); } nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } const char *prompt = "> "; while (1) { int offset = 0; char *cmd; #if defined(HAVE_READLINE) if (input == NULL) { // means we use stdin cmd = readline(prompt); // NULL if ctrl-d if (cmd == NULL) { printf("Bye!\n"); break; } add_history(cmd); } else { #endif //HAVE_READLINE size_t n = 512; char *ret = NULL; cmd = malloc(n); printf("%s", prompt); fflush(0); if (input != NULL) { ret = fgets(cmd, n, input); } else { ret = fgets(cmd, n, stdin); } if (ret == NULL || strlen(cmd) <= 0) { printf("Bye!\n"); free(cmd); break; } // FIXME print only if read from redirected stdin (i.e. script) printf("%s", cmd); #if defined(HAVE_READLINE) } #endif //HAVE_READLINE if (cmd[0] == 'q') { printf("Bye!\n"); free(cmd); break; } if (cmd[0] == 'p') { int ms = 0; offset++; while (isspace(cmd[offset])) { offset++; } sscanf(cmd + offset, "%10d", &ms); printf("Pause for %i msecs\n", ms); if (ms > 0) { msleep(ms); } free(cmd); continue; } szTx = 0; for (int i = 0; i < MAX_FRAME_LEN; i++) { int size; unsigned int byte; while (isspace(cmd[offset])) { offset++; } size = sscanf(cmd + offset, "%2x", &byte); if (size < 1) { break; } abtTx[i] = byte; szTx++; if (cmd[offset + 1] == 0) { // if last hex was only 1 symbol break; } offset += 2; } if ((int)szTx < 1) { free(cmd); continue; } printf("Tx: "); print_hex(abtTx, szTx); szRx = sizeof(abtRx); int res = 0; if ((res = pn53x_transceive(pnd, abtTx, szTx, abtRx, szRx, 0)) < 0) { free(cmd); nfc_perror(pnd, "Rx"); continue; } szRx = (size_t) res; printf("Rx: "); print_hex(abtRx, szRx); free(cmd); } if (input != NULL) { fclose(input); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/pn53x-tamashell.c
C
lgpl
5,736
.TH pn53x-sam 1 "June 15, 2010" "libnfc" "libnfc's examples" .SH NAME pn53x-sam \- PN53x SAM communication demonstration tool .SH SYNOPSIS .B pn53x-sam .SH DESCRIPTION .B pn53x-sam is a utility attempt to test a simple connection with a SAM (Secure Access Module) in several modes. To run this utility you must have a SAM (like the NXP's P5CN072 chip) successfully connected to your PN53x chip. Warning: the SAM inside a Touchatag/ACR122U is \fInot\fP hooked to the PN532 but to the intermediate controller so \fBpn53x-sam\fP won't work with a Touchatag/ACR122U. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Emanuele Bertoldi <emanuele.bertoldi@gmail.com> .PP This manual page was written by Emanuele Bertoldi <emanuele.bertoldi@gmail.com>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/pn53x-sam.1
Roff Manpage
lgpl
1,079
.TH nfc-mfsetuid 1 "Sep 05, 2011" "libnfc" "NFC Utilities" .SH NAME nfc-mfsetuid \- MIFARE 1K special card UID setting and recovery tool .SH SYNOPSIS .B nfc-mfsetuid [ .I UID ] .SH DESCRIPTION .B nfc-mfsetuid is a MIFARE tool that allows setting of UID on special versions (Chinese clones) of Mifare 1K cards. It will also recover damaged cards that have had invalid data written to block 0 (e.g. wrong BCC). Currently only 4 Byte UID is supported. Specify an eight hex character UID or leave blank for the default '01234567'. .SH OPTIONS .B -f Format. Wipe all data (set to 0xFF) and reset ACLs to defaults. .B -q Quiet. Suppress output of commands and responses. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Adam Laurie <adam@algroup.co.uk> .PP This manual page was written by Adam Laurie <adam@algroup.co.uk>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-mfsetuid.1
Roff Manpage
lgpl
1,150
/** * @file quick_start_example2.c * @brief Quick start example that presents how to use libnfc */ // This is same example as quick_start_example1.c but using // some helper functions existing in libnfc. // Those functions are not available yet in a library // so binary object must be linked statically: // $ gcc -o quick_start_example2 -lnfc -I../.. quick_start_example2.c ../../utils/nfc-utils.o #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdlib.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" int main(int argc, const char *argv[]) { nfc_device *pnd; nfc_target nt; // Allocate only a pointer to nfc_context nfc_context *context; // Initialize libnfc and set the nfc_context nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Display libnfc version const char *acLibnfcVersion = nfc_version(); (void)argc; printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); // Open, using the first available NFC device which can be in order of selection: // - default device specified using environment variable or // - first specified device in libnfc.conf (/etc/nfc) or // - first specified device in device-configuration directory (/etc/nfc/devices.d) or // - first auto-detected (if feature is not disabled in libnfc.conf) device pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("%s", "Unable to open NFC device."); exit(EXIT_FAILURE); } // Set opened NFC device to initiator mode if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); exit(EXIT_FAILURE); } printf("NFC reader: %s opened\n", nfc_device_get_name(pnd)); // Poll for a ISO14443A (MIFARE) tag const nfc_modulation nmMifare = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) { printf("The following (NFC) ISO14443A tag was found:\n"); printf(" ATQA (SENS_RES): "); print_hex(nt.nti.nai.abtAtqa, 2); printf(" UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1')); print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen); printf(" SAK (SEL_RES): "); print_hex(&nt.nti.nai.btSak, 1); if (nt.nti.nai.szAtsLen) { printf(" ATS (ATR): "); print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen); } } // Close NFC device nfc_close(pnd); // Release the context nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/doc/quick_start_example2.c
C
lgpl
2,529
/** * @file quick_start_example1.c * @brief Quick start example that presents how to use libnfc */ // To compile this simple example: // $ gcc -o quick_start_example1 quick_start_example1.c -lnfc #include <stdlib.h> #include <nfc/nfc.h> static void print_hex(const uint8_t *pbtData, const size_t szBytes) { size_t szPos; for (szPos = 0; szPos < szBytes; szPos++) { printf("%02x ", pbtData[szPos]); } printf("\n"); } int main(int argc, const char *argv[]) { nfc_device *pnd; nfc_target nt; // Allocate only a pointer to nfc_context nfc_context *context; // Initialize libnfc and set the nfc_context nfc_init(&context); if (context == NULL) { printf("Unable to init libnfc (malloc)\n"); exit(EXIT_FAILURE); } // Display libnfc version const char *acLibnfcVersion = nfc_version(); (void)argc; printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); // Open, using the first available NFC device which can be in order of selection: // - default device specified using environment variable or // - first specified device in libnfc.conf (/etc/nfc) or // - first specified device in device-configuration directory (/etc/nfc/devices.d) or // - first auto-detected (if feature is not disabled in libnfc.conf) device pnd = nfc_open(context, NULL); if (pnd == NULL) { printf("ERROR: %s", "Unable to open NFC device."); exit(EXIT_FAILURE); } // Set opened NFC device to initiator mode if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); exit(EXIT_FAILURE); } printf("NFC reader: %s opened\n", nfc_device_get_name(pnd)); // Poll for a ISO14443A (MIFARE) tag const nfc_modulation nmMifare = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) { printf("The following (NFC) ISO14443A tag was found:\n"); printf(" ATQA (SENS_RES): "); print_hex(nt.nti.nai.abtAtqa, 2); printf(" UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1')); print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen); printf(" SAK (SEL_RES): "); print_hex(&nt.nti.nai.btSak, 1); if (nt.nti.nai.szAtsLen) { printf(" ATS (ATR): "); print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen); } } // Close NFC device nfc_close(pnd); // Release the context nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/doc/quick_start_example1.c
C
lgpl
2,439
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-poll.c * @brief Polling example */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <err.h> #include <inttypes.h> #include <signal.h> #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <nfc/nfc.h> #include <nfc/nfc-types.h> #include "utils/nfc-utils.h" #define MAX_DEVICE_COUNT 16 static nfc_device *pnd = NULL; static nfc_context *context; static void stop_polling(int sig) { (void) sig; if (pnd != NULL) nfc_abort_command(pnd); else { nfc_exit(context); exit(EXIT_FAILURE); } } static void print_usage(const char *progname) { printf("usage: %s [-v]\n", progname); printf(" -v\t verbose display\n"); } int main(int argc, const char *argv[]) { bool verbose = false; signal(SIGINT, stop_polling); // Display libnfc version const char *acLibnfcVersion = nfc_version(); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); if (argc != 1) { if ((argc == 2) && (0 == strcmp("-v", argv[1]))) { verbose = true; } else { print_usage(argv[0]); exit(EXIT_FAILURE); } } const uint8_t uiPollNr = 20; const uint8_t uiPeriod = 2; const nfc_modulation nmModulations[5] = { { .nmt = NMT_ISO14443A, .nbr = NBR_106 }, { .nmt = NMT_ISO14443B, .nbr = NBR_106 }, { .nmt = NMT_FELICA, .nbr = NBR_212 }, { .nmt = NMT_FELICA, .nbr = NBR_424 }, { .nmt = NMT_JEWEL, .nbr = NBR_106 }, }; const size_t szModulations = 5; nfc_target nt; int res = 0; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("%s", "Unable to open NFC device."); nfc_exit(context); exit(EXIT_FAILURE); } if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } 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 %" PRIdPTR " 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) { nfc_perror(pnd, "nfc_initiator_poll_target"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (res > 0) { print_nfc_target(&nt, verbose); } else { printf("No target found.\n"); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-poll.c
C
lgpl
4,439
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-emulate-forum-tag2.c * @brief Emulates a NFC-Forum Tag Type 2 with a NDEF message * This example allow to emulate an NFC-Forum Tag Type 2 that contains * a read-only NDEF message. * * This example has been developed using PN533 USB hardware as target and * Google Nexus S phone as initiator. * * This is know to NOT work with Nokia 6212 Classic and could fail with * several NFC Forum compliant devices due to the following reasons: * - The emulated target has only a 4-byte UID while most devices assume a Tag * Type 2 has always a 7-byte UID (as a real Mifare Ultralight tag); * - The chip is emulating an ISO/IEC 14443-3 tag, without any hardware helper. * If the initiator has too strict timeouts for software-based emulation * (which is usually the case), this example will fail. This is not a bug * and we can't do anything using this hardware (PN531/PN533). */ /* * This implementation was written based on information provided by the * following documents: * * NFC Forum Type 2 Tag Operation * Technical Specification * NFCForum-TS-Type-2-Tag_1.0 - 2007-07-09 * * ISO/IEC 14443-3 * First edition - 2001-02-01 * Identification cards — Contactless integrated circuit(s) cards — Proximity cards * Part 3: Initialization and anticollision */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <errno.h> #include <signal.h> #include <stdlib.h> #include <nfc/nfc.h> #include <nfc/nfc-emulation.h> #include "utils/nfc-utils.h" static nfc_device *pnd; static nfc_context *context; static void stop_emulation(int sig) { (void)sig; if (pnd != NULL) { nfc_abort_command(pnd); } else { nfc_exit(context); exit(EXIT_FAILURE); } } static uint8_t __nfcforum_tag2_memory_area[] = { 0x00, 0x00, 0x00, 0x00, // Block 0 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, // Block 2 (Static lock bytes: CC area and data area are read-only locked) 0xE1, 0x10, 0x06, 0x0F, // Block 3 (CC - NFC-Forum Tag Type 2 version 1.0, Data area (from block 4 to the end) is 48 bytes, Read-only mode) 0x03, 33, 0xd1, 0x02, // Block 4 (NDEF) 0x1c, 0x53, 0x70, 0x91, 0x01, 0x09, 0x54, 0x02, 0x65, 0x6e, 0x4c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0x51, 0x01, 0x0b, 0x55, 0x03, 0x6c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0x2e, 0x6f, 0x72, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; #define READ 0x30 #define WRITE 0xA2 #define SECTOR_SELECT 0xC2 #define HALT 0x50 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) { int res = 0; uint8_t *nfcforum_tag2_memory_area = (uint8_t *)(emulator->user_data); printf(" In: "); print_hex(data_in, data_in_len); switch (data_in[0]) { case READ: if (data_out_len >= 16) { memcpy(data_out, nfcforum_tag2_memory_area + (data_in[1] * 4), 16); res = 16; } else { res = -ENOSPC; } break; case HALT: printf("HALT sent\n"); res = -ECONNABORTED; break; default: printf("Unknown command: 0x%02x\n", data_in[0]); res = -ENOTSUP; } if (res < 0) { ERR("%s (%d)", strerror(-res), -res); } else { printf(" Out: "); print_hex(data_out, res); } return res; } int main(int argc, char *argv[]) { (void)argc; (void)argv; nfc_target nt = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_UNDEFINED, // Will be updated by nfc_target_init() }, .nti = { .nai = { .abtAtqa = { 0x00, 0x04 }, .abtUid = { 0x08, 0x00, 0xb0, 0x0b }, .szUidLen = 4, .btSak = 0x00, .szAtsLen = 0, }, } }; struct nfc_emulation_state_machine state_machine = { .io = nfcforum_tag2_io }; struct nfc_emulator emulator = { .target = &nt, .state_machine = &state_machine, .user_data = __nfcforum_tag2_memory_area, }; signal(SIGINT, stop_emulation); nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Unable to open NFC device"); nfc_exit(context); exit(EXIT_FAILURE); } 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"); if (nfc_emulate_target(pnd, &emulator, 0) < 0) { nfc_perror(pnd, argv[0]); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-emulate-forum-tag2.c
C
lgpl
6,479
.TH nfc-dep-initiator 1 "October 8, 2010" "libnfc" "libnfc's examples" .SH NAME nfc-dep-initiator \- Demonstration tool to send/received data as D.E.P. initiator .SH SYNOPSIS .B nfc-dep-initiator .SH DESCRIPTION .B nfc-dep-initiator is a demonstration tool for putting NFC device in D.E.P. initiator mode. This example will attempt to select a passive D.E.P. target and exchange a simple "Hello" data with target. Note: this example is designed to work with a D.E.P. target driven by \fBnfc-dep-target\fP .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org>, .br Romuald Conty <romuald@libnfc.org>. .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-dep-initiator.1
Roff Manpage
lgpl
1,032
02; Get firmware version // Create NFC-Forum tag type2 with URL // WARNING It burns the OTP bits of sector 3!! // PLEASE PUT ULTRALIGHT TAG NOW 4A 01 00; 1 target requested // Clear memory from address 0x04 40 01 A2 04 00 00 00 00; Write 4 bytes from address 0x04 40 01 A2 05 00 00 00 00; Write 4 bytes from address 0x05 40 01 A2 06 00 00 00 00; Write 4 bytes from address 0x06 40 01 A2 07 00 00 00 00; Write 4 bytes from address 0x07 40 01 A2 08 00 00 00 00; Write 4 bytes from address 0x08 40 01 A2 09 00 00 00 00; Write 4 bytes from address 0x09 40 01 A2 0A 00 00 00 00; Write 4 bytes from address 0x0A 40 01 A2 0B 00 00 00 00; Write 4 bytes from address 0x0B 40 01 A2 0C 00 00 00 00; Write 4 bytes from address 0x0C // Read memory content from address 4 40 01 30 04; Read 16 bytes from address 0x04 40 01 30 08; Read 16 bytes from address 0x08 40 01 30 0C; Read 16 bytes from address 0x0C // cf NFC-Forum Type 1 Tag Operation Specification TS // Write @ address 0x03 (OTP): NDEF, v1.0, 48 bytes, RW 40 01 A2 03 E1 10 06 00; // Write @ address 0x04: NDEF TLV, 15 bytes,... // cf NFC-Forum NFC Data Exchange Format (NDEF) TS // ...,MB,ME,SR,TNF=1 (wkt), typeL=1 byte 40 01 A2 04 03 0F D1 01; // Write @ address 0x05: payloadL=11 bytes,... // cf NFC-Forum NFC Record Type Definition (RTD) TS // ...,type=urn:nfc:wkt:U = URI // cf NFC-Forum URI Record Type Definition TS // ...,01=>URI id code=http://www. // ...,"l" 40 01 A2 05 0B 55 01 6C; // Write @ address 0x06: "ibnf" 40 01 A2 06 69 62 6E 66; // Write @ address 0x07: "c.or" 40 01 A2 07 63 2E 6F 72; // Write @ address 0x08: "g",TLV:FE 40 01 A2 08 67 FE 00 00; // Read memory content from address 4 40 01 30 04; Read 16 bytes from address 0x04 40 01 30 08; Read 16 bytes from address 0x08 40 01 30 0C; Read 16 bytes from address 0x0C
zzyjames55-nfc0805
examples/pn53x-tamashell-scripts/UltraLightReadWrite.cmd
Batchfile
lgpl
2,229
#!/bin/sh ID=$(cat << EOF | \ pn53x-tamashell |\ grep -A1 "^Tx: 42 01 0b 3f 80" |\ sed -e '1d' -e "s/^Rx: 00 .. .. \(.. .. .. ..\).*/\1/" -e 's/ //g' # Timeouts 3205000002 # ListTarget ModeB 4a010300 # TypeB' APGEN 42010b3f80 EOF ) if [ -z "$ID" ]; then echo "Error: I was not abble to read Navigo ID" >&2 exit 1 fi cat << EOF | \ pn53x-tamashell |\ awk '\ /^> #.*:/{ sub(/^> #/,"") n=$0 for (i=0;i<8-length();i++) { n= n " " } getline getline getline sub(/Rx: 00/,"") gsub(/ +/," ") sub(/ 90 00 $/,"") print n toupper($0)}' # Timeouts 3205000002 # ListTarget ModeB 4a010300 # TypeB' 42010b3f80 # timings... 3202010b0c # TypeB' ATTRIB 42 01 0f $ID # Select ICC file 42 01 04 0a 00a4 0800 04 3f00 0002 #ICC: 42 01 06 06 00b2 0104 1d # Select EnvHol file 42 01 08 0a 00a4 0800 04 2000 2001 #EnvHol1: 42 01 0a 06 00b2 0104 1d # Select EvLog file 42 01 0c 0a 00a4 0800 04 2000 2010 #EvLog1: 42 01 0e 06 00b2 0104 1d #EvLog2: 42 01 00 06 00b2 0204 1d #EvLog3: 42 01 02 06 00b2 0304 1d # Select ConList file 42 01 04 0a 00a4 0800 04 2000 2050 #ConList: 42 01 06 06 00b2 0104 1d # Select Contra file 42 01 08 0a 00a4 0800 04 2000 2020 #Contra1: 42 01 0a 06 00b2 0104 1d #Contra2: 42 01 0c 06 00b2 0204 1d #Contra3: 42 01 0e 06 00b2 0304 1d #Contra4: 42 01 00 06 00b2 0404 1d # Select Counter file 42 01 02 0a 00a4 0800 04 2000 2069 #Counter: 42 01 04 06 00b2 0104 1d # Select SpecEv file 42 01 06 0a 00a4 08 0004 2000 2040 #SpecEv1: 42 01 08 06 00b2 0104 1d # TypeB' Disconnect 42 01 03 EOF
zzyjames55-nfc0805
examples/pn53x-tamashell-scripts/ReadNavigo.sh
Shell
lgpl
1,690
#!/bin/sh cat << EOF | \ pn53x-tamashell |\ awk '\ /^> #.*:/{ sub(/^> #/,"") n=$0 for (i=0;i<8-length();i++) { n= n " " } getline getline getline sub(/Rx: 00/,"") gsub(/ +/," ") sub(/ 90 00 $/,"") print n toupper($0)}' |\ grep -v ": 6A 83" # Select one typeB target 4A010300 # Select ICC file 4001 80a4 0800 04 3f00 0002 #ICC: 4001 80b2 0104 1d # Select Holder file 4001 80a4 0800 04 3f00 3f1c #Holder1: 4001 80b2 0104 1d #Holder2: 4001 80b2 0204 1d # Select EnvHol file 4001 00a4 0800 04 2000 2001 #EnvHol1: 4001 00b2 0104 1d #EnvHol2: 4001 00b2 0204 1d # Select EvLog file 4001 00a4 0800 04 2000 2010 #EvLog1: 4001 00b2 0104 1d #EvLog2: 4001 00b2 0204 1d #EvLog3: 4001 00b2 0304 1d # Select ConList file 4001 00a4 0800 04 2000 2050 #ConList: 4001 00b2 0104 1d # Select Contra file 4001 00a4 0800 04 2000 2020 #Contra1: 4001 00b2 0104 1d #Contra2: 4001 00b2 0204 1d #Contra3: 4001 00b2 0304 1d #Contra4: 4001 00b2 0404 1d #Contra5: 4001 00b2 0504 1d #Contra6: 4001 00b2 0604 1d #Contra7: 4001 00b2 0704 1d #Contra8: 4001 00b2 0804 1d #Contra9: 4001 00b2 0904 1d #ContraA: 4001 00b2 0a04 1d #ContraB: 4001 00b2 0b04 1d #ContraC: 4001 00b2 0c04 1d # Select Counter file 4001 00a4 0800 04 2000 2069 #Counter: 4001 00b2 0104 1d # Select LoadLog file 4001 00a4 0800 04 1000 1014 #LoadLog: 4001 00b2 0104 1d # Select Purcha file 4001 00a4 08 0004 1000 1015 #Purcha1: 4001 00b2 0104 1d #Purcha2: 4001 00b2 0204 1d #Purcha3: 4001 00b2 0304 1d # Select SpecEv file 4001 00a4 08 0004 2000 2040 #SpecEv1: 4001 00b2 0104 1d #SpecEv2: 4001 00b2 0204 1d #SpecEv3: 4001 00b2 0304 1d #SpecEv4: 4001 00b2 0404 1d EOF
zzyjames55-nfc0805
examples/pn53x-tamashell-scripts/ReadMobib.sh
Shell
lgpl
1,783
EXTRA_DIST = \ ReadMobib.sh \ ReadNavigo.sh \ UltraLightRead.cmd \ UltraLightReadWrite.cmd
zzyjames55-nfc0805
examples/pn53x-tamashell-scripts/Makefile.am
Makefile
lgpl
95
# To be used only on ASK LoGO readers!!! # As we don't know how GPIO can be wired, it may hurt your hardware!!! # P32=0 LED1 # P34=0 progressive field off # SFR_P3: 0x..101011 08 ff b0 2b p 100 # P32=0 LED1 # P31=0 LED2 # SFR_P3: 0x..101001 08 ff b0 29 p 100 # P32=0 LED1 # P31=0 LED2 # P30=0 P33=0 LED3 # SFR_P3: 0x..100000 08 ff b0 20 p 100 # P32=0 LED1 # P31=0 LED2 # P30=0 P33=0 LED3 # P35=0 LED4 # SFR_P3: 0x..000000 08 ff b0 00 p 100 # P32=0 LED1 # P31=0 LED2 # P30=0 P33=0 LED3 # SFR_P3: 0x..100000 08 ff b0 20 p 100 # P32=0 LED1 # P31=0 LED2 # SFR_P3: 0x..101001 08 ff b0 29 p 100 # P32=0 LED1 # SFR_P3: 0x..101011 08 ff b0 2b p 100 # P32=0 LED1 # SFR_P3: 0x..101011 08 ff b0 2b
zzyjames55-nfc0805
examples/pn53x-tamashell-scripts/ASK_LoGO_LEDs.cmd
Batchfile
lgpl
734
02; // Get firmware version // Reads content of a Mifare UltraLight // PLEASE PUT ULTRALIGHT TAG NOW 4A 01 00; // 1 target requested // Read memory content from address 4 40 01 30 00; Read 16 bytes from address 0x00 40 01 30 04; Read 16 bytes from address 0x04 40 01 30 08; Read 16 bytes from address 0x08 40 01 30 0C; Read 16 bytes from address 0x0C
zzyjames55-nfc0805
examples/pn53x-tamashell-scripts/UltraLightRead.cmd
Batchfile
lgpl
492
.TH nfc-relay 1 "June 26, 2009" "libnfc" "libnfc'examples" .SH NAME nfc-relay \- Relay attack command line tool based on libnfc .SH SYNOPSIS .B nfc-relay .SH DESCRIPTION .B nfc-relay is a utility that demonstrates a relay attack. This tool requires two NFC devices. One device (configured as target) will emulate an ISO/IEC 14443 type A tag, while the second device (configured as initiator) will act as a reader. The genuine tag can be placed on the second device (initiator) and the tag emulator (target) can be placed close to the original reader. All communication is now relayed and shown in the screen on real-time. This tool has the same issues regarding timing as \fBnfc-emulate-uid\fP has, therefore we advise you to try it against e.g. an OmniKey CardMan 5321 reader. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org> .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-relay.1
Roff Manpage
lgpl
1,263
.TH nfc-emulate-tag 1 "October 8, 2010" "libnfc" "libnfc's examples" .SH NAME nfc-emulate-tag \- Simple tag emulation command line demonstration tool .SH SYNOPSIS .B nfc-emulate-tag .SH DESCRIPTION .B nfc-emulate-tag is a simple tag emulation tool that demonstrates how emulation can be done using libnfc. Currently, this tool partially emulates a Mifare Mini: it is detected as Mifare Mini but internal MIFARE proprietary commands are not yet implemented. To be able to emulate a target, there are two main parts: - communication: handle modulation, anticollision, etc. - computation: process commands (input) and produce results (output). This demonstration tool proposes a logical structure to handle communication and a simple function to deal with computation. To improve the target capabilities, we can now implement more allowed commands in a single function: target_io() Please note that, due to timing issues, it is very difficult to implement an ISO14443-4 tag this way: RATS request expects a quick ATS answer. By the way, even if you implement another kind of tag, timing issues are often the source of problems like CRC or parity errors. The OmniKey CardMan 5321 is known to be very large on timings and is a good choice if you want to experiment with this emulator with a tolerant reader. .SH IMPORTANT ACR122 devices (like touchatag, etc.) can be used by this example (with probably timing issue), but if something goes wrong, you will have to unplug/replug your device. This is not a .B libnfc's bug, this problem is due to ACR122's internal MCU in front of NFC chip (PN532). .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Romuald Conty <romuald@libnfc.org> .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-emulate-tag.1
Roff Manpage
lgpl
2,086
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-dep-target.c * @brief Turns the NFC device into a D.E.P. target (see NFCIP-1) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #define MAX_FRAME_LEN 264 static nfc_device *pnd; static nfc_context *context; static void stop_dep_communication(int sig) { (void) sig; if (pnd != NULL) { nfc_abort_command(pnd); } else { nfc_exit(context); exit(EXIT_FAILURE); } } int main(int argc, const char *argv[]) { uint8_t abtRx[MAX_FRAME_LEN]; int szRx; uint8_t abtTx[] = "Hello Mars!"; if (argc > 1) { printf("Usage: %s\n", argv[0]); exit(EXIT_FAILURE); } nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } #define MAX_DEVICE_COUNT 2 nfc_connstring connstrings[MAX_DEVICE_COUNT]; size_t szDeviceFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); // Little hack to allow using nfc-dep-initiator & nfc-dep-target from // the same machine: if there is more than one readers opened // nfc-dep-target will open the second reader // (we hope they're always detected in the same order) if (szDeviceFound == 1) { pnd = nfc_open(context, connstrings[0]); } else if (szDeviceFound > 1) { pnd = nfc_open(context, connstrings[1]); } else { printf("No device found.\n"); nfc_exit(context); exit(EXIT_FAILURE); } nfc_target nt = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xff, 0x00, 0x00 }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_UNDEFINED, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, }, }; if (pnd == NULL) { printf("Unable to open NFC device.\n"); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC device: %s opened\n", nfc_device_get_name(pnd)); signal(SIGINT, stop_dep_communication); printf("NFC device will now act as: "); print_nfc_target(&nt, false); printf("Waiting for initiator request...\n"); if ((szRx = nfc_target_init(pnd, &nt, abtRx, sizeof(abtRx), 0)) < 0) { nfc_perror(pnd, "nfc_target_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("Initiator request received. Waiting for data...\n"); if ((szRx = nfc_target_receive_bytes(pnd, abtRx, sizeof(abtRx), 0)) < 0) { nfc_perror(pnd, "nfc_target_receive_bytes"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } abtRx[(size_t) szRx] = '\0'; printf("Received: %s\n", abtRx); printf("Sending: %s\n", abtTx); if (nfc_target_send_bytes(pnd, abtTx, sizeof(abtTx), 0) < 0) { nfc_perror(pnd, "nfc_target_send_bytes"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("Data sent.\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-dep-target.c
C
lgpl
5,031
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-emulate-tag.c * @brief Emulates a simple tag */ // Note that depending on the device (initiator) you'll use against, this // emulator it might work or not. Some readers are very strict on responses // timings, e.g. a Nokia NFC and will drop communication too soon for us. #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <signal.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #define MAX_FRAME_LEN (264) #define SAK_ISO14443_4_COMPLIANT 0x20 static uint8_t abtRx[MAX_FRAME_LEN]; static int szRx; static nfc_context *context; static nfc_device *pnd; static bool quiet_output = false; static bool init_mfc_auth = false; static void intr_hdlr(int sig) { (void) sig; printf("\nQuitting...\n"); if (pnd != NULL) { nfc_abort_command(pnd); } nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } static bool target_io(nfc_target *pnt, const uint8_t *pbtInput, const size_t szInput, uint8_t *pbtOutput, size_t *pszOutput) { bool loop = true; *pszOutput = 0; // Show transmitted command if (!quiet_output) { printf(" In: "); print_hex(pbtInput, szInput); } if (szInput) { switch (pbtInput[0]) { case 0x30: // Mifare read // block address is in pbtInput[1] *pszOutput = 15; strcpy((char *)pbtOutput, "You read block "); pbtOutput[15] = pbtInput[1]; break; case 0x50: // HLTA (ISO14443-3) if (!quiet_output) { printf("Initiator HLTA me. Bye!\n"); } loop = false; break; case 0x60: // Mifare authA case 0x61: // Mifare authB // Let's give back a very random nonce... *pszOutput = 2; pbtOutput[0] = 0x12; pbtOutput[1] = 0x34; // Next commands will be without CRC init_mfc_auth = true; break; case 0xe0: // RATS (ISO14443-4) // Send ATS *pszOutput = pnt->nti.nai.szAtsLen + 1; pbtOutput[0] = pnt->nti.nai.szAtsLen + 1; // ISO14443-4 says that ATS contains ATS_Length as first byte if (pnt->nti.nai.szAtsLen) { memcpy(pbtOutput + 1, pnt->nti.nai.abtAts, pnt->nti.nai.szAtsLen); } break; case 0xc2: // S-block DESELECT if (!quiet_output) { printf("Initiator DESELECT me. Bye!\n"); } loop = false; break; default: // Unknown if (!quiet_output) { printf("Unknown frame, emulated target abort.\n"); } loop = false; } } // Show transmitted command if ((!quiet_output) && *pszOutput) { printf(" Out: "); print_hex(pbtOutput, *pszOutput); } return loop; } static bool nfc_target_emulate_tag(nfc_device *dev, nfc_target *pnt) { size_t szTx; uint8_t abtTx[MAX_FRAME_LEN]; bool loop = true; if ((szRx = nfc_target_init(dev, pnt, abtRx, sizeof(abtRx), 0)) < 0) { nfc_perror(dev, "nfc_target_init"); return false; } while (loop) { loop = target_io(pnt, abtRx, (size_t) szRx, abtTx, &szTx); if (szTx) { if (nfc_target_send_bytes(dev, abtTx, szTx, 0) < 0) { nfc_perror(dev, "nfc_target_send_bytes"); return false; } } if (loop) { if (init_mfc_auth) { nfc_device_set_property_bool(dev, NP_HANDLE_CRC, false); init_mfc_auth = false; } if ((szRx = nfc_target_receive_bytes(dev, abtRx, sizeof(abtRx), 0)) < 0) { nfc_perror(dev, "nfc_target_receive_bytes"); return false; } } } return true; } int main(int argc, char *argv[]) { (void) argc; const char *acLibnfcVersion; #ifdef WIN32 signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr); #else signal(SIGINT, intr_hdlr); #endif nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Display libnfc version acLibnfcVersion = nfc_version(); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); // Try to open the NFC reader pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Unable to open NFC device"); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC device: %s opened\n", nfc_device_get_name(pnd)); // Notes for ISO14443-A emulated tags: // * Only short UIDs are supported // If your UID is longer it will be truncated // Therefore e.g. an UltraLight can only have short UID, which is // typically badly handled by readers who still try to send their "0x95" // * First byte of UID will be masked by 0x08 by the PN53x firmware // as security countermeasure against real UID emulation // Example of a Mifare Classic Mini // Note that crypto1 is not implemented in this example nfc_target nt = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_UNDEFINED, }, .nti = { .nai = { .abtAtqa = { 0x00, 0x04 }, .abtUid = { 0x08, 0xab, 0xcd, 0xef }, .btSak = 0x09, .szUidLen = 4, .szAtsLen = 0, }, }, }; /* // Example of a FeliCa nfc_target nt = { .nm = { .nmt = NMT_FELICA, .nbr = NBR_UNDEFINED, }, .nti = { .nfi = { .abtId = { 0x01, 0xFE, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xFF }, .abtPad = { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xFF }, .abtSysCode = { 0xFF, 0xFF }, }, }, }; */ /* // Example of a ISO14443-4 (DESfire) nfc_target nt = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_UNDEFINED, }, .nti = { .nai = { abtAtqa = { 0x03, 0x44 }, abtUid = { 0x08, 0xab, 0xcd, 0xef }, btSak = 0x20, .szUidLen = 4, .abtAts = { 0x75, 0x77, 0x81, 0x02, 0x80 }, .szAtsLen = 5, }, }, }; */ printf("%s will emulate this ISO14443-A tag:\n", argv[0]); print_nfc_target(&nt, true); // 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)); 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)) { nfc_perror(pnd, "nfc_target_emulate_tag"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-emulate-tag.c
C
lgpl
8,277
.TH nfc-emulate-uid 1 "June 26, 2009" "libnfc" "libnfc's examples" .SH NAME nfc-emulate-uid \- NFC target emulation command line tool based on libnfc .SH SYNOPSIS .B nfc-emulate-uid .RI [ OPTIONS ] .RI [ UID ] .SH DESCRIPTION .B nfc-emulate-uid is a tag emulation tool that allows one to choose any tag UID. Tag emulation is one of the main added features in NFC. But to avoid abuse of existing systems, manufacturers of the NFC controller intentionally did not support emulation of fully customized UID but only of "random" UIDs, which always start with 0x08. The nfc-emulate-uid tool demonstrates that this can still be done using transmission of raw frames, and the desired UID can be optionally specified. This makes it a serious thread for security systems that rely only on the uniqueness of the UID. Unfortunately, this example can't directly start in fully customisable target mode. Just after launching this example, you will have to go through the hardcoded initial anti-collision with the 0x08-prefixed UID. To achieve it, you can e.g. send a RATS (Request for Answer To Select) command by using a second NFC device (placed in target's field) and launching nfc-list or nfc-anticol. After this first step, you now have a NFC device (configured as target) that really emulates a custom UID. You could view it using the second NFC device with nfc-list. Timing control is very important for a successful anti-collision sequence: - The emulator must be very fast to react: Using the ACR122 device gives many timing issues, "PN53x only" USB devices also give some timing issues but an embedded microprocessor would probably improve greatly the situation. - The reader should not be too strict on timing (the standard is very strict). The OmniKey CardMan 5321 is known to be very large on timings and is a good choice if you want to experiment with this emulator with a tolerant reader. Nokia NFC 6212 and Pegoda readers are much too strict and won't be fooled. .SH OPTIONS .IR UID 8 hex digits format that represents desired UID (default is DEADBEEF). .SH IMPORTANT ACR122 devices (like touchatag, etc.) can be used by this example (with timing issues), but if something goes wrong, you will have to unplug/replug your device. This is not a .B libnfc's bug, this problem is due to ACR122's internal MCU in front of NFC chip (PN532). .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org> .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
examples/nfc-emulate-uid.1
Roff Manpage
lgpl
2,828
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-anticol.c * @brief Generates one ISO14443-A anti-collision process "by-hand" */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <nfc/nfc.h> #include "utils/nfc-utils.h" #define SAK_FLAG_ATS_SUPPORTED 0x20 #define MAX_FRAME_LEN 264 static uint8_t abtRx[MAX_FRAME_LEN]; static int szRxBits; static size_t szRx = sizeof(abtRx); static uint8_t abtRawUid[12]; static uint8_t abtAtqa[2]; static uint8_t abtSak; static uint8_t abtAts[MAX_FRAME_LEN]; static uint8_t szAts = 0; static size_t szCL = 1;//Always start with Cascade Level 1 (CL1) static nfc_device *pnd; bool quiet_output = false; bool force_rats = false; bool timed = false; bool iso_ats_supported = false; // ISO14443A Anti-Collision Commands uint8_t abtReqa[1] = { 0x26 }; uint8_t abtSelectAll[2] = { 0x93, 0x20 }; uint8_t abtSelectTag[9] = { 0x93, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t abtRats[4] = { 0xe0, 0x50, 0x00, 0x00 }; uint8_t abtHalt[4] = { 0x50, 0x00, 0x00, 0x00 }; #define CASCADE_BIT 0x04 static bool transmit_bits(const uint8_t *pbtTx, const size_t szTxBits) { uint32_t cycles = 0; // Show transmitted command if (!quiet_output) { printf("Sent bits: "); print_hex_bits(pbtTx, szTxBits); } // Transmit the bit frame command, we don't use the arbitrary parity feature if (timed) { if ((szRxBits = nfc_initiator_transceive_bits_timed(pnd, pbtTx, szTxBits, NULL, abtRx, sizeof(abtRx), NULL, &cycles)) < 0) return false; if ((!quiet_output) && (szRxBits > 0)) { printf("Response after %u cycles\n", cycles); } } else { if ((szRxBits = nfc_initiator_transceive_bits(pnd, pbtTx, szTxBits, NULL, abtRx, sizeof(abtRx), NULL)) < 0) return false; } // Show received answer if (!quiet_output) { printf("Received bits: "); print_hex_bits(abtRx, szRxBits); } // Succesful transfer return true; } static bool transmit_bytes(const uint8_t *pbtTx, const size_t szTx) { uint32_t cycles = 0; // Show transmitted command if (!quiet_output) { printf("Sent bits: "); print_hex(pbtTx, szTx); } int res; // Transmit the command bytes if (timed) { if ((res = nfc_initiator_transceive_bytes_timed(pnd, pbtTx, szTx, abtRx, sizeof(abtRx), &cycles)) < 0) return false; if ((!quiet_output) && (res > 0)) { printf("Response after %u cycles\n", cycles); } } else { if ((res = nfc_initiator_transceive_bytes(pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0) return false; } szRx = res; // Show received answer if (!quiet_output) { printf("Received bits: "); print_hex(abtRx, szRx); } // Succesful transfer return true; } static void print_usage(char *argv[]) { printf("Usage: %s [OPTIONS]\n", argv[0]); printf("Options:\n"); printf("\t-h\tHelp. Print this message.\n"); printf("\t-q\tQuiet mode. Suppress output of READER and EMULATOR data (improves timing).\n"); printf("\t-f\tForce RATS.\n"); printf("\t-t\tMeasure response time (in cycles).\n"); } int main(int argc, char *argv[]) { int arg; // Get commandline options for (arg = 1; arg < argc; arg++) { if (0 == strcmp(argv[arg], "-h")) { print_usage(argv); exit(EXIT_SUCCESS); } else if (0 == strcmp(argv[arg], "-q")) { quiet_output = true; } else if (0 == strcmp(argv[arg], "-f")) { force_rats = true; } else if (0 == strcmp(argv[arg], "-t")) { timed = true; } else { ERR("%s is not supported option.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } } nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Try to open the NFC reader pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Error opening NFC reader"); nfc_exit(context); exit(EXIT_FAILURE); } // Initialise NFC device as "initiator" if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Configure the CRC if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Use raw send/receive methods if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Disable 14443-4 autoswitching if (nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC reader: %s opened\n\n", nfc_device_get_name(pnd)); // Send the 7 bits request command specified in ISO 14443A (0x26) if (!transmit_bits(abtReqa, 7)) { printf("Error: No tag available\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } memcpy(abtAtqa, abtRx, 2); // Anti-collision transmit_bytes(abtSelectAll, 2); // Check answer if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { printf("WARNING: BCC check failed!\n"); } // Save the UID CL1 memcpy(abtRawUid, abtRx, 4); //Prepare and send CL1 Select-Command memcpy(abtSelectTag + 2, abtRx, 5); iso14443a_crc_append(abtSelectTag, 7); transmit_bytes(abtSelectTag, 9); abtSak = abtRx[0]; // Test if we are dealing with a CL2 if (abtSak & CASCADE_BIT) { szCL = 2;//or more // Check answer if (abtRawUid[0] != 0x88) { printf("WARNING: Cascade bit set but CT != 0x88!\n"); } } if (szCL == 2) { // We have to do the anti-collision for cascade level 2 // Prepare CL2 commands abtSelectAll[0] = 0x95; // Anti-collision transmit_bytes(abtSelectAll, 2); // Check answer if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { printf("WARNING: BCC check failed!\n"); } // Save UID CL2 memcpy(abtRawUid + 4, abtRx, 4); // Selection abtSelectTag[0] = 0x95; memcpy(abtSelectTag + 2, abtRx, 5); iso14443a_crc_append(abtSelectTag, 7); transmit_bytes(abtSelectTag, 9); abtSak = abtRx[0]; // Test if we are dealing with a CL3 if (abtSak & CASCADE_BIT) { szCL = 3; // Check answer if (abtRawUid[0] != 0x88) { printf("WARNING: Cascade bit set but CT != 0x88!\n"); } } if (szCL == 3) { // We have to do the anti-collision for cascade level 3 // Prepare and send CL3 AC-Command abtSelectAll[0] = 0x97; transmit_bytes(abtSelectAll, 2); // Check answer if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) { printf("WARNING: BCC check failed!\n"); } // Save UID CL3 memcpy(abtRawUid + 8, abtRx, 4); // Prepare and send final Select-Command abtSelectTag[0] = 0x97; memcpy(abtSelectTag + 2, abtRx, 5); iso14443a_crc_append(abtSelectTag, 7); transmit_bytes(abtSelectTag, 9); abtSak = abtRx[0]; } } // Request ATS, this only applies to tags that support ISO 14443A-4 if (abtRx[0] & SAK_FLAG_ATS_SUPPORTED) { iso_ats_supported = true; } if ((abtRx[0] & SAK_FLAG_ATS_SUPPORTED) || force_rats) { iso14443a_crc_append(abtRats, 2); if (transmit_bytes(abtRats, 4)) { memcpy(abtAts, abtRx, szRx); szAts = szRx; } } // Done, halt the tag now iso14443a_crc_append(abtHalt, 2); transmit_bytes(abtHalt, 4); printf("\nFound tag with\n UID: "); switch (szCL) { case 1: printf("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]); break; case 2: printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]); printf("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]); break; case 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%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]); break; } printf("\n"); 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 (force_rats && ! iso_ats_supported) { printf(" RATS forced\n"); } printf(" ATS: "); print_hex(abtAts, szAts); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
examples/nfc-anticol.c
C
lgpl
10,569
#!/bin/sh WITH_USB=1 LIBUSB_WIN32_BIN_VERSION="1.2.6.0" LIBUSB_WIN32_BIN_ARCHIVE="libusb-win32-bin-$LIBUSB_WIN32_BIN_VERSION.zip" LIBUSB_WIN32_BIN_URL="http://freefr.dl.sourceforge.net/project/libusb-win32/libusb-win32-releases/$LIBUSB_WIN32_BIN_VERSION/$LIBUSB_WIN32_BIN_ARCHIVE" LIBUSB_WIN32_BIN_DIR="libusb-win32-bin-$LIBUSB_WIN32_BIN_VERSION" if [ "$WITH_USB" = "1" ]; then if [ ! -d $LIBUSB_WIN32_BIN_DIR ]; then wget -c $LIBUSB_WIN32_BIN_URL unzip $LIBUSB_WIN32_BIN_ARCHIVE fi fi MINGW="${MINGW:=i686-w64-mingw32}" MINGW_DIR="/usr/$MINGW" # Use MinGW binaries before others #export PATH=$MINGW_DIR/bin:$PATH # Set CPATH to MinGW include files export CPATH=$MINGW_DIR/include export LD_LIBRARY_PATH=$MINGW_DIR/lib export LD_RUN_PATH=$MINGW_DIR/lib # Force pkg-config to search in cross environement directory export PKG_CONFIG_LIBDIR=$MINGW_DIR/lib/pkgconfig # Stop compilation on first error export CFLAGS="-Wfatal-errors" # Include default MinGW include directory, and libnfc's win32 files export CFLAGS="$CFLAGS -I$MINGW_DIR/include -I$PWD/contrib/win32" if [ "$MINGW" = "i686-w64-mingw32" ]; then # mingw-64 includes winscard.a and winscard.h # # It is not enough to set libpcsclite_LIBS to "-lwinscard", because it is # forgotten when libnfc is created with libtool. That's why we are setting # LIBS. export LIBS="-lwinscard" echo "MinGW-w64 ships all requirements libnfc." echo "Unfortunately the MinGW-w64 header are currently" echo "buggy. Also, Libtool doesn't support MinGW-w64" echo "very well." echo "" echo "Warning ________________________________________" echo "You will only be able to compile libnfc.dll, but" echo "none of the executables (see utils and examples)." echo "" # You can fix winbase.h by adding the following lines: # #include <basetsd.h> # #include <windef.h> # But the problem with Libtool remains. else if [ -z "$libpcsclite_LIBS$libpcsclite_CFLAGS" ]; then echo "Error __________________________________________" echo "You need to get the PC/SC library from a Windows" echo "machine and the appropriate header files. Then" echo "specify libpcsclite_LIBS=.../WinScard.dll and" echo "libpcsclite_CFLAGS=-I..." fi exit 1 fi ## Configure to cross-compile using mingw32msvc if [ "$WITH_USB" = "1" ]; then # with direct-USB drivers (use libusb-win32) DRIVERS="all" else # with UART divers only (can be tested under wine) DRIVERS="pn532_uart,arygon" fi if [ ! -x configure ]; then autoreconf -is fi ./configure --target=$MINGW --host=$MINGW \ --with-drivers=$DRIVERS \ --with-libusb-win32=$PWD/$LIBUSB_WIN32_BIN_DIR \ $* if [ "$MINGW" = "i686-w64-mingw32" ]; then # due to the buggy headers from MINGW-64 we always add "contrib/windows.h", # otherwise some windows types won't be available. echo "#include \"contrib/windows.h\"" >> config.h fi
zzyjames55-nfc0805
mingw-cross-configure.sh
Shell
lgpl
2,880
EXTRA_DIST = \ blacklist-libnfc.conf
zzyjames55-nfc0805
contrib/linux/Makefile.am
Makefile
lgpl
38
EXTRA_DIST = \ pn532_via_uart2usb.conf.sample \ arygon.conf.sample \ pn532_uart_on_rpi.conf.sample
zzyjames55-nfc0805
contrib/libnfc/Makefile.am
Makefile
lgpl
116
SUBDIRS = \ devd \ libnfc \ linux \ udev \ win32 EXTRA_DIST = \ windows.h
zzyjames55-nfc0805
contrib/Makefile.am
Makefile
lgpl
81
SUBDIRS = buses . EXTRA_DIST = \ log-internal.c
zzyjames55-nfc0805
contrib/win32/libnfc/Makefile.am
Makefile
lgpl
50
EXTRA_DIST = \ uart.c
zzyjames55-nfc0805
contrib/win32/libnfc/buses/Makefile.am
Makefile
lgpl
23
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file uart.c * @brief Windows UART driver */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "uart.h" #include <nfc/nfc.h> #include "nfc-internal.h" #include <inttypes.h> #include "log.h" #define LOG_GROUP NFC_LOG_GROUP_COM #define LOG_CATEGORY "libnfc.bus.uart_win32" // Handle platform specific includes #include "contrib/windows.h" #define delay_ms( X ) Sleep( X ) struct serial_port_windows { HANDLE hPort; // Serial port handle DCB dcb; // Device control settings COMMTIMEOUTS ct; // Serial port time-out configuration }; serial_port uart_open(const char *pcPortName) { char acPortName[255]; struct serial_port_windows *sp = malloc(sizeof(struct serial_port_windows)); if (sp == 0) return INVALID_SERIAL_PORT; // Copy the input "com?" to "\\.\COM?" format sprintf(acPortName, "\\\\.\\%s", pcPortName); _strupr(acPortName); // Try to open the serial port sp->hPort = CreateFileA(acPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (sp->hPort == INVALID_HANDLE_VALUE) { uart_close(sp); return INVALID_SERIAL_PORT; } // Prepare the device control memset(&sp->dcb, 0, sizeof(DCB)); sp->dcb.DCBlength = sizeof(DCB); if (!BuildCommDCBA("baud=9600 data=8 parity=N stop=1", &sp->dcb)) { uart_close(sp); return INVALID_SERIAL_PORT; } // Update the active serial port if (!SetCommState(sp->hPort, &sp->dcb)) { uart_close(sp); return INVALID_SERIAL_PORT; } sp->ct.ReadIntervalTimeout = 30; sp->ct.ReadTotalTimeoutMultiplier = 0; sp->ct.ReadTotalTimeoutConstant = 30; sp->ct.WriteTotalTimeoutMultiplier = 30; sp->ct.WriteTotalTimeoutConstant = 0; if (!SetCommTimeouts(sp->hPort, &sp->ct)) { uart_close(sp); return INVALID_SERIAL_PORT; } PurgeComm(sp->hPort, PURGE_RXABORT | PURGE_RXCLEAR); return sp; } void uart_close(const serial_port sp) { if (((struct serial_port_windows *) sp)->hPort != INVALID_HANDLE_VALUE) { CloseHandle(((struct serial_port_windows *) sp)->hPort); } free(sp); } void uart_flush_input(const serial_port sp) { PurgeComm(((struct serial_port_windows *) sp)->hPort, PURGE_RXABORT | PURGE_RXCLEAR); } void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { struct serial_port_windows *spw; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Serial port speed requested to be set to %d bauds.", uiPortSpeed); // Set port speed (Input and Output) switch (uiPortSpeed) { case 9600: case 19200: case 38400: case 57600: case 115200: case 230400: case 460800: break; default: log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_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; }; spw = (struct serial_port_windows *) sp; // Set baud rate spw->dcb.BaudRate = uiPortSpeed; if (!SetCommState(spw->hPort, &spw->dcb)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to apply new speed settings."); return; } PurgeComm(spw->hPort, PURGE_RXABORT | PURGE_RXCLEAR); } uint32_t uart_get_speed(const serial_port sp) { const struct serial_port_windows *spw = (struct serial_port_windows *) sp; if (!GetCommState(spw->hPort, (serial_port) & spw->dcb)) return spw->dcb.BaudRate; return 0; } int uart_receive(serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout) { DWORD dwBytesToGet = (DWORD)szRx; DWORD dwBytesReceived = 0; DWORD dwTotalBytesReceived = 0; BOOL res; // XXX Put this part into uart_win32_timeouts () ? DWORD timeout_ms = timeout; COMMTIMEOUTS timeouts; timeouts.ReadIntervalTimeout = 0; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = timeout_ms; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = timeout_ms; if (!SetCommTimeouts(((struct serial_port_windows *) sp)->hPort, &timeouts)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to apply new timeout settings."); return NFC_EIO; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Timeouts are set to %lu ms", timeout_ms); // TODO Enhance the reception method // - According to MSDN, it could be better to implement nfc_abort_command() mecanism using Cancello() volatile bool *abort_flag_p = (volatile bool *)abort_p; do { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "ReadFile"); res = ReadFile(((struct serial_port_windows *) sp)->hPort, pbtRx + dwTotalBytesReceived, dwBytesToGet, &dwBytesReceived, NULL); dwTotalBytesReceived += dwBytesReceived; if (!res) { DWORD err = GetLastError(); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "ReadFile error: %lu", err); return NFC_EIO; } else if (dwBytesReceived == 0) { return NFC_ETIMEOUT; } if (((DWORD)szRx) > dwTotalBytesReceived) { dwBytesToGet -= dwBytesReceived; } if (abort_flag_p != NULL && (*abort_flag_p) && dwTotalBytesReceived == 0) { return NFC_EOPABORTED; } } while (((DWORD)szRx) > dwTotalBytesReceived); LOG_HEX(LOG_GROUP, "RX", pbtRx, szRx); return (dwTotalBytesReceived == (DWORD) szRx) ? 0 : NFC_EIO; } int uart_send(serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout) { DWORD dwTxLen = 0; COMMTIMEOUTS timeouts; timeouts.ReadIntervalTimeout = 0; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = timeout; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = timeout; if (!SetCommTimeouts(((struct serial_port_windows *) sp)->hPort, &timeouts)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to apply new timeout settings."); return NFC_EIO; } LOG_HEX(LOG_GROUP, "TX", pbtTx, szTx); if (!WriteFile(((struct serial_port_windows *) sp)->hPort, pbtTx, szTx, &dwTxLen, NULL)) { return NFC_EIO; } if (!dwTxLen) return NFC_EIO; return 0; } BOOL is_port_available(int nPort) { TCHAR szPort[15]; COMMCONFIG cc; DWORD dwCCSize; sprintf(szPort, "COM%d", nPort); // Check if this port is available dwCCSize = sizeof(cc); return GetDefaultCommConfig(szPort, &cc, &dwCCSize); } // Path to the serial port is OS-dependant. // Try to guess what we should use. #define MAX_SERIAL_PORT_WIN 255 char ** uart_list_ports(void) { char **availablePorts = malloc((1 + MAX_SERIAL_PORT_WIN) * sizeof(char *)); if (!availablePorts) { perror("malloc"); return availablePorts; } int curIndex = 0; int i; for (i = 1; i <= MAX_SERIAL_PORT_WIN; i++) { if (is_port_available(i)) { availablePorts[curIndex] = (char *)malloc(10); if (!availablePorts[curIndex]) { perror("malloc"); break; } sprintf(availablePorts[curIndex], "COM%d", i); // printf("found candidate port: %s\n", availablePorts[curIndex]); curIndex++; } } availablePorts[curIndex] = NULL; return availablePorts; }
zzyjames55-nfc0805
contrib/win32/libnfc/buses/uart.c
C
lgpl
8,329
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Alex Lian * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "log-internal.h" #include <stdio.h> #include <stdarg.h> #include <strsafe.h> static void log_output_debug(const char *format, va_list args) { char buffer[1024]; HRESULT hr = StringCbVPrintf(buffer, sizeof(buffer), format, args); // Spew what we got, even if the buffer is not sized large enough if ((STRSAFE_E_INSUFFICIENT_BUFFER == hr) || (S_OK == hr)) OutputDebugString(buffer); } void log_vput_internal(const char *format, va_list args) { vfprintf(stderr, format, args); // Additional windows output to the debug window for debugging purposes log_output_debug(format, args); } void log_put_internal(const char *format, ...) { va_list va; va_start(va, format); vfprintf(stderr, format, va); // Additional windows output to the debug window for debugging purposes log_output_debug(format, va); va_end(va); }
zzyjames55-nfc0805
contrib/win32/libnfc/log-internal.c
C
lgpl
1,971
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file unistd.h * @brief This file intended to serve as a drop-in replacement for unistd.h on Windows */ #ifndef _UNISTD_H_ #define _UNISTD_H_ #include "contrib/windows.h" // Needed by Sleep() under Windows # include <winbase.h> # define sleep(X) Sleep( X * 1000) // With MinGW, getopt(3) is provided as separate header #if defined(WIN32) && defined(__GNUC__) /* mingw compiler */ #include <getopt.h> #endif #endif /* _UNISTD_H_ */
zzyjames55-nfc0805
contrib/win32/unistd.h
C
lgpl
1,531
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Alex Lian * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file stdlib.c * @brief Windows System compatibility */ // Handle platform specific includes #include "contrib/windows.h" int setenv(const char *name, const char *value, int overwrite) { int exists = GetEnvironmentVariableA(name, NULL, 0); if ((exists && overwrite) || (!exists)) { if (!SetEnvironmentVariableA(name, value)) { // Set errno here correctly return -1; } return 0; } // Exists and overwrite is 0. return -1; } void unsetenv(const char *name) { SetEnvironmentVariableA(name, NULL); }
zzyjames55-nfc0805
contrib/win32/stdlib.c
C
lgpl
1,666
EXTRA_DIST = \ select.h
zzyjames55-nfc0805
contrib/win32/sys/Makefile.am
Makefile
lgpl
25
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file select.h * @brief Dummy file to make the code compile under Windows */
zzyjames55-nfc0805
contrib/win32/sys/select.h
C
lgpl
1,061
SUBDIRS = libnfc sys . EXTRA_DIST = \ err.h \ nfc.def \ stdlib.c \ unistd.h \ version.rc.in
zzyjames55-nfc0805
contrib/win32/Makefile.am
Makefile
lgpl
100
#ifndef _ERR_H_ #define _ERR_H_ #include <stdlib.h> #define warnx(...) do { \ fprintf (stderr, __VA_ARGS__); \ fprintf (stderr, "\n"); \ } while (0) #define errx(code, ...) do { \ fprintf (stderr, __VA_ARGS__); \ fprintf (stderr, "\n"); \ exit (code); \ } while (0) #define err errx #endif /* !_ERR_H_ */
zzyjames55-nfc0805
contrib/win32/err.h
C
lgpl
353
EXTRA_DIST = \ pn53x.conf
zzyjames55-nfc0805
contrib/devd/Makefile.am
Makefile
lgpl
27
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2011 Glenn Ergeerts * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file windows.h * @brief Provide some windows related hacks due to lack of POSIX compat */ #ifndef __WINDOWS_H__ #define __WINDOWS_H__ # include <windows.h> # include <winerror.h> # include "win32/err.h" # if defined (__MINGW32__) /* * Cheating here on the snprintf to incorporate the format argument * into the VA_ARGS. Else we get MinGW errors regarding number of arguments * if doing a fixed string with no arguments. */ # define snprintf(S, n, ...) sprintf(S, __VA_ARGS__) # define pipe(fds) _pipe(fds, 5000, _O_BINARY) # define ETIMEDOUT WSAETIMEDOUT # define ENOTSUP WSAEOPNOTSUPP # define ECONNABORTED WSAECONNABORTED # else # define snprintf sprintf_s # define strdup _strdup # endif /* * setenv and unsetenv are not Windows compliant nor implemented in MinGW. * These declarations get rid of the "implicit declaration warning." */ int setenv(const char *name, const char *value, int overwrite); void unsetenv(const char *name); #endif
zzyjames55-nfc0805
contrib/windows.h
C
lgpl
2,125
EXTRA_DIST = \ 42-pn53x.rules
zzyjames55-nfc0805
contrib/udev/Makefile.am
Makefile
lgpl
31
dnl Check for LIBUSB dnl On success, HAVE_LIBUSB is set to 1 and PKG_CONFIG_REQUIRES is filled when dnl libusb is found using pkg-config AC_DEFUN([LIBNFC_CHECK_LIBUSB], [ if test x"$libusb_required" = "xyes"; then HAVE_LIBUSB=0 AC_ARG_WITH([libusb-win32], [AS_HELP_STRING([--with-libusb-win32], [use libusb-win32 from the following location])], [LIBUSB_WIN32_DIR=$withval], [LIBUSB_WIN32_DIR=""]) # --with-libusb-win32 directory have been set if test "x$LIBUSB_WIN32_DIR" != "x"; then AC_MSG_NOTICE(["use libusb-win32 from $LIBUSB_WIN32_DIR"]) libusb_CFLAGS="-I$LIBUSB_WIN32_DIR/include" libusb_LIBS="-L$LIBUSB_WIN32_DIR/lib/gcc -lusb" HAVE_LIBUSB=1 fi # Search using libusb module using pkg-config if test x"$HAVE_LIBUSB" = "x0"; then if test x"$PKG_CONFIG" != "x"; then PKG_CHECK_MODULES([libusb], [libusb], [HAVE_LIBUSB=1], [HAVE_LIBUSB=0]) if test x"$HAVE_LIBUSB" = "x1"; then if test x"$PKG_CONFIG_REQUIRES" != x""; then PKG_CONFIG_REQUIRES="$PKG_CONFIG_REQUIRES," fi PKG_CONFIG_REQUIRES="$PKG_CONFIG_REQUIRES libusb" fi fi fi # Search using libusb-legacy module using pkg-config if test x"$HAVE_LIBUSB" = "x0"; then if test x"$PKG_CONFIG" != "x"; then PKG_CHECK_MODULES([libusb], [libusb-legacy], [HAVE_LIBUSB=1], [HAVE_LIBUSB=0]) if test x"$HAVE_LIBUSB" = "x1"; then if test x"$PKG_CONFIG_REQUIRES" != x""; then PKG_CONFIG_REQUIRES="$PKG_CONFIG_REQUIRES," fi PKG_CONFIG_REQUIRES="$PKG_CONFIG_REQUIRES libusb" fi fi fi # Search using libusb-config if test x"$HAVE_LIBUSB" = "x0"; then AC_PATH_PROG(libusb_CONFIG,libusb-config) if test x"$libusb_CONFIG" != "x" ; then libusb_CFLAGS=`$libusb_CONFIG --cflags` libusb_LIBS=`$libusb_CONFIG --libs` HAVE_LIBUSB=1 fi fi # Search the library and headers directly (last chance) if test x"$HAVE_LIBUSB" = "x0"; then AC_CHECK_HEADER(usb.h, [], [AC_MSG_ERROR([The libusb headers are missing])]) AC_CHECK_LIB(usb, libusb_init, [], [AC_MSG_ERROR([The libusb library is missing])]) libusb_LIBS="-lusb" HAVE_LIBUSB=1 fi if test x"$HAVE_LIBUSB" = "x0"; then AC_MSG_ERROR([libusb is mandatory.]) fi AC_SUBST(libusb_LIBS) AC_SUBST(libusb_CFLAGS) fi ])
zzyjames55-nfc0805
m4/libnfc_check_libusb.m4
M4Sugar
lgpl
2,471
dnl Check for PCSC presence (if required) dnl On success, HAVE_PCSC is set to 1 and PKG_CONFIG_REQUIRES is filled when dnl libpcsclite is found using pkg-config AC_DEFUN([LIBNFC_CHECK_PCSC], [ if test "x$pcsc_required" = "xyes"; then PKG_CHECK_MODULES([libpcsclite], [libpcsclite], [HAVE_PCSC=1], [HAVE_PCSC=0]) if test x"$HAVE_PCSC" = "x1" ; then if test x"$PKG_CONFIG_REQUIRES" != x""; then PKG_CONFIG_REQUIRES="$PKG_CONFIG_REQUIRES," fi PKG_CONFIG_REQUIRES="$PKG_CONFIG_REQUIRES libpcsclite" fi case "$host" in *darwin*) if test x"$HAVE_PCSC" = "x0" ; then AC_MSG_CHECKING(for PC/SC) libpcsclite_LIBS="-Wl,-framework,PCSC" libpcsclite_CFLAGS="" HAVE_PCSC=1 AC_MSG_RESULT(yes: darwin PC/SC framework) fi ;; *mingw*) dnl FIXME Find a way to cross-compile for Windows HAVE_PCSC=0 AC_MSG_RESULT(no: Windows PC/SC framework) ;; *) if test x"$HAVE_PCSC" = "x0" ; then AC_MSG_ERROR([libpcsclite is required for building the acr122_pcsc driver.]) fi ;; esac AC_SUBST(libpcsclite_LIBS) AC_SUBST(libpcsclite_CFLAGS) fi ])
zzyjames55-nfc0805
m4/libnfc_check_pcsc.m4
M4Sugar
lgpl
1,226
dnl Based on wojtekka's m4 from http://wloc.wsinf.edu.pl/~kklos/ekg-20080219/m4/readline.m4 AC_DEFUN([AC_CHECK_READLINE],[ AC_SUBST(READLINE_LIBS) AC_SUBST(READLINE_INCLUDES) AC_ARG_WITH(readline, [[ --with-readline[=dir] Compile with readline/locate base dir]], if test "x$withval" = "xno" ; then without_readline=yes elif test "x$withval" != "xyes" ; then with_arg="$withval/include:-L$withval/lib $withval/include/readline:-L$withval/lib" fi) AC_MSG_CHECKING(for readline.h) if test "x$cross_compiling" == "xyes"; then without_readline=yes fi if test "x$without_readline" != "xyes"; then for i in $with_arg \ /usr/include: \ /usr/local/include:-L/usr/local/lib \ /usr/pkg/include:-L/usr/pkg/lib; do incl=`echo "$i" | sed 's/:.*//'` lib=`echo "$i" | sed 's/.*://'` if test -f $incl/readline/readline.h ; then AC_MSG_RESULT($incl/readline/readline.h) READLINE_LIBS="$lib -lreadline" if test "$incl" != "/usr/include"; then READLINE_INCLUDES="-I$incl/readline -I$incl" else READLINE_INCLUDES="-I$incl/readline" fi AC_DEFINE(HAVE_READLINE, 1, [define if you have readline]) have_readline=yes break elif test -f $incl/readline.h -a "x$incl" != "x/usr/include"; then AC_MSG_RESULT($incl/readline.h) READLINE_LIBS="$lib -lreadline" READLINE_INCLUDES="-I$incl" AC_DEFINE(HAVE_READLINE, 1, [define if you have readline]) have_readline=yes break fi done fi if test "x$have_readline" != "xyes"; then AC_MSG_RESULT(not found) fi ])
zzyjames55-nfc0805
m4/readline.m4
M4Sugar
lgpl
1,650
dnl Handle drivers arguments list AC_DEFUN([LIBNFC_ARG_WITH_DRIVERS], [ AC_MSG_CHECKING(which drivers to build) AC_ARG_WITH(drivers, AS_HELP_STRING([--with-drivers=DRIVERS], [Use a custom driver set, where DRIVERS is a coma-separated list of drivers to build support for. Available drivers are: 'acr122_pcsc', 'acr122_usb', 'acr122s', 'arygon', 'pn532_i2c', 'pn532_spi', 'pn532_uart' and 'pn53x_usb'. Default drivers set is 'acr122_usb,acr122s,arygon,pn532_i2c,pn532_spi,pn532_uart,pn53x_usb'. The special driver set 'all' compile all available drivers.]), [ case "${withval}" in yes | no) dnl ignore calls without any arguments DRIVER_BUILD_LIST="default" AC_MSG_RESULT(default drivers) ;; *) DRIVER_BUILD_LIST=`echo ${withval} | sed "s/,/ /g"` AC_MSG_RESULT(${DRIVER_BUILD_LIST}) ;; esac ], [ DRIVER_BUILD_LIST="default" AC_MSG_RESULT(default drivers) ] ) case "${DRIVER_BUILD_LIST}" in default) DRIVER_BUILD_LIST="acr122_usb acr122s arygon pn53x_usb pn532_uart" if test x"$spi_available" = x"yes" then DRIVER_BUILD_LIST="$DRIVER_BUILD_LIST pn532_spi" fi if test x"$i2c_available" = x"yes" then DRIVER_BUILD_LIST="$DRIVER_BUILD_LIST pn532_i2c" fi ;; all) DRIVER_BUILD_LIST="acr122_pcsc acr122_usb acr122s arygon pn53x_usb pn532_uart" if test x"$spi_available" = x"yes" then DRIVER_BUILD_LIST="$DRIVER_BUILD_LIST pn532_spi" fi if test x"$i2c_available" = x"yes" then DRIVER_BUILD_LIST="$DRIVER_BUILD_LIST pn532_i2c" fi ;; esac DRIVERS_CFLAGS="" driver_acr122_pcsc_enabled="no" driver_acr122_usb_enabled="no" driver_acr122s_enabled="no" driver_pn53x_usb_enabled="no" driver_arygon_enabled="no" driver_pn532_uart_enabled="no" driver_pn532_spi_enabled="no" driver_pn532_i2c_enabled="no" for driver in ${DRIVER_BUILD_LIST} do case "${driver}" in acr122_pcsc) pcsc_required="yes" driver_acr122_pcsc_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_ACR122_PCSC_ENABLED" ;; acr122_usb) libusb_required="yes" driver_acr122_usb_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_ACR122_USB_ENABLED" ;; acr122s) uart_required="yes" driver_acr122s_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_ACR122S_ENABLED" ;; pn53x_usb) libusb_required="yes" driver_pn53x_usb_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_PN53X_USB_ENABLED" ;; arygon) uart_required="yes" driver_arygon_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_ARYGON_ENABLED" ;; pn532_uart) uart_required="yes" driver_pn532_uart_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_PN532_UART_ENABLED" ;; pn532_spi) spi_required="yes" driver_pn532_spi_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_PN532_SPI_ENABLED" ;; pn532_i2c) i2c_required="yes" driver_pn532_i2c_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_PN532_I2C_ENABLED" ;; *) AC_MSG_ERROR([Unknow driver: $driver]) ;; esac done AC_SUBST(DRIVERS_CFLAGS) AM_CONDITIONAL(DRIVER_ACR122_PCSC_ENABLED, [test x"$driver_acr122_pcsc_enabled" = xyes]) AM_CONDITIONAL(DRIVER_ACR122_USB_ENABLED, [test x"$driver_acr122_usb_enabled" = xyes]) AM_CONDITIONAL(DRIVER_ACR122S_ENABLED, [test x"$driver_acr122s_enabled" = xyes]) AM_CONDITIONAL(DRIVER_PN53X_USB_ENABLED, [test x"$driver_pn53x_usb_enabled" = xyes]) AM_CONDITIONAL(DRIVER_ARYGON_ENABLED, [test x"$driver_arygon_enabled" = xyes]) AM_CONDITIONAL(DRIVER_PN532_UART_ENABLED, [test x"$driver_pn532_uart_enabled" = xyes]) AM_CONDITIONAL(DRIVER_PN532_SPI_ENABLED, [test x"$driver_pn532_spi_enabled" = xyes]) AM_CONDITIONAL(DRIVER_PN532_I2C_ENABLED, [test x"$driver_pn532_i2c_enabled" = xyes]) ]) AC_DEFUN([LIBNFC_DRIVERS_SUMMARY],[ echo echo "Selected drivers:" echo " acr122_pcsc...... $driver_acr122_pcsc_enabled" echo " acr122_usb....... $driver_acr122_usb_enabled" echo " acr122s.......... $driver_acr122s_enabled" echo " arygon........... $driver_arygon_enabled" echo " pn53x_usb........ $driver_pn53x_usb_enabled" echo " pn532_uart....... $driver_pn532_uart_enabled" echo " pn532_spi....... $driver_pn532_spi_enabled" echo " pn532_i2c........ $driver_pn532_i2c_enabled" ])
zzyjames55-nfc0805
m4/libnfc_drivers.m4
M4Sugar
lgpl
5,293
ADD_SUBDIRECTORY(nfc)
zzyjames55-nfc0805
include/CMakeLists.txt
CMake
lgpl
23
# Headers FILE(GLOB headers "${CMAKE_CURRENT_SOURCE_DIR}/*.h") INSTALL(FILES ${headers} DESTINATION ${INCLUDE_INSTALL_DIR}/nfc COMPONENT headers)
zzyjames55-nfc0805
include/nfc/CMakeLists.txt
CMake
lgpl
147
nfcinclude_HEADERS = \ nfc.h \ nfc-emulation.h \ nfc-types.h nfcincludedir = $(includedir)/nfc EXTRA_DIST = CMakeLists.txt
zzyjames55-nfc0805
include/nfc/Makefile.am
Makefile
lgpl
146
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc-types.h * @brief Define NFC types */ #ifndef __NFC_TYPES_H__ #define __NFC_TYPES_H__ #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <stdio.h> #ifndef NFC_BUFSIZE_CONNSTRING #define NFC_BUFSIZE_CONNSTRING 1024 #endif /** * NFC context */ typedef struct nfc_context nfc_context; /** * NFC device */ typedef struct nfc_device nfc_device; /** * NFC device driver */ typedef struct nfc_driver nfc_driver; /** * Connection string */ typedef char nfc_connstring[NFC_BUFSIZE_CONNSTRING]; /** * Properties */ typedef enum { /** * Default command processing timeout * Property value's (duration) unit is ms and 0 means no timeout (infinite). * Default value is set by driver layer */ NP_TIMEOUT_COMMAND, /** * Timeout between ATR_REQ and ATR_RES * When the device is in initiator mode, a target is considered as mute if no * valid ATR_RES is received within this timeout value. * Default value for this property is 103 ms on PN53x based devices. */ NP_TIMEOUT_ATR, /** * Timeout value to give up reception from the target in case of no answer. * Default value for this property is 52 ms). */ NP_TIMEOUT_COM, /** Let the PN53X chip handle the CRC bytes. This means that the chip appends * the CRC bytes to the frames that are transmitted. It will parse the last * bytes from received frames as incoming CRC bytes. They will be verified * against the used modulation and protocol. If an frame is expected with * incorrect CRC bytes this option should be disabled. Example frames where * this is useful are the ATQA and UID+BCC that are transmitted without CRC * bytes during the anti-collision phase of the ISO14443-A protocol. */ NP_HANDLE_CRC, /** Parity bits in the network layer of ISO14443-A are by default generated and * validated in the PN53X chip. This is a very convenient feature. On certain * times though it is useful to get full control of the transmitted data. The * proprietary MIFARE Classic protocol uses for example custom (encrypted) * parity bits. For interoperability it is required to be completely * compatible, including the arbitrary parity bits. When this option is * disabled, the functions to communicating bits should be used. */ NP_HANDLE_PARITY, /** This option can be used to enable or disable the electronic field of the * NFC device. */ NP_ACTIVATE_FIELD, /** The internal CRYPTO1 co-processor can be used to transmit messages * encrypted. This option is automatically activated after a successful MIFARE * Classic authentication. */ NP_ACTIVATE_CRYPTO1, /** The default configuration defines that the PN53X chip will try indefinitely * to invite a tag in the field to respond. This could be desired when it is * certain a tag will enter the field. On the other hand, when this is * uncertain, it will block the application. This option could best be compared * to the (NON)BLOCKING option used by (socket)network programming. */ NP_INFINITE_SELECT, /** If this option is enabled, frames that carry less than 4 bits are allowed. * According to the standards these frames should normally be handles as * invalid frames. */ NP_ACCEPT_INVALID_FRAMES, /** If the NFC device should only listen to frames, it could be useful to let * it gather multiple frames in a sequence. They will be stored in the internal * FIFO of the PN53X chip. This could be retrieved by using the receive data * functions. Note that if the chip runs out of bytes (FIFO = 64 bytes long), * it will overwrite the first received frames, so quick retrieving of the * received data is desirable. */ NP_ACCEPT_MULTIPLE_FRAMES, /** This option can be used to enable or disable the auto-switching mode to * ISO14443-4 is device is compliant. * In initiator mode, it means that NFC chip will send RATS automatically when * select and it will automatically poll for ISO14443-4 card when ISO14443A is * requested. * In target mode, with a NFC chip compliant (ie. PN532), the chip will * emulate a 14443-4 PICC using hardware capability */ NP_AUTO_ISO14443_4, /** Use automatic frames encapsulation and chaining. */ NP_EASY_FRAMING, /** Force the chip to switch in ISO14443-A */ NP_FORCE_ISO14443_A, /** Force the chip to switch in ISO14443-B */ NP_FORCE_ISO14443_B, /** Force the chip to run at 106 kbps */ NP_FORCE_SPEED_106, } nfc_property; // Compiler directive, set struct alignment to 1 uint8_t for compatibility # pragma pack(1) /** * @enum nfc_dep_mode * @brief NFC D.E.P. (Data Exchange Protocol) active/passive mode */ typedef enum { NDM_UNDEFINED = 0, NDM_PASSIVE, NDM_ACTIVE, } nfc_dep_mode; /** * @struct nfc_dep_info * @brief NFC target information in D.E.P. (Data Exchange Protocol) see ISO/IEC 18092 (NFCIP-1) */ typedef struct { /** NFCID3 */ uint8_t abtNFCID3[10]; /** DID */ uint8_t btDID; /** Supported send-bit rate */ uint8_t btBS; /** Supported receive-bit rate */ uint8_t btBR; /** Timeout value */ uint8_t btTO; /** PP Parameters */ uint8_t btPP; /** General Bytes */ uint8_t abtGB[48]; size_t szGB; /** DEP mode */ nfc_dep_mode ndm; } nfc_dep_info; /** * @struct nfc_iso14443a_info * @brief NFC ISO14443A tag (MIFARE) information */ typedef struct { uint8_t abtAtqa[2]; uint8_t btSak; size_t szUidLen; uint8_t abtUid[10]; size_t szAtsLen; uint8_t abtAts[254]; // Maximal theoretical ATS is FSD-2, FSD=256 for FSDI=8 in RATS } nfc_iso14443a_info; /** * @struct nfc_felica_info * @brief NFC FeLiCa tag information */ typedef struct { size_t szLen; uint8_t btResCode; uint8_t abtId[8]; uint8_t abtPad[8]; uint8_t abtSysCode[2]; } nfc_felica_info; /** * @struct nfc_iso14443b_info * @brief NFC ISO14443B tag information */ typedef struct { /** abtPupi store PUPI contained in ATQB (Answer To reQuest of type B) (see ISO14443-3) */ uint8_t abtPupi[4]; /** abtApplicationData store Application Data contained in ATQB (see ISO14443-3) */ uint8_t abtApplicationData[4]; /** abtProtocolInfo store Protocol Info contained in ATQB (see ISO14443-3) */ uint8_t abtProtocolInfo[3]; /** ui8CardIdentifier store CID (Card Identifier) attributted by PCD to the PICC */ uint8_t ui8CardIdentifier; } nfc_iso14443b_info; /** * @struct nfc_iso14443bi_info * @brief NFC ISO14443B' tag information */ typedef struct { /** DIV: 4 LSBytes of tag serial number */ uint8_t abtDIV[4]; /** Software version & type of REPGEN */ uint8_t btVerLog; /** Config Byte, present if long REPGEN */ uint8_t btConfig; /** ATR, if any */ size_t szAtrLen; uint8_t abtAtr[33]; } nfc_iso14443bi_info; /** * @struct nfc_iso14443b2sr_info * @brief NFC ISO14443-2B ST SRx tag information */ typedef struct { uint8_t abtUID[8]; } nfc_iso14443b2sr_info; /** * @struct nfc_iso14443b2ct_info * @brief NFC ISO14443-2B ASK CTx tag information */ typedef struct { uint8_t abtUID[4]; uint8_t btProdCode; uint8_t btFabCode; } nfc_iso14443b2ct_info; /** * @struct nfc_jewel_info * @brief NFC Jewel tag information */ typedef struct { uint8_t btSensRes[2]; uint8_t btId[4]; } nfc_jewel_info; /** * @union nfc_target_info * @brief Union between all kind of tags information structures. */ typedef union { nfc_iso14443a_info nai; nfc_felica_info nfi; nfc_iso14443b_info nbi; nfc_iso14443bi_info nii; nfc_iso14443b2sr_info nsi; nfc_iso14443b2ct_info nci; nfc_jewel_info nji; nfc_dep_info ndi; } nfc_target_info; /** * @enum nfc_baud_rate * @brief NFC baud rate enumeration */ typedef enum { NBR_UNDEFINED = 0, NBR_106, NBR_212, NBR_424, NBR_847, } nfc_baud_rate; /** * @enum nfc_modulation_type * @brief NFC modulation type enumeration */ typedef enum { NMT_ISO14443A = 1, NMT_JEWEL, NMT_ISO14443B, NMT_ISO14443BI, // pre-ISO14443B aka ISO/IEC 14443 B' or Type B' NMT_ISO14443B2SR, // ISO14443-2B ST SRx NMT_ISO14443B2CT, // ISO14443-2B ASK CTx NMT_FELICA, NMT_DEP, } nfc_modulation_type; /** * @enum nfc_mode * @brief NFC mode type enumeration */ typedef enum { N_TARGET, N_INITIATOR, } nfc_mode; /** * @struct nfc_modulation * @brief NFC modulation structure */ typedef struct { nfc_modulation_type nmt; nfc_baud_rate nbr; } nfc_modulation; /** * @struct nfc_target * @brief NFC target structure */ typedef struct { nfc_target_info nti; nfc_modulation nm; } nfc_target; // Reset struct alignment to default # pragma pack() #endif // _LIBNFC_TYPES_H_
zzyjames55-nfc0805
include/nfc/nfc-types.h
C
lgpl
9,675
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc.h * @brief libnfc interface * * Provide all usefull functions (API) to handle NFC devices. */ #ifndef _LIBNFC_H_ # define _LIBNFC_H_ # include <sys/time.h> # include <stdint.h> # include <stdbool.h> # ifdef _WIN32 /* Windows platform */ # ifndef _WINDLL /* CMake compilation */ # ifdef nfc_EXPORTS # define NFC_EXPORT __declspec(dllexport) # else /* nfc_EXPORTS */ # define NFC_EXPORT __declspec(dllimport) # endif /* nfc_EXPORTS */ # else /* _WINDLL */ /* Manual makefile */ # define NFC_EXPORT # endif /* _WINDLL */ # else /* _WIN32 */ # define NFC_EXPORT # endif /* _WIN32 */ # include <nfc/nfc-types.h> # ifndef __has_attribute # define __has_attribute(x) 0 # endif # if __has_attribute(nonnull) || defined(__GNUC__) # define __has_attribute_nonnull 1 # endif # if __has_attribute_nonnull # define ATTRIBUTE_NONNULL( param ) __attribute__((nonnull (param))) # else # define ATTRIBUTE_NONNULL( param ) # endif # ifdef __cplusplus extern "C" { # endif // __cplusplus /* Library initialization/deinitialization */ NFC_EXPORT void nfc_init(nfc_context **context) ATTRIBUTE_NONNULL(1); NFC_EXPORT void nfc_exit(nfc_context *context) ATTRIBUTE_NONNULL(1); NFC_EXPORT int nfc_register_driver(const nfc_driver *driver); /* NFC Device/Hardware manipulation */ NFC_EXPORT nfc_device *nfc_open(nfc_context *context, const nfc_connstring connstring) ATTRIBUTE_NONNULL(1); NFC_EXPORT void nfc_close(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) ATTRIBUTE_NONNULL(1); NFC_EXPORT int nfc_idle(nfc_device *pnd); /* NFC initiator: act as "reader" */ NFC_EXPORT int nfc_initiator_init(nfc_device *pnd); NFC_EXPORT int nfc_initiator_init_secure_element(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_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_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_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_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, const size_t szRx, 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, const size_t szRx, 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, const size_t szRx, uint8_t *pbtRxPar, uint32_t *cycles); NFC_EXPORT int nfc_initiator_target_is_present(nfc_device *pnd, const nfc_target *pnt); /* 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_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_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); /* Error reporting */ 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 void nfc_perror(const nfc_device *pnd, const char *s); NFC_EXPORT int nfc_device_get_last_error(const nfc_device *pnd); /* Special data accessors */ NFC_EXPORT const char *nfc_device_get_name(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_baud_rate(nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); /* 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_bool(nfc_device *pnd, const nfc_property property, const bool bEnable); /* Misc. functions */ 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 uint8_t *iso14443a_locate_historical_bytes(uint8_t *pbtAts, size_t szAts, size_t *pszTk); NFC_EXPORT void nfc_free(void *p); NFC_EXPORT const char *nfc_version(void); NFC_EXPORT int nfc_device_get_information_about(nfc_device *pnd, char **buf); /* String converter functions */ 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 int str_nfc_target(char **buf, const nfc_target *pnt, bool verbose); /* Error codes */ /** @ingroup error * @hideinitializer * Success (no error) */ #define NFC_SUCCESS 0 /** @ingroup error * @hideinitializer * Input / output error, device may not be usable anymore without re-open it */ #define NFC_EIO -1 /** @ingroup error * @hideinitializer * Invalid argument(s) */ #define NFC_EINVARG -2 /** @ingroup error * @hideinitializer * Operation not supported by device */ #define NFC_EDEVNOTSUPP -3 /** @ingroup error * @hideinitializer * No such device */ #define NFC_ENOTSUCHDEV -4 /** @ingroup error * @hideinitializer * Buffer overflow */ #define NFC_EOVFLOW -5 /** @ingroup error * @hideinitializer * Operation timed out */ #define NFC_ETIMEOUT -6 /** @ingroup error * @hideinitializer * Operation aborted (by user) */ #define NFC_EOPABORTED -7 /** @ingroup error * @hideinitializer * Not (yet) implemented */ #define NFC_ENOTIMPL -8 /** @ingroup error * @hideinitializer * Target released */ #define NFC_ETGRELEASED -10 /** @ingroup error * @hideinitializer * Error while RF transmission */ #define NFC_ERFTRANS -20 /** @ingroup error * @hideinitializer * MIFARE Classic: authentication failed */ #define NFC_EMFCAUTHFAIL -30 /** @ingroup error * @hideinitializer * Software error (allocation, file/pipe creation, etc.) */ #define NFC_ESOFT -80 /** @ingroup error * @hideinitializer * Device's internal chip error */ #define NFC_ECHIP -90 # ifdef __cplusplus } # endif // __cplusplus #endif // _LIBNFC_H_
zzyjames55-nfc0805
include/nfc/nfc.h
C
lgpl
8,598
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc-emulation.h * @brief Provide a small API to ease emulation in libnfc */ #ifndef __NFC_EMULATION_H__ #define __NFC_EMULATION_H__ #include <sys/types.h> #include <nfc/nfc.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ struct nfc_emulator; struct nfc_emulation_state_machine; /** * @struct nfc_emulator * @brief NFC emulator structure */ struct nfc_emulator { nfc_target *target; struct nfc_emulation_state_machine *state_machine; void *user_data; }; /** * @struct nfc_emulation_state_machine * @brief NFC emulation state machine structure */ struct nfc_emulation_state_machine { int (*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); void *data; }; NFC_EXPORT int nfc_emulate_target(nfc_device *pnd, struct nfc_emulator *emulator, const int timeout); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __NFC_EMULATION_H__ */
zzyjames55-nfc0805
include/nfc/nfc-emulation.h
C
lgpl
2,056
SUBDIRS = nfc EXTRA_DIST = CMakeLists.txt
zzyjames55-nfc0805
include/Makefile.am
Makefile
lgpl
43
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-scan-device.c * @brief Lists each available NFC device */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <err.h> #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-utils.h" #define MAX_DEVICE_COUNT 16 #define MAX_TARGET_COUNT 16 static nfc_device *pnd; static void print_usage(const char *argv[]) { printf("Usage: %s [OPTIONS]\n", argv[0]); printf("Options:\n"); printf("\t-h\tPrint this help message.\n"); printf("\t-v\tSet verbose display.\n"); printf("\t-i\tAllow intrusive scan.\n"); } int main(int argc, const char *argv[]) { const char *acLibnfcVersion; size_t i; bool verbose = false; nfc_context *context; // Get commandline options for (int arg = 1; arg < argc; arg++) { if (0 == strcmp(argv[arg], "-h")) { print_usage(argv); exit(EXIT_SUCCESS); } else if (0 == strcmp(argv[arg], "-v")) { verbose = true; } else if (0 == strcmp(argv[arg], "-i")) { // This has to be done before the call to nfc_init() setenv("LIBNFC_INTRUSIVE_SCAN", "yes", 1); } else { ERR("%s is not supported option.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } } nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)\n"); exit(EXIT_FAILURE); } // Display libnfc version acLibnfcVersion = nfc_version(); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); nfc_connstring connstrings[MAX_DEVICE_COUNT]; size_t szDeviceFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (szDeviceFound == 0) { printf("No NFC device found.\n"); nfc_exit(context); exit(EXIT_FAILURE); } printf("%d NFC device(s) found:\n", (int)szDeviceFound); char *strinfo = NULL; for (i = 0; i < szDeviceFound; i++) { pnd = nfc_open(context, connstrings[i]); if (pnd != NULL) { printf("- %s:\n %s\n", nfc_device_get_name(pnd), nfc_device_get_connstring(pnd)); if (verbose) { if (nfc_device_get_information_about(pnd, &strinfo) >= 0) { printf("%s", strinfo); nfc_free(strinfo); } } nfc_close(pnd); } else { printf("nfc_open failed for %s\n", connstrings[i]); } } nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
utils/nfc-scan-device.c
C
lgpl
4,173
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-utils.h * @brief Provide some examples shared functions like print, parity calculation, options parsing. */ #ifndef _EXAMPLES_NFC_UTILS_H_ # define _EXAMPLES_NFC_UTILS_H_ # include <stdlib.h> # include <string.h> # include <err.h> /** * @macro DBG * @brief Print a message of standard output only in DEBUG mode */ #ifdef DEBUG # define DBG(...) do { \ warnx ("DBG %s:%d", __FILE__, __LINE__); \ warnx (" " __VA_ARGS__ ); \ } while (0) #else # define DBG(...) {} #endif /** * @macro WARN * @brief Print a warn message */ #ifdef DEBUG # define WARN(...) do { \ warnx ("WARNING %s:%d", __FILE__, __LINE__); \ warnx (" " __VA_ARGS__ ); \ } while (0) #else # define WARN(...) warnx ("WARNING: " __VA_ARGS__ ) #endif /** * @macro ERR * @brief Print a error message */ #ifdef DEBUG # define ERR(...) do { \ warnx ("ERROR %s:%d", __FILE__, __LINE__); \ warnx (" " __VA_ARGS__ ); \ } while (0) #else # define ERR(...) warnx ("ERROR: " __VA_ARGS__ ) #endif #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif uint8_t oddparity(const uint8_t bt); 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_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_nfc_target(const nfc_target *pnt, bool verbose); #endif
zzyjames55-nfc0805
utils/nfc-utils.h
C
lgpl
3,396
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-read-forum-tag3.c * @brief Extract NDEF Message from a NFC Forum Tag Type 3 * This utility extract (if available) the NDEF Message contained in an NFC Forum Tag Type 3. */ /* * This implementation was written based on information provided by the * following documents: * * NFC Forum Type 3 Tag Operation Specification * Technical Specification * NFCForum-TS-Type-3-Tag_1.1 - 2011-06-28 */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <errno.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include <nfc/nfc.h> #include "nfc-utils.h" #if defined(WIN32) && defined(__GNUC__) /* mingw compiler */ #include <getopt.h> #endif static nfc_device *pnd; static nfc_context *context; static void print_usage(char *progname) { fprintf(stderr, "usage: %s -o FILE\n", progname); fprintf(stderr, "\nOptions:\n"); fprintf(stderr, " -o Extract NDEF message if available in FILE\n"); } static void stop_select(int sig) { (void) sig; if (pnd != NULL) { nfc_abort_command(pnd); } else { nfc_exit(context); exit(EXIT_FAILURE); } } static void build_felica_frame(const nfc_felica_info nfi, const uint8_t command, const uint8_t *payload, const size_t payload_len, uint8_t *frame, size_t *frame_len) { frame[0] = 1 + 1 + 8 + payload_len; *frame_len = frame[0]; frame[1] = command; memcpy(frame + 2, nfi.abtId, 8); memcpy(frame + 10, payload, payload_len); } #define CHECK 0x06 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) { uint8_t payload[1024] = { 1, // Services 0x0B, 0x00, // NFC Forum Tag Type 3's Service code block_count, 0x80, block, // block 0 }; size_t payload_len = 1 + 2 + 1; for (uint8_t b = 0; b < block_count; b++) { if (block < 0x100) { payload[payload_len++] = 0x80; payload[payload_len++] = block + b; } else { payload[payload_len++] = 0x00; payload[payload_len++] = (block + b) >> 8; payload[payload_len++] = (block + b) & 0xff; } } uint8_t frame[1024]; size_t frame_len = sizeof(frame); build_felica_frame(nt.nti.nfi, CHECK, payload, payload_len, frame, &frame_len); uint8_t rx[1024]; int res; if ((res = nfc_initiator_transceive_bytes(dev, frame, frame_len, rx, sizeof(rx), 0)) < 0) { return res; } const int res_overhead = 1 + 1 + 8 + 2; // 1+1+8+2: LEN + CMD + NFCID2 + STATUS if (res < res_overhead) { // Not enough data return -1; } uint8_t felica_res_len = rx[0]; if (res != felica_res_len) { // Error while receiving felica frame return -1; } if ((CHECK + 1) != rx[1]) { // Command return does not match return -1; } if (0 != memcmp(&rx[2], nt.nti.nfi.abtId, 8)) { // NFCID2 does not match return -1; } const uint8_t status_flag1 = rx[10]; const uint8_t status_flag2 = rx[11]; if ((status_flag1) || (status_flag2)) { // Felica card's error fprintf(stderr, "Status bytes: %02x, %02x\n", status_flag1, status_flag2); return -1; } // const uint8_t res_block_count = res[12]; *data_len = res - res_overhead + 1; // +1 => block count is stored on 1 byte memcpy(data, &rx[res_overhead + 1], *data_len); return *data_len; } int main(int argc, char *argv[]) { (void)argc; (void)argv; int ch; char *ndef_output = NULL; while ((ch = getopt(argc, argv, "ho:")) != -1) { switch (ch) { case 'h': print_usage(argv[0]); exit(EXIT_SUCCESS); break; case 'o': ndef_output = optarg; break; case '?': if (optopt == 'o') fprintf(stderr, "Option -%c requires an argument.\n", optopt); default: print_usage(argv[0]); exit(EXIT_FAILURE); } } if (ndef_output == NULL) { print_usage(argv[0]); exit(EXIT_FAILURE); } FILE *message_stream = NULL; FILE *ndef_stream = NULL; if ((strlen(ndef_output) == 1) && (ndef_output[0] == '-')) { message_stream = stderr; ndef_stream = stdout; } else { message_stream = stdout; ndef_stream = fopen(ndef_output, "wb"); if (!ndef_stream) { fprintf(stderr, "Could not open file %s.\n", ndef_output); exit(EXIT_FAILURE); } } nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)\n"); exit(EXIT_FAILURE); } pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Unable to open NFC device"); fclose(ndef_stream); nfc_exit(context); exit(EXIT_FAILURE); } fprintf(message_stream, "NFC device: %s opened\n", nfc_device_get_name(pnd)); nfc_modulation nm = { .nmt = NMT_FELICA, .nbr = NBR_212, }; signal(SIGINT, stop_select); nfc_target nt; if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } fprintf(message_stream, "Place your NFC Forum Tag Type 3 in the field...\n"); // Polling payload (SENSF_REQ) must be present (see NFC Digital Protol) const uint8_t *pbtSensfReq = (uint8_t *)"\x00\xff\xff\x01\x00"; if (nfc_initiator_select_passive_target(pnd, nm, pbtSensfReq, 5, &nt) <= 0) { nfc_perror(pnd, "nfc_initiator_select_passive_target"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Check if System Code equals 0x12fc const uint8_t abtNfcForumSysCode[] = { 0x12, 0xfc }; if (0 != memcmp(nt.nti.nfi.abtSysCode, abtNfcForumSysCode, 2)) { // Retry with special polling const uint8_t *pbtSensfReqNfcForum = (uint8_t *)"\x00\x12\xfc\x01\x00"; if (nfc_initiator_select_passive_target(pnd, nm, pbtSensfReqNfcForum, 5, &nt) <= 0) { nfc_perror(pnd, "nfc_initiator_select_passive_target"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Check again if System Code equals 0x12fc if (0 != memcmp(nt.nti.nfi.abtSysCode, abtNfcForumSysCode, 2)) { fprintf(stderr, "Tag is not NFC Forum Tag Type 3 compliant.\n"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } } //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)) { nfc_perror(pnd, "nfc_device_set_property_bool"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } uint8_t data[1024]; size_t data_len = sizeof(data); if (nfc_forum_tag_type3_check(pnd, nt, 0, 1, data, &data_len) <= 0) { nfc_perror(pnd, "nfc_forum_tag_type3_check"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } const int ndef_major_version = (data[0] & 0xf0) >> 4; const int ndef_minor_version = (data[0] & 0x0f); 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]; 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]; fprintf(message_stream, "NDEF data length: %d bytes\n", ndef_data_len); uint16_t ndef_calculated_checksum = 0; for (size_t n = 0; n < 14; n++) ndef_calculated_checksum += data[n]; const uint16_t ndef_checksum = (data[14] << 8) + data[15]; if (ndef_calculated_checksum != ndef_checksum) { fprintf(stderr, "NDEF CRC does not match with calculated one\n"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (!ndef_data_len) { fprintf(stderr, "Empty NFC Forum Tag Type 3\n"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } const uint8_t block_max_per_check = data[1]; const uint16_t block_count_to_check = (ndef_data_len / 16) + 1; data_len = 0; 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; 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"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } data_len += size; } if (fwrite(data, 1, data_len, ndef_stream) != data_len) { fprintf(stderr, "Could not write to file.\n"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
utils/nfc-read-forum-tag3.c
C
lgpl
10,709
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-list.c * @brief Lists the first target present of each founded device */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <err.h> #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-utils.h" #define MAX_DEVICE_COUNT 16 #define MAX_TARGET_COUNT 16 static nfc_device *pnd; static void print_usage(const char *progname) { printf("usage: %s [-v]\n", progname); printf(" -v\t verbose display\n"); } int main(int argc, const char *argv[]) { (void) argc; const char *acLibnfcVersion; size_t i; bool verbose = false; int res = 0; nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Display libnfc version acLibnfcVersion = nfc_version(); printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); if (argc != 1) { if ((argc == 2) && (0 == strcmp("-v", argv[1]))) { verbose = true; } else { print_usage(argv[0]); exit(EXIT_FAILURE); } } /* Lazy way to open an NFC device */ #if 0 pnd = nfc_open(context, NULL); #endif /* If specific device is wanted, i.e. an ARYGON device on /dev/ttyUSB0 */ #if 0 nfc_device_desc_t ndd; ndd.pcDriver = "ARYGON"; ndd.pcPort = "/dev/ttyUSB0"; ndd.uiSpeed = 115200; pnd = nfc_open(context, &ndd); #endif /* If specific device is wanted, i.e. a SCL3711 on USB */ #if 0 nfc_device_desc_t ndd; ndd.pcDriver = "PN533_USB"; strcpy(ndd.acDevice, "SCM Micro / SCL3711-NFC&RW"); pnd = nfc_open(context, &ndd); #endif nfc_connstring connstrings[MAX_DEVICE_COUNT]; size_t szDeviceFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (szDeviceFound == 0) { printf("No NFC device found.\n"); } for (i = 0; i < szDeviceFound; i++) { nfc_target ant[MAX_TARGET_COUNT]; pnd = nfc_open(context, connstrings[i]); if (pnd == NULL) { ERR("Unable to open NFC device: %s", connstrings[i]); continue; } if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC device: %s opened\n", nfc_device_get_name(pnd)); nfc_modulation nm; nm.nmt = NMT_ISO14443A; nm.nbr = NBR_106; // List ISO14443A targets if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d ISO14443A passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nm.nmt = NMT_FELICA; nm.nbr = NBR_212; // List Felica tags if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d Felica (212 kbps) passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nm.nbr = NBR_424; if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d Felica (424 kbps) passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nm.nmt = NMT_ISO14443B; nm.nbr = NBR_106; // List ISO14443B targets if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d ISO14443B passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nm.nmt = NMT_ISO14443BI; nm.nbr = NBR_106; // List ISO14443B' targets if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d ISO14443B' passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nm.nmt = NMT_ISO14443B2SR; nm.nbr = NBR_106; // List ISO14443B-2 ST SRx family targets if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d ISO14443B-2 ST SRx passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nm.nmt = NMT_ISO14443B2CT; nm.nbr = NBR_106; // List ISO14443B-2 ASK CTx family targets if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d ISO14443B-2 ASK CTx passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nm.nmt = NMT_JEWEL; nm.nbr = NBR_106; // List Jewel targets if ((res = nfc_initiator_list_passive_targets(pnd, nm, ant, MAX_TARGET_COUNT)) >= 0) { int n; if (verbose || (res > 0)) { printf("%d Jewel passive target(s) found%s\n", res, (res == 0) ? ".\n" : ":"); } for (n = 0; n < res; n++) { print_nfc_target(&ant[n], verbose); printf("\n"); } } nfc_close(pnd); } nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
utils/nfc-list.c
C
lgpl
7,625
SET(UTILS-SOURCES nfc-emulate-forum-tag4 nfc-list nfc-mfclassic nfc-mfultralight nfc-read-forum-tag3 nfc-relay-picc nfc-scan-device ) ADD_LIBRARY(nfcutils STATIC nfc-utils.c ) TARGET_LINK_LIBRARIES(nfcutils nfc) # Examples FOREACH(source ${UTILS-SOURCES}) SET (TARGETS ${source}.c) IF(WIN32) SET(RC_COMMENT "${PACKAGE_NAME} utility") SET(RC_INTERNAL_NAME ${source}) SET(RC_ORIGINAL_NAME ${source}.exe) SET(RC_FILE_TYPE VFT_APP) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/../contrib/win32/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/../windows/${source}.rc @ONLY) LIST(APPEND TARGETS ${CMAKE_CURRENT_BINARY_DIR}/../windows/${source}.rc) ENDIF(WIN32) IF((${source} MATCHES "nfc-mfultralight") OR (${source} MATCHES "nfc-mfclassic")) LIST(APPEND TARGETS mifare) ENDIF((${source} MATCHES "nfc-mfultralight") OR (${source} MATCHES "nfc-mfclassic")) IF(WIN32) IF(${source} MATCHES "nfc-scan-device") LIST(APPEND TARGETS ../contrib/win32/stdlib) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../contrib/win32) ENDIF(${source} MATCHES "nfc-scan-device") ENDIF(WIN32) ADD_EXECUTABLE(${source} ${TARGETS}) TARGET_LINK_LIBRARIES(${source} nfc) TARGET_LINK_LIBRARIES(${source} nfcutils) INSTALL(TARGETS ${source} RUNTIME DESTINATION bin COMPONENT utils) ENDFOREACH(source) #install required libraries IF(WIN32) INCLUDE(InstallRequiredSystemLibraries) CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/cmake/FixBundle.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FixBundle.cmake @ONLY) INSTALL(SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/FixBundle.cmake) ENDIF(WIN32) IF(NOT WIN32) # Manuals for the examples FILE(GLOB manuals "${CMAKE_CURRENT_SOURCE_DIR}/*.1") INSTALL(FILES ${manuals} DESTINATION ${SHARE_INSTALL_PREFIX}/man/man1 COMPONENT manuals) ENDIF(NOT WIN32)
zzyjames55-nfc0805
utils/CMakeLists.txt
CMake
lgpl
1,833
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-utils.c * @brief Provide some examples shared functions like print, parity calculation, options parsing. */ #include <nfc/nfc.h> #include <err.h> #include "nfc-utils.h" uint8_t oddparity(const uint8_t bt) { // cf http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel return (0x9669 >> ((bt ^ (bt >> 4)) & 0xF)) & 1; } void oddparity_bytes_ts(const uint8_t *pbtData, const size_t szLen, uint8_t *pbtPar) { size_t szByteNr; // Calculate the parity bits for the command for (szByteNr = 0; szByteNr < szLen; szByteNr++) { pbtPar[szByteNr] = oddparity(pbtData[szByteNr]); } } void print_hex(const uint8_t *pbtData, const size_t szBytes) { size_t szPos; for (szPos = 0; szPos < szBytes; szPos++) { printf("%02x ", pbtData[szPos]); } printf("\n"); } void print_hex_bits(const uint8_t *pbtData, const size_t szBits) { uint8_t uRemainder; size_t szPos; size_t szBytes = szBits / 8; for (szPos = 0; szPos < szBytes; szPos++) { printf("%02x ", pbtData[szPos]); } uRemainder = szBits % 8; // Print the rest bits if (uRemainder != 0) { if (uRemainder < 5) printf("%01x (%d bits)", pbtData[szBytes], uRemainder); else printf("%02x (%d bits)", pbtData[szBytes], uRemainder); } printf("\n"); } void print_hex_par(const uint8_t *pbtData, const size_t szBits, const uint8_t *pbtDataPar) { uint8_t uRemainder; size_t szPos; size_t szBytes = szBits / 8; for (szPos = 0; szPos < szBytes; szPos++) { printf("%02x", pbtData[szPos]); if (oddparity(pbtData[szPos]) != pbtDataPar[szPos]) { printf("! "); } else { printf(" "); } } uRemainder = szBits % 8; // Print the rest bits, these cannot have parity bit if (uRemainder != 0) { if (uRemainder < 5) printf("%01x (%d bits)", pbtData[szBytes], uRemainder); else printf("%02x (%d bits)", pbtData[szBytes], uRemainder); } printf("\n"); } void print_nfc_target(const nfc_target *pnt, bool verbose) { char *s; str_nfc_target(&s, pnt, verbose); printf("%s", s); nfc_free(s); }
zzyjames55-nfc0805
utils/nfc-utils.c
C
lgpl
3,909
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file mifare.h * @brief provide samples structs and functions to manipulate MIFARE Classic and Ultralight tags using libnfc */ #ifndef _LIBNFC_MIFARE_H_ # define _LIBNFC_MIFARE_H_ # include <nfc/nfc-types.h> // Compiler directive, set struct alignment to 1 uint8_t for compatibility # pragma pack(1) typedef enum { MC_AUTH_A = 0x60, MC_AUTH_B = 0x61, MC_READ = 0x30, MC_WRITE = 0xA0, MC_TRANSFER = 0xB0, MC_DECREMENT = 0xC0, MC_INCREMENT = 0xC1, MC_STORE = 0xC2 } mifare_cmd; // MIFARE command params struct mifare_param_auth { uint8_t abtKey[6]; uint8_t abtAuthUid[4]; }; struct mifare_param_data { uint8_t abtData[16]; }; struct mifare_param_value { uint8_t abtValue[4]; }; typedef union { struct mifare_param_auth mpa; struct mifare_param_data mpd; struct mifare_param_value mpv; } mifare_param; // Reset struct alignment to default # pragma pack() 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 # pragma pack(1) // MIFARE Classic typedef struct { uint8_t abtUID[4]; // beware for 7bytes UID it goes over next fields uint8_t btBCC; uint8_t btSAK; // beware it's not always exactly SAK uint8_t abtATQA[2]; uint8_t abtManufacturer[8]; } mifare_classic_block_manufacturer; typedef struct { uint8_t abtData[16]; } mifare_classic_block_data; typedef struct { uint8_t abtKeyA[6]; uint8_t abtAccessBits[4]; uint8_t abtKeyB[6]; } mifare_classic_block_trailer; typedef union { mifare_classic_block_manufacturer mbm; mifare_classic_block_data mbd; mifare_classic_block_trailer mbt; } mifare_classic_block; typedef struct { mifare_classic_block amb[256]; } mifare_classic_tag; // MIFARE Ultralight typedef struct { uint8_t sn0[3]; uint8_t btBCC0; uint8_t sn1[4]; uint8_t btBCC1; uint8_t internal; uint8_t lock[2]; uint8_t otp[4]; } mifareul_block_manufacturer; typedef struct { uint8_t abtData[16]; } mifareul_block_data; typedef union { mifareul_block_manufacturer mbm; mifareul_block_data mbd; } mifareul_block; typedef struct { mifareul_block amb[4]; } mifareul_tag; // Reset struct alignment to default # pragma pack() #endif // _LIBNFC_MIFARE_H_
zzyjames55-nfc0805
utils/mifare.h
C
lgpl
4,141
.TH nfc-read-forum-tag3 1 "November 22, 2011" "libnfc" "NFC Utilities" .SH NAME nfc-read-forum-tag3 \- Extract NDEF Message from a NFC Forum Tag Type 3 .SH SYNOPSIS .B nfc-read-forum-tag3 .RI \fR\fB\-o\fR .IR FILE .SH DESCRIPTION .B nfc-read-forum-tag3 This utility extracts (if available) NDEF Messages contained in a NFC Forum Tag Type 3 to .IR FILE . .SH OPTIONS \fR\fB\-o\fR output extracted NDEF Message to .IR FILE .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org>, .br Romain Tartière <romain@libnfc.org>, .br Romuald Conty <romuald@libnfc.org>. .PP This manual page was written by Audrey Diacre <adiacre@il4p.fr>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
utils/nfc-read-forum-tag3.1
Roff Manpage
lgpl
987
.TH nfc-mfclassic 1 "Nov 02, 2009" "libnfc" "NFC Utilities" .SH NAME nfc-mfclassic \- MIFARE Classic command line tool .SH SYNOPSIS .B nfc-mfclassic .RI \fR\fBr\fR|\fR\fBR\fR|\fBw\fR\fR|\fBW\fR .RI \fR\fBa\fR|\fR\fBA\fR|\fBb\fR\fR|\fBB\fR .IR DUMP .IR [KEYS] .SH DESCRIPTION .B nfc-mfclassic is a MIFARE Classic tool that allow to read or write .IR DUMP file using MIFARE keys provided in .IR KEYS file. MIFARE Classic tag is one of the most widely used RFID tags. The firmware in the NFC controller supports authenticating, reading and writing to/from MIFARE Classic tags. This tool demonstrates the speed of this library and its ease-of-use. It's possible to read and write the complete content of a MIFARE Classic 4KB tag within 1 second. It uses a binary MIFARE Dump file (MFD) to store the keys and data for all sectors. Be cautious that some parts of a MIFARE Classic memory are used for r/w access of the rest of the memory, so please read the tag documentation before experimenting too much! The .B W option allows writing of special MIFARE cards that can be 'unlocked' to allow block 0 to be overwritten. This includes UID and manufacturer data. Take care when amending UIDs to set the correct BCC (UID checksum). Currently only 4 byte UIDs are supported. Similarly, the .B R option allows an 'unlocked' read. This bypasses authentication and allows reading of the Key A and Key B data regardless of ACLs. R/W errors on some blocks can be either considered as critical or ignored. To halt on first error, specify keys with lowercase ( .B a or .B b ). To ignore such errors, use uppercase ( .B A or .B B ). *** Note that .B W and .B R options only work on special versions of MIFARE 1K cards (Chinese clones). .SH OPTIONS .TP .BR r " | " R " | " w " | " W Perform read from ( .B r ) or unlocked read from ( .B R ) or write to ( .B w ) or unlocked write to ( .B W ) card. .TP .BR a " | " A " | " b " | " B Use A or B MIFARE keys. Halt on errors ( .B a | .B b ) or tolerate errors ( .B A | .B B ). .TP .IR DUMP MiFare Dump (MFD) used to write (card to MFD) or (MFD to card) .TP .IR KEYS MiFare Dump (MFD) that contains the keys (optional). Data part of the dump is ignored. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Adam Laurie <adam@algroup.co.uk>, .br Roel Verdult <roel@libnfc.org>, .br Romain Tartière <romain@libnfc.org>, .br Romuald Conty <romuald@libnfc.org>. .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
utils/nfc-mfclassic.1
Roff Manpage
lgpl
2,798
bin_PROGRAMS = \ nfc-emulate-forum-tag4 \ nfc-list \ nfc-mfclassic \ nfc-mfultralight \ nfc-read-forum-tag3 \ nfc-relay-picc \ nfc-scan-device # set the include path found by configure AM_CPPFLAGS = $(all_includes) $(LIBNFC_CFLAGS) noinst_LTLIBRARIES = libnfcutils.la libnfcutils_la_SOURCES = nfc-utils.c nfc_emulate_forum_tag4_SOURCES = nfc-emulate-forum-tag4.c nfc-utils.h nfc_emulate_forum_tag4_LDADD = $(top_builddir)/libnfc/libnfc.la \ libnfcutils.la nfc_list_SOURCES = nfc-list.c nfc-utils.h nfc_list_LDADD = $(top_builddir)/libnfc/libnfc.la \ libnfcutils.la nfc_mfclassic_SOURCES = nfc-mfclassic.c mifare.c mifare.h nfc-utils.h nfc_mfclassic_LDADD = $(top_builddir)/libnfc/libnfc.la \ libnfcutils.la nfc_mfultralight_SOURCES = nfc-mfultralight.c mifare.c mifare.h nfc-utils.h nfc_mfultralight_LDADD = $(top_builddir)/libnfc/libnfc.la nfc_read_forum_tag3_SOURCES = nfc-read-forum-tag3.c nfc-utils.h nfc_read_forum_tag3_LDADD = $(top_builddir)/libnfc/libnfc.la \ libnfcutils.la nfc_relay_picc_SOURCES = nfc-relay-picc.c nfc-utils.h nfc_relay_picc_LDADD = $(top_builddir)/libnfc/libnfc.la \ libnfcutils.la nfc_scan_device_SOURCES = nfc-scan-device.c nfc-utils.h nfc_scan_device_LDADD = $(top_builddir)/libnfc/libnfc.la \ libnfcutils.la dist_man_MANS = \ nfc-emulate-forum-tag4.1 \ nfc-list.1 \ nfc-mfclassic.1 \ nfc-mfultralight.1 \ nfc-read-forum-tag3.1 \ nfc-relay-picc.1 \ nfc-scan-device.1 EXTRA_DIST = CMakeLists.txt
zzyjames55-nfc0805
utils/Makefile.am
Makefile
lgpl
1,511
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2011 Adam Laurie * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-mfclassic.c * @brief MIFARE Classic manipulation example */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include <string.h> #include <ctype.h> #include <nfc/nfc.h> #include "mifare.h" #include "nfc-utils.h" static nfc_context *context; static nfc_device *pnd; static nfc_target nt; static mifare_param mp; static mifare_classic_tag mtKeys; static mifare_classic_tag mtDump; static bool bUseKeyA; static bool bUseKeyFile; static bool bForceKeyFile; static bool bTolerateFailures; static bool magic2 = false; static uint8_t uiBlocks; static uint8_t keys[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd, 0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xab, 0xcd, 0xef, 0x12, 0x34, 0x56 }; static const nfc_modulation nmMifare = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; static size_t num_keys = sizeof(keys) / 6; #define MAX_FRAME_LEN 264 static uint8_t abtRx[MAX_FRAME_LEN]; static int szRxBits; uint8_t abtHalt[4] = { 0x50, 0x00, 0x00, 0x00 }; // special unlock command uint8_t abtUnlock1[1] = { 0x40 }; uint8_t abtUnlock2[1] = { 0x43 }; static bool transmit_bits(const uint8_t *pbtTx, const size_t szTxBits) { // Show transmitted command printf("Sent bits: "); print_hex_bits(pbtTx, szTxBits); // Transmit the bit frame command, we don't use the arbitrary parity feature if ((szRxBits = nfc_initiator_transceive_bits(pnd, pbtTx, szTxBits, NULL, abtRx, sizeof(abtRx), NULL)) < 0) return false; // Show received answer printf("Received bits: "); print_hex_bits(abtRx, szRxBits); // Succesful transfer return true; } static bool transmit_bytes(const uint8_t *pbtTx, const size_t szTx) { // Show transmitted command printf("Sent bits: "); print_hex(pbtTx, szTx); // Transmit the command bytes int res; if ((res = nfc_initiator_transceive_bytes(pnd, pbtTx, szTx, abtRx, sizeof(abtRx), 0)) < 0) return false; // Show received answer printf("Received bits: "); print_hex(abtRx, res); // Succesful transfer return true; } static void print_success_or_failure(bool bFailure, uint32_t *uiBlockCounter) { printf("%c", (bFailure) ? 'x' : '.'); if (uiBlockCounter && !bFailure) *uiBlockCounter += 1; } static bool is_first_block(uint32_t uiBlock) { // Test if we are in the small or big sectors if (uiBlock < 128) return ((uiBlock) % 4 == 0); else return ((uiBlock) % 16 == 0); } static bool is_trailer_block(uint32_t uiBlock) { // Test if we are in the small or big sectors if (uiBlock < 128) return ((uiBlock + 1) % 4 == 0); else return ((uiBlock + 1) % 16 == 0); } static uint32_t get_trailer_block(uint32_t uiFirstBlock) { // Test if we are in the small or big sectors uint32_t trailer_block = 0; if (uiFirstBlock < 128) { trailer_block = uiFirstBlock + (3 - (uiFirstBlock % 4)); } else { trailer_block = uiFirstBlock + (15 - (uiFirstBlock % 16)); } return trailer_block; } static bool authenticate(uint32_t uiBlock) { mifare_cmd mc; uint32_t uiTrailerBlock; // Set the authentication information (uid) memcpy(mp.mpa.abtAuthUid, nt.nti.nai.abtUid + nt.nti.nai.szUidLen - 4, 4); // Should we use key A or B? mc = (bUseKeyA) ? MC_AUTH_A : MC_AUTH_B; // Key file authentication. if (bUseKeyFile) { // Locate the trailer (with the keys) used for this sector uiTrailerBlock = get_trailer_block(uiBlock); // Extract the right key from dump file if (bUseKeyA) memcpy(mp.mpa.abtKey, mtKeys.amb[uiTrailerBlock].mbt.abtKeyA, 6); else memcpy(mp.mpa.abtKey, mtKeys.amb[uiTrailerBlock].mbt.abtKeyB, 6); // Try to authenticate for the current sector if (nfc_initiator_mifare_cmd(pnd, mc, uiBlock, &mp)) return true; } else { // Try to guess the right key for (size_t key_index = 0; key_index < num_keys; key_index++) { memcpy(mp.mpa.abtKey, keys + (key_index * 6), 6); if (nfc_initiator_mifare_cmd(pnd, mc, uiBlock, &mp)) { if (bUseKeyA) memcpy(mtKeys.amb[uiBlock].mbt.abtKeyA, &mp.mpa.abtKey, 6); else memcpy(mtKeys.amb[uiBlock].mbt.abtKeyB, &mp.mpa.abtKey, 6); return true; } nfc_initiator_select_passive_target(pnd, nmMifare, nt.nti.nai.abtUid, nt.nti.nai.szUidLen, NULL); } } return false; } static bool unlock_card(void) { if (magic2) { printf("Don't use R/W with this card, this is not required!\n"); return false; } // Configure the CRC if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) { nfc_perror(pnd, "nfc_configure"); return false; } // Use raw send/receive methods if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) { nfc_perror(pnd, "nfc_configure"); return false; } iso14443a_crc_append(abtHalt, 2); transmit_bytes(abtHalt, 4); // now send unlock if (!transmit_bits(abtUnlock1, 7)) { printf("unlock failure!\n"); return false; } if (!transmit_bytes(abtUnlock2, 1)) { printf("unlock failure!\n"); return false; } // reset reader // Configure the CRC if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); return false; } // Switch off raw send/receive methods if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); return false; } return true; } static int get_rats(void) { int res; uint8_t abtRats[2] = { 0xe0, 0x50}; // Use raw send/receive methods if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) { nfc_perror(pnd, "nfc_configure"); return -1; } res = nfc_initiator_transceive_bytes(pnd, abtRats, sizeof(abtRats), abtRx, sizeof(abtRx), 0); if (res > 0) { // ISO14443-4 card, turn RF field off/on to access ISO14443-3 again nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false); nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, true); } // Reselect tag if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) { printf("Error: tag disappeared\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } return res; } static bool read_card(int read_unlocked) { int32_t iBlock; bool bFailure = false; uint32_t uiReadBlocks = 0; if (read_unlocked) if (!unlock_card()) return false; printf("Reading out %d blocks |", uiBlocks + 1); // Read the card from end to begin for (iBlock = uiBlocks; iBlock >= 0; iBlock--) { // Authenticate everytime we reach a trailer block if (is_trailer_block(iBlock)) { if (bFailure) { // When a failure occured we need to redo the anti-collision if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) { printf("!\nError: tag was removed\n"); return false; } bFailure = false; } fflush(stdout); // Try to authenticate for the current sector if (!read_unlocked && !authenticate(iBlock)) { printf("!\nError: authentication failed for block 0x%02x\n", iBlock); return false; } // Try to read out the trailer if (nfc_initiator_mifare_cmd(pnd, MC_READ, iBlock, &mp)) { if (read_unlocked) { memcpy(mtDump.amb[iBlock].mbd.abtData, mp.mpd.abtData, 16); } else { // 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.abtAccessBits, mp.mpd.abtData + 6, 4); memcpy(mtDump.amb[iBlock].mbt.abtKeyB, mtKeys.amb[iBlock].mbt.abtKeyB, 6); } } else { printf("!\nfailed to read trailer block 0x%02x\n", iBlock); bFailure = true; } } else { // Make sure a earlier readout did not fail if (!bFailure) { // Try to read out the data block if (nfc_initiator_mifare_cmd(pnd, MC_READ, iBlock, &mp)) { memcpy(mtDump.amb[iBlock].mbd.abtData, mp.mpd.abtData, 16); } else { printf("!\nError: unable to read block 0x%02x\n", iBlock); bFailure = true; } } } // Show if the readout went well for each block print_success_or_failure(bFailure, &uiReadBlocks); if ((! bTolerateFailures) && bFailure) return false; } printf("|\n"); printf("Done, %d of %d blocks read.\n", uiReadBlocks, uiBlocks + 1); fflush(stdout); return true; } static bool write_card(int write_block_zero) { uint32_t uiBlock; bool bFailure = false; uint32_t uiWriteBlocks = 0; if (write_block_zero) if (!unlock_card()) return false; printf("Writing %d blocks |", uiBlocks + 1); // Write the card from begin to end; for (uiBlock = 0; uiBlock <= uiBlocks; uiBlock++) { // Authenticate everytime we reach the first sector of a new block if (is_first_block(uiBlock)) { if (bFailure) { // When a failure occured we need to redo the anti-collision if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) { printf("!\nError: tag was removed\n"); return false; } bFailure = false; } fflush(stdout); // Try to authenticate for the current sector if (!write_block_zero && !authenticate(uiBlock)) { printf("!\nError: authentication failed for block %02x\n", uiBlock); return false; } } if (is_trailer_block(uiBlock)) { // 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 + 6, mtDump.amb[uiBlock].mbt.abtAccessBits, 4); memcpy(mp.mpd.abtData + 10, mtDump.amb[uiBlock].mbt.abtKeyB, 6); // Try to write the trailer if (nfc_initiator_mifare_cmd(pnd, MC_WRITE, uiBlock, &mp) == false) { printf("failed to write trailer block %d \n", uiBlock); bFailure = true; } } else { // The first block 0x00 is read only, skip this if (uiBlock == 0 && ! write_block_zero && ! magic2) continue; // Make sure a earlier write did not fail if (!bFailure) { // Try to write the data block memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData, 16); // do not write a block 0 with incorrect BCC - card will be made invalid! 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 && !magic2) { printf("!\nError: incorrect BCC in MFD file!\n"); printf("Expecting BCC=%02X\n", mp.mpd.abtData[0] ^ mp.mpd.abtData[1] ^ mp.mpd.abtData[2] ^ mp.mpd.abtData[3]); return false; } } if (!nfc_initiator_mifare_cmd(pnd, MC_WRITE, uiBlock, &mp)) bFailure = true; } } // Show if the write went well for each block print_success_or_failure(bFailure, &uiWriteBlocks); if ((! bTolerateFailures) && bFailure) return false; } printf("|\n"); printf("Done, %d of %d blocks written.\n", uiWriteBlocks, uiBlocks + 1); fflush(stdout); return true; } typedef enum { ACTION_READ, ACTION_WRITE, ACTION_USAGE } action_t; static void print_usage(const char *pcProgramName) { printf("Usage: "); printf("%s r|R|w|W a|b <dump.mfd> [<keys.mfd> [f]]\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(" *** 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(" *** unlocking only works with special Mifare 1K cards (Chinese clones)\n"); printf(" a|A|b|B - Use A or B keys for action; Halt on errors (a|b) or tolerate errors (A|B)\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(" f - Force using the keyfile even if UID does not match (optional)\n"); } int main(int argc, const char *argv[]) { action_t atAction = ACTION_USAGE; uint8_t *pbtUID; int unlock = 0; if (argc < 2) { print_usage(argv[0]); exit(EXIT_FAILURE); } const char *command = argv[1]; if (strcmp(command, "r") == 0 || strcmp(command, "R") == 0) { if (argc < 4) { print_usage(argv[0]); exit(EXIT_FAILURE); } atAction = ACTION_READ; if (strcmp(command, "R") == 0) unlock = 1; bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a'; bTolerateFailures = tolower((int)((unsigned char) * (argv[2]))) != (int)((unsigned char) * (argv[2])); bUseKeyFile = (argc > 4); bForceKeyFile = ((argc > 5) && (strcmp((char *)argv[5], "f") == 0)); } else if (strcmp(command, "w") == 0 || strcmp(command, "W") == 0) { if (argc < 4) { print_usage(argv[0]); exit(EXIT_FAILURE); } atAction = ACTION_WRITE; if (strcmp(command, "W") == 0) unlock = 1; bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a'; bTolerateFailures = tolower((int)((unsigned char) * (argv[2]))) != (int)((unsigned char) * (argv[2])); bUseKeyFile = (argc > 4); bForceKeyFile = ((argc > 5) && (strcmp((char *)argv[5], "f") == 0)); } if (atAction == ACTION_USAGE) { print_usage(argv[0]); exit(EXIT_FAILURE); } // We don't know yet the card size so let's read only the UID from the keyfile for the moment if (bUseKeyFile) { FILE *pfKeys = fopen(argv[4], "rb"); if (pfKeys == NULL) { printf("Could not open keys file: %s\n", argv[4]); exit(EXIT_FAILURE); } if (fread(&mtKeys, 1, 4, pfKeys) != 4) { printf("Could not read UID from key file: %s\n", argv[4]); fclose(pfKeys); exit(EXIT_FAILURE); } fclose(pfKeys); } nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Try to open the NFC reader pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Error opening NFC reader"); nfc_exit(context); exit(EXIT_FAILURE); } if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); }; // Let the reader only try once to find a tag if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // 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); printf("NFC reader: %s opened\n", nfc_device_get_name(pnd)); // Try to find a MIFARE Classic tag if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) { printf("Error: no tag was found\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Test if we are dealing with a MIFARE compatible tag if ((nt.nti.nai.btSak & 0x08) == 0) { printf("Warning: tag is probably not a MFC!\n"); } // Get the info from the current tag pbtUID = nt.nti.nai.abtUid; if (bUseKeyFile) { uint8_t fileUid[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 if (memcmp(pbtUID, fileUid, 4) != 0) { printf("Expected MIFARE Classic card with UID starting as: %02x%02x%02x%02x\n", fileUid[0], fileUid[1], fileUid[2], fileUid[3]); printf("Got card with UID starting as: %02x%02x%02x%02x\n", pbtUID[0], pbtUID[1], pbtUID[2], pbtUID[3]); if (! bForceKeyFile) { printf("Aborting!\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } } } printf("Found MIFARE Classic card:\n"); print_nfc_target(&nt, false); // Guessing size if ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x02) // 4K uiBlocks = 0xff; else if ((nt.nti.nai.btSak & 0x01) == 0x01) // 320b uiBlocks = 0x13; else // 1K/2K, checked through RATS uiBlocks = 0x3f; // Testing RATS int res; if ((res = get_rats()) > 0) { if ((res >= 10) && (abtRx[5] == 0xc1) && (abtRx[6] == 0x05) && (abtRx[7] == 0x2f) && (abtRx[8] == 0x2f) && ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x00)) { // MIFARE Plus 2K uiBlocks = 0x7f; } // Chinese magic emulation card, ATS=0978009102:dabc1910 if ((res == 9) && (abtRx[5] == 0xda) && (abtRx[6] == 0xbc) && (abtRx[7] == 0x19) && (abtRx[8] == 0x10)) { magic2 = true; } } printf("Guessing size: seems to be a %i-byte card\n", (uiBlocks + 1) * 16); if (bUseKeyFile) { FILE *pfKeys = fopen(argv[4], "rb"); if (pfKeys == NULL) { printf("Could not open keys file: %s\n", argv[4]); exit(EXIT_FAILURE); } if (fread(&mtKeys, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfKeys) != (uiBlocks + 1) * sizeof(mifare_classic_block)) { printf("Could not read keys file: %s\n", argv[4]); fclose(pfKeys); exit(EXIT_FAILURE); } fclose(pfKeys); } if (atAction == ACTION_READ) { memset(&mtDump, 0x00, sizeof(mtDump)); } else { FILE *pfDump = fopen(argv[3], "rb"); if (pfDump == NULL) { printf("Could not open dump file: %s\n", argv[3]); exit(EXIT_FAILURE); } if (fread(&mtDump, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfDump) != (uiBlocks + 1) * sizeof(mifare_classic_block)) { printf("Could not read dump file: %s\n", argv[3]); fclose(pfDump); exit(EXIT_FAILURE); } fclose(pfDump); } // printf("Successfully opened required files\n"); if (atAction == ACTION_READ) { if (read_card(unlock)) { printf("Writing data to file: %s ...", argv[3]); fflush(stdout); FILE *pfDump = fopen(argv[3], "wb"); if (pfDump == NULL) { printf("Could not open dump file: %s\n", argv[3]); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (fwrite(&mtDump, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfDump) != ((uiBlocks + 1) * sizeof(mifare_classic_block))) { printf("\nCould not write to file: %s\n", argv[3]); fclose(pfDump); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("Done.\n"); fclose(pfDump); } } else if (atAction == ACTION_WRITE) { write_card(unlock); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
utils/nfc-mfclassic.c
C
lgpl
21,101
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file mifare.c * @brief provide samples structs and functions to manipulate MIFARE Classic and Ultralight tags using libnfc */ #include "mifare.h" #include <string.h> #include <nfc/nfc.h> /** * @brief Execute a MIFARE Classic Command * @return Returns true if action was successfully performed; otherwise returns false. * @param pmp Some commands need additional information. This information should be supplied in the mifare_param union. * * The specified MIFARE command will be executed on the tag. There are different commands possible, they all require the destination block number. * @note There are three different types of information (Authenticate, Data and Value). * * First an authentication must take place using Key A or B. It requires a 48 bit Key (6 bytes) and the UID. * They are both used to initialize the internal cipher-state of the PN53X chip. * After a successful authentication it will be possible to execute other commands (e.g. Read/Write). * The MIFARE Classic Specification (http://www.nxp.com/acrobat/other/identification/M001053_MF1ICS50_rev5_3.pdf) explains more about this process. */ bool nfc_initiator_mifare_cmd(nfc_device *pnd, const mifare_cmd mc, const uint8_t ui8Block, mifare_param *pmp) { uint8_t abtRx[265]; size_t szParamLen; uint8_t abtCmd[265]; //bool bEasyFraming; abtCmd[0] = mc; // The MIFARE Classic command abtCmd[1] = ui8Block; // The block address (1K=0x00..0x39, 4K=0x00..0xff) switch (mc) { // Read and store command have no parameter case MC_READ: case MC_STORE: szParamLen = 0; break; // Authenticate command case MC_AUTH_A: case MC_AUTH_B: szParamLen = sizeof(struct mifare_param_auth); break; // Data command case MC_WRITE: szParamLen = sizeof(struct mifare_param_data); break; // Value command case MC_DECREMENT: case MC_INCREMENT: case MC_TRANSFER: szParamLen = sizeof(struct mifare_param_value); break; // Please fix your code, you never should reach this statement default: return false; break; } // When available, copy the parameter bytes if (szParamLen) memcpy(abtCmd + 2, (uint8_t *) pmp, szParamLen); // FIXME: Save and restore bEasyFraming // bEasyFraming = nfc_device_get_property_bool (pnd, NP_EASY_FRAMING, &bEasyFraming); if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); return false; } // Fire the mifare command int res; if ((res = nfc_initiator_transceive_bytes(pnd, abtCmd, 2 + szParamLen, abtRx, sizeof(abtRx), -1)) < 0) { if (res == NFC_ERFTRANS) { // "Invalid received frame", usual means we are // authenticated on a sector but the requested MIFARE cmd (read, write) // is not permitted by current acces bytes; // So there is nothing to do here. } else { nfc_perror(pnd, "nfc_initiator_transceive_bytes"); } // XXX nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, bEasyFraming); return false; } /* XXX if (nfc_device_set_property_bool (pnd, NP_EASY_FRAMING, bEasyFraming) < 0) { nfc_perror (pnd, "nfc_device_set_property_bool"); return false; } */ // When we have executed a read command, copy the received bytes into the param if (mc == MC_READ) { if (res == 16) { memcpy(pmp->mpd.abtData, abtRx, 16); } else { return false; } } // Command succesfully executed return true; }
zzyjames55-nfc0805
utils/mifare.c
C
lgpl
5,375
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-mfultralight.c * @brief MIFARE Ultralight dump/restore tool */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include <string.h> #include <ctype.h> #include <nfc/nfc.h> #include "nfc-utils.h" #include "mifare.h" static nfc_device *pnd; static nfc_target nt; static mifare_param mp; static mifareul_tag mtDump; static uint32_t uiBlocks = 0xF; static const nfc_modulation nmMifare = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; static void print_success_or_failure(bool bFailure, uint32_t *uiCounter) { printf("%c", (bFailure) ? 'x' : '.'); if (uiCounter) *uiCounter += (bFailure) ? 0 : 1; } static bool read_card(void) { uint32_t page; bool bFailure = false; uint32_t uiReadedPages = 0; printf("Reading %d pages |", uiBlocks + 1); for (page = 0; page <= uiBlocks; page += 4) { // Try to read out the data block if (nfc_initiator_mifare_cmd(pnd, MC_READ, page, &mp)) { memcpy(mtDump.amb[page / 4].mbd.abtData, mp.mpd.abtData, 16); } else { bFailure = true; 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); } printf("|\n"); printf("Done, %d of %d pages readed.\n", uiReadedPages, uiBlocks + 1); fflush(stdout); return (!bFailure); } static bool write_card(void) { uint32_t uiBlock = 0; bool bFailure = false; uint32_t uiWritenPages = 0; uint32_t uiSkippedPages; char buffer[BUFSIZ]; bool write_otp; bool write_lock; printf("Write OTP bytes ? [yN] "); if (!fgets(buffer, BUFSIZ, stdin)) { ERR("Unable to read standard input."); } write_otp = ((buffer[0] == 'y') || (buffer[0] == 'Y')); printf("Write Lock bytes ? [yN] "); if (!fgets(buffer, BUFSIZ, stdin)) { ERR("Unable to read standard input."); } write_lock = ((buffer[0] == 'y') || (buffer[0] == 'Y')); printf("Writing %d pages |", uiBlocks + 1); /* We need to skip 2 first pages. */ printf("ss"); uiSkippedPages = 2; for (int page = 0x2; page <= 0xF; page++) { if ((page == 0x2) && (!write_lock)) { printf("s"); uiSkippedPages++; continue; } if ((page == 0x3) && (!write_otp)) { printf("s"); uiSkippedPages++; continue; } // Show if the readout went well if (bFailure) { // When a failure occured we need to redo the anti-collision if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) { ERR("tag was removed"); return false; } bFailure = false; } // For the Mifare Ultralight, this write command can be used // in compatibility mode, which only actually writes the first // page (4 bytes). The Ultralight-specific Write command only // writes one page at a time. uiBlock = page / 4; memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData + ((page % 4) * 4), 16); if (!nfc_initiator_mifare_cmd(pnd, MC_WRITE, page, &mp)) bFailure = true; print_success_or_failure(bFailure, &uiWritenPages); } printf("|\n"); printf("Done, %d of %d pages written (%d pages skipped).\n", uiWritenPages, uiBlocks + 1, uiSkippedPages); return true; } int main(int argc, const char *argv[]) { bool bReadAction; FILE *pfDump; if (argc < 3) { printf("\n"); printf("%s r|w <dump.mfd>\n", argv[0]); printf("\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("\n"); exit(EXIT_FAILURE); } DBG("\nChecking arguments and settings\n"); bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r'); if (bReadAction) { memset(&mtDump, 0x00, sizeof(mtDump)); } else { pfDump = fopen(argv[2], "rb"); if (pfDump == NULL) { ERR("Could not open dump file: %s\n", argv[2]); exit(EXIT_FAILURE); } if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) { ERR("Could not read from dump file: %s\n", argv[2]); fclose(pfDump); exit(EXIT_FAILURE); } fclose(pfDump); } DBG("Successfully opened the dump file\n"); nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } // Try to open the NFC device pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Error opening NFC device"); nfc_exit(context); exit(EXIT_FAILURE); } if (nfc_initiator_init(pnd) < 0) { nfc_perror(pnd, "nfc_initiator_init"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Let the device only try once to find a tag if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) { nfc_perror(pnd, "nfc_device_set_property_bool"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC device: %s opened\n", nfc_device_get_name(pnd)); // Try to find a MIFARE Ultralight tag if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) { ERR("no tag was found\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Test if we are dealing with a MIFARE compatible tag if (nt.nti.nai.abtAtqa[1] != 0x44) { ERR("tag is not a MIFARE Ultralight card\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Get the info from the current tag printf("Found MIFARE Ultralight card with UID: "); size_t szPos; for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) { printf("%02x", nt.nti.nai.abtUid[szPos]); } printf("\n"); if (bReadAction) { if (read_card()) { printf("Writing data to file: %s ... ", argv[2]); fflush(stdout); pfDump = fopen(argv[2], "wb"); if (pfDump == NULL) { printf("Could not open file: %s\n", argv[2]); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) { printf("Could not write to file: %s\n", argv[2]); fclose(pfDump); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } fclose(pfDump); printf("Done.\n"); } } else { write_card(); } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
utils/nfc-mfultralight.c
C
lgpl
8,397
.TH nfc-scan-device 1 "October 21, 2012" "libnfc" "NFC Utilities" .SH NAME nfc-scan-device \- Scan NFC devices .SH SYNOPSIS .B nfc-scan-device [ .I options ] .SH DESCRIPTION .B nfc-scan-device is a utility for listing any available device compliant with libnfc. It can optionnally display device's capabilities. .SH OPTIONS .TP .B \-v Tells .I nfc-scan-device to be verbose and display detailed information about the devices found. .TP .B \-i Tells .I nfc-scan-device to allow intrusive scan (eg. serial ports scan). This is equivalent to set environment variable LIBNFC_INTRUSIVE_SCAN to "yes". .SH EXAMPLE For a SCL3711 device (in verbose mode): - SCM Micro / SCL3711-NFC&RW: pn53x_usb:002:017 chip: PN533 v2.7 initator mode modulations: ISO/IEC 14443A (106 kbps), FeliCa (424 kbps, 212 kbps), ISO/IEC 14443-4B (847 kbps, 424 kbps, 212 kbps, 106 kbps), Innovision Jewel (106 kbps), D.E.P. (424 kbps, 212 kbps, 106 kbps) target mode modulations: ISO/IEC 14443A (106 kbps), FeliCa (424 kbps, 212 kbps), D.E.P. (424 kbps, 212 kbps, 106 kbps) .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org>, .br Romain Tartière <romain@libnfc.org>, .br Romuald Conty <romuald@libnfc.org>. .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
utils/nfc-scan-device.1
Roff Manpage
lgpl
1,621
.TH nfc-mfultralight 1 "Nov 02, 2009" "libnfc" "NFC Utilities" .SH NAME nfc-mfultralight \- MIFARE Ultralight command line tool .SH SYNOPSIS .B nfc-mfultralight .RI \fR\fBr\fR|\fBw\fR .IR DUMP .SH DESCRIPTION .B nfc-mfultralight is a MIFARE Ultralight tool that allows one to read or write a tag data to/from a .IR DUMP file. MIFARE Ultralight tag is one of the most widely used RFID tags for ticketing application. It uses a binary Mifare Dump file (MFD) to store data for all sectors. Be cautious that some parts of a Ultralight memory can be written only once and some parts are used as lock bits, so please read the tag documentation before experimenting too much! .SH OPTIONS .BR r " | " w Perform read from ( .B r ) or write to ( .B w ) card. .TP .IR DUMP MiFare Dump (MFD) used to write (card to MFD) or (MFD to card) .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org>, .br Romuald Conty <romuald@libnfc.org>. .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
utils/nfc-mfultralight.1
Roff Manpage
lgpl
1,355
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-relay-picc.c * @brief Relay example using two PN532 devices. */ // Notes & differences with nfc-relay: // - This example only works with PN532 because it relies on // its internal handling of ISO14443-4 specificities. // - Thanks to this internal handling & injection of WTX frames, // this example works on readers very strict on timing #ifdef HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <nfc/nfc.h> #include "nfc-utils.h" #define MAX_FRAME_LEN 264 #define MAX_DEVICE_COUNT 2 static uint8_t abtCapdu[MAX_FRAME_LEN]; static size_t szCapduLen; static uint8_t abtRapdu[MAX_FRAME_LEN]; static size_t szRapduLen; static nfc_device *pndInitiator; static nfc_device *pndTarget; static bool quitting = false; static bool quiet_output = false; static bool initiator_only_mode = false; static bool target_only_mode = false; static bool swap_devices = false; static int waiting_time = 0; FILE *fd3; FILE *fd4; static void intr_hdlr(int sig) { (void) sig; printf("\nQuitting...\n"); printf("Please send a last command to the emulator to quit properly.\n"); quitting = true; return; } static void print_usage(char *argv[]) { printf("Usage: %s [OPTIONS]\n", argv[0]); printf("Options:\n"); printf("\t-h\tHelp. Print this message.\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-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"); } static int print_hex_fd4(const uint8_t *pbtData, const size_t szBytes, const char *pchPrefix) { size_t szPos; if (szBytes > MAX_FRAME_LEN) { return -1; } if (fprintf(fd4, "#%s %04" PRIxPTR ": ", pchPrefix, szBytes) < 0) { return -1; } for (szPos = 0; szPos < szBytes; szPos++) { if (fprintf(fd4, "%02x ", pbtData[szPos]) < 0) { return -1; } } if (fprintf(fd4, "\n") < 0) { return -1; } fflush(fd4); return 0; } static int scan_hex_fd3(uint8_t *pbtData, size_t *pszBytes, const char *pchPrefix) { size_t szPos; unsigned int uiBytes; unsigned int uiData; char pchScan[256]; int c; // Look for our next sync marker while ((c = fgetc(fd3)) != '#') { if (c == EOF) { return -1; } } strncpy(pchScan, pchPrefix, 250); pchScan[sizeof(pchScan) - 1] = '\0'; strcat(pchScan, " %04x:"); if (fscanf(fd3, pchScan, &uiBytes) < 1) { return -1; } *pszBytes = uiBytes; if (*pszBytes > MAX_FRAME_LEN) { return -1; } for (szPos = 0; szPos < *pszBytes; szPos++) { if (fscanf(fd3, "%02x", &uiData) < 1) { return -1; } pbtData[szPos] = uiData; } return 0; } int main(int argc, char *argv[]) { int arg; const char *acLibnfcVersion = nfc_version(); nfc_target ntRealTarget; // Get commandline options for (arg = 1; arg < argc; arg++) { if (0 == strcmp(argv[arg], "-h")) { print_usage(argv); exit(EXIT_SUCCESS); } else if (0 == strcmp(argv[arg], "-q")) { quiet_output = true; } else if (0 == strcmp(argv[arg], "-t")) { printf("INFO: %s\n", "Target mode only."); initiator_only_mode = false; target_only_mode = true; } else if (0 == strcmp(argv[arg], "-i")) { printf("INFO: %s\n", "Initiator mode only."); initiator_only_mode = true; target_only_mode = false; } else if (0 == strcmp(argv[arg], "-s")) { printf("INFO: %s\n", "Swapping devices."); swap_devices = true; } else if (0 == strcmp(argv[arg], "-n")) { if (++arg == argc || (sscanf(argv[arg], "%10i", &waiting_time) < 1)) { ERR("Missing or wrong waiting time value: %s.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } printf("Waiting time: %i secs.\n", waiting_time); } else { ERR("%s is not supported option.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } } // Display libnfc version printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion); #ifdef WIN32 signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr); #else signal(SIGINT, intr_hdlr); #endif nfc_context *context; nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)"); exit(EXIT_FAILURE); } nfc_connstring connstrings[MAX_DEVICE_COUNT]; // List available devices size_t szFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (initiator_only_mode || target_only_mode) { if (szFound < 1) { ERR("No device found"); nfc_exit(context); exit(EXIT_FAILURE); } if ((fd3 = fdopen(3, "r")) == NULL) { ERR("Could not open file descriptor 3"); nfc_exit(context); exit(EXIT_FAILURE); } if ((fd4 = fdopen(4, "r")) == NULL) { ERR("Could not open file descriptor 4"); nfc_exit(context); exit(EXIT_FAILURE); } } else { if (szFound < 2) { ERR("%" PRIdPTR " device found but two opened devices are needed to relay NFC.", szFound); nfc_exit(context); exit(EXIT_FAILURE); } } if (!target_only_mode) { // Try to open the NFC reader used as initiator // Little hack to allow using initiator no matter if // there is already a target used locally or not on the same machine: // if there is more than one readers opened we open the second reader // (we hope they're always detected in the same order) if ((szFound == 1) || swap_devices) { pndInitiator = nfc_open(context, connstrings[0]); } else { pndInitiator = nfc_open(context, connstrings[1]); } if (pndInitiator == NULL) { printf("Error opening NFC reader\n"); nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC reader device: %s opened\n", nfc_device_get_name(pndInitiator)); if (nfc_initiator_init(pndInitiator) < 0) { printf("Error: fail initializing initiator\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } // Try to find a ISO 14443-4A tag nfc_modulation nm = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; if (nfc_initiator_select_passive_target(pndInitiator, nm, NULL, 0, &ntRealTarget) <= 0) { printf("Error: no tag was found\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } printf("Found tag:\n"); print_nfc_target(&ntRealTarget, false); if (initiator_only_mode) { if (print_hex_fd4(ntRealTarget.nti.nai.abtUid, ntRealTarget.nti.nai.szUidLen, "UID") < 0) { fprintf(stderr, "Error while printing UID to FD4\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } if (print_hex_fd4(ntRealTarget.nti.nai.abtAtqa, 2, "ATQA") < 0) { fprintf(stderr, "Error while printing ATQA to FD4\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } if (print_hex_fd4(&(ntRealTarget.nti.nai.btSak), 1, "SAK") < 0) { fprintf(stderr, "Error while printing SAK to FD4\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } if (print_hex_fd4(ntRealTarget.nti.nai.abtAts, ntRealTarget.nti.nai.szAtsLen, "ATS") < 0) { fprintf(stderr, "Error while printing ATS to FD4\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } } } if (initiator_only_mode) { printf("Hint: tag <---> *INITIATOR* (relay) <-FD3/FD4-> target (relay) <---> original reader\n\n"); } else if (target_only_mode) { printf("Hint: tag <---> initiator (relay) <-FD3/FD4-> *TARGET* (relay) <---> original reader\n\n"); } else { printf("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n"); } if (!initiator_only_mode) { nfc_target ntEmulatedTarget = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }, }; if (target_only_mode) { size_t foo; if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtUid, &(ntEmulatedTarget.nti.nai.szUidLen), "UID") < 0) { fprintf(stderr, "Error while scanning UID from FD3\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAtqa, &foo, "ATQA") < 0) { fprintf(stderr, "Error while scanning ATQA from FD3\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } if (scan_hex_fd3(&(ntEmulatedTarget.nti.nai.btSak), &foo, "SAK") < 0) { fprintf(stderr, "Error while scanning SAK from FD3\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAts, &(ntEmulatedTarget.nti.nai.szAtsLen), "ATS") < 0) { fprintf(stderr, "Error while scanning ATS from FD3\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } } else { ntEmulatedTarget.nti = ntRealTarget.nti; } // We can only emulate a short UID, so fix length & ATQA bit: ntEmulatedTarget.nti.nai.szUidLen = 4; ntEmulatedTarget.nti.nai.abtAtqa[1] &= (0xFF - 0x40); // First byte of UID is always automatically replaced by 0x08 in this mode anyway ntEmulatedTarget.nti.nai.abtUid[0] = 0x08; // ATS is always automatically replaced by PN532, we've no control on it: // ATS = (05) 75 33 92 03 // (TL) T0 TA TB TC // | | | +-- CID supported, NAD supported // | | +----- FWI=9 SFGI=2 => FWT=154ms, SFGT=1.21ms // | +-------- DR=2,4 DS=2,4 => supports 106, 212 & 424bps in both directions // +----------- TA,TB,TC, FSCI=5 => FSC=64 // It seems hazardous to tell we support NAD if the tag doesn't support NAD but I don't know how to disable it // PC/SC pseudo-ATR = 3B 80 80 01 01 if there is no historical bytes // Creates ATS and copy max 48 bytes of Tk: uint8_t *pbtTk; size_t szTk; pbtTk = iso14443a_locate_historical_bytes(ntEmulatedTarget.nti.nai.abtAts, ntEmulatedTarget.nti.nai.szAtsLen, &szTk); szTk = (szTk > 48) ? 48 : szTk; uint8_t pbtTkt[48]; memcpy(pbtTkt, pbtTk, szTk); ntEmulatedTarget.nti.nai.abtAts[0] = 0x75; ntEmulatedTarget.nti.nai.abtAts[1] = 0x33; ntEmulatedTarget.nti.nai.abtAts[2] = 0x92; ntEmulatedTarget.nti.nai.abtAts[3] = 0x03; ntEmulatedTarget.nti.nai.szAtsLen = 4 + szTk; memcpy(&(ntEmulatedTarget.nti.nai.abtAts[4]), pbtTkt, szTk); printf("We will emulate:\n"); print_nfc_target(&ntEmulatedTarget, false); // Try to open the NFC emulator device if (swap_devices) { pndTarget = nfc_open(context, connstrings[1]); } else { pndTarget = nfc_open(context, connstrings[0]); } if (pndTarget == NULL) { printf("Error opening NFC emulator device\n"); if (!target_only_mode) { nfc_close(pndInitiator); } nfc_exit(context); exit(EXIT_FAILURE); } printf("NFC emulator device: %s opened\n", nfc_device_get_name(pndTarget)); if (nfc_target_init(pndTarget, &ntEmulatedTarget, abtCapdu, sizeof(abtCapdu), 0) < 0) { ERR("%s", "Initialization of NFC emulator failed"); if (!target_only_mode) { nfc_close(pndInitiator); } nfc_close(pndTarget); nfc_exit(context); exit(EXIT_FAILURE); } printf("%s\n", "Done, relaying frames now!"); } while (!quitting) { bool ret; int res = 0; if (!initiator_only_mode) { // Receive external reader command through target if ((res = nfc_target_receive_bytes(pndTarget, abtCapdu, sizeof(abtCapdu), 0)) < 0) { nfc_perror(pndTarget, "nfc_target_receive_bytes"); if (!target_only_mode) { nfc_close(pndInitiator); } nfc_close(pndTarget); nfc_exit(context); exit(EXIT_FAILURE); } szCapduLen = (size_t) res; if (target_only_mode) { if (print_hex_fd4(abtCapdu, szCapduLen, "C-APDU") < 0) { fprintf(stderr, "Error while printing C-APDU to FD4\n"); nfc_close(pndTarget); nfc_exit(context); exit(EXIT_FAILURE); } } } else { if (scan_hex_fd3(abtCapdu, &szCapduLen, "C-APDU") < 0) { fprintf(stderr, "Error while scanning C-APDU from FD3\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } } // Show transmitted response if (!quiet_output) { printf("Forwarding C-APDU: "); print_hex(abtCapdu, szCapduLen); } if (!target_only_mode) { // Forward the frame to the original tag if ((res = nfc_initiator_transceive_bytes(pndInitiator, abtCapdu, szCapduLen, abtRapdu, sizeof(abtRapdu), -1)) < 0) { ret = false; } else { szRapduLen = (size_t) res; ret = true; } } else { if (scan_hex_fd3(abtRapdu, &szRapduLen, "R-APDU") < 0) { fprintf(stderr, "Error while scanning R-APDU from FD3\n"); nfc_close(pndTarget); nfc_exit(context); exit(EXIT_FAILURE); } ret = true; } if (ret) { // Redirect the answer back to the external reader if (waiting_time > 0) { if (!quiet_output) { printf("Waiting %is to simulate longer relay...\n", waiting_time); } sleep(waiting_time); } // Show transmitted response if (!quiet_output) { printf("Forwarding R-APDU: "); print_hex(abtRapdu, szRapduLen); } if (!initiator_only_mode) { // Transmit the response bytes if (nfc_target_send_bytes(pndTarget, abtRapdu, szRapduLen, 0) < 0) { nfc_perror(pndTarget, "nfc_target_send_bytes"); if (!target_only_mode) { nfc_close(pndInitiator); } if (!initiator_only_mode) { nfc_close(pndTarget); nfc_exit(context); } nfc_exit(context); exit(EXIT_FAILURE); } } else { if (print_hex_fd4(abtRapdu, szRapduLen, "R-APDU") < 0) { fprintf(stderr, "Error while printing R-APDU to FD4\n"); nfc_close(pndInitiator); nfc_exit(context); exit(EXIT_FAILURE); } } } } if (!target_only_mode) { nfc_close(pndInitiator); } if (!initiator_only_mode) { nfc_close(pndTarget); } nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
utils/nfc-relay-picc.c
C
lgpl
16,672
.TH nfc-relay-picc 1 "October 12, 2010" "libnfc" "NFC Utilities" .SH NAME nfc-relay-picc \- Relay demonstration tool for ISO14443-4 .SH SYNOPSIS .B nfc-relay-picc .SH DESCRIPTION .B nfc-relay-picc This tool requires two NFC devices. One device (configured as target) will emulate an ISO/IEC 14443-4 type A tag, while the second device (configured as initiator) will act as a reader. The genuine tag can be placed on the second device (initiator) and the tag emulator (target) can be placed close to the original reader. All communication is now relayed and shown in the screen on real-time. tag <---> initiator (relay) <---> target (relay) <---> original reader .SH OPTIONS \fB-h\fP Help List options \fB-q\fP Quiet mode Suppress printing of relayed data (improves timing) \fB-t\fP Target mode only (to be used on reader side) Commands are sent to file descriptor 4 Responses are read from file descriptor 3 \fB-i\fP Initiator mode only (to be used on tag side) Commands are read from file descriptor 3 Responses are sent to file descriptor 4 \fB-n\fP \fIN\fP Adds a waiting time of \fIN\fP seconds (integer) in the loop .SH EXAMPLES Basic usage: \fBnfc-relay-picc\fP Remote relay over TCP/IP: \fBsocat\fP TCP-LISTEN:port,reuseaddr "EXEC:\fBnfc-relay-picc \-i\fP,fdin=3,fdout=4" \fBsocat\fP TCP:remotehost:port "EXEC:\fBnfc-relay-picc \-t\fP,fdin=3,fdout=4" .SH NOTES There are some differences with \fBnfc-relay\fP: This example only works with PN532 because it relies on its internal handling of ISO14443-4 specificities. Thanks to this internal handling & injection of WTX frames, this example works on readers very strict on timing. .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .PP This manual page is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
utils/nfc-relay-picc.1
Roff Manpage
lgpl
2,103
.Dd March 12, 2011 .Dt NFC-EMULATE-FORUM-TAG4 1 URM .Sh NAME .Nm nfc-emulate-forum-tag4 .Nd NFC Forum tag type 4 emulation command line demonstration tool .Sh SYNOPSIS .Nm .Op -1 .Op infile Op outfile .Sh DESCRIPTION .Nm is a demonstration tool that emulates a NFC Forum tag type 4 v2.0 (or v1.0) with NDEF content. .Pp .Ar -1 can be provided to force old Tag Type 4 version 1.0 behavior. .Pp .Ar infile is the file which contains NDEF message you want to share with the NFC-Forum compliant initiator device (e.g. Nokia 6212 Classic for a v1.0 tag) .Pp If you want to save a shared content by the initiator device, we have to give .Ar outfile argument to point where the NDEF message will be saved. .Pp This example uses the hardware capability of PN532 to handle ISO/IEC 14443-4 low-level frames like RATS/ATS, WTX, etc. .Pp All devices compliant with NFC-Forum Tag Type 4 (Version 2.0 or 1.0) can be used with this example in read-write mode. .Pp If no argument is given, a default NDEF file is available. .Sh IMPLEMENTATION NOTES You can specify the same .Ar infile and .Ar outfile .Sh IMPORTANT Only PN532 equipped devices can use this example. (e.g. PN532 breakout board) .Pp ACR122 devices (like touchatag, etc.) can be used by this example, but if something goes wrong, you will have to unplug/replug your device. This is not a .Em libnfc's bug, this problem is due to ACR122's internal MCU in front of NFC chip (PN532). .Sh BUGS Please report any bugs on the .Em libnfc issue tracker at: .Em http://code.google.com/p/libnfc/issues .Sh LICENCE .Em libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .Em libnfc-utils and .Em libnfc-examples are covered by the BSD 2-Clause license. .Sh AUTHORS .An Roel Verdult Aq roel@libnfc.org .An Romain Tartière Aq romain@libnfc.org .An Romuald Conty Aq romuald@libnfc.org .Pp This manual page was written by Romuald Conty. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
utils/nfc-emulate-forum-tag4.1
Roff Manpage
lgpl
1,973
.TH nfc-list 1 "June 26, 2009" "libnfc" "NFC Utilities" .SH NAME nfc-list \- list NFC targets .SH SYNOPSIS .B nfc-list [ .I options ] .SH DESCRIPTION .B nfc-list is a utility for listing any available tags like ISO14443-A, FeliCa, Jewel or ISO14443-B (according to the device capabilities). It may detect several tags at once thanks to a mechanism called anti-collision but all types of tags don't support anti-collision and there is some physical limitation of the number of tags the reader can discover. This tool displays all available information at selection time. .SH OPTIONS .TP .B \-v Tells .I nfc-list to be verbose and display detailed information about the targets shown. This includes SAK decoding and fingerprinting is available. .SH EXAMPLE For an ISO/IEC 14443-A tag (i.e.Mifare DESFire): ATQA (SENS_RES): 03 44 UID (NFCID1): 04 45 35 01 db 24 80 SAK (SEL_RES): 20 ATS (ATR): 75 77 81 02 80 .SH BUGS Please report any bugs on the .B libnfc issue tracker at: .br .BR http://code.google.com/p/libnfc/issues .SH LICENCE .B libnfc is licensed under the GNU Lesser General Public License (LGPL), version 3. .br .B libnfc-utils and .B libnfc-examples are covered by the the BSD 2-Clause license. .SH AUTHORS Roel Verdult <roel@libnfc.org>, .br Romain Tartière <romain@libnfc.org>, .br Romuald Conty <romuald@libnfc.org>. .PP This manual page was written by Romuald Conty <romuald@libnfc.org>. It is licensed under the terms of the GNU GPL (version 2 or later).
zzyjames55-nfc0805
utils/nfc-list.1
Roff Manpage
lgpl
1,524
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2 )Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Note that this license only applies on the examples, NFC library itself is under LGPL * */ /** * @file nfc-emulate-forum-tag4.c * @brief Emulates a NFC Forum Tag Type 4 v2.0 (or v1.0) with a NDEF message */ /* * This implementation was written based on information provided by the * following documents: * * NFC Forum Type 4 Tag Operation * Technical Specification * NFCForum-TS-Type-4-Tag_1.0 - 2007-03-13 * NFCForum-TS-Type-4-Tag_2.0 - 2010-11-18 */ // Notes & differences with nfc-emulate-tag: // - This example only works with PN532 because it relies on // its internal handling of ISO14443-4 specificities. // - Thanks to this internal handling & injection of WTX frames, // this example works on readers very strict on timing #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <nfc/nfc.h> #include <nfc/nfc-emulation.h> #include "nfc-utils.h" static nfc_device *pnd; static nfc_context *context; static bool quiet_output = false; // Version of the emulated type4 tag: static int type4v = 2; #define SYMBOL_PARAM_fISO14443_4_PICC 0x20 typedef enum { NONE, CC_FILE, NDEF_FILE } file; struct nfcforum_tag4_ndef_data { uint8_t *ndef_file; size_t ndef_file_len; }; struct nfcforum_tag4_state_machine_data { file current_file; }; uint8_t nfcforum_capability_container[] = { 0x00, 0x0F, /* CCLEN 15 bytes */ 0x20, /* Mapping version 2.0, use option -1 to force v1.0 */ 0x00, 0x54, /* MLe Maximum R-ADPU data size */ // Notes: // - I (Romuald) don't know why Nokia 6212 Classic refuses the NDEF message if MLe is more than 0xFD (any suggests are welcome); // - ARYGON devices doesn't support extended frame sending, consequently these devices can't sent more than 0xFE bytes as APDU, so 0xFB APDU data bytes. // - I (Romuald) don't know why ARYGON device doesn't ACK when MLe > 0x54 (ARYGON frame length = 0xC2 (192 bytes)) 0x00, 0xFF, /* MLc Maximum C-ADPU data size */ 0x04, /* T field of the NDEF File-Control TLV */ 0x06, /* L field of the NDEF File-Control TLV */ /* V field of the NDEF File-Control TLV */ 0xE1, 0x04, /* File identifier */ 0xFF, 0xFE, /* Maximum NDEF Size */ 0x00, /* NDEF file read access condition */ 0x00, /* NDEF file write access condition */ }; /* C-ADPU offsets */ #define CLA 0 #define INS 1 #define P1 2 #define P2 3 #define LC 4 #define DATA 5 #define ISO144434A_RATS 0xE0 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) { int res = 0; struct nfcforum_tag4_ndef_data *ndef_data = (struct nfcforum_tag4_ndef_data *)(emulator->user_data); struct nfcforum_tag4_state_machine_data *state_machine_data = (struct nfcforum_tag4_state_machine_data *)(emulator->state_machine->data); if (data_in_len == 0) { // No input data, nothing to do return res; } // Show transmitted command if (!quiet_output) { printf(" In: "); print_hex(data_in, data_in_len); } if (data_in_len >= 4) { if (data_in[CLA] != 0x00) return -ENOTSUP; #define ISO7816_SELECT 0xA4 #define ISO7816_READ_BINARY 0xB0 #define ISO7816_UPDATE_BINARY 0xD6 switch (data_in[INS]) { case ISO7816_SELECT: switch (data_in[P1]) { case 0x00: /* Select by ID */ if ((data_in[P2] | 0x0C) != 0x0C) return -ENOTSUP; const uint8_t ndef_capability_container[] = { 0xE1, 0x03 }; 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]))) { memcpy(data_out, "\x90\x00", res = 2); 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]))) { memcpy(data_out, "\x90\x00", res = 2); state_machine_data->current_file = NDEF_FILE; } else { memcpy(data_out, "\x6a\x00", res = 2); state_machine_data->current_file = NONE; } break; case 0x04: /* Select by name */ if (data_in[P2] != 0x00) return -ENOTSUP; 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 }; 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); 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); else memcpy(data_out, "\x6a\x82", res = 2); break; default: return -ENOTSUP; } break; case ISO7816_READ_BINARY: if ((size_t)(data_in[LC] + 2) > data_out_len) { return -ENOSPC; } switch (state_machine_data->current_file) { case NONE: memcpy(data_out, "\x6a\x82", res = 2); break; case CC_FILE: 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); res = data_in[LC] + 2; break; case NDEF_FILE: 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); res = data_in[LC] + 2; break; } break; case ISO7816_UPDATE_BINARY: 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) { ndef_data->ndef_file_len = (ndef_data->ndef_file[0] << 8) + ndef_data->ndef_file[1] + 2; } memcpy(data_out, "\x90\x00", res = 2); break; default: // Unknown if (!quiet_output) { printf("Unknown frame, emulated target abort.\n"); } res = -ENOTSUP; } } else { res = -ENOTSUP; } // Show transmitted command if (!quiet_output) { if (res < 0) { ERR("%s (%d)", strerror(-res), -res); } else { printf(" Out: "); print_hex(data_out, res); } } return res; } static void stop_emulation(int sig) { (void) sig; if (pnd != NULL) { nfc_abort_command(pnd); } else { nfc_exit(context); exit(EXIT_FAILURE); } } static int ndef_message_load(char *filename, struct nfcforum_tag4_ndef_data *tag_data) { struct stat sb; if (stat(filename, &sb) < 0) { printf("file not found or not accessible '%s'", filename); return -1; } /* Check file size */ if (sb.st_size > 0xFFFF) { printf("file size too large '%s'", filename); return -1; } tag_data->ndef_file_len = sb.st_size + 2; tag_data->ndef_file[0] = (uint8_t)(sb.st_size >> 8); tag_data->ndef_file[1] = (uint8_t)(sb.st_size); FILE *F; if (!(F = fopen(filename, "r"))) { printf("fopen (%s, \"r\")", filename); return -1; } if (1 != fread(tag_data->ndef_file + 2, sb.st_size, 1, F)) { printf("Can't read from %s", filename); fclose(F); return -1; } fclose(F); return sb.st_size; } static int ndef_message_save(char *filename, struct nfcforum_tag4_ndef_data *tag_data) { FILE *F; if (!(F = fopen(filename, "w"))) { printf("fopen (%s, w)", filename); return -1; } if (1 != fwrite(tag_data->ndef_file + 2, tag_data->ndef_file_len - 2, 1, F)) { printf("fwrite (%d)", (int) tag_data->ndef_file_len - 2); fclose(F); return -1; } fclose(F); return tag_data->ndef_file_len - 2; } static void usage(char *progname) { fprintf(stderr, "usage: %s [-1] [infile [outfile]]\n", progname); fprintf(stderr, " -1: force Tag Type 4 v1.0 (default is v2.0)\n"); } int main(int argc, char *argv[]) { int options = 0; nfc_target nt = { .nm = { .nmt = NMT_ISO14443A, .nbr = NBR_UNDEFINED, // Will be updated by nfc_target_init() }, .nti = { .nai = { .abtAtqa = { 0x00, 0x04 }, .abtUid = { 0x08, 0x00, 0xb0, 0x0b }, .szUidLen = 4, .btSak = 0x20, .abtAts = { 0x75, 0x33, 0x92, 0x03 }, /* Not used by PN532 */ .szAtsLen = 4, }, }, }; uint8_t ndef_file[0xfffe] = { 0x00, 33, 0xd1, 0x02, 0x1c, 0x53, 0x70, 0x91, 0x01, 0x09, 0x54, 0x02, 0x65, 0x6e, 0x4c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0x51, 0x01, 0x0b, 0x55, 0x03, 0x6c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0x2e, 0x6f, 0x72, 0x67 }; struct nfcforum_tag4_ndef_data nfcforum_tag4_data = { .ndef_file = ndef_file, .ndef_file_len = ndef_file[1] + 2, }; struct nfcforum_tag4_state_machine_data state_machine_data = { .current_file = NONE, }; struct nfc_emulation_state_machine state_machine = { .io = nfcforum_tag4_io, .data = &state_machine_data, }; struct nfc_emulator emulator = { .target = &nt, .state_machine = &state_machine, .user_data = &nfcforum_tag4_data, }; if ((argc > (1 + options)) && (0 == strcmp("-h", argv[1 + options]))) { usage(argv[0]); exit(EXIT_SUCCESS); } if ((argc > (1 + options)) && (0 == strcmp("-1", argv[1 + options]))) { type4v = 1; nfcforum_capability_container[2] = 0x10; options += 1; } if (argc > (3 + options)) { usage(argv[0]); exit(EXIT_FAILURE); } // If some file is provided load it if (argc >= (2 + options)) { if (ndef_message_load(argv[1 + options], &nfcforum_tag4_data) < 0) { printf("Can't load NDEF file '%s'", argv[1 + options]); exit(EXIT_FAILURE); } } nfc_init(&context); if (context == NULL) { ERR("Unable to init libnfc (malloc)\n"); exit(EXIT_FAILURE); } // Try to open the NFC reader pnd = nfc_open(context, NULL); if (pnd == NULL) { ERR("Unable to open NFC device"); nfc_exit(context); exit(EXIT_FAILURE); } signal(SIGINT, stop_emulation); 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"); if (0 != nfc_emulate_target(pnd, &emulator, 0)) { // contains already nfc_target_init() call nfc_perror(pnd, "nfc_emulate_target"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (argc == (3 + options)) { if (ndef_message_save(argv[2 + options], &nfcforum_tag4_data) < 0) { printf("Can't save NDEF file '%s'", argv[2 + options]); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } } nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
zzyjames55-nfc0805
utils/nfc-emulate-forum-tag4.c
C
lgpl
12,976
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Zzva.Common { public partial class TProgressBar : Form { public TProgressBar() { InitializeComponent(); } } }
zzvalib
trunk/Common/Zzva.Common/TProgressBar.cs
C#
bsd
355
using System; using System.Collections.Generic; using System.Text; namespace Zzva.Common { public class CommonDateTime { public static string GetShortDateIso(DateTime Ddate) { try { string ShortDateIso; string Yyear; string Mmonth; string Dday; Yyear = Ddate.Year.ToString(); if (Yyear.Length != 4) {throw (new CommonException("Нет такого года")); } Mmonth = Ddate.Month.ToString(); if (Mmonth.Length == 2){} else if (Mmonth.Length == 1){Mmonth = "0" + Mmonth;} else {throw (new CommonException("Нет такого месяца")); } Dday = Ddate.Day.ToString(); if (Dday.Length == 2) { } else if (Dday.Length == 1) { Dday = "0" + Dday; } else { throw (new CommonException("Нет такого дня")); } ShortDateIso = Yyear + Mmonth + Dday; return ShortDateIso; } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/Common/Zzva.Common/CommonDateTime.cs
C#
bsd
1,343
using System; using System.Collections.Generic; using System.Text; namespace Zzva.Common { public class TCodeComponent { private string mvarDse; private string mvarDisp; private string mvarOrder; private int mvarDop; private string mvarFullCode; private string mvarOhZzak; //анализ идет от конца полного обозначения private const string mvarSmbBeforeOrder = "_"; private const string mvarSmbBeforeDisp = "/"; private const string mvarSmbBeforeDse = "-"; private const string mvarSmbDop = "Д"; private const string mvarSmbOrder = "К"; private const string mvarSmbBeforeOhZzak = "-"; private const string mvarSmbBeetwenDispAndOrderInOhzzak = " "; public string OhZzak { get { return mvarOhZzak; } } public int Dop { get { return mvarDop; } } public string Order { get { return mvarOrder; } } public string Disp { get { return mvarDisp; } } public string Dse { get { return mvarDse; } } public string FullCode{get{return mvarFullCode;}} private bool CheckDse(string pDse) { if (pDse == null | pDse == "") { return false; } else { return true; } } private bool CheckDisp(string pDisp) { if (pDisp != null) { if (pDisp != "") { if (float.Parse(pDisp) <= 0) { return false; } else { return true; } } else { return false; } } else { return true; } } private bool CheckOrder(string pOrder) { if (pOrder == null | pOrder == "") { return false; } else { return true; } } private bool CheckDop(int pDop) { if (pDop <= 0) { return false; } else { return true; } } private bool CheckOhZzak(string pOhZzak) { if (pOhZzak == null | pOhZzak == "") { return false; } else { return true; } } //Инициализация кода для заказного компонента //(pDse != null) and (pDse != "") //pOhZzak: //(pOhZzak != null) and (pOhZzak != "") //(pOrder != null) and (pOrder != "") // pDop <= 0 public TCodeComponent(string pDse, string pOhZzak, int pDop) { try { } catch (Exception e) { throw e; } finally { } } ////private GetDispAndOrder(string pOhZzak,out string pDisp,out string pOrder) ////{ ////} //Инициализация кода для заказного компонента //(pDse != null) and (pDse != "") //pDisp: //для нулевого исполнения pDisp = null //для ненулевого исполнения Numeric(pDisp) <> 0 //(pOrder != null) and (pOrder != "") // pDop <= 0 public TCodeComponent(string pDse, string pDisp, string pOrder, int pDop) { try { string lFullCodeBaseComp; string lOhZzak; if (CheckDop(pDop) == false) { throw (new CommonException("Ошибка в кодировании заказного компонента")); } lFullCodeBaseComp = GetFullCodeBaseComp(pDse, pDisp); lOhZzak = GetOhZzak(pDisp, pOrder); mvarDse = pDse; mvarDisp = pDisp; mvarOrder = pOrder; mvarDop = pDop; mvarFullCode = lFullCodeBaseComp + mvarSmbBeforeDisp + pOrder + mvarSmbBeforeOrder + mvarSmbDop + pDop.ToString(); mvarOhZzak = lOhZzak; } catch (Exception e) { throw e; } finally { } } private string GetOhZzak(string pDisp, string pOrder) { try { string lOhZzak; string lOrder; if (CheckDisp(pDisp) == false) { throw (new CommonException("Ошибка в кодировании заказного компонента")); } if (CheckOrder(pOrder) == false) { throw (new CommonException("Ошибка в кодировании заказного компонента")); } lOrder = mvarSmbOrder + pOrder; if (pDisp == null){lOhZzak = lOrder; } else { lOhZzak = mvarSmbBeforeOhZzak + pDisp + mvarSmbBeetwenDispAndOrderInOhzzak + lOrder; } return lOhZzak; } catch (Exception e) { throw e; } finally { } } //Инициализация кода для базового компонента //pDisp: //для нулевого исполнения pDisp = null //для ненулевого исполнения Numeric(pDisp) <> 0 public TCodeComponent(string pDse, string pDisp) { try { string lFullCodeBaseComp; lFullCodeBaseComp = GetFullCodeBaseComp(pDse, pDisp); mvarDse = pDse; mvarDisp = pDisp; mvarOrder = null; mvarDop = 0; mvarFullCode = lFullCodeBaseComp; mvarOhZzak = null; } catch (Exception e) { throw e; } finally { } } //Вернуть полный код для базового компонента private string GetFullCodeBaseComp(string pDse, string pDisp) { try { string lDispForFullCode; string lFullCodeBaseComp; if (CheckDse(pDse) == false) { throw (new CommonException("Ошибка в кодировании заказного компонента")); } if (CheckDisp(pDisp) == false) { throw (new CommonException("Ошибка в кодировании заказного компонента")); } if (pDisp != null) { lDispForFullCode = mvarSmbBeforeDse + pDisp; } else { lDispForFullCode = ""; } lFullCodeBaseComp = pDse + lDispForFullCode; return lFullCodeBaseComp; } catch (Exception e) { throw e; } finally { } } //На входе полный код public TCodeComponent(string pFullCode) { } } }
zzvalib
trunk/Common/Zzva.Common/TCodeComponent.cs
C#
bsd
7,704
using System; using System.Collections.Generic; using System.Text; namespace Zzva.Common { //Класс Поле-значение public class TFieldValue { public string Field; //обозначение поля public object Value;//значение поля public TFieldValue(string pField, object pValue) { this.Field = pField; this.Value = pValue; } } }
zzvalib
trunk/Common/Zzva.Common/TFieldValue.cs
C#
bsd
467
using System; using System.Collections.Generic; using System.Text; using System.Collections.ObjectModel; namespace Zzva.Common { public class TListFieldValueEventArgs : EventArgs { public Collection<TFieldValue> ListFieldValue; public TListFieldValueEventArgs(Collection<TFieldValue> pListFieldValue) { this.ListFieldValue = pListFieldValue; } } }
zzvalib
trunk/Common/Zzva.Common/TListFieldValueEventArgs.cs
C#
bsd
447
using System; using System.Collections.Generic; using System.Text; namespace Zzva.Common { public class CommonException : System.Exception { public CommonException(String msg): base("1406 " + msg){} } }
zzvalib
trunk/Common/Zzva.Common/CommonException.cs
C#
bsd
244
using System; using System.Collections.Generic; using System.Text; namespace Zzva.Common { public struct TCodeComp { public string FullCode; public string Dse; public float DispNumeric; public string DispString; public string Order; public int DopIsp; } public class TConvertCodeComp { private const string mvarSmbOrder = "/"; private const string mvarSmbDopIsp = "/"; private const string mvarSmbDisp = "-"; private const string mvarDispNull = "00"; public static TCodeComp GetCodeComp(string pFullObozn) { try { TCodeComp lCodeComp; string lDseDisp; string lOrderDopIsp; string lDse; string lDisp; string lOrder; string lDopIsp; pFullObozn.TrimEnd(); int IndexSmbOrder = pFullObozn.IndexOf(mvarSmbOrder); if (IndexSmbOrder == -1) //Это не заказаная { lDseDisp = pFullObozn; lOrder = ""; lDopIsp = "0"; } else //это заказная { lDseDisp = pFullObozn.Substring(0, IndexSmbOrder); lOrderDopIsp = pFullObozn.Substring(IndexSmbOrder + 1); int IndexSmbDopIsp = lOrderDopIsp.IndexOf(mvarSmbDopIsp); if (IndexSmbDopIsp == -1){throw (new CommonException("Не найден DopIsp в коде " + pFullObozn));} lOrder = lOrderDopIsp.Substring(0, IndexSmbDopIsp); lDopIsp = lOrderDopIsp.Substring(IndexSmbDopIsp + 1); } int IndexSmbDisp = lDseDisp.IndexOf(mvarSmbDisp); if (IndexSmbDisp == -1) //это нулевое исполнение { lDse = lDseDisp; lDisp = mvarDispNull; } else { lDse = lDseDisp.Substring(0, IndexSmbDisp); lDisp = lDseDisp.Substring(IndexSmbDisp + 1); } lCodeComp = new TCodeComp(); lCodeComp.FullCode = pFullObozn; lCodeComp.Dse = lDse; lCodeComp.DispString = lDisp; lCodeComp.DispNumeric = float.Parse(lDisp); lCodeComp.Order = lOrder; lCodeComp.DopIsp = int.Parse(lDopIsp); return lCodeComp; } catch (Exception e) { throw e; } finally { } } public static TCodeComp GetCodeComp(string Dse,string Disp, string Order,int DopIsp) { try { TCodeComp lCodeComp; lCodeComp = new TCodeComp(); return lCodeComp; } catch (Exception e) { throw e; } finally { } } public static TCodeComp GetCodeComp(string Dse, string Order, int DopIsp) { try { TCodeComp lCodeComp; lCodeComp = new TCodeComp(); return lCodeComp; } catch (Exception e) { throw e; } finally { } } public static TCodeComp GetCodeComp(string Dse, float Disp, string Order, int DopIsp) { try { TCodeComp lCodeComp; lCodeComp = new TCodeComp(); return lCodeComp; } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/Common/Zzva.Common/Rules.cs
C#
bsd
4,078
using System; using System.Collections.Generic; using System.Text; using System.Data; namespace Zzva.Common { /// public abstract class TBeBase: DataTable /// { /// public TBeBase() /// { /// DataColumn fldId; /// fldId = new DataColumn("Id",typeof(int)); /// fldId.AutoIncrement = true; /// fldId.Unique = true; /// this.Columns.Add(fldId); /// /// DataColumn fldObozn; /// fldObozn = new DataColumn("Obozn",typeof(string)); /// ////fldObozn.Unique = true; /// this.Columns.Add(fldObozn); /// /// DataColumn fldNaim; /// fldNaim = new DataColumn("Naim",typeof(string)); /// this.Columns.Add(fldNaim); /// /// //первичный ключ /// DataColumn[] PprimeryKey; /// PprimeryKey = new DataColumn[1]; /// PprimeryKey[0] = fldId; /// this.PrimaryKey = PprimeryKey; /// } /// } /// public class TOrder : TBeBase /// { /// public TOrder() /// { /// //планируеая дата окончания производства /// DataColumn fldDateEnd; /// fldDateEnd = new DataColumn("DateEnd", typeof(DateTime)); /// this.Columns.Add(fldDateEnd); /// } /// } /// public class TOrderItem : TBeBase /// { /// public TOrderItem() /// { /// //ссылка на заказ /// DataColumn fldOrder; /// fldOrder = new DataColumn("Order", typeof(int)); /// this.Columns.Add(fldOrder); /// /// //ссылка на Компонент /// DataColumn fldComponent; /// fldComponent = new DataColumn("Component", typeof(int)); /// this.Columns.Add(fldComponent); /// /// DataColumn fldCol; /// fldCol = new DataColumn("Col", typeof(int)); /// this.Columns.Add(fldCol); /// } /// /// } /// public class TComponent : TBeBase /// { /// public TComponent() /// { /// DataColumn fldDse; /// fldDse = new DataColumn("Dse", typeof(string)); /// this.Columns.Add(fldDse); /// /// DataColumn fldDisp; /// fldDisp = new DataColumn("Disp", typeof(string)); /// this.Columns.Add(fldDisp); /// /// //ссылка на заказ /// DataColumn fldOrder; /// fldOrder = new DataColumn("Order", typeof(int)); /// this.Columns.Add(fldOrder); /// /// DataColumn fldDopIsp; /// fldDopIsp = new DataColumn("DopIsp", typeof(int)); /// this.Columns.Add(fldDopIsp); /// /// DataColumn fldRazd; /// fldRazd = new DataColumn("Razd", typeof(byte)); /// this.Columns.Add(fldRazd); /// /// DataColumn fldFlgDop; /// fldFlgDop = new DataColumn("FlgDop", typeof(bool)); /// this.Columns.Add(fldFlgDop); /// /// DataColumn fldOboznAltern; /// fldOboznAltern = new DataColumn("OboznAltern", typeof(string)); /// //fldObozn.Unique = true; /// this.Columns.Add(fldOboznAltern); /// /// //способ воспроизводства по умолчанию /// //комплектующее, материал, производственный компонент, /// DataColumn fldTtype; /// fldTtype = new DataColumn("Ttype", typeof(byte)); /// this.Columns.Add(fldTtype); /// } /// } /// public class TSostav : TBeBase /// { /// public TSostav() /// { /// //ссылка на Компонент /// DataColumn fldComponent; /// fldComponent = new DataColumn("Component", typeof(int)); /// this.Columns.Add(fldComponent); /// /// //ссылка на Родителя Компонента /// DataColumn fldComponentParent; /// fldComponentParent = new DataColumn("ComponentParent", typeof(int)); /// this.Columns.Add(fldComponentParent); /// /// //Количество Компонента в Родителе /// DataColumn flgCol; /// flgCol = new DataColumn("Col", typeof(float)); /// this.Columns.Add(flgCol); /// /// //ссылка на Элемент Заказа /// DataColumn fldOrderItem; /// fldOrderItem = new DataColumn("OrderItem", typeof(int)); /// this.Columns.Add(fldOrderItem); /// /// //Количество Компонента в Элементе Заказа /// DataColumn flgColInOrderItem; /// flgColInOrderItem = new DataColumn("ColInOrderItem", typeof(float)); /// this.Columns.Add(flgColInOrderItem); /// } /// } /// //главный календарный план производства /// public class TMps : TBeBase /// { /// public TMps() /// { /// //ссылка на заводской заказ /// DataColumn fldOrder; /// fldOrder = new DataColumn("Order", typeof(int)); /// this.Columns.Add(fldOrder); /// /// //планируеая дата окончания производства /// DataColumn fldDateEnd; /// fldDateEnd = new DataColumn("DateEnd", typeof(DateTime)); /// this.Columns.Add(fldDateEnd); /// } /// } //полуфабрикат /// public class THalf : TBeBase /// { /// public THalf() /// { /// //ссылка на родительский Компонент /// DataColumn fldComponent; /// fldComponent = new DataColumn("Component", typeof(int)); /// this.Columns.Add(fldComponent); /// /// //Фаза изготовления компонента согласно маршрута /// DataColumn fldPhase; /// fldPhase = new DataColumn("Phase", typeof(byte)); /// this.Columns.Add(fldPhase); /// /// //Флаг, что это завершающая фаза изготовления компонента /// DataColumn fldPhaseEnd; /// fldPhaseEnd = new DataColumn("PhaseEnd", typeof(bool)); /// this.Columns.Add(fldPhaseEnd); /// /// //Ссылка на цех, который выпустил полуфабрикат /// DataColumn fldCeh; /// fldCeh = new DataColumn("Ceh", typeof(int)); /// this.Columns.Add(fldCeh); /// } /// } }
zzvalib
trunk/Common/Zzva.Common/BusinessEntities.cs
C#
bsd
7,038
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Zzva.Common { public class TLog { private const string LogFileName = "Log.txt"; protected TLog() { } private static void CreateLogFile() { try { string NameObject; bool FindTextListener; FindTextListener = false; foreach (TraceListener Listener in Trace.Listeners) { NameObject = Listener.GetType().Name; if (NameObject == "TextWriterTraceListener") { FindTextListener = true; break; } } if (FindTextListener == false)//создаем, это первое обращение { System.IO.FileStream Log = new System.IO.FileStream(LogFileName, System.IO.FileMode.Create); TextWriterTraceListener TextListener = new TextWriterTraceListener(Log); Trace.Listeners.Add(TextListener); Trace.AutoFlush = true; } } catch (Exception e) { throw e; } finally { } } //открыть лог файл программой по умолчанию public static void View() { try { CreateLogFile(); Process.Start(LogFileName); } catch (Exception e) { throw e; } finally { } } //заменить текстовый файл для логирования на чистый или создать public static void Reset() { try { string NameObject; foreach (TraceListener Listener in Trace.Listeners) { NameObject = Listener.GetType().Name; if (NameObject == "TextWriterTraceListener") { Trace.Listeners.Remove(Listener); Listener.Close(); break; } } } catch (Exception e) { throw e; } finally { } } //записать строку в лог-файл public static void Write(string Category,string Message) { try { CreateLogFile(); Trace.WriteLine(Message, Category); } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/Common/Zzva.Common/Log.cs
C#
bsd
2,859
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.Common")] [assembly: AssemblyCopyright("Copyright © zzva 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("234c7b46-c628-47d6-aaab-6a04e72df801")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/Common/Zzva.Common/Properties/AssemblyInfo.cs
C#
bsd
1,442