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
/*- * 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 Evgeny Boger * * 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 spi.h * @brief SPI driver header */ #ifndef __NFC_BUS_SPI_H__ # define __NFC_BUS_SPI_H__ # include <sys/time.h> # include <stdio.h> # include <string.h> # include <stdlib.h> # include <linux/spi/spidev.h> # include <nfc/nfc-types.h> // Define shortcut to types to make code more readable typedef void *spi_port; # define INVALID_SPI_PORT (void*)(~1) # define CLAIMED_SPI_PORT (void*)(~2) spi_port spi_open(const char *pcPortName); void spi_close(const spi_port sp); void spi_set_speed(spi_port sp, const uint32_t uiPortSpeed); void spi_set_mode(spi_port sp, const uint32_t uiPortMode); uint32_t spi_get_speed(const spi_port sp); int spi_receive(spi_port sp, uint8_t *pbtRx, const size_t szRx, bool lsb_first); int spi_send(spi_port sp, const uint8_t *pbtTx, const size_t szTx, bool lsb_first); int spi_send_receive(spi_port sp, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, bool lsb_first); char **spi_list_ports(void); #endif // __NFC_BUS_SPI_H__
1060840728-lvgang
libnfc/buses/spi.h
C
lgpl
2,160
/*- * 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 usbbus.h * @brief libusb 0.1 driver header */ #ifndef __NFC_BUS_USB_H__ # define __NFC_BUS_USB_H__ #ifndef _WIN32 // Under POSIX system, we use libusb (>= 0.1.12) #include <usb.h> #define USB_TIMEDOUT ETIMEDOUT #define _usb_strerror( X ) strerror(-X) #else // Under Windows we use libusb-win32 (>= 1.2.5) #include <lusb0_usb.h> #define USB_TIMEDOUT 116 #define _usb_strerror( X ) usb_strerror() #endif #include <stdbool.h> #include <string.h> int usb_prepare(void); #endif // __NFC_BUS_USB_H__
1060840728-lvgang
libnfc/buses/usbbus.h
C
lgpl
1,600
/*- * 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 Laurent Latil * * 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 i2c.h * @brief I2C driver header */ #ifndef __NFC_BUS_I2C_H__ # define __NFC_BUS_I2C_H__ # include <sys/time.h> # include <stdio.h> # include <string.h> # include <stdlib.h> # include <linux/i2c-dev.h> # include <nfc/nfc-types.h> typedef void *i2c_device; # define INVALID_I2C_BUS (void*)(~1) # define INVALID_I2C_ADDRESS (void*)(~2) i2c_device i2c_open(const char *pcI2C_busName, uint32_t devAddr); void i2c_close(const i2c_device id); ssize_t i2c_read(i2c_device id, uint8_t *pbtRx, const size_t szRx); int i2c_write(i2c_device id, const uint8_t *pbtTx, const size_t szTx); char **i2c_list_ports(void); #endif // __NFC_BUS_I2C_H__
1060840728-lvgang
libnfc/buses/i2c.h
C
lgpl
1,813
/* empty source code file */ #include <stdio.h>
1060840728-lvgang
libnfc/buses/empty.c
C
lgpl
48
/*- * 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 Laurent Latil * * 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 i2c.c * @brief I2C driver (implemented / tested for Linux only currently) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "i2c.h" #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <nfc/nfc.h> #include "nfc-internal.h" #define LOG_GROUP NFC_LOG_GROUP_COM #define LOG_CATEGORY "libnfc.bus.i2c" # if defined (__linux__) const char *i2c_ports_device_radix[] = { "i2c-", NULL }; # else # error "Can't determine I2C devices standard names for your system" # endif struct i2c_device_unix { int fd; // I2C device file descriptor }; #define I2C_DATA( X ) ((struct i2c_device_unix *) X) /** * @brief Open an I2C device * * @param pcI2C_busName I2C bus device name * @param devAddr address of the I2C device on the bus * @return pointer to the I2C device structure, or INVALID_I2C_BUS, INVALID_I2C_ADDRESS error codes. */ i2c_device i2c_open(const char *pcI2C_busName, uint32_t devAddr) { struct i2c_device_unix *id = malloc(sizeof(struct i2c_device_unix)); if (id == 0) return INVALID_I2C_BUS ; id->fd = open(pcI2C_busName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (id->fd == -1) { perror("Cannot open I2C bus"); i2c_close(id); return INVALID_I2C_BUS ; } if (ioctl(id->fd, I2C_SLAVE, devAddr) < 0) { perror("Cannot select I2C device"); i2c_close(id); return INVALID_I2C_ADDRESS ; } return id; } /** * @brief Close the I2C device * * @param id I2C device to close. */ void i2c_close(const i2c_device id) { if (I2C_DATA(id) ->fd >= 0) { close(I2C_DATA(id) ->fd); } free(id); } /** * @brief Read a frame from the I2C device and copy data to \a pbtRx * * @param id I2C device. * @param pbtRx pointer on buffer used to store data * @param szRx length of the buffer * @return length (in bytes) of read data, or driver error code (negative value) */ ssize_t i2c_read(i2c_device id, uint8_t *pbtRx, const size_t szRx) { ssize_t res; ssize_t recCount; recCount = read(I2C_DATA(id) ->fd, pbtRx, szRx); if (recCount < 0) { res = NFC_EIO; } else { if (recCount < (ssize_t)szRx) { res = NFC_EINVARG; } else { res = recCount; } } return res; } /** * @brief Write a frame to I2C device containing \a pbtTx content * * @param id I2C device. * @param pbtTx pointer on buffer containing data * @param szTx length of the buffer * @return NFC_SUCCESS on success, otherwise driver error code */ int i2c_write(i2c_device id, const uint8_t *pbtTx, const size_t szTx) { LOG_HEX(LOG_GROUP, "TX", pbtTx, szTx); ssize_t writeCount; writeCount = write(I2C_DATA(id) ->fd, pbtTx, szTx); if ((const ssize_t) szTx == writeCount) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "wrote %d bytes successfully.", (int)szTx); return NFC_SUCCESS; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Error: wrote only %d bytes (%d expected).", (int)writeCount, (int) szTx); return NFC_EIO; } } /** * @brief Get the path of all I2C bus devices. * * @return array of strings defining the names of all I2C buses available. This array, and each string, are allocated * by this function and must be freed by caller. */ char ** i2c_list_ports(void) { char **res = malloc(sizeof(char *)); if (!res) { perror("malloc"); return res; } size_t szRes = 1; res[0] = NULL; DIR *dir; if ((dir = opendir("/dev")) == NULL) { perror("opendir error: /dev"); return res; } struct dirent entry; struct dirent *result; while ((readdir_r(dir, &entry, &result) == 0) && (result != NULL)) { const char **p = i2c_ports_device_radix; while (*p) { if (!strncmp(entry.d_name, *p, strlen(*p))) { char **res2 = realloc(res, (szRes + 1) * sizeof(char *)); if (!res2) { perror("malloc"); goto oom; } res = res2; if (!(res[szRes - 1] = malloc(6 + strlen(entry.d_name)))) { perror("malloc"); goto oom; } sprintf(res[szRes - 1], "/dev/%s", entry.d_name); szRes++; res[szRes - 1] = NULL; } p++; } } oom: closedir(dir); return res; }
1060840728-lvgang
libnfc/buses/i2c.c
C
lgpl
5,624
/*- * 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 UART driver */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "uart.h" #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include <stdlib.h> #include <nfc/nfc.h> #include "nfc-internal.h" #define LOG_GROUP NFC_LOG_GROUP_COM #define LOG_CATEGORY "libnfc.bus.uart" #ifndef _WIN32 // Needed by sleep() under Unix # include <unistd.h> # 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 // Needed by Sleep() under Windows # include <winbase.h> # define msleep Sleep #endif # if defined(__APPLE__) const char *serial_ports_device_radix[] = { "tty.SLAB_USBtoUART", "tty.usbserial-", NULL }; # elif defined (__FreeBSD__) || defined (__OpenBSD__) || defined(__FreeBSD_kernel__) const char *serial_ports_device_radix[] = { "cuaU", "cuau", NULL }; # elif defined (__linux__) const char *serial_ports_device_radix[] = { "ttyUSB", "ttyS", "ttyACM", "ttyAMA", "ttyO", NULL }; # else # error "Can't determine serial string for your system" # endif // Work-around to claim uart interface using the c_iflag (software input processing) from the termios struct # define CCLAIMED 0x80000000 struct serial_port_unix { int fd; // Serial port file descriptor struct termios termios_backup; // Terminal info before using the port struct termios termios_new; // Terminal info during the transaction }; #define UART_DATA( X ) ((struct serial_port_unix *) X) void uart_close_ext(const serial_port sp, const bool restore_termios); serial_port uart_open(const char *pcPortName) { struct serial_port_unix *sp = malloc(sizeof(struct serial_port_unix)); if (sp == 0) return INVALID_SERIAL_PORT; sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (sp->fd == -1) { uart_close_ext(sp, false); return INVALID_SERIAL_PORT; } if (tcgetattr(sp->fd, &sp->termios_backup) == -1) { uart_close_ext(sp, false); return INVALID_SERIAL_PORT; } // Make sure the port is not claimed already if (sp->termios_backup.c_iflag & CCLAIMED) { uart_close_ext(sp, false); return CLAIMED_SERIAL_PORT; } // Copy the old terminal info struct sp->termios_new = sp->termios_backup; sp->termios_new.c_cflag = CS8 | CLOCAL | CREAD; sp->termios_new.c_iflag = CCLAIMED | IGNPAR; sp->termios_new.c_oflag = 0; sp->termios_new.c_lflag = 0; sp->termios_new.c_cc[VMIN] = 0; // block until n bytes are received sp->termios_new.c_cc[VTIME] = 0; // block until a timer expires (n * 100 mSec.) if (tcsetattr(sp->fd, TCSANOW, &sp->termios_new) == -1) { uart_close_ext(sp, true); return INVALID_SERIAL_PORT; } return sp; } void uart_flush_input(serial_port sp, bool wait) { // flush commands may seem to be without effect // if asked too quickly after previous event, cf comments below // therefore a "wait" argument allows now to wait before flushing // I believe that now the byte-eater part is not required anymore --Phil if (wait) { msleep(50); // 50 ms } // This line seems to produce absolutely no effect on my system (GNU/Linux 2.6.35) tcflush(UART_DATA(sp)->fd, TCIFLUSH); // So, I wrote this byte-eater // Retrieve the count of the incoming bytes int available_bytes_count = 0; int res; res = ioctl(UART_DATA(sp)->fd, FIONREAD, &available_bytes_count); if (res != 0) { return; } if (available_bytes_count == 0) { return; } char *rx = malloc(available_bytes_count); if (!rx) { perror("malloc"); return; } // There is something available, read the data if (read(UART_DATA(sp)->fd, rx, available_bytes_count) < 0) { perror("uart read"); free(rx); return; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d bytes have eaten.", available_bytes_count); free(rx); } void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Serial port speed requested to be set to %d baud.", uiPortSpeed); // Portability note: on some systems, B9600 != 9600 so we have to do // uint32_t <=> speed_t associations by hand. speed_t stPortSpeed = B9600; switch (uiPortSpeed) { case 9600: stPortSpeed = B9600; break; case 19200: stPortSpeed = B19200; break; case 38400: stPortSpeed = B38400; break; # ifdef B57600 case 57600: stPortSpeed = B57600; break; # endif # ifdef B115200 case 115200: stPortSpeed = B115200; break; # endif # ifdef B230400 case 230400: stPortSpeed = B230400; break; # endif # ifdef B460800 case 460800: stPortSpeed = B460800; break; # endif default: log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set serial port speed to %d baud. Speed value must be one of those defined in termios(3).", uiPortSpeed); return; }; // Set port speed (Input and Output) cfsetispeed(&(UART_DATA(sp)->termios_new), stPortSpeed); cfsetospeed(&(UART_DATA(sp)->termios_new), stPortSpeed); if (tcsetattr(UART_DATA(sp)->fd, TCSADRAIN, &(UART_DATA(sp)->termios_new)) == -1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to apply new speed settings."); } } uint32_t uart_get_speed(serial_port sp) { uint32_t uiPortSpeed = 0; switch (cfgetispeed(&UART_DATA(sp)->termios_new)) { case B9600: uiPortSpeed = 9600; break; case B19200: uiPortSpeed = 19200; break; case B38400: uiPortSpeed = 38400; break; # ifdef B57600 case B57600: uiPortSpeed = 57600; break; # endif # ifdef B115200 case B115200: uiPortSpeed = 115200; break; # endif # ifdef B230400 case B230400: uiPortSpeed = 230400; break; # endif # ifdef B460800 case B460800: uiPortSpeed = 460800; break; # endif } return uiPortSpeed; } void uart_close_ext(const serial_port sp, const bool restore_termios) { if (UART_DATA(sp)->fd >= 0) { if (restore_termios) tcsetattr(UART_DATA(sp)->fd, TCSANOW, &UART_DATA(sp)->termios_backup); close(UART_DATA(sp)->fd); } free(sp); } void uart_close(const serial_port sp) { uart_close_ext(sp, true); } /** * @brief Receive data from UART and copy data to \a pbtRx * * @return 0 on success, otherwise driver error code */ int uart_receive(serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout) { int iAbortFd = abort_p ? *((int *)abort_p) : 0; int received_bytes_count = 0; int available_bytes_count = 0; const int expected_bytes_count = (int)szRx; int res; fd_set rfds; do { select: // Reset file descriptor FD_ZERO(&rfds); FD_SET(UART_DATA(sp)->fd, &rfds); if (iAbortFd) { FD_SET(iAbortFd, &rfds); } struct timeval timeout_tv; if (timeout > 0) { timeout_tv.tv_sec = (timeout / 1000); timeout_tv.tv_usec = ((timeout % 1000) * 1000); } res = select(MAX(UART_DATA(sp)->fd, iAbortFd) + 1, &rfds, NULL, NULL, timeout ? &timeout_tv : NULL); if ((res < 0) && (EINTR == errno)) { // The system call was interupted by a signal and a signal handler was // run. Restart the interupted system call. goto select; } // Read error if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error: %s", strerror(errno)); return NFC_EIO; } // Read time-out if (res == 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Timeout!"); return NFC_ETIMEOUT; } if (FD_ISSET(iAbortFd, &rfds)) { // Abort requested log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Abort!"); close(iAbortFd); return NFC_EOPABORTED; } // Retrieve the count of the incoming bytes res = ioctl(UART_DATA(sp)->fd, FIONREAD, &available_bytes_count); if (res != 0) { return NFC_EIO; } // There is something available, read the data res = read(UART_DATA(sp)->fd, pbtRx + received_bytes_count, MIN(available_bytes_count, (expected_bytes_count - received_bytes_count))); // Stop if the OS has some troubles reading the data if (res <= 0) { return NFC_EIO; } received_bytes_count += res; } while (expected_bytes_count > received_bytes_count); LOG_HEX(LOG_GROUP, "RX", pbtRx, szRx); return NFC_SUCCESS; } /** * @brief Send \a pbtTx content to UART * * @return 0 on success, otherwise a driver error is returned */ int uart_send(serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout) { (void) timeout; LOG_HEX(LOG_GROUP, "TX", pbtTx, szTx); if ((int) szTx == write(UART_DATA(sp)->fd, pbtTx, szTx)) return NFC_SUCCESS; else return NFC_EIO; } char ** uart_list_ports(void) { char **res = malloc(sizeof(char *)); if (!res) { perror("malloc"); return res; } size_t szRes = 1; res[0] = NULL; DIR *dir; if ((dir = opendir("/dev")) == NULL) { perror("opendir error: /dev"); return res; } struct dirent entry; struct dirent *result; while ((readdir_r(dir, &entry, &result) == 0) && (result != NULL)) { #if !defined(__APPLE__) if (!isdigit(entry.d_name[strlen(entry.d_name) - 1])) continue; #endif const char **p = serial_ports_device_radix; while (*p) { if (!strncmp(entry.d_name, *p, strlen(*p))) { char **res2 = realloc(res, (szRes + 1) * sizeof(char *)); if (!res2) { perror("malloc"); goto oom; } res = res2; if (!(res[szRes - 1] = malloc(6 + strlen(entry.d_name)))) { perror("malloc"); goto oom; } sprintf(res[szRes - 1], "/dev/%s", entry.d_name); szRes++; res[szRes - 1] = NULL; } p++; } } oom: closedir(dir); return res; }
1060840728-lvgang
libnfc/buses/uart.c
C
lgpl
11,334
# set the include path found by configure AM_CPPFLAGS = $(all_includes) $(LIBNFC_CFLAGS) noinst_LTLIBRARIES = libnfcbuses.la libnfcbuses_la_SOURCES = empty.c libnfcbuses_la_CFLAGS = -I$(top_srcdir)/libnfc libnfcbuses_la_LIBADD = EXTRA_DIST = if SPI_ENABLED libnfcbuses_la_SOURCES += spi.c spi.h libnfcbuses_la_CFLAGS += libnfcbuses_la_LIBADD += endif EXTRA_DIST += spi.c spi.h if UART_ENABLED libnfcbuses_la_SOURCES += uart.c uart.h libnfcbuses_la_CFLAGS += libnfcbuses_la_LIBADD += endif EXTRA_DIST += uart.c uart.h if LIBUSB_ENABLED libnfcbuses_la_SOURCES += usbbus.c usbbus.h libnfcbuses_la_CFLAGS += @libusb_CFLAGS@ libnfcbuses_la_LIBADD += @libusb_LIBS@ endif EXTRA_DIST += usbbus.c usbbus.h if I2C_ENABLED libnfcbuses_la_SOURCES += i2c.c i2c.h libnfcbuses_la_CFLAGS += libnfcbuses_la_LIBADD += endif EXTRA_DIST += i2c.c i2c.h
1060840728-lvgang
libnfc/buses/Makefile.am
Makefile
lgpl
858
/*- * 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.h * @brief UART driver header */ #ifndef __NFC_BUS_UART_H__ # define __NFC_BUS_UART_H__ # include <sys/time.h> # include <stdio.h> # include <string.h> # include <stdlib.h> # include <nfc/nfc-types.h> // Define shortcut to types to make code more readable typedef void *serial_port; # define INVALID_SERIAL_PORT (void*)(~1) # define CLAIMED_SERIAL_PORT (void*)(~2) serial_port uart_open(const char *pcPortName); void uart_close(const serial_port sp); void uart_flush_input(const serial_port sp, bool wait); void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed); uint32_t uart_get_speed(const serial_port sp); int uart_receive(serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout); int uart_send(serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout); char **uart_list_ports(void); #endif // __NFC_BUS_UART_H__
1060840728-lvgang
libnfc/buses/uart.h
C
lgpl
2,002
/*- * 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 Evgeny Boger * * 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 spi.c * @brief SPI driver */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "spi.h" #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/types.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include <nfc/nfc.h> #include "nfc-internal.h" #define LOG_GROUP NFC_LOG_GROUP_COM #define LOG_CATEGORY "libnfc.bus.spi" # if defined(__APPLE__) const char *spi_ports_device_radix[] = { "spidev", NULL }; # elif defined (__FreeBSD__) || defined (__OpenBSD__) const char *spi_ports_device_radix[] = { "spidev", NULL }; # elif defined (__linux__) const char *spi_ports_device_radix[] = { "spidev", NULL }; # else # error "Can't determine spi port string for your system" # endif struct spi_port_unix { int fd; // Serial port file descriptor //~ struct termios termios_backup; // Terminal info before using the port //~ struct termios termios_new; // Terminal info during the transaction }; #define SPI_DATA( X ) ((struct spi_port_unix *) X) spi_port spi_open(const char *pcPortName) { struct spi_port_unix *sp = malloc(sizeof(struct spi_port_unix)); if (sp == 0) return INVALID_SPI_PORT; sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (sp->fd == -1) { spi_close(sp); return INVALID_SPI_PORT; } return sp; } void spi_set_speed(spi_port sp, const uint32_t uiPortSpeed) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "SPI port speed requested to be set to %d Hz.", uiPortSpeed); int ret; ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_WR_MAX_SPEED_HZ, &uiPortSpeed); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "ret %d", ret); if (ret == -1) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error setting SPI speed."); } void spi_set_mode(spi_port sp, const uint32_t uiPortMode) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "SPI port mode requested to be set to %d.", uiPortMode); int ret; ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_WR_MODE, &uiPortMode); if (ret == -1) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error setting SPI mode."); } uint32_t spi_get_speed(spi_port sp) { uint32_t uiPortSpeed = 0; int ret; ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_RD_MAX_SPEED_HZ, &uiPortSpeed); if (ret == -1) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error reading SPI speed."); return uiPortSpeed; } void spi_close(const spi_port sp) { close(SPI_DATA(sp)->fd); free(sp); } /** * @brief Perform bit reversal on one byte \a x * * @return reversed byte */ static uint8_t bit_reversal(const uint8_t x) { uint8_t ret = x; ret = (((ret & 0xaa) >> 1) | ((ret & 0x55) << 1)); ret = (((ret & 0xcc) >> 2) | ((ret & 0x33) << 2)); ret = (((ret & 0xf0) >> 4) | ((ret & 0x0f) << 4)); return ret; } /** * @brief Send \a pbtTx content to SPI then receive data from SPI and copy data to \a pbtRx. CS line stays active between transfers as well as during transfers. * * @return 0 on success, otherwise a driver error is returned */ int spi_send_receive(spi_port sp, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, bool lsb_first) { size_t transfers = 0; struct spi_ioc_transfer tr[2]; uint8_t *pbtTxLSB = 0; if (szTx) { LOG_HEX(LOG_GROUP, "TX", pbtTx, szTx); if (lsb_first) { pbtTxLSB = malloc(szTx * sizeof(uint8_t)); if (!pbtTxLSB) { return NFC_ESOFT; } size_t i; for (i = 0; i < szTx; ++i) { pbtTxLSB[i] = bit_reversal(pbtTx[i]); } pbtTx = pbtTxLSB; } struct spi_ioc_transfer tr_send = { .tx_buf = (unsigned long) pbtTx, .rx_buf = 0, .len = szTx , .delay_usecs = 0, .speed_hz = 0, .bits_per_word = 0, }; tr[transfers] = tr_send; ++transfers; } if (szRx) { struct spi_ioc_transfer tr_receive = { .tx_buf = 0, .rx_buf = (unsigned long) pbtRx, .len = szRx, .delay_usecs = 0, .speed_hz = 0, .bits_per_word = 0, }; tr[transfers] = tr_receive; ++transfers; } if (transfers) { int ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_MESSAGE(transfers), tr); if (szTx && lsb_first) { free(pbtTxLSB); } if (ret != (int)(szRx + szTx)) { return NFC_EIO; } // Reverse received bytes if needed if (szRx) { if (lsb_first) { size_t i; for (i = 0; i < szRx; ++i) { pbtRx[i] = bit_reversal(pbtRx[i]); } } LOG_HEX(LOG_GROUP, "RX", pbtRx, szRx); } } return NFC_SUCCESS; } /** * @brief Receive data from SPI and copy data to \a pbtRx * * @return 0 on success, otherwise driver error code */ int spi_receive(spi_port sp, uint8_t *pbtRx, const size_t szRx, bool lsb_first) { return spi_send_receive(sp, 0, 0, pbtRx, szRx, lsb_first); } /** * @brief Send \a pbtTx content to SPI * * @return 0 on success, otherwise a driver error is returned */ int spi_send(spi_port sp, const uint8_t *pbtTx, const size_t szTx, bool lsb_first) { return spi_send_receive(sp, pbtTx, szTx, 0, 0, lsb_first); } char ** spi_list_ports(void) { char **res = malloc(sizeof(char *)); size_t szRes = 1; res[0] = NULL; DIR *pdDir = opendir("/dev"); struct dirent *pdDirEnt; struct dirent entry; struct dirent *result; while ((readdir_r(pdDir, &entry, &result) == 0) && (result != NULL)) { pdDirEnt = &entry; #if !defined(__APPLE__) if (!isdigit(pdDirEnt->d_name[strlen(pdDirEnt->d_name) - 1])) continue; #endif const char **p = spi_ports_device_radix; while (*p) { if (!strncmp(pdDirEnt->d_name, *p, strlen(*p))) { char **res2 = realloc(res, (szRes + 1) * sizeof(char *)); if (!res2) goto oom; res = res2; if (!(res[szRes - 1] = malloc(6 + strlen(pdDirEnt->d_name)))) goto oom; sprintf(res[szRes - 1], "/dev/%s", pdDirEnt->d_name); szRes++; res[szRes - 1] = NULL; } p++; } } oom: closedir(pdDir); return res; }
1060840728-lvgang
libnfc/buses/spi.c
C
lgpl
7,388
/*- * 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 usbbus.c * @brief libusb 0.1 driver wrapper */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdlib.h> #include "usbbus.h" #include "log.h" #define LOG_CATEGORY "libnfc.buses.usbbus" #define LOG_GROUP NFC_LOG_GROUP_DRIVER int usb_prepare(void) { static bool usb_initialized = false; if (!usb_initialized) { #ifdef ENVVARS char *env_log_level = getenv("LIBNFC_LOG_LEVEL"); // Set libusb debug only if asked explicitely: // LIBUSB_LOG_LEVEL=12288 (= NFC_LOG_PRIORITY_DEBUG * 2 ^ NFC_LOG_GROUP_LIBUSB) if (env_log_level && (((atoi(env_log_level) >> (NFC_LOG_GROUP_LIBUSB * 2)) & 0x00000003) >= NFC_LOG_PRIORITY_DEBUG)) { setenv("USB_DEBUG", "255", 1); } #endif usb_init(); usb_initialized = true; } int res; // usb_find_busses will find all of the busses on the system. Returns the // number of changes since previous call to this function (total of new // busses and busses removed). if ((res = usb_find_busses()) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror(res)); return -1; } // usb_find_devices will find all of the devices on each bus. This should be // called after usb_find_busses. Returns the number of changes since the // previous call to this function (total of new device and devices removed). if ((res = usb_find_devices()) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror(res)); return -1; } return 0; }
1060840728-lvgang
libnfc/buses/usbbus.c
C
lgpl
2,669
/*- * 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 drivers.h * @brief Supported drivers header */ #ifndef __NFC_DRIVERS_H__ #define __NFC_DRIVERS_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver_list *nfc_drivers; #endif // __NFC_DRIVERS_H__
1060840728-lvgang
libnfc/drivers.h
C
lgpl
1,305
PROJECT(libnfc C) CMAKE_MINIMUM_REQUIRED(VERSION 2.6) SET(VERSION_MAJOR "1") SET(VERSION_MINOR "7") SET(VERSION_PATCH "1") SET(VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}") SET(PACKAGE_NAME "libnfc") SET(PACKAGE_VERSION ${VERSION}) SET(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") # config.h IF(WIN32) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/cmake/config_windows.h.cmake ${CMAKE_CURRENT_SOURCE_DIR}/config.h) SET(LIBNFC_SYSCONFDIR "${CMAKE_INSTALL_PREFIX}/config" CACHE PATH "libnfc configuration directory") INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/contrib/win32) ELSE(WIN32) SET(_XOPEN_SOURCE 600) SET(SYSCONFDIR "/etc" CACHE PATH "System configuration directory") CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/cmake/config_posix.h.cmake ${CMAKE_CURRENT_SOURCE_DIR}/config.h) ENDIF(WIN32) ADD_DEFINITIONS("-DHAVE_CONFIG_H") INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/include) # make it easy to locate CMake modules for finding libraries SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules/") # Options SET(LIBNFC_LOG ON CACHE BOOL "Enable log facility (errors, warning, info and debug messages)") IF(LIBNFC_LOG) ADD_DEFINITIONS(-DLOG) ENDIF(LIBNFC_LOG) SET(LIBNFC_ENVVARS ON CACHE BOOL "Enable envvars facility") IF(LIBNFC_ENVVARS) ADD_DEFINITIONS(-DENVVARS) ENDIF(LIBNFC_ENVVARS) SET(LIBNFC_DEBUG_MODE OFF CACHE BOOL "Debug mode") IF(LIBNFC_DEBUG_MODE) ADD_DEFINITIONS(-DDEBUG) SET(CMAKE_C_FLAGS "-g3 ${CMAKE_C_FLAGS}") SET(WIN32_MODE "debug") SET(CMAKE_RC_FLAGS "-D_DEBUG ${CMAKE_RC_FLAGS}") ELSE(LIBNFC_DEBUG_MODE) SET(WIN32_MODE "release") ENDIF(LIBNFC_DEBUG_MODE) SET(LIBNFC_CONFFILES_MODE ON CACHE BOOL "Enable configuration files") IF(LIBNFC_CONFFILES_MODE) ADD_DEFINITIONS(-DCONFFILES) ENDIF(LIBNFC_CONFFILES_MODE) # Doxygen SET(builddir "${CMAKE_BINARY_DIR}") SET(top_srcdir "${CMAKE_SOURCE_DIR}") INCLUDE(UseDoxygen) IF(DEFINED CMAKE_INSTALL_LIBDIR) SET(libdir ${CMAKE_INSTALL_LIBDIR}) ELSE(DEFINED CMAKE_INSTALL_LIBDIR) SET(CMAKE_INSTALL_LIBDIR lib) SET(libdir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}) ENDIF(DEFINED CMAKE_INSTALL_LIBDIR) IF(DEFINED INCLUDE_INSTALL_DIR) SET(includedir ${INCLUDE_INSTALL_DIR}) ELSE(DEFINED INCLUDE_INSTALL_DIR) SET(INCLUDE_INSTALL_DIR include) SET(includedir ${CMAKE_INSTALL_PREFIX}/${INCLUDE_INSTALL_DIR}) ENDIF(DEFINED INCLUDE_INSTALL_DIR) IF(NOT DEFINED SHARE_INSTALL_PREFIX) SET(SHARE_INSTALL_PREFIX share) ENDIF(NOT DEFINED SHARE_INSTALL_PREFIX) # Additonnal GCC flags IF(CMAKE_COMPILER_IS_GNUCC) # Make sure we will not miss some warnings ;) SET(CMAKE_C_FLAGS "-Wall -pedantic -std=c99 ${CMAKE_C_FLAGS}") ENDIF(CMAKE_COMPILER_IS_GNUCC) # Workarounds for libusb in C99 ADD_DEFINITIONS(-Du_int8_t=uint8_t -Du_int16_t=uint16_t) IF(MINGW) # force MinGW-w64 in 32bit mode SET(CMAKE_C_FLAGS "-m32 ${CMAKE_C_FLAGS}") SET(CMAKE_MODULE_LINKER_FLAGS "-m32 -Wl,--enable-stdcall-fixup ${CMAKE_SHARED_LINKER_FLAGS}") SET(CMAKE_SHARED_LINKER_FLAGS "-m32 -Wl,--enable-stdcall-fixup ${CMAKE_SHARED_LINKER_FLAGS}") SET(CMAKE_EXE_LINKER_FLAGS "-m32 -Wl,--enable-stdcall-fixup ${CMAKE_EXE_LINKER_FLAGS}") SET(CMAKE_RC_FLAGS "--target=pe-i386 --output-format=coff ${CMAKE_RC_FLAGS}") ENDIF(MINGW) IF(NOT WIN32) # Set some pkg-config variables SET(prefix ${CMAKE_INSTALL_PREFIX}) SET(exec_prefix ${CMAKE_INSTALL_PREFIX}) SET(PACKAGE "libnfc") IF(LIBNFC_DRIVER_PN53X_USB) SET(PKG_REQ ${PKG_REQ} "libusb") ENDIF(LIBNFC_DRIVER_PN53X_USB) IF(LIBNFC_DRIVER_ACR122) SET(PKG_REQ ${PKG_REQ} "libpcsclite") ENDIF(LIBNFC_DRIVER_ACR122) # CMake lists are separated by a semi colon, replace with colon STRING(REPLACE ";" "," PKG_CONFIG_REQUIRES "${PKG_REQ}") CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/libnfc.pc.in ${CMAKE_CURRENT_BINARY_DIR}/libnfc.pc @ONLY) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/libnfc.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) ENDIF(NOT WIN32) # Require PCRE for Win32 IF (WIN32) FIND_PACKAGE(PCRE REQUIRED) IF(PCRE_INCLUDE_DIRS) INCLUDE_DIRECTORIES(${PCRE_INCLUDE_DIRS}) LINK_DIRECTORIES(${PCRE_LIBRARY_DIRS}) ENDIF(PCRE_INCLUDE_DIRS) ENDIF(WIN32) INCLUDE(LibnfcDrivers) IF(PCSC_INCLUDE_DIRS) INCLUDE_DIRECTORIES(${PCSC_INCLUDE_DIRS}) LINK_DIRECTORIES(${PCSC_LIBRARY_DIRS}) ENDIF(PCSC_INCLUDE_DIRS) IF(LIBUSB_INCLUDE_DIRS) INCLUDE_DIRECTORIES(${LIBUSB_INCLUDE_DIRS}) LINK_DIRECTORIES(${LIBUSB_LIBRARY_DIRS}) SET(LIBUSB_FOUND TRUE) ENDIF(LIBUSB_INCLUDE_DIRS) # version.rc for Windows IF(WIN32) # Date for filling in rc file information MACRO (GET_CURRENT_YEAR RESULT) EXECUTE_PROCESS(COMMAND "cmd" " /C date /T" OUTPUT_VARIABLE ${RESULT}) STRING(REGEX REPLACE "\n" "" ${RESULT} ${${RESULT}}) STRING(REGEX REPLACE ".*(..)/(..)/(....).*" "\\3" ${RESULT} ${${RESULT}}) ENDMACRO (GET_CURRENT_YEAR) GET_CURRENT_YEAR(CURRENT_YEAR) MESSAGE("Year for copyright is " ${CURRENT_YEAR}) SET(RC_COMMENT "${PACKAGE_NAME} library") SET(RC_INTERNAL_NAME "${PACKAGE_NAME} ${WIN32_MODE}") SET(RC_ORIGINAL_NAME ${PACKAGE_NAME}.dll) SET(RC_FILE_TYPE VFT_DLL) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/contrib/win32/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/windows/libnfc.rc @ONLY) ENDIF(WIN32) ADD_SUBDIRECTORY(libnfc) ADD_SUBDIRECTORY(include) ADD_SUBDIRECTORY(utils) ADD_SUBDIRECTORY(examples) # Binary Package IF(WIN32) SET(CPACK_GENERATOR "ZIP") ELSE(WIN32) SET(CPACK_GENERATOR "TBZ2") ENDIF(WIN32) SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Near Field Communication (NFC) library") SET(CPACK_PACKAGE_VENDOR "Roel Verdult") SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README") SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING") SET(CPACK_PACKAGE_INSTALL_DIRECTORY "libnfc") SET(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR}) SET(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR}) SET(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH}) SET(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "NFC Library") SET(CPACK_COMPONENT_EXAMPLES_DISPLAY_NAME "Example Applications") SET(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "Development Headers") IF(NOT WIN32) SET(CPACK_COMPONENT_MANUALS_DISPLAY_NAME "Example Applications Manuals") SET(CPACK_COMPONENT_MANUALS_DISABLED TRUE) SET(CPACK_COMPONENT_MANUALS_DEPENDS examples) ENDIF(NOT WIN32) SET(CPACK_COMPONENT_HEADERS_DISABLED TRUE) SET(CPACK_COMPONENT_HEADERS_DEPENDS libraries) SET(CPACK_COMPONENT_EXAMPLES_DEPENDS libraries) # Source Package IF(WIN32) SET(CPACK_SOURCE_GENERATOR "ZIP") ELSE(WIN32) SET(CPACK_SOURCE_GENERATOR "ZIP;TBZ2") ENDIF(WIN32) SET(CPACK_SOURCE_PACKAGE_FILE_NAME "libnfc-${VERSION}") SET(CPACK_SOURCE_IGNORE_FILES "~$" "/\\\\.git/" "bin/") INCLUDE(CPack)
1060840728-lvgang
CMakeLists.txt
CMake
lgpl
6,734
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 ])
1060840728-lvgang
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 ])
1060840728-lvgang
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 ])
1060840728-lvgang
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" ])
1060840728-lvgang
m4/libnfc_drivers.m4
M4Sugar
lgpl
5,293
/*- * 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) 2014 Pim 't Hart * * 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-jewel.c * @brief Jewel 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 "jewel.h" static nfc_device *pnd; static nfc_target nt; static jewel_req req; static jewel_res res; static jewel_tag ttDump; static uint32_t uiBlocks = 0x0E; static uint32_t uiBytesPerBlock = 0x08; static const nfc_modulation nmJewel = { .nmt = NMT_JEWEL, .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 block; uint32_t byte; bool bFailure = false; uint32_t uiReadBlocks = 0; printf("Reading %d blocks |", uiBlocks + 1); for (block = 0; block <= uiBlocks; block++) { for (byte = 0; byte < uiBytesPerBlock; byte++) { // Try to read the byte req.read.btCmd = TC_READ; req.read.btAdd = (block << 3) + byte; if (nfc_initiator_jewel_cmd(pnd, req, &res)) { ttDump.ttd.abtData[(block << 3) + byte] = res.read.btDat; } else { bFailure = true; break; } } print_success_or_failure(bFailure, &uiReadBlocks); fflush(stdout); } printf("|\n"); printf("Done, %d of %d blocks read.\n", uiReadBlocks, uiBlocks + 1); return (!bFailure); } static bool write_card(void) { uint32_t block; uint32_t byte; bool bFailure = false; uint32_t uiWrittenBlocks = 0; uint32_t uiSkippedBlocks = 0; uint32_t uiPartialBlocks = 0; char buffer[BUFSIZ]; bool write_otp; bool write_lock; 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("Write OTP bytes ? [yN] "); if (!fgets(buffer, BUFSIZ, stdin)) { ERR("Unable to read standard input."); } write_otp = ((buffer[0] == 'y') || (buffer[0] == 'Y')); printf("Writing %d pages |", uiBlocks + 1); // Skip block 0 - as far as I know there are no Jewel tags with block 0 writeable printf("s"); uiSkippedBlocks++; for (block = uiSkippedBlocks; block <= uiBlocks; block++) { // Skip block 0x0D - it is reserved for internal use and can't be written if (block == 0x0D) { printf("s"); uiSkippedBlocks++; continue; } // Skip block 0X0E if lock-bits and OTP shouldn't be written if ((block == 0x0E) && (!write_lock) && (!write_otp)) { printf("s"); uiSkippedBlocks++; continue; } // Write block 0x0E partially if lock-bits or OTP shouldn't be written if ((block == 0x0E) && (!write_lock || !write_otp)) { printf("p"); uiPartialBlocks++; } for (byte = 0; byte < uiBytesPerBlock; byte++) { if ((block == 0x0E) && (byte == 0 || byte == 1) && (!write_lock)) { continue; } if ((block == 0x0E) && (byte > 1) && (!write_otp)) { 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, nmJewel, NULL, 0, &nt) <= 0) { ERR("tag was removed"); return false; } bFailure = false; } req.writee.btCmd = TC_WRITEE; req.writee.btAdd = (block << 3) + byte; req.writee.btDat = ttDump.ttd.abtData[(block << 3) + byte]; if (!nfc_initiator_jewel_cmd(pnd, req, &res)) { bFailure = true; } } print_success_or_failure(bFailure, &uiWrittenBlocks); fflush(stdout); } printf("|\n"); printf("Done, %d of %d blocks written (%d blocks partial, %d blocks skipped).\n", uiWrittenBlocks, uiBlocks + 1, uiPartialBlocks, uiSkippedBlocks); return true; } int main(int argc, const char *argv[]) { bool bReadAction; FILE *pfDump; if (argc < 3) { printf("\n"); printf("%s r|w <dump.jwd>\n", argv[0]); printf("\n"); printf("r|w - Perform read from or write to card\n"); printf("<dump.jwd> - JeWel Dump (JWD) used to write (card to JWD) or (JWD 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(&ttDump, 0x00, sizeof(ttDump)); } else { pfDump = fopen(argv[2], "rb"); if (pfDump == NULL) { ERR("Could not open dump file: %s\n", argv[2]); exit(EXIT_FAILURE); } if (fread(&ttDump, 1, sizeof(ttDump), pfDump) != sizeof(ttDump)) { 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 Jewel tag if (nfc_initiator_select_passive_target(pnd, nmJewel, NULL, 0, &nt) <= 0) { ERR("no tag was found\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } // Get the info from the current tag printf("Found Jewel card with UID: "); size_t szPos; for (szPos = 0; szPos < 4; szPos++) { printf("%02x", nt.nti.nji.btId[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(&ttDump, 1, sizeof(ttDump), pfDump) != sizeof(ttDump)) { 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); }
1060840728-lvgang
utils/nfc-jewel.c
C
lgpl
8,766
/*- * 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; FILE *F; if (!(F = fopen(filename, "r"))) { printf("File not found or not accessible '%s'\n", filename); return -1; } if (stat(filename, &sb) < 0) { printf("File not found or not accessible '%s'\n", filename); fclose(F); return -1; } /* Check file size */ if (sb.st_size > 0xFFFF) { printf("File size too large '%s'\n", filename); fclose(F); 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); if (1 != fread(tag_data->ndef_file + 2, sb.st_size, 1, F)) { printf("Can't read from %s\n", 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)\n", filename); return -1; } if (1 != fwrite(tag_data->ndef_file + 2, tag_data->ndef_file_len - 2, 1, F)) { printf("fwrite (%d)\n", (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'\n", 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); }
1060840728-lvgang
utils/nfc-emulate-forum-tag4.c
C
lgpl
13,040
/*- * 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; } // 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; }
1060840728-lvgang
utils/mifare.c
C
lgpl
5,362
.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).
1060840728-lvgang
utils/nfc-scan-device.1
Roff Manpage
lgpl
1,621
/*- * 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) 2014 Pim 't Hart * * 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 jewel.c * @brief provide samples structs and functions to manipulate Jewel Topaz tags using libnfc */ #include "jewel.h" #include <string.h> #include <nfc/nfc.h> /** * @brief Execute a Jewel Topaz Command * @return Returns true if action was successfully performed; otherwise returns false. * @param req The request * @param res The response * */ bool nfc_initiator_jewel_cmd(nfc_device *pnd, const jewel_req req, jewel_res *pres) { size_t nLenReq; size_t nLenRes; switch (req.rid.btCmd) { case TC_RID: nLenReq = sizeof(jewel_req_rid); nLenRes = sizeof(jewel_res_rid); break; case TC_RALL: nLenReq = sizeof(jewel_req_rall); nLenRes = sizeof(jewel_res_rall); break; case TC_READ: nLenReq = sizeof(jewel_req_read); nLenRes = sizeof(jewel_res_read); break; case TC_WRITEE: nLenReq = sizeof(jewel_req_writee); nLenRes = sizeof(jewel_res_writee); break; case TC_WRITENE: nLenReq = sizeof(jewel_req_writene); nLenRes = sizeof(jewel_res_writene); break; case TC_RSEG: nLenReq = sizeof(jewel_req_rseg); nLenRes = sizeof(jewel_res_rseg); break; case TC_READ8: nLenReq = sizeof(jewel_req_read8); nLenRes = sizeof(jewel_res_read8); break; case TC_WRITEE8: nLenReq = sizeof(jewel_req_writee8); nLenRes = sizeof(jewel_res_writee8); break; case TC_WRITENE8: nLenReq = sizeof(jewel_req_writene8); nLenRes = sizeof(jewel_res_writene8); break; default: return false; } if (nfc_initiator_transceive_bytes(pnd, (uint8_t *)&req, nLenReq, (uint8_t *)pres, nLenRes, -1) < 0) { nfc_perror(pnd, "nfc_initiator_transceive_bytes"); return false; } return true; }
1060840728-lvgang
utils/jewel.c
C
lgpl
3,646
.TH nfc-jewel 1 "Feb 02, 2014" "libnfc" "NFC Utilities" .SH NAME nfc-jewel \- Jewel command line tool .SH SYNOPSIS .B nfc-jewel .RI \fR\fBr\fR|\fBw\fR .IR DUMP .SH DESCRIPTION .B nfc-jewel is a Jewel tool that allows one to read or write a tag data to/from a .IR DUMP file. Jewel tag by Broadcom, previously Innovision, uses a binary Dump file to store data for all sectors. Be cautious that some parts of a Jewel 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 JeWel Dump (JWD) used to write (card to JWD) or (JWD 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).
1060840728-lvgang
utils/nfc-jewel.1
Roff Manpage
lgpl
1,237
/*- * 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 unsigned 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], "%10u", &waiting_time) < 1)) { ERR("Missing or wrong waiting time value: %s.", argv[arg]); print_usage(argv); exit(EXIT_FAILURE); } printf("Waiting time: %u 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 %us 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); 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); }
1060840728-lvgang
utils/nfc-relay-picc.c
C
lgpl
16,651
.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 [ .RI \fR\fB\-q\fR .RI ] .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 .IR FILE : output extracted NDEF Message to .IR FILE (use \fR\fB\-o \-\fR to output to stdout) \fR\fB\-q\fR : be quiet, don't display Attribute Block parsing info .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).
1060840728-lvgang
utils/nfc-read-forum-tag3.1
Roff Manpage
lgpl
1,140
/*- * 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 [-q] -o FILE\n", progname); fprintf(stderr, "\nOptions:\n"); fprintf(stderr, " -o FILE Extract NDEF message if available in FILE\n"); fprintf(stderr, " -o - Extract NDEF message if available to stdout\n"); fprintf(stderr, " -q Be quiet, don't display Attribute Block parsing info\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; bool quiet = false; char *ndef_output = NULL; while ((ch = getopt(argc, argv, "hqo:")) != -1) { switch (ch) { case 'h': print_usage(argv[0]); exit(EXIT_SUCCESS); case 'q': quiet = true; break; case 'o': ndef_output = optarg; break; 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); } if (!quiet) { 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); } if (!quiet) { 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); const int ndef_nbr = data[1]; const int ndef_nbw = data[2]; const int ndef_nmaxb = (data[3] << 8) + data[4]; const int ndef_writeflag = data[9]; const int ndef_rwflag = data[10]; uint32_t ndef_data_len = (data[11] << 16) + (data[12] << 8) + data[13]; 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 (!quiet) { fprintf(message_stream, "NDEF Attribute Block:\n"); fprintf(message_stream, "* Mapping version: %d.%d\n", ndef_major_version, ndef_minor_version); fprintf(message_stream, "* Maximum nr of blocks to read by Check Command: %3d block%s\n", ndef_nbr, ndef_nbr > 1 ? "s" : ""); fprintf(message_stream, "* Maximum nr of blocks to write by Update Command: %3d block%s\n", ndef_nbw, ndef_nbw > 1 ? "s" : ""); fprintf(message_stream, "* Maximum nr of blocks available for NDEF data: %3d block%s (%d bytes)\n", ndef_nmaxb, ndef_nmaxb > 1 ? "s" : "", ndef_nmaxb * 16); fprintf(message_stream, "* NDEF writing state: "); switch (ndef_writeflag) { case 0x00: fprintf(message_stream, "finished (0x00)\n"); break; case 0x0f: fprintf(message_stream, "in progress (0x0F)\n"); break; default: fprintf(message_stream, "invalid (0x%02X)\n", ndef_writeflag); break; } fprintf(message_stream, "* NDEF Access Attribute: "); switch (ndef_rwflag) { case 0x00: fprintf(message_stream, "Read only (0x00)\n"); break; case 0x01: fprintf(message_stream, "Read/Write (0x01)\n"); break; default: fprintf(message_stream, "invalid (0x%02X)\n", ndef_rwflag); break; } fprintf(message_stream, "* NDEF message length: %d bytes\n", ndef_data_len); if (ndef_calculated_checksum != ndef_checksum) { fprintf(message_stream, "* Checksum: fail (0x%04X != 0x%04X)\n", ndef_calculated_checksum, ndef_checksum); } else { fprintf(message_stream, "* Checksum: ok (0x%04X)\n", ndef_checksum); } } if (ndef_calculated_checksum != ndef_checksum) { fprintf(stderr, "Error: Checksum failed! Exiting now.\n"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } if (!ndef_data_len) { fprintf(stderr, "Error: empty NFC Forum Tag Type 3, nothing to read!\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 - 1) / block_max_per_check + 1); 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, ndef_data_len, ndef_stream) != ndef_data_len) { fprintf(stderr, "Error: could not write to file.\n"); fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } else { if (!quiet) { fprintf(stderr, "%i bytes written to %s\n", ndef_data_len, ndef_output); } } fclose(ndef_stream); nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
1060840728-lvgang
utils/nfc-read-forum-tag3.c
C
lgpl
12,569
SET(UTILS-SOURCES nfc-emulate-forum-tag4 nfc-jewel 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-jewel") LIST(APPEND TARGETS jewel) ENDIF(${source} MATCHES "nfc-jewel") 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)
1060840728-lvgang
utils/CMakeLists.txt
CMake
lgpl
1,952
/*- * 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_
1060840728-lvgang
utils/mifare.h
C
lgpl
4,141
.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).
1060840728-lvgang
utils/nfc-emulate-forum-tag4.1
Roff Manpage
lgpl
1,973
/*- * 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
1060840728-lvgang
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: * Copyright (C) 2013 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-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 = 0; char buffer[BUFSIZ]; bool write_otp; bool write_lock; bool write_uid; 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("Write UID bytes (only for special writeable UID cards) ? [yN] "); if (!fgets(buffer, BUFSIZ, stdin)) { ERR("Unable to read standard input."); } write_uid = ((buffer[0] == 'y') || (buffer[0] == 'Y')); printf("Writing %d pages |", uiBlocks + 1); /* We may need to skip 2 first pages. */ if (!write_uid) { printf("ss"); uiSkippedPages = 2; } for (int page = uiSkippedPages; 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), 4); memset(mp.mpd.abtData + 4, 0, 12); 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); }
1060840728-lvgang
utils/nfc-mfultralight.c
C
lgpl
8,762
.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! To set the UID of a special writeable UID card, edit the first 7 bytes of a dump file and then write it back, answering 'Y' to the question 'Write UID bytes?'. .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).
1060840728-lvgang
utils/nfc-mfultralight.1
Roff Manpage
lgpl
1,516
/*- * 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] [-t X]\n", progname); printf(" -v\t verbose display\n"); printf(" -t X\t poll only for types according to bitfield X:\n"); printf("\t 1: ISO14443A\n"); printf("\t 2: Felica (212 kbps)\n"); printf("\t 4: Felica (424 kbps)\n"); printf("\t 8: ISO14443B\n"); printf("\t 16: ISO14443B'\n"); printf("\t 32: ISO14443B-2 ST SRx\n"); printf("\t 64: ISO14443B-2 ASK CTx\n"); printf("\t 128: Jewel\n"); printf("\tSo 255 (default) polls for all types.\n"); printf("\tNote that if 16, 32 or 64 then 8 is selected too.\n"); } int main(int argc, const char *argv[]) { (void) argc; const char *acLibnfcVersion; size_t i; bool verbose = false; int res = 0; int mask = 0xff; int arg; 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); // Get commandline options for (arg = 1; arg < argc; arg++) { if (0 == strcmp(argv[arg], "-h")) { print_usage(argv[0]); exit(EXIT_SUCCESS); } else if (0 == strcmp(argv[arg], "-v")) { verbose = true; } else if ((0 == strcmp(argv[arg], "-t")) && (arg + 1 < argc)) { arg++; mask = atoi(argv[arg]); if ((mask < 1) || (mask > 255)) { ERR("%i is invalid value for type bitfield.", mask); print_usage(argv[0]); exit(EXIT_FAILURE); } // Force TypeB for all derivatives of B if (mask & 0x70) mask |= 0x08; } else { ERR("%s is not supported option.", argv[arg]); print_usage(argv[0]); exit(EXIT_FAILURE); } } /* Lazy way to open an NFC device */ #if 0 pnd = nfc_open(context, NULL); #endif /* Use connection string if specific device is wanted, * i.e. PN532 UART device on /dev/ttyUSB1 */ #if 0 pnd = nfc_open(context, "pn532_uart:/dev/ttyUSB1"); #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; if (mask & 0x1) { 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"); } } } if (mask & 0x02) { 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"); } } } if (mask & 0x04) { nm.nmt = NMT_FELICA; 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"); } } } if (mask & 0x08) { 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"); } } } if (mask & 0x10) { 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"); } } } if (mask & 0x20) { 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"); } } } if (mask & 0x40) { 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"); } } } if (mask & 0x80) { 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); }
1060840728-lvgang
utils/nfc-list.c
C
lgpl
8,895
/*- * 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) 2014 Pim 't Hart * * 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 jewel.h * @brief provide samples structs and functions to manipulate Jewel Topaz tags using libnfc */ #ifndef _LIBNFC_JEWEL_H_ # define _LIBNFC_JEWEL_H_ # include <nfc/nfc-types.h> // Compiler directive, set struct alignment to 1 uint8_t for compatibility # pragma pack(1) typedef enum { TC_RID = 0x78, // Read ID // List of commands (Static memory model) TC_RALL = 0x00, // Real All TC_READ = 0x01, // Read (single byte) TC_WRITEE = 0x53, // Write-with-Erase (single byte) TC_WRITENE = 0x1A, // Write-without-Erase (single byte) // List of commands (Dynamic memory model) TC_RSEG = 0x10, // Read segment TC_READ8 = 0x02, // Read (8-bytes) TC_WRITEE8 = 0x54, // Write-with-Erase (8 bytes) TC_WRITENE8 = 0x1B // Write-without-Erase (8 byes) } jewel_cmd; // Jewel request typedef struct { uint8_t btCmd; } jewel_req_rid; typedef struct { uint8_t btCmd; } jewel_req_rall; typedef struct { uint8_t btCmd; uint8_t btAdd; } jewel_req_read; typedef struct { uint8_t btCmd; uint8_t btAdd; uint8_t btDat; } jewel_req_writee; typedef struct { uint8_t btCmd; uint8_t btAdd; uint8_t btDat; } jewel_req_writene; typedef struct { uint8_t btCmd; uint8_t btAddS; } jewel_req_rseg; typedef struct { uint8_t btCmd; uint8_t btAdd8; } jewel_req_read8; typedef struct { uint8_t btCmd; uint8_t btAdd8; uint8_t abtDat[8]; } jewel_req_writee8; typedef struct { uint8_t btCmd; uint8_t btAdd8; uint8_t abtDat[8]; } jewel_req_writene8; typedef union { jewel_req_rid rid; jewel_req_rall rall; jewel_req_read read; jewel_req_writee writee; jewel_req_writene writene; jewel_req_rseg rseg; jewel_req_read8 read8; jewel_req_writee8 writee8; jewel_req_writene8 writene8; } jewel_req; // Jewel responses typedef struct { uint8_t abtHr[2]; uint8_t abtUid[4]; // 4-LSB from UID } jewel_res_rid; typedef struct { uint8_t abtHr[2]; uint8_t abtDat[104]; // Block 0 - E, but not block D (reserved) } jewel_res_rall; typedef struct { uint8_t btDat; } jewel_res_read; typedef struct { uint8_t btDat; } jewel_res_writee; typedef struct { uint8_t btDat; } jewel_res_writene; typedef struct { uint8_t abtDat[128]; } jewel_res_rseg; typedef struct { uint8_t abtDat[8]; } jewel_res_read8; typedef struct { uint8_t abtDat[8]; } jewel_res_writee8; typedef struct { uint8_t abtDat[8]; } jewel_res_writene8; typedef union { jewel_res_rid rid; jewel_res_rall rall; jewel_res_read read; jewel_res_writee writee; jewel_res_writene writene; jewel_res_rseg rseg; jewel_res_read8 read8; jewel_res_writee8 writee8; jewel_res_writene8 writene8; } jewel_res; // Jewel tag typedef struct { uint8_t abtUid[7]; uint8_t btReserved; } jewel_block_uid; typedef struct { uint8_t abtData[8]; } jewel_block_data; typedef struct { uint8_t abtReserved[8]; } jewel_block_reserved; typedef struct { uint8_t abtLock[2]; uint8_t abtOtp[6]; } jewel_block_lockotp; typedef struct { jewel_block_uid bu; jewel_block_data abd[12]; jewel_block_reserved br; jewel_block_lockotp bl; } jewel_tag_blocks; typedef struct { uint8_t abtData[120]; } jewel_tag_data; typedef union { jewel_tag_blocks ttb; jewel_tag_data ttd; } jewel_tag; // Reset struct alignment to default # pragma pack() bool nfc_initiator_jewel_cmd(nfc_device *pnd, const jewel_req req, jewel_res *pres); #endif // _LIBNFC_JEWEL_H_
1060840728-lvgang
utils/jewel.h
C
lgpl
5,351
bin_PROGRAMS = \ nfc-emulate-forum-tag4 \ nfc-jewel \ 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_jewel_SOURCES = nfc-jewel.c jewel.c jewel.h nfc-utils.h nfc_jewel_LDADD = $(top_builddir)/libnfc/libnfc.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-jewel.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
1060840728-lvgang
utils/Makefile.am
Makefile
lgpl
1,653
.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).
1060840728-lvgang
utils/nfc-relay-picc.1
Roff Manpage
lgpl
2,103
.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\fBf\fR|\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 .RI [ .IR KEYS .RI [\fR\fBf\fR] .RI ] .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 f option to format the card will reset all keys to FFFFFFFFFFFF, all data to 00 and all ACLs to default. 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 f " | " r " | " R " | " w " | " W Perform format ( .B f ) or 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. .TP .B f Force using the keyfile .IR KEYS even if UID does not match (optional). .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).
1060840728-lvgang
utils/nfc-mfclassic.1
Roff Manpage
lgpl
3,057
/*- * 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-2013 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 bFormatCard; 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 uint8_t default_key[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static uint8_t default_acl[] = {0xff, 0x07, 0x80, 0x69}; 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; } // If formatting or not using key file, try to guess the right key if (bFormatCard || !bUseKeyFile) { 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; } if (nfc_initiator_select_passive_target(pnd, nmMifare, nt.nti.nai.abtUid, nt.nti.nai.szUidLen, NULL) <= 0) { ERR("tag was removed"); return false; } } } 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 if (nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false) < 0) { nfc_perror(pnd, "nfc_configure"); return -1; } if (nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, true) < 0) { nfc_perror(pnd, "nfc_configure"); return -1; } } // 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) && !bTolerateFailures) { printf("!\nError: authentication failed for block %02x\n", uiBlock); return false; } } if (is_trailer_block(uiBlock)) { if (bFormatCard) { // Copy the default key and reset the access bits memcpy(mp.mpd.abtData, default_key, 6); memcpy(mp.mpd.abtData + 6, default_acl, 4); memcpy(mp.mpd.abtData + 10, default_key, 6); } else { // 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 if (bFormatCard && uiBlock) memset(mp.mpd.abtData, 0x00, 16); else 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 f|r|R|w|W a|b <dump.mfd> [<keys.mfd> [f]]\n", pcProgramName); printf(" f|r|R|w|W - Perform format (f) or read from (r) or unlocked read from (R) or write to (w) or unlocked write to (W) card\n"); printf(" *** format will reset all keys to FFFFFFFFFFFF and all data to 00 and all ACLs to default\n"); printf(" *** unlocked read does not require authentication and will reveal A and B keys\n"); printf(" *** note that unlocked write will attempt to overwrite block 0 including UID\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"); printf("Examples: \n\n"); printf(" Read card to file, using key A:\n\n"); printf(" %s r a mycard.mfd\n\n", pcProgramName); printf(" Write file to blank card, using key A:\n\n"); printf(" %s w a mycard.mfd\n\n", pcProgramName); printf(" Write new data and/or keys to previously written card, using key A:\n\n"); printf(" %s w a newdata.mfd mycard.mfd\n\n", pcProgramName); printf(" Format/wipe card (note two passes required to ensure writes for all ACL cases):\n\n"); printf(" %s f A dummy.mfd keyfile.mfd f\n", pcProgramName); printf(" %s f B dummy.mfd keyfile.mfd f\n\n", pcProgramName); } 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 || strcmp(command, "f") == 0) { if (argc < 4) { print_usage(argv[0]); exit(EXIT_FAILURE); } atAction = ACTION_WRITE; if (strcmp(command, "W") == 0) unlock = 1; bFormatCard = (strcmp(command, "f") == 0); 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. 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)); // 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); }
1060840728-lvgang
utils/nfc-mfclassic.c
C
lgpl
22,899
.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. .TP \fB-t\fP \fIX\fP Polls only for types according to bitfield value of \fIX\fP: 1: ISO14443A 2: Felica (212 kbps) 4: Felica (424 kbps) 8: ISO14443B 16: ISO14443B' 32: ISO14443B-2 ST SRx 64: ISO14443B-2 ASK CTx 128: Jewel So 255 (default) polls for all types. Note that if 16, 32 or 64 then 8 is selected too. .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).
1060840728-lvgang
utils/nfc-list.1
Roff Manpage
lgpl
1,856
/*- * 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); }
1060840728-lvgang
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 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); }
1060840728-lvgang
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: * 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
1060840728-lvgang
contrib/windows.h
C
lgpl
2,125
EXTRA_DIST = \ pn532_via_uart2usb.conf.sample \ arygon.conf.sample \ pn532_uart_on_rpi.conf.sample
1060840728-lvgang
contrib/libnfc/Makefile.am
Makefile
lgpl
116
EXTRA_DIST = \ pn53x.conf
1060840728-lvgang
contrib/devd/Makefile.am
Makefile
lgpl
27
SUBDIRS = \ devd \ libnfc \ linux \ udev \ win32 EXTRA_DIST = \ windows.h
1060840728-lvgang
contrib/Makefile.am
Makefile
lgpl
81
EXTRA_DIST = \ 42-pn53x.rules
1060840728-lvgang
contrib/udev/Makefile.am
Makefile
lgpl
31
EXTRA_DIST = \ blacklist-libnfc.conf
1060840728-lvgang
contrib/linux/Makefile.am
Makefile
lgpl
38
/*- * 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); }
1060840728-lvgang
contrib/win32/stdlib.c
C
lgpl
1,666
/*- * 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); }
1060840728-lvgang
contrib/win32/libnfc/log-internal.c
C
lgpl
1,971
SUBDIRS = buses . EXTRA_DIST = \ log-internal.c
1060840728-lvgang
contrib/win32/libnfc/Makefile.am
Makefile
lgpl
50
/*- * 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, bool wait) { 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 baud.", 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 baud. 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; }
1060840728-lvgang
contrib/win32/libnfc/buses/uart.c
C
lgpl
8,338
EXTRA_DIST = \ uart.c
1060840728-lvgang
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 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_ */
1060840728-lvgang
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 * * 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 */
1060840728-lvgang
contrib/win32/sys/select.h
C
lgpl
1,061
EXTRA_DIST = \ select.h
1060840728-lvgang
contrib/win32/sys/Makefile.am
Makefile
lgpl
25
SUBDIRS = libnfc sys . EXTRA_DIST = \ err.h \ nfc.def \ stdlib.c \ unistd.h \ version.rc.in
1060840728-lvgang
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_ */
1060840728-lvgang
contrib/win32/err.h
C
lgpl
353
#!/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
1060840728-lvgang
mingw-cross-configure.sh
Shell
lgpl
2,880
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 .
1060840728-lvgang
Makefile.am
Makefile
lgpl
1,510
/*- * 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); }
1060840728-lvgang
examples/nfc-mfsetuid.c
C
lgpl
11,280
/*- * 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) { if (nfc_device_set_property_bool(dev, NP_HANDLE_CRC, false) < 0) { nfc_perror(pnd, "nfc_target_emulate_tag"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } 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 if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, (nt.nti.nai.btSak & SAK_ISO14443_4_COMPLIANT)) < 0) { nfc_perror(pnd, "nfc_target_emulate_tag"); nfc_close(pnd); nfc_exit(context); exit(EXIT_FAILURE); } 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); }
1060840728-lvgang
examples/nfc-emulate-tag.c
C
lgpl
8,563
/*- * 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); }
1060840728-lvgang
examples/nfc-dep-initiator.c
C
lgpl
3,925
.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).
1060840728-lvgang
examples/nfc-emulate-uid.1
Roff Manpage
lgpl
2,828
.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).
1060840728-lvgang
examples/nfc-emulate-forum-tag2.1
Roff Manpage
lgpl
1,860
/*- * 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 int 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); }
1060840728-lvgang
examples/pn53x-sam.c
C
lgpl
7,059
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)
1060840728-lvgang
examples/CMakeLists.txt
CMake
lgpl
1,393
.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).
1060840728-lvgang
examples/nfc-poll.1
Roff Manpage
lgpl
1,927
.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).
1060840728-lvgang
examples/nfc-dep-initiator.1
Roff Manpage
lgpl
1,032
.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).
1060840728-lvgang
examples/nfc-emulate-tag.1
Roff Manpage
lgpl
2,086
.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).
1060840728-lvgang
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 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); }
1060840728-lvgang
examples/pn53x-diagnose.c
C
lgpl
4,938
.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).
1060840728-lvgang
examples/pn53x-sam.1
Roff Manpage
lgpl
1,079
/*- * 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); }
1060840728-lvgang
examples/nfc-dep-target.c
C
lgpl
5,031
.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).
1060840728-lvgang
examples/nfc-relay.1
Roff Manpage
lgpl
1,263
/*- * 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); nfc_close(pnd); } nfc_exit(context); exit(EXIT_SUCCESS); } 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); } } } } }
1060840728-lvgang
examples/nfc-emulate-uid.c
C
lgpl
7,807
/** * @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\n", "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); }
1060840728-lvgang
examples/doc/quick_start_example1.c
C
lgpl
2,441
/** * @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); }
1060840728-lvgang
examples/doc/quick_start_example2.c
C
lgpl
2,529
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
1060840728-lvgang
examples/Makefile.am
Makefile
lgpl
2,905
/*- * 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); }
1060840728-lvgang
examples/nfc-anticol.c
C
lgpl
10,569
.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).
1060840728-lvgang
examples/nfc-anticol.1
Roff Manpage
lgpl
1,536
/*- * 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); }
1060840728-lvgang
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 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"); } printf("Waiting for card removing..."); while (0 == nfc_initiator_target_is_present(pnd, NULL)) {} nfc_perror(pnd, "nfc_initiator_target_is_present"); printf("done.\n"); nfc_close(pnd); nfc_exit(context); exit(EXIT_SUCCESS); }
1060840728-lvgang
examples/nfc-poll.c
C
lgpl
4,619
/*- * 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); }
1060840728-lvgang
examples/pn53x-tamashell.c
C
lgpl
5,736
/*- * 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); }
1060840728-lvgang
examples/nfc-emulate-forum-tag2.c
C
lgpl
6,479
.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).
1060840728-lvgang
examples/nfc-mfsetuid.1
Roff Manpage
lgpl
1,150
#!/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
1060840728-lvgang
examples/pn53x-tamashell-scripts/ReadMobib.sh
Shell
lgpl
1,783
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
1060840728-lvgang
examples/pn53x-tamashell-scripts/UltraLightReadWrite.cmd
Batchfile
lgpl
2,229
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
1060840728-lvgang
examples/pn53x-tamashell-scripts/UltraLightRead.cmd
Batchfile
lgpl
492
#!/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
1060840728-lvgang
examples/pn53x-tamashell-scripts/ReadNavigo.sh
Shell
lgpl
1,690
# 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
1060840728-lvgang
examples/pn53x-tamashell-scripts/ASK_LoGO_LEDs.cmd
Batchfile
lgpl
734
EXTRA_DIST = \ ReadMobib.sh \ ReadNavigo.sh \ UltraLightRead.cmd \ UltraLightReadWrite.cmd
1060840728-lvgang
examples/pn53x-tamashell-scripts/Makefile.am
Makefile
lgpl
95
.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).
1060840728-lvgang
examples/pn53x-diagnose.1
Roff Manpage
lgpl
762
.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).
1060840728-lvgang
examples/pn53x-tamashell.1
Roff Manpage
lgpl
2,021
/*- * 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_mode mode, 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 void iso14443b_crc(uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc); NFC_EXPORT void iso14443b_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_
1060840728-lvgang
include/nfc/nfc.h
C
lgpl
8,769
/*- * 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__ */
1060840728-lvgang
include/nfc/nfc-emulation.h
C
lgpl
2,056
# Headers FILE(GLOB headers "${CMAKE_CURRENT_SOURCE_DIR}/*.h") INSTALL(FILES ${headers} DESTINATION ${INCLUDE_INSTALL_DIR}/nfc COMPONENT headers)
1060840728-lvgang
include/nfc/CMakeLists.txt
CMake
lgpl
147
nfcinclude_HEADERS = \ nfc.h \ nfc-emulation.h \ nfc-types.h nfcincludedir = $(includedir)/nfc EXTRA_DIST = CMakeLists.txt
1060840728-lvgang
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_
1060840728-lvgang
include/nfc/nfc-types.h
C
lgpl
9,675
ADD_SUBDIRECTORY(nfc)
1060840728-lvgang
include/CMakeLists.txt
CMake
lgpl
23
SUBDIRS = nfc EXTRA_DIST = CMakeLists.txt
1060840728-lvgang
include/Makefile.am
Makefile
lgpl
43
#! /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
1060840728-lvgang
make_release.sh
Shell
lgpl
1,604