code
stringlengths
2
2.01M
language
stringclasses
1 value
/* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TESSERACT_JNI_COMMON_H #define TESSERACT_JNI_COMMON_H #include <jni.h> #include <android/log.h> #include <assert.h> #define LOG_TAG "Tesseract(native)" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__) #endif
C
/* Copyright (C) 2007 Eric Blake * Permission to use, copy, modify, and distribute this software * is freely granted, provided that this notice is preserved. * * Modifications for Android written Jul 2009 by Alan Viverette */ /* FUNCTION <<fmemopen>>---open a stream around a fixed-length string INDEX fmemopen ANSI_SYNOPSIS #include <stdio.h> FILE *fmemopen(void *restrict <[buf]>, size_t <[size]>, const char *restrict <[mode]>); DESCRIPTION <<fmemopen>> creates a seekable <<FILE>> stream that wraps a fixed-length buffer of <[size]> bytes starting at <[buf]>. The stream is opened with <[mode]> treated as in <<fopen>>, where append mode starts writing at the first NUL byte. If <[buf]> is NULL, then <[size]> bytes are automatically provided as if by <<malloc>>, with the initial size of 0, and <[mode]> must contain <<+>> so that data can be read after it is written. The stream maintains a current position, which moves according to bytes read or written, and which can be one past the end of the array. The stream also maintains a current file size, which is never greater than <[size]>. If <[mode]> starts with <<r>>, the position starts at <<0>>, and file size starts at <[size]> if <[buf]> was provided. If <[mode]> starts with <<w>>, the position and file size start at <<0>>, and if <[buf]> was provided, the first byte is set to NUL. If <[mode]> starts with <<a>>, the position and file size start at the location of the first NUL byte, or else <[size]> if <[buf]> was provided. When reading, NUL bytes have no significance, and reads cannot exceed the current file size. When writing, the file size can increase up to <[size]> as needed, and NUL bytes may be embedded in the stream (see <<open_memstream>> for an alternative that automatically enlarges the buffer). When the stream is flushed or closed after a write that changed the file size, a NUL byte is written at the current position if there is still room; if the stream is not also open for reading, a NUL byte is additionally written at the last byte of <[buf]> when the stream has exceeded <[size]>, so that a write-only <[buf]> is always NUL-terminated when the stream is flushed or closed (and the initial <[size]> should take this into account). It is not possible to seek outside the bounds of <[size]>. A NUL byte written during a flush is restored to its previous value when seeking elsewhere in the string. RETURNS The return value is an open FILE pointer on success. On error, <<NULL>> is returned, and <<errno>> will be set to EINVAL if <[size]> is zero or <[mode]> is invalid, ENOMEM if <[buf]> was NULL and memory could not be allocated, or EMFILE if too many streams are already open. PORTABILITY This function is being added to POSIX 200x, but is not in POSIX 2001. Supporting OS subroutines required: <<sbrk>>. */ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <malloc.h> #include "extrastdio.h" /* Describe details of an open memstream. */ typedef struct fmemcookie { void *storage; /* storage to free on close */ char *buf; /* buffer start */ size_t pos; /* current position */ size_t eof; /* current file size */ size_t max; /* maximum file size */ char append; /* nonzero if appending */ char writeonly; /* 1 if write-only */ char saved; /* saved character that lived at pos before write-only NUL */ } fmemcookie; /* Read up to non-zero N bytes into BUF from stream described by COOKIE; return number of bytes read (0 on EOF). */ static int fmemread(void *cookie, char *buf, int n) { fmemcookie *c = (fmemcookie *) cookie; /* Can't read beyond current size, but EOF condition is not an error. */ if (c->pos > c->eof) return 0; if (n >= c->eof - c->pos) n = c->eof - c->pos; memcpy (buf, c->buf + c->pos, n); c->pos += n; return n; } /* Write up to non-zero N bytes of BUF into the stream described by COOKIE, returning the number of bytes written or EOF on failure. */ static int fmemwrite(void *cookie, const char *buf, int n) { fmemcookie *c = (fmemcookie *) cookie; int adjust = 0; /* true if at EOF, but still need to write NUL. */ /* Append always seeks to eof; otherwise, if we have previously done a seek beyond eof, ensure all intermediate bytes are NUL. */ if (c->append) c->pos = c->eof; else if (c->pos > c->eof) memset (c->buf + c->eof, '\0', c->pos - c->eof); /* Do not write beyond EOF; saving room for NUL on write-only stream. */ if (c->pos + n > c->max - c->writeonly) { adjust = c->writeonly; n = c->max - c->pos; } /* Now n is the number of bytes being modified, and adjust is 1 if the last byte is NUL instead of from buf. Write a NUL if write-only; or if read-write, eof changed, and there is still room. When we are within the file contents, remember what we overwrite so we can restore it if we seek elsewhere later. */ if (c->pos + n > c->eof) { c->eof = c->pos + n; if (c->eof - adjust < c->max) c->saved = c->buf[c->eof - adjust] = '\0'; } else if (c->writeonly) { if (n) { c->saved = c->buf[c->pos + n - adjust]; c->buf[c->pos + n - adjust] = '\0'; } else adjust = 0; } c->pos += n; if (n - adjust) memcpy (c->buf + c->pos - n, buf, n - adjust); else { return EOF; } return n; } /* Seek to position POS relative to WHENCE within stream described by COOKIE; return resulting position or fail with EOF. */ static fpos_t fmemseek(void *cookie, fpos_t pos, int whence) { fmemcookie *c = (fmemcookie *) cookie; off_t offset = (off_t) pos; if (whence == SEEK_CUR) offset += c->pos; else if (whence == SEEK_END) offset += c->eof; if (offset < 0) { offset = -1; } else if (offset > c->max) { offset = -1; } else { if (c->writeonly && c->pos < c->eof) { c->buf[c->pos] = c->saved; c->saved = '\0'; } c->pos = offset; if (c->writeonly && c->pos < c->eof) { c->saved = c->buf[c->pos]; c->buf[c->pos] = '\0'; } } return (fpos_t) offset; } /* Reclaim resources used by stream described by COOKIE. */ static int fmemclose(void *cookie) { fmemcookie *c = (fmemcookie *) cookie; free (c->storage); return 0; } /* Open a memstream around buffer BUF of SIZE bytes, using MODE. Return the new stream, or fail with NULL. */ FILE * fmemopen(void *buf, size_t size, const char *mode) { FILE *fp; fmemcookie *c; int flags; int dummy; if ((flags = __sflags (mode, &dummy)) == 0) return NULL; if (!size || !(buf || flags & __SAPP)) { return NULL; } if ((fp = (FILE *) __sfp ()) == NULL) return NULL; if ((c = (fmemcookie *) malloc (sizeof *c + (buf ? 0 : size))) == NULL) { fp->_flags = 0; /* release */ return NULL; } c->storage = c; c->max = size; /* 9 modes to worry about. */ /* w/a, buf or no buf: Guarantee a NUL after any file writes. */ c->writeonly = (flags & __SWR) != 0; c->saved = '\0'; if (!buf) { /* r+/w+/a+, and no buf: file starts empty. */ c->buf = (char *) (c + 1); *(char *) buf = '\0'; c->pos = c->eof = 0; c->append = (flags & __SAPP) != 0; } else { c->buf = (char *) buf; switch (*mode) { case 'a': /* a/a+ and buf: position and size at first NUL. */ buf = memchr (c->buf, '\0', size); c->eof = c->pos = buf ? (char *) buf - c->buf : size; if (!buf && c->writeonly) /* a: guarantee a NUL within size even if no writes. */ c->buf[size - 1] = '\0'; c->append = 1; break; case 'r': /* r/r+ and buf: read at beginning, full size available. */ c->pos = c->append = 0; c->eof = size; break; case 'w': /* w/w+ and buf: write at beginning, truncate to empty. */ c->pos = c->append = c->eof = 0; *c->buf = '\0'; break; default: abort(); } } fp->_file = -1; fp->_flags = flags; fp->_cookie = c; fp->_read = flags & (__SRD | __SRW) ? fmemread : NULL; fp->_write = flags & (__SWR | __SRW) ? fmemwrite : NULL; fp->_seek = fmemseek; fp->_close = fmemclose; return fp; }
C
/* Copyright (C) 2007 Eric Blake * Permission to use, copy, modify, and distribute this software * is freely granted, provided that this notice is preserved. * * Modifications for Android written Jul 2009 by Alan Viverette */ /* FUNCTION <<open_memstream>>---open a write stream around an arbitrary-length string INDEX open_memstream ANSI_SYNOPSIS #include <stdio.h> FILE *open_memstream(char **restrict <[buf]>, size_t *restrict <[size]>); DESCRIPTION <<open_memstream>> creates a seekable <<FILE>> stream that wraps an arbitrary-length buffer, created as if by <<malloc>>. The current contents of *<[buf]> are ignored; this implementation uses *<[size]> as a hint of the maximum size expected, but does not fail if the hint was wrong. The parameters <[buf]> and <[size]> are later stored through following any call to <<fflush>> or <<fclose>>, set to the current address and usable size of the allocated string; although after fflush, the pointer is only valid until another stream operation that results in a write. Behavior is undefined if the user alters either *<[buf]> or *<[size]> prior to <<fclose>>. The stream is write-only, since the user can directly read *<[buf]> after a flush; see <<fmemopen>> for a way to wrap a string with a readable stream. The user is responsible for calling <<free>> on the final *<[buf]> after <<fclose>>. Any time the stream is flushed, a NUL byte is written at the current position (but is not counted in the buffer length), so that the string is always NUL-terminated after at most *<[size]> bytes. However, data previously written beyond the current stream offset is not lost, and the NUL byte written during a flush is restored to its previous value when seeking elsewhere in the string. RETURNS The return value is an open FILE pointer on success. On error, <<NULL>> is returned, and <<errno>> will be set to EINVAL if <[buf]> or <[size]> is NULL, ENOMEM if memory could not be allocated, or EMFILE if too many streams are already open. PORTABILITY This function is being added to POSIX 200x, but is not in POSIX 2001. Supporting OS subroutines required: <<sbrk>>. */ #include <stdio.h> #include <errno.h> #include <string.h> #include <malloc.h> #include "extrastdio.h" /* Describe details of an open memstream. */ typedef struct memstream { void *storage; /* storage to free on close */ char **pbuf; /* pointer to the current buffer */ size_t *psize; /* pointer to the current size, smaller of pos or eof */ size_t pos; /* current position */ size_t eof; /* current file size */ size_t max; /* current malloc buffer size, always > eof */ char saved; /* saved character that lived at *psize before NUL */ } memstream; /* Write up to non-zero N bytes of BUF into the stream described by COOKIE, returning the number of bytes written or EOF on failure. */ static int memwrite(void *cookie, const char *buf, int n) { memstream *c = (memstream *) cookie; char *cbuf = *c->pbuf; /* size_t is unsigned, but off_t is signed. Don't let stream get so big that user cannot do ftello. */ if (sizeof (off_t) == sizeof (size_t) && (ssize_t) (c->pos + n) < 0) { return EOF; } /* Grow the buffer, if necessary. Choose a geometric growth factor to avoid quadratic realloc behavior, but use a rate less than (1+sqrt(5))/2 to accomodate malloc overhead. Overallocate, so that we can add a trailing \0 without reallocating. The new allocation should thus be max(prev_size*1.5, c->pos+n+1). */ if (c->pos + n >= c->max) { size_t newsize = c->max * 3 / 2; if (newsize < c->pos + n + 1) newsize = c->pos + n + 1; cbuf = realloc (cbuf, newsize); if (! cbuf) return EOF; /* errno already set to ENOMEM */ *c->pbuf = cbuf; c->max = newsize; } /* If we have previously done a seek beyond eof, ensure all intermediate bytes are NUL. */ if (c->pos > c->eof) memset (cbuf + c->eof, '\0', c->pos - c->eof); memcpy (cbuf + c->pos, buf, n); c->pos += n; /* If the user has previously written further, remember what the trailing NUL is overwriting. Otherwise, extend the stream. */ if (c->pos > c->eof) c->eof = c->pos; else c->saved = cbuf[c->pos]; cbuf[c->pos] = '\0'; *c->psize = c->pos; return n; } /* Seek to position POS relative to WHENCE within stream described by COOKIE; return resulting position or fail with EOF. */ static fpos_t memseek(void *cookie, fpos_t pos, int whence) { memstream *c = (memstream *) cookie; off_t offset = (off_t) pos; if (whence == SEEK_CUR) offset += c->pos; else if (whence == SEEK_END) offset += c->eof; if (offset < 0) { offset = -1; } else if ((size_t) offset != offset) { offset = -1; } else { if (c->pos < c->eof) { (*c->pbuf)[c->pos] = c->saved; c->saved = '\0'; } c->pos = offset; if (c->pos < c->eof) { c->saved = (*c->pbuf)[c->pos]; (*c->pbuf)[c->pos] = '\0'; *c->psize = c->pos; } else *c->psize = c->eof; } return (fpos_t) offset; } /* Reclaim resources used by stream described by COOKIE. */ static int memclose(void *cookie) { memstream *c = (memstream *) cookie; char *buf; /* Be nice and try to reduce any unused memory. */ buf = realloc (*c->pbuf, *c->psize + 1); if (buf) *c->pbuf = buf; free (c->storage); return 0; } /* Open a memstream that tracks a dynamic buffer in BUF and SIZE. Return the new stream, or fail with NULL. */ FILE * open_memstream(char **buf, size_t *size) { FILE *fp; memstream *c; int flags; if (!buf || !size) { return NULL; } if ((fp = (FILE *) __sfp ()) == NULL) return NULL; if ((c = (memstream *) malloc (sizeof *c)) == NULL) { fp->_flags = 0; /* release */ return NULL; } /* Use *size as a hint for initial sizing, but bound the initial malloc between 64 bytes (same as asprintf, to avoid frequent mallocs on small strings) and 64k bytes (to avoid overusing the heap if *size was garbage). */ c->max = *size; if (c->max < 64) c->max = 64; else if (c->max > 64 * 1024) c->max = 64 * 1024; *size = 0; *buf = malloc (c->max); if (!*buf) { fp->_flags = 0; /* release */ free (c); return NULL; } **buf = '\0'; c->storage = c; c->pbuf = buf; c->psize = size; c->eof = 0; c->saved = '\0'; fp->_file = -1; fp->_flags = __SWR; fp->_cookie = c; fp->_read = NULL; fp->_write = memwrite; fp->_seek = memseek; fp->_close = memclose; return fp; }
C
#ifndef LEPTONICA__STDIO_H #define LEPTONICA__STDIO_H #ifndef BUILD_HOST #include <stdio.h> #include <stdint.h> typedef struct cookie_io_functions_t { ssize_t (*read)(void *cookie, char *buf, size_t n); ssize_t (*write)(void *cookie, const char *buf, size_t n); int (*seek)(void *cookie, off_t *pos, int whence); int (*close)(void *cookie); } cookie_io_functions_t; FILE *fopencookie(void *cookie, const char *mode, cookie_io_functions_t functions); FILE *fmemopen(void *buf, size_t size, const char *mode); FILE *open_memstream(char **buf, size_t *size); #endif #endif /* LEPTONICA__STDIO_H */
C
/* Copyright (C) 2007 Eric Blake * Permission to use, copy, modify, and distribute this software * is freely granted, provided that this notice is preserved. * * Modifications for Android written Jul 2009 by Alan Viverette */ /* FUNCTION <<fopencookie>>---open a stream with custom callbacks INDEX fopencookie ANSI_SYNOPSIS #include <stdio.h> typedef ssize_t (*cookie_read_function_t)(void *_cookie, char *_buf, size_t _n); typedef ssize_t (*cookie_write_function_t)(void *_cookie, const char *_buf, size_t _n); typedef int (*cookie_seek_function_t)(void *_cookie, off_t *_off, int _whence); typedef int (*cookie_close_function_t)(void *_cookie); FILE *fopencookie(const void *<[cookie]>, const char *<[mode]>, cookie_io_functions_t <[functions]>); DESCRIPTION <<fopencookie>> creates a <<FILE>> stream where I/O is performed using custom callbacks. The callbacks are registered via the structure: . typedef struct . { . cookie_read_function_t *read; . cookie_write_function_t *write; . cookie_seek_function_t *seek; . cookie_close_function_t *close; . } cookie_io_functions_t; The stream is opened with <[mode]> treated as in <<fopen>>. The callbacks <[functions.read]> and <[functions.write]> may only be NULL when <[mode]> does not require them. <[functions.read]> should return -1 on failure, or else the number of bytes read (0 on EOF). It is similar to <<read>>, except that <[cookie]> will be passed as the first argument. <[functions.write]> should return -1 on failure, or else the number of bytes written. It is similar to <<write>>, except that <[cookie]> will be passed as the first argument. <[functions.seek]> should return -1 on failure, and 0 on success, with *<[_off]> set to the current file position. It is a cross between <<lseek>> and <<fseek>>, with the <[_whence]> argument interpreted in the same manner. A NULL <[functions.seek]> makes the stream behave similarly to a pipe in relation to stdio functions that require positioning. <[functions.close]> should return -1 on failure, or 0 on success. It is similar to <<close>>, except that <[cookie]> will be passed as the first argument. A NULL <[functions.close]> merely flushes all data then lets <<fclose>> succeed. A failed close will still invalidate the stream. Read and write I/O functions are allowed to change the underlying buffer on fully buffered or line buffered streams by calling <<setvbuf>>. They are also not required to completely fill or empty the buffer. They are not, however, allowed to change streams from unbuffered to buffered or to change the state of the line buffering flag. They must also be prepared to have read or write calls occur on buffers other than the one most recently specified. RETURNS The return value is an open FILE pointer on success. On error, <<NULL>> is returned, and <<errno>> will be set to EINVAL if a function pointer is missing or <[mode]> is invalid, ENOMEM if the stream cannot be created, or EMFILE if too many streams are already open. PORTABILITY This function is a newlib extension, copying the prototype from Linux. It is not portable. See also the <<funopen>> interface from BSD. Supporting OS subroutines required: <<sbrk>>. */ #include <stdio.h> #include <errno.h> #include <malloc.h> #include "extrastdio.h" typedef struct fccookie { void *cookie; FILE *fp; ssize_t (*readfn)(void *, char *, size_t); ssize_t (*writefn)(void *, const char *, size_t); int (*seekfn)(void *, off_t *, int); int (*closefn)(void *); } fccookie; static int fcread(void *cookie, char *buf, int n) { int result; fccookie *c = (fccookie *) cookie; result = c->readfn (c->cookie, buf, n); return result; } static int fcwrite(void *cookie, const char *buf, int n) { int result; fccookie *c = (fccookie *) cookie; if (c->fp->_flags & __SAPP && c->fp->_seek) { c->fp->_seek (cookie, 0, SEEK_END); } result = c->writefn (c->cookie, buf, n); return result; } static fpos_t fcseek(void *cookie, fpos_t pos, int whence) { fccookie *c = (fccookie *) cookie; off_t offset = (off_t) pos; c->seekfn (c->cookie, &offset, whence); return (fpos_t) offset; } static int fcclose(void *cookie) { int result = 0; fccookie *c = (fccookie *) cookie; if (c->closefn) { result = c->closefn (c->cookie); } free (c); return result; } FILE * fopencookie(void *cookie, const char *mode, cookie_io_functions_t functions) { FILE *fp; fccookie *c; int flags; int dummy; if ((flags = __sflags (mode, &dummy)) == 0) return NULL; if (((flags & (__SRD | __SRW)) && !functions.read) || ((flags & (__SWR | __SRW)) && !functions.write)) { return NULL; } if ((fp = (FILE *) __sfp ()) == NULL) return NULL; if ((c = (fccookie *) malloc (sizeof *c)) == NULL) { fp->_flags = 0; return NULL; } fp->_file = -1; fp->_flags = flags; c->cookie = cookie; c->fp = fp; fp->_cookie = c; c->readfn = functions.read; fp->_read = fcread; c->writefn = functions.write; fp->_write = fcwrite; c->seekfn = functions.seek; fp->_seek = functions.seek ? fcseek : NULL; c->closefn = functions.close; fp->_close = fcclose; return fp; }
C
/* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LEPTONICA_JNI_CONFIG_AUTO_H #define LEPTONICA_JNI_CONFIG_AUTO_H #define HAVE_LIBJPEG 0 #define HAVE_LIBTIFF 0 #define HAVE_LIBPNG 0 #define HAVE_LIBZ 1 #define HAVE_LIBGIF 0 #define HAVE_LIBUNGIF 0 #define HAVE_FMEMOPEN 1 #endif
C
/* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LEPTONICA_JNI_COMMON_H #define LEPTONICA_JNI_COMMON_H #include <jni.h> #include <assert.h> #include <allheaders.h> #include <android/log.h> #include <asm/byteorder.h> #ifdef __BIG_ENDIAN #define SK_A32_SHIFT 0 #define SK_R32_SHIFT 8 #define SK_G32_SHIFT 16 #define SK_B32_SHIFT 24 #else #define SK_A32_SHIFT 24 #define SK_R32_SHIFT 16 #define SK_G32_SHIFT 8 #define SK_B32_SHIFT 0 #endif /* __BIG_ENDIAN */ #define LOG_TAG "Leptonica(native)" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__) #endif
C
/* --------------------------------------------------------------------------- Copyright (c) 2003, Dominik Reichl <dominik.reichl@t-online.de>, Germany. All rights reserved. Distributed under the terms of the GNU General Public License v2. This software is provided 'as is' with no explicit or implied warranties in respect of its properties, including, but not limited to, correctness and/or fitness for purpose. --------------------------------------------------------------------------- */ #ifndef ___CRC32_H___ #define ___CRC32_H___ void crc32Init(unsigned long *pCrc32); void crc32Update(unsigned long *pCrc32, unsigned char *pData, unsigned long uSize); void crc32Finish(unsigned long *pCrc32); #endif /* ___CRC32_H___ */
C
/* ___________________________________________________ Opcode Length Disassembler. Coded By Ms-Rem ( Ms-Rem@yandex.ru ) ICQ 286370715 --------------------------------------------------- 12.08.2005 - fixed many bugs... 09.08.2005 - fixed bug with 0F BA opcode. 07.08.2005 - added SSE, SSE2, SSE3 and 3Dnow instruction support. 06.08.2005 - fixed bug with F6 and F7 opcodes. 29.07.2005 - fixed bug with OP_WORD opcodes. */ #include "LDasm.h" #define OP_NONE 0x00 #define OP_MODRM 0x01 #define OP_DATA_I8 0x02 #define OP_DATA_I16 0x04 #define OP_DATA_I32 0x08 #define OP_DATA_PRE66_67 0x10 #define OP_WORD 0x20 #define OP_REL32 0x40 #define UCHAR unsigned char #define ULONG unsigned long #define PVOID void* #define PUCHAR unsigned char* #define BOOLEAN char #define FALSE 0 #define TRUE 1 UCHAR OpcodeFlags[256] = { OP_MODRM, // 00 OP_MODRM, // 01 OP_MODRM, // 02 OP_MODRM, // 03 OP_DATA_I8, // 04 OP_DATA_PRE66_67, // 05 OP_NONE, // 06 OP_NONE, // 07 OP_MODRM, // 08 OP_MODRM, // 09 OP_MODRM, // 0A OP_MODRM, // 0B OP_DATA_I8, // 0C OP_DATA_PRE66_67, // 0D OP_NONE, // 0E OP_NONE, // 0F OP_MODRM, // 10 OP_MODRM, // 11 OP_MODRM, // 12 OP_MODRM, // 13 OP_DATA_I8, // 14 OP_DATA_PRE66_67, // 15 OP_NONE, // 16 OP_NONE, // 17 OP_MODRM, // 18 OP_MODRM, // 19 OP_MODRM, // 1A OP_MODRM, // 1B OP_DATA_I8, // 1C OP_DATA_PRE66_67, // 1D OP_NONE, // 1E OP_NONE, // 1F OP_MODRM, // 20 OP_MODRM, // 21 OP_MODRM, // 22 OP_MODRM, // 23 OP_DATA_I8, // 24 OP_DATA_PRE66_67, // 25 OP_NONE, // 26 OP_NONE, // 27 OP_MODRM, // 28 OP_MODRM, // 29 OP_MODRM, // 2A OP_MODRM, // 2B OP_DATA_I8, // 2C OP_DATA_PRE66_67, // 2D OP_NONE, // 2E OP_NONE, // 2F OP_MODRM, // 30 OP_MODRM, // 31 OP_MODRM, // 32 OP_MODRM, // 33 OP_DATA_I8, // 34 OP_DATA_PRE66_67, // 35 OP_NONE, // 36 OP_NONE, // 37 OP_MODRM, // 38 OP_MODRM, // 39 OP_MODRM, // 3A OP_MODRM, // 3B OP_DATA_I8, // 3C OP_DATA_PRE66_67, // 3D OP_NONE, // 3E OP_NONE, // 3F OP_NONE, // 40 OP_NONE, // 41 OP_NONE, // 42 OP_NONE, // 43 OP_NONE, // 44 OP_NONE, // 45 OP_NONE, // 46 OP_NONE, // 47 OP_NONE, // 48 OP_NONE, // 49 OP_NONE, // 4A OP_NONE, // 4B OP_NONE, // 4C OP_NONE, // 4D OP_NONE, // 4E OP_NONE, // 4F OP_NONE, // 50 OP_NONE, // 51 OP_NONE, // 52 OP_NONE, // 53 OP_NONE, // 54 OP_NONE, // 55 OP_NONE, // 56 OP_NONE, // 57 OP_NONE, // 58 OP_NONE, // 59 OP_NONE, // 5A OP_NONE, // 5B OP_NONE, // 5C OP_NONE, // 5D OP_NONE, // 5E OP_NONE, // 5F OP_NONE, // 60 OP_NONE, // 61 OP_MODRM, // 62 OP_MODRM, // 63 OP_NONE, // 64 OP_NONE, // 65 OP_NONE, // 66 OP_NONE, // 67 OP_DATA_PRE66_67, // 68 OP_MODRM | OP_DATA_PRE66_67, // 69 OP_DATA_I8, // 6A OP_MODRM | OP_DATA_I8, // 6B OP_NONE, // 6C OP_NONE, // 6D OP_NONE, // 6E OP_NONE, // 6F OP_DATA_I8, // 70 OP_DATA_I8, // 71 OP_DATA_I8, // 72 OP_DATA_I8, // 73 OP_DATA_I8, // 74 OP_DATA_I8, // 75 OP_DATA_I8, // 76 OP_DATA_I8, // 77 OP_DATA_I8, // 78 OP_DATA_I8, // 79 OP_DATA_I8, // 7A OP_DATA_I8, // 7B OP_DATA_I8, // 7C OP_DATA_I8, // 7D OP_DATA_I8, // 7E OP_DATA_I8, // 7F OP_MODRM | OP_DATA_I8, // 80 OP_MODRM | OP_DATA_PRE66_67, // 81 OP_MODRM | OP_DATA_I8, // 82 OP_MODRM | OP_DATA_I8, // 83 OP_MODRM, // 84 OP_MODRM, // 85 OP_MODRM, // 86 OP_MODRM, // 87 OP_MODRM, // 88 OP_MODRM, // 89 OP_MODRM, // 8A OP_MODRM, // 8B OP_MODRM, // 8C OP_MODRM, // 8D OP_MODRM, // 8E OP_MODRM, // 8F OP_NONE, // 90 OP_NONE, // 91 OP_NONE, // 92 OP_NONE, // 93 OP_NONE, // 94 OP_NONE, // 95 OP_NONE, // 96 OP_NONE, // 97 OP_NONE, // 98 OP_NONE, // 99 OP_DATA_I16 | OP_DATA_PRE66_67,// 9A OP_NONE, // 9B OP_NONE, // 9C OP_NONE, // 9D OP_NONE, // 9E OP_NONE, // 9F OP_DATA_PRE66_67, // A0 OP_DATA_PRE66_67, // A1 OP_DATA_PRE66_67, // A2 OP_DATA_PRE66_67, // A3 OP_NONE, // A4 OP_NONE, // A5 OP_NONE, // A6 OP_NONE, // A7 OP_DATA_I8, // A8 OP_DATA_PRE66_67, // A9 OP_NONE, // AA OP_NONE, // AB OP_NONE, // AC OP_NONE, // AD OP_NONE, // AE OP_NONE, // AF OP_DATA_I8, // B0 OP_DATA_I8, // B1 OP_DATA_I8, // B2 OP_DATA_I8, // B3 OP_DATA_I8, // B4 OP_DATA_I8, // B5 OP_DATA_I8, // B6 OP_DATA_I8, // B7 OP_DATA_PRE66_67, // B8 OP_DATA_PRE66_67, // B9 OP_DATA_PRE66_67, // BA OP_DATA_PRE66_67, // BB OP_DATA_PRE66_67, // BC OP_DATA_PRE66_67, // BD OP_DATA_PRE66_67, // BE OP_DATA_PRE66_67, // BF OP_MODRM | OP_DATA_I8, // C0 OP_MODRM | OP_DATA_I8, // C1 OP_DATA_I16, // C2 OP_NONE, // C3 OP_MODRM, // C4 OP_MODRM, // C5 OP_MODRM | OP_DATA_I8, // C6 OP_MODRM | OP_DATA_PRE66_67, // C7 OP_DATA_I8 | OP_DATA_I16, // C8 OP_NONE, // C9 OP_DATA_I16, // CA OP_NONE, // CB OP_NONE, // CC OP_DATA_I8, // CD OP_NONE, // CE OP_NONE, // CF OP_MODRM, // D0 OP_MODRM, // D1 OP_MODRM, // D2 OP_MODRM, // D3 OP_DATA_I8, // D4 OP_DATA_I8, // D5 OP_NONE, // D6 OP_NONE, // D7 OP_WORD, // D8 OP_WORD, // D9 OP_WORD, // DA OP_WORD, // DB OP_WORD, // DC OP_WORD, // DD OP_WORD, // DE OP_WORD, // DF OP_DATA_I8, // E0 OP_DATA_I8, // E1 OP_DATA_I8, // E2 OP_DATA_I8, // E3 OP_DATA_I8, // E4 OP_DATA_I8, // E5 OP_DATA_I8, // E6 OP_DATA_I8, // E7 OP_DATA_PRE66_67 | OP_REL32, // E8 OP_DATA_PRE66_67 | OP_REL32, // E9 OP_DATA_I16 | OP_DATA_PRE66_67,// EA OP_DATA_I8, // EB OP_NONE, // EC OP_NONE, // ED OP_NONE, // EE OP_NONE, // EF OP_NONE, // F0 OP_NONE, // F1 OP_NONE, // F2 OP_NONE, // F3 OP_NONE, // F4 OP_NONE, // F5 OP_MODRM, // F6 OP_MODRM, // F7 OP_NONE, // F8 OP_NONE, // F9 OP_NONE, // FA OP_NONE, // FB OP_NONE, // FC OP_NONE, // FD OP_MODRM, // FE OP_MODRM | OP_REL32 // FF }; UCHAR OpcodeFlagsExt[256] = { OP_MODRM, // 00 OP_MODRM, // 01 OP_MODRM, // 02 OP_MODRM, // 03 OP_NONE, // 04 OP_NONE, // 05 OP_NONE, // 06 OP_NONE, // 07 OP_NONE, // 08 OP_NONE, // 09 OP_NONE, // 0A OP_NONE, // 0B OP_NONE, // 0C OP_MODRM, // 0D OP_NONE, // 0E OP_MODRM | OP_DATA_I8, // 0F OP_MODRM, // 10 OP_MODRM, // 11 OP_MODRM, // 12 OP_MODRM, // 13 OP_MODRM, // 14 OP_MODRM, // 15 OP_MODRM, // 16 OP_MODRM, // 17 OP_MODRM, // 18 OP_NONE, // 19 OP_NONE, // 1A OP_NONE, // 1B OP_NONE, // 1C OP_NONE, // 1D OP_NONE, // 1E OP_NONE, // 1F OP_MODRM, // 20 OP_MODRM, // 21 OP_MODRM, // 22 OP_MODRM, // 23 OP_MODRM, // 24 OP_NONE, // 25 OP_MODRM, // 26 OP_NONE, // 27 OP_MODRM, // 28 OP_MODRM, // 29 OP_MODRM, // 2A OP_MODRM, // 2B OP_MODRM, // 2C OP_MODRM, // 2D OP_MODRM, // 2E OP_MODRM, // 2F OP_NONE, // 30 OP_NONE, // 31 OP_NONE, // 32 OP_NONE, // 33 OP_NONE, // 34 OP_NONE, // 35 OP_NONE, // 36 OP_NONE, // 37 OP_NONE, // 38 OP_NONE, // 39 OP_NONE, // 3A OP_NONE, // 3B OP_NONE, // 3C OP_NONE, // 3D OP_NONE, // 3E OP_NONE, // 3F OP_MODRM, // 40 OP_MODRM, // 41 OP_MODRM, // 42 OP_MODRM, // 43 OP_MODRM, // 44 OP_MODRM, // 45 OP_MODRM, // 46 OP_MODRM, // 47 OP_MODRM, // 48 OP_MODRM, // 49 OP_MODRM, // 4A OP_MODRM, // 4B OP_MODRM, // 4C OP_MODRM, // 4D OP_MODRM, // 4E OP_MODRM, // 4F OP_MODRM, // 50 OP_MODRM, // 51 OP_MODRM, // 52 OP_MODRM, // 53 OP_MODRM, // 54 OP_MODRM, // 55 OP_MODRM, // 56 OP_MODRM, // 57 OP_MODRM, // 58 OP_MODRM, // 59 OP_MODRM, // 5A OP_MODRM, // 5B OP_MODRM, // 5C OP_MODRM, // 5D OP_MODRM, // 5E OP_MODRM, // 5F OP_MODRM, // 60 OP_MODRM, // 61 OP_MODRM, // 62 OP_MODRM, // 63 OP_MODRM, // 64 OP_MODRM, // 65 OP_MODRM, // 66 OP_MODRM, // 67 OP_MODRM, // 68 OP_MODRM, // 69 OP_MODRM, // 6A OP_MODRM, // 6B OP_MODRM, // 6C OP_MODRM, // 6D OP_MODRM, // 6E OP_MODRM, // 6F OP_MODRM | OP_DATA_I8, // 70 OP_MODRM | OP_DATA_I8, // 71 OP_MODRM | OP_DATA_I8, // 72 OP_MODRM | OP_DATA_I8, // 73 OP_MODRM, // 74 OP_MODRM, // 75 OP_MODRM, // 76 OP_NONE, // 77 OP_NONE, // 78 OP_NONE, // 79 OP_NONE, // 7A OP_NONE, // 7B OP_MODRM, // 7C OP_MODRM, // 7D OP_MODRM, // 7E OP_MODRM, // 7F OP_DATA_PRE66_67 | OP_REL32, // 80 OP_DATA_PRE66_67 | OP_REL32, // 81 OP_DATA_PRE66_67 | OP_REL32, // 82 OP_DATA_PRE66_67 | OP_REL32, // 83 OP_DATA_PRE66_67 | OP_REL32, // 84 OP_DATA_PRE66_67 | OP_REL32, // 85 OP_DATA_PRE66_67 | OP_REL32, // 86 OP_DATA_PRE66_67 | OP_REL32, // 87 OP_DATA_PRE66_67 | OP_REL32, // 88 OP_DATA_PRE66_67 | OP_REL32, // 89 OP_DATA_PRE66_67 | OP_REL32, // 8A OP_DATA_PRE66_67 | OP_REL32, // 8B OP_DATA_PRE66_67 | OP_REL32, // 8C OP_DATA_PRE66_67 | OP_REL32, // 8D OP_DATA_PRE66_67 | OP_REL32, // 8E OP_DATA_PRE66_67 | OP_REL32, // 8F OP_MODRM, // 90 OP_MODRM, // 91 OP_MODRM, // 92 OP_MODRM, // 93 OP_MODRM, // 94 OP_MODRM, // 95 OP_MODRM, // 96 OP_MODRM, // 97 OP_MODRM, // 98 OP_MODRM, // 99 OP_MODRM, // 9A OP_MODRM, // 9B OP_MODRM, // 9C OP_MODRM, // 9D OP_MODRM, // 9E OP_MODRM, // 9F OP_NONE, // A0 OP_NONE, // A1 OP_NONE, // A2 OP_MODRM, // A3 OP_MODRM | OP_DATA_I8, // A4 OP_MODRM, // A5 OP_NONE, // A6 OP_NONE, // A7 OP_NONE, // A8 OP_NONE, // A9 OP_NONE, // AA OP_MODRM, // AB OP_MODRM | OP_DATA_I8, // AC OP_MODRM, // AD OP_MODRM, // AE OP_MODRM, // AF OP_MODRM, // B0 OP_MODRM, // B1 OP_MODRM, // B2 OP_MODRM, // B3 OP_MODRM, // B4 OP_MODRM, // B5 OP_MODRM, // B6 OP_MODRM, // B7 OP_NONE, // B8 OP_NONE, // B9 OP_MODRM | OP_DATA_I8, // BA OP_MODRM, // BB OP_MODRM, // BC OP_MODRM, // BD OP_MODRM, // BE OP_MODRM, // BF OP_MODRM, // C0 OP_MODRM, // C1 OP_MODRM | OP_DATA_I8, // C2 OP_MODRM, // C3 OP_MODRM | OP_DATA_I8, // C4 OP_MODRM | OP_DATA_I8, // C5 OP_MODRM | OP_DATA_I8, // C6 OP_MODRM, // C7 OP_NONE, // C8 OP_NONE, // C9 OP_NONE, // CA OP_NONE, // CB OP_NONE, // CC OP_NONE, // CD OP_NONE, // CE OP_NONE, // CF OP_MODRM, // D0 OP_MODRM, // D1 OP_MODRM, // D2 OP_MODRM, // D3 OP_MODRM, // D4 OP_MODRM, // D5 OP_MODRM, // D6 OP_MODRM, // D7 OP_MODRM, // D8 OP_MODRM, // D9 OP_MODRM, // DA OP_MODRM, // DB OP_MODRM, // DC OP_MODRM, // DD OP_MODRM, // DE OP_MODRM, // DF OP_MODRM, // E0 OP_MODRM, // E1 OP_MODRM, // E2 OP_MODRM, // E3 OP_MODRM, // E4 OP_MODRM, // E5 OP_MODRM, // E6 OP_MODRM, // E7 OP_MODRM, // E8 OP_MODRM, // E9 OP_MODRM, // EA OP_MODRM, // EB OP_MODRM, // EC OP_MODRM, // ED OP_MODRM, // EE OP_MODRM, // EF OP_MODRM, // F0 OP_MODRM, // F1 OP_MODRM, // F2 OP_MODRM, // F3 OP_MODRM, // F4 OP_MODRM, // F5 OP_MODRM, // F6 OP_MODRM, // F7 OP_MODRM, // F8 OP_MODRM, // F9 OP_MODRM, // FA OP_MODRM, // FB OP_MODRM, // FC OP_MODRM, // FD OP_MODRM, // FE OP_NONE // FF }; unsigned long __fastcall SizeOfCode(void *Code, unsigned char **pOpcode) { PUCHAR cPtr; UCHAR Flags; BOOLEAN PFX66, PFX67; BOOLEAN SibPresent; UCHAR iMod, iRM, iReg; UCHAR OffsetSize, Add; UCHAR Opcode; OffsetSize = 0; PFX66 = FALSE; PFX67 = FALSE; cPtr = (PUCHAR)Code; while ( (*cPtr == 0x2E) || (*cPtr == 0x3E) || (*cPtr == 0x36) || (*cPtr == 0x26) || (*cPtr == 0x64) || (*cPtr == 0x65) || (*cPtr == 0xF0) || (*cPtr == 0xF2) || (*cPtr == 0xF3) || (*cPtr == 0x66) || (*cPtr == 0x67) ) { if (*cPtr == 0x66) PFX66 = TRUE; if (*cPtr == 0x67) PFX67 = TRUE; cPtr++; if (cPtr > (PUCHAR)Code + 16) return 0; } Opcode = *cPtr; if (pOpcode) *pOpcode = cPtr; if (*cPtr == 0x0F) { cPtr++; Flags = OpcodeFlagsExt[*cPtr]; } else { Flags = OpcodeFlags[Opcode]; if (Opcode >= 0xA0 && Opcode <= 0xA3) PFX66 = !PFX66; } cPtr++; if (Flags & OP_WORD)cPtr++; if (Flags & OP_MODRM) { iMod = *cPtr >> 6; iReg = (*cPtr & 0x38) >> 3; iRM = *cPtr & 7; cPtr++; if ((Opcode == 0xF6) && !iReg) Flags |= OP_DATA_I8; if ((Opcode == 0xF7) && !iReg) Flags |= OP_DATA_PRE66_67; SibPresent = !PFX67 & (iRM == 4); switch (iMod) { case 0: if ( PFX67 && (iRM == 6)) OffsetSize = 2; if (!PFX67 && (iRM == 5)) OffsetSize = 4; break; case 1: OffsetSize = 1; break; case 2: if (PFX67) OffsetSize = 2; else OffsetSize = 4; break; case 3: SibPresent = FALSE; } if (SibPresent) { if (((*cPtr & 7) == 5) && ( (!iMod) || (iMod == 2) )) OffsetSize = 4; cPtr++; } cPtr = (PUCHAR)(ULONG)cPtr + OffsetSize; } if (Flags & OP_DATA_I8) cPtr++; if (Flags & OP_DATA_I16) cPtr += 2; if (Flags & OP_DATA_I32) cPtr += 4; if (PFX66) Add = 2; else Add = 4; if (Flags & OP_DATA_PRE66_67) cPtr += Add; return (ULONG)cPtr - (ULONG)Code; } unsigned long __fastcall SizeOfProc(void *Proc) { ULONG Length; PUCHAR pOpcode; ULONG Result = 0; do { Length = SizeOfCode(Proc, &pOpcode); Result += Length; if ((Length == 1) && (*pOpcode == 0xC3)) break; Proc = (PVOID)((ULONG)Proc + Length); } while (Length); return Result; } char __fastcall IsRelativeCmd(unsigned char *pOpcode) { UCHAR Flags; if (*pOpcode == 0x0F) Flags = OpcodeFlagsExt[*(PUCHAR)((ULONG)pOpcode + 1)]; else Flags = OpcodeFlags[*pOpcode]; return (Flags & OP_REL32); }
C
#ifndef _LDASM_ #define _LDASM_ #ifdef __cplusplus extern "C" { #endif unsigned long __fastcall SizeOfCode(void *Code, unsigned char **pOpcode); unsigned long __fastcall SizeOfProc(void *Proc); char __fastcall IsRelativeCmd(unsigned char *pOpcode); #ifdef __cplusplus } #endif #endif
C
#ifndef __NONAME_UNDOCUMENT_H__ #define __NONAME_UNDOCUMENT_H__ #include <ntifs.h> #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 typedef struct _IMAGE_EXPORT_DIRECTORY { ULONG Characteristics; ULONG TimeDateStamp; USHORT MajorVersion; USHORT MinorVersion; ULONG Name; ULONG Base; ULONG NumberOfFunctions; ULONG NumberOfNames; ULONG AddressOfFunctions; // RVA from base of image ULONG AddressOfNames; // RVA from base of image ULONG AddressOfNameOrdinals; // RVA from base of image } IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; typedef struct _NON_PAGED_DEBUG_INFO { USHORT Signature; USHORT Flags; ULONG Size; USHORT Machine; USHORT Characteristics; ULONG TimeDateStamp; ULONG CheckSum; ULONG SizeOfImage; ULONGLONG ImageBase; } NON_PAGED_DEBUG_INFO, *PNON_PAGED_DEBUG_INFO; typedef struct _KLDR_DATA_TABLE_ENTRY { LIST_ENTRY InLoadOrderLinks; PVOID ExceptionTable; ULONG ExceptionTableSize; // ULONG padding on IA64 PVOID GpValue; PNON_PAGED_DEBUG_INFO NonPagedDebugInfo; PVOID DllBase; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; ULONG Flags; USHORT LoadCount; USHORT __Unused5; PVOID SectionPointer; ULONG CheckSum; // ULONG padding on IA64 PVOID LoadedImports; PVOID PatchInformation; } KLDR_DATA_TABLE_ENTRY, *PKLDR_DATA_TABLE_ENTRY; #ifdef __cplusplus extern "C" { #endif NTKERNELAPI NTSTATUS KeSetAffinityThread( PKTHREAD Thread, KAFFINITY Affinity ); NTKERNELAPI PVOID RtlImageDirectoryEntryToData ( IN PVOID Base, IN BOOLEAN MappedAsImage, IN USHORT DirectoryEntry, OUT PULONG Size ); #ifdef __cplusplus }; #endif #endif
C
#ifndef __SECTOR_MON_H__ #define __SECTOR_MON_H__ #include <ntifs.h> #include <Ntddvol.h> #define DEVICE_TYPE_CTRL 0 #define DEVICE_TYPE_FILTER 1 typedef struct _DISK_FLT_DEVICE_EXT { ULONG DeviceType; PDEVICE_OBJECT FilterDeviceObject; PDEVICE_OBJECT LowerDeviceObject; PDEVICE_OBJECT PhysicalDeviceObject; LIST_ENTRY ReqList; KSPIN_LOCK ReqLock; KEVENT ReqEvent; BOOLEAN ThreadFlag; PETHREAD ThreadObject; PAGED_LOOKASIDE_LIST WriteElemHeader; PAGED_LOOKASIDE_LIST SectorBufHeader; } DISK_FLT_DEVICE_EXT, *PDISK_FLT_DEVICE_EXT; typedef struct _WRITE_ELEMENT { LIST_ENTRY ListEntry; HANDLE File; PVOID Buffer; ULONG Length; LARGE_INTEGER Offset; BOOLEAN NeedFree; ULONG Tag; } WRITE_ELEMENT, *PWRITE_ELEMENT; typedef struct _GLOBAL_CONTEXT { HANDLE FileHandle; PVOID MapBuffer; ULONG MapSize; HANDLE SparseFileHandle; } GLOBAL_CONTEXT, *PGLOBAL_CONTEXT; #pragma pack(push, 1) typedef struct _NTFS_BPB { USHORT BytesPerSector; UCHAR SectorsPerCluster; USHORT ReservedSectors; UCHAR NumberOfFATs; // always 0 USHORT RootEntries; // always 0 USHORT SmallSectors; // not used by NTFS UCHAR MediaDescriptor; USHORT SectorsPerFAT; // always 0 USHORT SectorsPerTrack; USHORT NumberOfHeads; ULONG HiddenSectors; ULONG LargeSectors; // not used by NTFS } NTFS_BPB, *PNTFS_BPB; typedef struct _NTFS_EXBPB { // Extended BIOS parameter block for FAT16 ULONG Reserved; // not used by NTFS ULONGLONG TotalSectors; ULONGLONG MFT; ULONGLONG MFTMirr; ULONG ClustersPerFileRecordSegment; ULONG ClustersPerIndexBlock; ULONGLONG VolumeSerialNumber; ULONG Checksum; } NTFS_EXBPB, *PNTFS_EXBPB; typedef struct _NTFS_BOOT_SEC { UCHAR JumpInstruction[3]; UCHAR OemID[8]; NTFS_BPB Bpb; NTFS_EXBPB ExBpb; UCHAR BootstrapCode[426]; UCHAR EndOfSector[2]; } NTFS_BOOT_SEC, *PNTFS_BOOT_SEC; #pragma pack(pop) #define DIRECT_READ 0 #define DIRECT_WRITE 1 #define BITOFF_TO_MAPOFF(off) (ULONG)(off >> 3) #define BITLEN_TO_MAPLEN(off, len) ((ULONG)((off + len) >> 3) - BITOFF_TO_MAPOFF(off) + 1) #define BYTEOFF_TO_BITOFF(off) (off / BytesPerSector) #define BYTELEN_TO_BITLEN(len) (len / BytesPerSector) NTSTATUS SkipAndCallDriver( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ); NTSTATUS SyncIrpCompletionRoutine( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PVOID Context ); NTSTATUS SendSyncIrp( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ); NTSTATUS DispatchPassThrough( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ); NTSTATUS DispatchPower( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ); NTSTATUS DispatchPnp( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ); NTSTATUS DispatchReadWrite( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ); NTSTATUS DispatchDeviceControl( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ); NTSTATUS DirectReadWrite( __in PDEVICE_OBJECT DeviceObject, __in ULONG ReadWrite, __out PVOID Buffer, __in PLARGE_INTEGER Offset, __in ULONG Length ); LONGLONG GetFileSize( __in HANDLE Handle ); BOOLEAN __fastcall SetBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit ); BOOLEAN __fastcall ClearBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit ); ULONG __fastcall GetBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit ); NTSTATUS OpenMapping( __in PWCHAR Name, __out PHANDLE File, __out PVOID *Buffer, __out ULONG *BufferSize ); VOID CloseMapping( __in HANDLE File, __in PVOID Buffer ); NTSTATUS CreateSparseFile( __out PHANDLE Handle, __in PWCHAR FileName, __in ULONGLONG FileSize, __in BOOLEAN Restore ); NTSTATUS AddDevice( __in PDRIVER_OBJECT DriverObject, __in PDEVICE_OBJECT PhysicalDeviceObject ); VOID Unload( __in PDRIVER_OBJECT DriverObject ); VOID ReinitializationRoutine( __in PDRIVER_OBJECT DriverObject, __in PVOID Context, __in ULONG Count ); NTSTATUS DriverEntry( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath ); NTSTATUS FlushBuffer( __in PDISK_FLT_DEVICE_EXT DevExt, __in HANDLE File, __in PVOID Buffer, __in ULONG Offset, __in ULONG Size ); NTSTATUS __fastcall BackupSectorAndSetBit( __in PDEVICE_OBJECT PhysicalDeviceObject, __in HANDLE File, __in PLARGE_INTEGER Offset, __in ULONG Length, __in PDISK_FLT_DEVICE_EXT DevExt ); VOID WriteWorkThread( __in PVOID Context ); NTSTATUS RestoreDisk( __in PDISK_FLT_DEVICE_EXT DevExt ); BOOLEAN IsRestoreDisk(); #endif
C
#include "SectorMon.h" BOOLEAN StartFilter = FALSE; BOOLEAN InitFilter = FALSE; NTFS_BOOT_SEC BootSec; GLOBAL_CONTEXT GlobalContext = {0}; USHORT BytesPerSector = 512; NTSTATUS RecoverBootStatus() { NTSTATUS ns; HANDLE FileHandle; OBJECT_ATTRIBUTES oa; IO_STATUS_BLOCK Iob; LARGE_INTEGER Offset = {0}; UCHAR Buffer[16]; DECLARE_CONST_UNICODE_STRING(FileName, L"\\??\\C:\\Windows\\bootstat.dat"); InitializeObjectAttributes(&oa, (PUNICODE_STRING)&FileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); ns = ZwCreateFile(&FileHandle, FILE_READ_DATA | FILE_WRITE_DATA | SYNCHRONIZE, &oa, &Iob, NULL, 0, FILE_SHARE_READ, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (!NT_SUCCESS(ns)) { return ns; } ns = ZwReadFile(FileHandle, NULL, NULL, NULL, &Iob, Buffer, 16, &Offset, NULL); if (!NT_SUCCESS(ns)) { ZwClose(FileHandle); return ns; } if (Buffer[10] == 0) { Buffer[10] = 1; } ns = ZwWriteFile(FileHandle, NULL, NULL, NULL, &Iob, Buffer, 16, &Offset, NULL); ZwClose(FileHandle); return ns; } BOOLEAN IsRestoreDisk() { NTSTATUS ns; UNICODE_STRING SecMonName; UNICODE_STRING RestoreDiskName; OBJECT_ATTRIBUTES oa; HANDLE SecMonHandle; UCHAR ValueBuffer[128]; ULONG RetLength; PKEY_VALUE_PARTIAL_INFORMATION Value = (PKEY_VALUE_PARTIAL_INFORMATION)ValueBuffer; RtlInitUnicodeString(&SecMonName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\SecMon"); InitializeObjectAttributes(&oa, &SecMonName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); ns = ZwOpenKey(&SecMonHandle, KEY_READ, &oa); if (!NT_SUCCESS(ns)) { return FALSE; } RtlInitUnicodeString(&RestoreDiskName, L"Current"); ns = ZwQueryValueKey(SecMonHandle, &RestoreDiskName, KeyValuePartialInformation, ValueBuffer, sizeof(ValueBuffer), &RetLength); ZwClose(SecMonHandle); if (!NT_SUCCESS(ns)) { return FALSE; } if (*((ULONG *)Value->Data) == 0) { return FALSE; } return TRUE; } NTSTATUS RestoreDisk( __in PDISK_FLT_DEVICE_EXT DevExt ) { ULONGLONG BitCount; PVOID BitBuf = GlobalContext.MapBuffer; ULONG BitSize = GlobalContext.MapSize; LARGE_INTEGER Offset; ULONGLONG i; LONG Ret; PVOID SectorBuf; NTSTATUS ns = STATUS_SUCCESS; IO_STATUS_BLOCK Iob; HANDLE FileHandle = GlobalContext.SparseFileHandle; PDEVICE_OBJECT PhyDevObj = DevExt->PhysicalDeviceObject; FILE_DISPOSITION_INFORMATION FileDisInfo; LARGE_INTEGER Mm3Second = {(ULONG)(-3 * 1000 * 1000 * 10), -1}; BitCount = BitSize << 3; SectorBuf = ExAllocatePoolWithTag(PagedPool, BytesPerSector, 'rsdk'); for (i = 0; i < BitCount; i++) { if (i % 0x1000 == 0) { KdPrint(("Per : %I64d / %I64d\n", i, BitCount)); } Ret = GetBit(BitBuf, BitSize, i); ASSERT(Ret != -1); if (Ret == -1) { ns = STATUS_UNSUCCESSFUL; break; } else if (Ret == 1) { Offset.QuadPart = i * BytesPerSector; ns = ZwReadFile(FileHandle, NULL, NULL, NULL, &Iob, SectorBuf, BytesPerSector, &Offset, NULL); ASSERT(NT_SUCCESS(ns)); if (!NT_SUCCESS(ns)) { break; } ns = DirectReadWrite(PhyDevObj, DIRECT_WRITE, SectorBuf, &Offset, BytesPerSector); ASSERT(NT_SUCCESS(ns)); if (!NT_SUCCESS(ns)) { break; } } } ExFreePoolWithTag(SectorBuf, 'rsdk'); if (!NT_SUCCESS(ns)) { return ns; } Offset.QuadPart = 0; RtlZeroMemory(BitBuf, BitSize); ns = ZwWriteFile(GlobalContext.FileHandle, NULL, NULL, NULL, &Iob, BitBuf, BitSize, &Offset, NULL); if (!NT_SUCCESS(ns)) { return ns; } FileDisInfo.DeleteFile = TRUE; ns = ZwSetInformationFile(FileHandle, &Iob, &FileDisInfo, sizeof(FILE_DISPOSITION_INFORMATION), FileDispositionInformation); if (!NT_SUCCESS(ns)) { return ns; } ZwClose(FileHandle); ns = RecoverBootStatus(); KeDelayExecutionThread(KernelMode, FALSE, &Mm3Second); KeBugCheck(POWER_FAILURE_SIMULATE); } VOID WriteWorkThread( __in PVOID Context ) { PWRITE_ELEMENT ReqEntry = NULL; PDISK_FLT_DEVICE_EXT DevExt = (PDISK_FLT_DEVICE_EXT)Context; IO_STATUS_BLOCK Iob; KeSetPriorityThread(KeGetCurrentThread(), LOW_REALTIME_PRIORITY); for(;;) { KeWaitForSingleObject( &DevExt->ReqEvent, Executive, KernelMode, FALSE, NULL ); if (DevExt->ThreadFlag) { PsTerminateSystemThread(STATUS_SUCCESS); return; } while ((ReqEntry = (PWRITE_ELEMENT)ExInterlockedRemoveHeadList(&DevExt->ReqList, &DevExt->ReqLock)) != NULL) { ZwWriteFile(ReqEntry->File, NULL, NULL, NULL, &Iob, ReqEntry->Buffer, ReqEntry->Length, &ReqEntry->Offset, NULL); if (ReqEntry->NeedFree) { ExFreeToPagedLookasideList(&DevExt->SectorBufHeader, ReqEntry->Buffer); } ExFreeToPagedLookasideList(&DevExt->WriteElemHeader, ReqEntry); } } } NTSTATUS SkipAndCallDriver( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { IoSkipCurrentIrpStackLocation(Irp); return IoCallDriver(DeviceObject, Irp); } NTSTATUS SyncIrpCompletionRoutine( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PVOID Context ) { PKEVENT Event = (PKEVENT) Context; UNREFERENCED_PARAMETER(DeviceObject); if (Irp->PendingReturned) { KeSetEvent(Event, IO_NO_INCREMENT, FALSE); } return STATUS_MORE_PROCESSING_REQUIRED; } NTSTATUS SendSyncIrp( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { KEVENT Event; NTSTATUS ns; KeInitializeEvent(&Event, NotificationEvent, FALSE); IoCopyCurrentIrpStackLocationToNext(Irp); IoSetCompletionRoutine( Irp, SyncIrpCompletionRoutine, &Event, TRUE, TRUE, TRUE); ns = IoCallDriver(DeviceObject, Irp); if (ns == STATUS_PENDING) { KeWaitForSingleObject( &Event, Executive, KernelMode, FALSE, NULL); ns = Irp->IoStatus.Status; } return ns; } NTSTATUS DispatchPassThrough( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension; return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp); } NTSTATUS DispatchPower( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension; #if (NTDDI_VERSION < NTDDI_VISTA) PoStartNextPowerIrp(Irp); IoSkipCurrentIrpStackLocation(Irp); return PoCallDriver(DevExt->LowerDeviceObject, Irp); #else return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp); #endif } NTSTATUS DispatchPnp( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension; PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp); NTSTATUS ns; switch (IrpSp->MinorFunction) { case IRP_MN_REMOVE_DEVICE: { StartFilter = FALSE; if (DevExt->LowerDeviceObject != NULL) { IoDetachDevice(DevExt->LowerDeviceObject); DevExt->LowerDeviceObject = NULL; } if (DevExt->ThreadObject != NULL && DevExt->ThreadFlag != TRUE) { DevExt->ThreadFlag = TRUE; KeSetEvent(&DevExt->ReqEvent, (KPRIORITY)0, FALSE); KeWaitForSingleObject( DevExt->ThreadObject, Executive, KernelMode, FALSE, NULL ); ObDereferenceObject(DevExt->ThreadObject); DevExt->ThreadObject = NULL; } ExDeletePagedLookasideList(&DevExt->SectorBufHeader); ExDeletePagedLookasideList(&DevExt->WriteElemHeader); if (DevExt->FilterDeviceObject != NULL) { IoDeleteDevice(DevExt->FilterDeviceObject); } if (GlobalContext.FileHandle != NULL) { CloseMapping(GlobalContext.FileHandle, GlobalContext.MapBuffer); GlobalContext.FileHandle = NULL; } if (GlobalContext.SparseFileHandle != NULL) { ZwClose(GlobalContext.SparseFileHandle); GlobalContext.SparseFileHandle = NULL; } } break; case IRP_MN_DEVICE_USAGE_NOTIFICATION: { if (IrpSp->Parameters.UsageNotification.Type != DeviceUsageTypePaging) { ns = SkipAndCallDriver(DevExt->LowerDeviceObject, Irp); return ns; } ns = SendSyncIrp(DevExt->LowerDeviceObject, Irp); if (NT_SUCCESS(ns)) { if (DevExt->LowerDeviceObject->Flags & DO_POWER_PAGABLE) { DeviceObject->Flags |= DO_POWER_PAGABLE; } else { DeviceObject->Flags &= ~DO_POWER_PAGABLE; } } IoCompleteRequest(Irp, IO_NO_INCREMENT); return ns; } break; default: break; } return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp); } NTSTATUS DispatchReadWrite( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension; PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp); NTSTATUS ns; if (StartFilter && InitFilter) { if (IrpSp->MajorFunction == IRP_MJ_READ) { // KdPrint(("Read Offset:%016I64X Length:%08X\n", // IrpSp->Parameters.Read.ByteOffset.QuadPart, // IrpSp->Parameters.Read.Length)); } else { // KdPrint(("Write Offset:%016I64X Length:%08X\n", // IrpSp->Parameters.Write.ByteOffset.QuadPart, // IrpSp->Parameters.Write.Length)); ns = BackupSectorAndSetBit(DevExt->PhysicalDeviceObject, GlobalContext.SparseFileHandle, &IrpSp->Parameters.Write.ByteOffset, IrpSp->Parameters.Write.Length, DevExt); if (!NT_SUCCESS(ns)) { KdPrint(("[FAILED] Write Offset:%016I64X Length:%08X\n", IrpSp->Parameters.Write.ByteOffset.QuadPart, IrpSp->Parameters.Write.Length)); } } } return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp); } NTSTATUS DispatchDeviceControl( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension; NTSTATUS ns; PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp); KEVENT Event; PIRP SynIrp; UCHAR DBR[512]; ULONG DBRLength = 512; IO_STATUS_BLOCK Iob; LARGE_INTEGER ReadOffset = {0}; switch (IrpSp->Parameters.DeviceIoControl.IoControlCode) { case IOCTL_VOLUME_ONLINE: { KeInitializeEvent(&Event, NotificationEvent, FALSE); IoCopyCurrentIrpStackLocationToNext(Irp); IoSetCompletionRoutine(Irp, SyncIrpCompletionRoutine, &Event, TRUE, TRUE, TRUE); ns = IoCallDriver(DevExt->LowerDeviceObject, Irp); if (ns == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); } KeClearEvent(&Event); SynIrp = IoBuildAsynchronousFsdRequest(IRP_MJ_READ, DevExt->PhysicalDeviceObject, DBR, DBRLength, &ReadOffset, &Iob); if (SynIrp != NULL) { IoSetCompletionRoutine(SynIrp, SyncIrpCompletionRoutine, &Event, TRUE, TRUE, TRUE); ns = IoCallDriver(DevExt->PhysicalDeviceObject, SynIrp); if(ns == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); } ns = SynIrp->IoStatus.Status; IoFreeIrp(SynIrp); if (NT_SUCCESS(ns)) { RtlCopyMemory(&BootSec, DBR, sizeof(NTFS_BOOT_SEC)); BytesPerSector = BootSec.Bpb.BytesPerSector; ExInitializePagedLookasideList(&DevExt->SectorBufHeader, NULL, NULL, 0, BytesPerSector, 'back', 0); StartFilter = TRUE; } } IoCompleteRequest(Irp, IO_NO_INCREMENT); return ns; } break; default: break; } return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp); } NTSTATUS __fastcall BackupSectorAndSetBit( __in PDEVICE_OBJECT PhysicalDeviceObject, __in HANDLE File, __in PLARGE_INTEGER Offset, __in ULONG Length, __in PDISK_FLT_DEVICE_EXT DevExt ) { ULONGLONG BitOffset = BYTEOFF_TO_BITOFF(Offset->QuadPart); ULONG BitLength = BYTELEN_TO_BITLEN(Length); ULONG i; ULONG BitStatus; BOOLEAN BitRet; PUCHAR BitBuf = (PUCHAR)GlobalContext.MapBuffer; ULONG BitSize = GlobalContext.MapSize; LARGE_INTEGER BackupOffset; PUCHAR BackupBuf; NTSTATUS ns; PWRITE_ELEMENT WriteElem; ASSERT((Offset->QuadPart % BytesPerSector) == 0); ASSERT((Length % BytesPerSector) == 0); for (i = 0; i < BitLength; i++) { BitStatus = GetBit(BitBuf, BitSize, BitOffset + i); if (BitStatus == -1) { return STATUS_UNSUCCESSFUL; } else if (BitStatus == 0) { BackupBuf = ExAllocateFromPagedLookasideList(&DevExt->SectorBufHeader); BackupOffset.QuadPart = (i + BitOffset) * BytesPerSector; ns = DirectReadWrite(PhysicalDeviceObject, DIRECT_READ, BackupBuf, &BackupOffset, BytesPerSector); if (!NT_SUCCESS(ns)) { ExFreeToPagedLookasideList(&DevExt->SectorBufHeader, BackupBuf); return ns; } WriteElem = (PWRITE_ELEMENT)ExAllocateFromPagedLookasideList(&DevExt->WriteElemHeader); if (WriteElem == NULL) { ExFreeToPagedLookasideList(&DevExt->SectorBufHeader, BackupBuf); return STATUS_INSUFFICIENT_RESOURCES; } WriteElem->File = File; WriteElem->Buffer = BackupBuf; WriteElem->Length = BytesPerSector; WriteElem->Offset.QuadPart = BackupOffset.QuadPart; WriteElem->NeedFree = TRUE; WriteElem->Tag = 'back'; ExInterlockedInsertTailList(&DevExt->ReqList, &WriteElem->ListEntry, &DevExt->ReqLock); KeSetEvent(&DevExt->ReqEvent, (KPRIORITY)0, FALSE); BitRet = SetBit(BitBuf, BitSize, BitOffset + i); if (!BitRet) { return STATUS_UNSUCCESSFUL; } } } FlushBuffer(DevExt, GlobalContext.FileHandle, BitBuf, BITOFF_TO_MAPOFF(BitOffset), BITLEN_TO_MAPLEN(BitOffset, BitLength)); return STATUS_SUCCESS; } NTSTATUS FlushBuffer( __in PDISK_FLT_DEVICE_EXT DevExt, __in HANDLE File, __in PVOID Buffer, __in ULONG Offset, __in ULONG Size ) { PUCHAR FlushBuf = (PUCHAR)Buffer; PWRITE_ELEMENT WriteElem = (PWRITE_ELEMENT)ExAllocateFromPagedLookasideList(&DevExt->WriteElemHeader); if (WriteElem == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } WriteElem->File = File; WriteElem->Buffer = FlushBuf + Offset; WriteElem->Length = Size; WriteElem->Offset.QuadPart = (LONGLONG)Offset; WriteElem->NeedFree = FALSE; ExInterlockedInsertTailList(&DevExt->ReqList, &WriteElem->ListEntry, &DevExt->ReqLock); KeSetEvent(&DevExt->ReqEvent, (KPRIORITY)0, FALSE); return STATUS_SUCCESS; } NTSTATUS DirectReadWrite( __in PDEVICE_OBJECT DeviceObject, __in ULONG ReadWrite, __out PVOID Buffer, __in PLARGE_INTEGER Offset, __in ULONG Length ) { NTSTATUS ns; ULONG MjFunc; KEVENT Event; PIRP Irp; IO_STATUS_BLOCK Iob; PMDL NextMdl; if (ReadWrite == DIRECT_READ) { MjFunc = IRP_MJ_READ; } else if (ReadWrite == DIRECT_WRITE) { MjFunc = IRP_MJ_WRITE; } else { return STATUS_INVALID_PARAMETER; } KeInitializeEvent(&Event, NotificationEvent, FALSE); Irp = IoBuildAsynchronousFsdRequest(MjFunc, DeviceObject, Buffer, Length, Offset, &Iob); if (Irp == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } IoSetCompletionRoutine(Irp, SyncIrpCompletionRoutine, &Event, TRUE, TRUE, TRUE); ns = IoCallDriver(DeviceObject, Irp); if(ns == STATUS_PENDING) { KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); } ns = Irp->IoStatus.Status; while (Irp->MdlAddress != NULL) { NextMdl = Irp->MdlAddress->Next; MmUnlockPages(Irp->MdlAddress); IoFreeMdl(Irp->MdlAddress); Irp->MdlAddress = NextMdl; } IoFreeIrp(Irp); return ns; } LONGLONG GetFileSize( __in HANDLE Handle ) { IO_STATUS_BLOCK Iob; FILE_STANDARD_INFORMATION FileStdInfo; NTSTATUS ns; ns = ZwQueryInformationFile(Handle, &Iob, &FileStdInfo, sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation); if (!NT_SUCCESS(ns)) { return 0; } return FileStdInfo.EndOfFile.QuadPart; } BOOLEAN __fastcall SetBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit ) { ULONG ByteOffset = 0; ULONG BitOffset = 0; ByteOffset = (ULONG)(Bit / 8); if (ByteOffset >= BitSize) { return FALSE; } BitOffset = (ULONG)(Bit % 8); BitBuf[ByteOffset] |= (UCHAR)(1 << BitOffset); return TRUE; } BOOLEAN __fastcall ClearBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit ) { ULONG ByteOffset = 0; ULONG BitOffset = 0; ByteOffset = (ULONG)(Bit / 8); if (ByteOffset >= BitSize) { return FALSE; } BitOffset = (ULONG)(Bit % 8); BitBuf[ByteOffset] &= (UCHAR)(~(1 << BitOffset)); return TRUE; } ULONG __fastcall GetBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit ) { ULONG ByteOffset = 0; ULONG BitOffset = 0; ByteOffset = (ULONG)(Bit / 8); if (ByteOffset >= BitSize) { return (ULONG)-1; } BitOffset = (ULONG)(Bit % 8); return (BitBuf[ByteOffset] & (UCHAR)(1 << BitOffset)) != 0; } NTSTATUS OpenMapping( __in PWCHAR Name, __out PHANDLE File, __out PVOID *Buffer, __out ULONG *BufferSize ) { NTSTATUS ns; HANDLE FileHandle; UNICODE_STRING FileName; OBJECT_ATTRIBUTES oa; IO_STATUS_BLOCK Iob; LARGE_INTEGER MaxSize; PVOID MapBuffer; LARGE_INTEGER Offset = {0}; RtlInitUnicodeString(&FileName, Name); InitializeObjectAttributes(&oa, &FileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); ns = ZwCreateFile(&FileHandle, FILE_READ_DATA | FILE_WRITE_DATA | SYNCHRONIZE, &oa, &Iob, NULL, 0, FILE_SHARE_READ, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_WRITE_THROUGH, NULL, 0); if (!NT_SUCCESS(ns)) { return ns; } MaxSize.QuadPart = GetFileSize(FileHandle); if (MaxSize.QuadPart == 0) { ZwClose(FileHandle); return STATUS_UNSUCCESSFUL; } MapBuffer = ExAllocatePoolWithTag(PagedPool, MaxSize.LowPart, 'bmp '); if (MapBuffer == NULL) { ZwClose(FileHandle); return STATUS_INSUFFICIENT_RESOURCES; } ns = ZwReadFile(FileHandle, NULL, NULL, NULL, &Iob, MapBuffer, MaxSize.LowPart, &Offset, NULL); if (!NT_SUCCESS(ns)) { ExFreePoolWithTag(MapBuffer, 'bmp '); ZwClose(FileHandle); return ns; } *File = FileHandle; *Buffer = MapBuffer; *BufferSize = MaxSize.LowPart; return ns; } VOID CloseMapping( __in HANDLE File, __in PVOID Buffer ) { ExFreePoolWithTag(Buffer, 'bmp '); ZwClose(File); } NTSTATUS CreateSparseFile( __out PHANDLE Handle, __in PWCHAR FileName, __in ULONGLONG FileSize, __in BOOLEAN Restore ) { NTSTATUS ns; HANDLE FileHandle; UNICODE_STRING SparseFileName; IO_STATUS_BLOCK Iob; OBJECT_ATTRIBUTES oa; FILE_END_OF_FILE_INFORMATION FileEndInfo = {0}; ULONG ExtFlag = 0; if (!Restore) { ExtFlag = FILE_RANDOM_ACCESS | FILE_NO_INTERMEDIATE_BUFFERING | FILE_WRITE_THROUGH; } RtlInitUnicodeString(&SparseFileName, FileName); InitializeObjectAttributes(&oa, &SparseFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); ns = ZwCreateFile( &FileHandle, FILE_READ_DATA | FILE_WRITE_DATA | SYNCHRONIZE | DELETE, &oa, &Iob, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN_IF, FILE_SYNCHRONOUS_IO_NONALERT | ExtFlag, NULL, 0); if(!NT_SUCCESS(ns)) { return ns; } if (Iob.Information == FILE_CREATED) { ns = ZwFsControlFile(FileHandle, NULL, NULL, NULL, &Iob, FSCTL_SET_SPARSE, NULL, 0, NULL, 0); if(!NT_SUCCESS(ns)) { ZwClose(FileHandle); return ns; } FileEndInfo.EndOfFile.QuadPart = FileSize + 10*1024*1024; ns = ZwSetInformationFile(FileHandle, &Iob, &FileEndInfo, sizeof(FILE_END_OF_FILE_INFORMATION), FileEndOfFileInformation); if (!NT_SUCCESS(ns)) { ZwClose(FileHandle); return ns; } } *Handle = FileHandle; return ns; } NTSTATUS AddDevice( __in PDRIVER_OBJECT DriverObject, __in PDEVICE_OBJECT PhysicalDeviceObject ) { NTSTATUS ns; PDISK_FLT_DEVICE_EXT DevExt; PDEVICE_OBJECT LowerDevObj; PDEVICE_OBJECT FltDevObj; ULONG RetLength; HANDLE ThreadHandle; UCHAR NameBuffer[1024 + sizeof(OBJECT_NAME_INFORMATION)]; POBJECT_NAME_INFORMATION DeviceNameInfo = (POBJECT_NAME_INFORMATION)NameBuffer; DECLARE_CONST_UNICODE_STRING(Vol1, L"\\Device\\HarddiskVolume1"); ns = ObQueryNameString(PhysicalDeviceObject, DeviceNameInfo, 1024, &RetLength); if (!NT_SUCCESS(ns)) { return ns; } if (RtlCompareUnicodeString(&Vol1, &DeviceNameInfo->Name, TRUE) != 0) { return STATUS_SUCCESS; } KdPrint(("Physical Device Dos Name : %wZ\n", &DeviceNameInfo->Name)); ns = IoCreateDevice(DriverObject, sizeof(DISK_FLT_DEVICE_EXT), NULL, FILE_DEVICE_DISK, FILE_DEVICE_SECURE_OPEN, FALSE, &FltDevObj); if (!NT_SUCCESS(ns)) { return ns; } DevExt = FltDevObj->DeviceExtension; RtlZeroMemory(DevExt,sizeof(DISK_FLT_DEVICE_EXT)); LowerDevObj = IoAttachDeviceToDeviceStack(FltDevObj, PhysicalDeviceObject); if (LowerDevObj == NULL) { IoDeleteDevice(FltDevObj); ns = STATUS_NO_SUCH_DEVICE; return ns; } FltDevObj->Flags |= LowerDevObj->Flags & (DO_DIRECT_IO | DO_BUFFERED_IO | DO_POWER_PAGABLE); FltDevObj->Flags &= ~DO_DEVICE_INITIALIZING; DevExt->DeviceType = DEVICE_TYPE_FILTER; DevExt->FilterDeviceObject = FltDevObj; DevExt->PhysicalDeviceObject = PhysicalDeviceObject; DevExt->LowerDeviceObject = LowerDevObj; InitializeListHead(&DevExt->ReqList); KeInitializeSpinLock(&DevExt->ReqLock); KeInitializeEvent(&DevExt->ReqEvent, SynchronizationEvent, FALSE); DevExt->ThreadFlag = FALSE; ns = PsCreateSystemThread(&ThreadHandle, (ACCESS_MASK)0L, NULL, NULL, NULL, WriteWorkThread, DevExt); if (!NT_SUCCESS(ns)) { IoDeleteDevice(FltDevObj); return ns; } ns = ObReferenceObjectByHandle(ThreadHandle, THREAD_ALL_ACCESS, NULL, KernelMode, &DevExt->ThreadObject, NULL); ZwClose(ThreadHandle); if (!NT_SUCCESS(ns)) { DevExt->ThreadFlag = TRUE; KeSetEvent(&DevExt->ReqEvent, (KPRIORITY)0, FALSE); IoDeleteDevice(FltDevObj); return ns; } ExInitializePagedLookasideList(&DevExt->WriteElemHeader, NULL, NULL, 0, sizeof(WRITE_ELEMENT), 'welm', 0); return ns; } VOID Unload( __in PDRIVER_OBJECT DriverObject ) { PDEVICE_OBJECT NextDevObj; PDEVICE_OBJECT CurDevObj; PDISK_FLT_DEVICE_EXT DevExt; NextDevObj = DriverObject->DeviceObject; while (NextDevObj != NULL) { CurDevObj = NextDevObj; DevExt = (PDISK_FLT_DEVICE_EXT)CurDevObj->DeviceExtension; NextDevObj = CurDevObj->NextDevice; if (DevExt->DeviceType == DEVICE_TYPE_FILTER) { IoDetachDevice(DevExt->LowerDeviceObject); if (DevExt->ThreadObject != NULL && DevExt->ThreadFlag != TRUE) { DevExt->ThreadFlag = TRUE; KeSetEvent(&DevExt->ReqEvent, (KPRIORITY)0, FALSE); KeWaitForSingleObject( DevExt->ThreadObject, Executive, KernelMode, FALSE, NULL ); ObDereferenceObject(DevExt->ThreadObject); DevExt->ThreadObject = NULL; } ExDeletePagedLookasideList(&DevExt->SectorBufHeader); ExDeletePagedLookasideList(&DevExt->WriteElemHeader); DevExt->LowerDeviceObject = NULL; } IoDeleteDevice(CurDevObj); } if (GlobalContext.FileHandle != NULL) { CloseMapping(GlobalContext.FileHandle, GlobalContext.MapBuffer); GlobalContext.FileHandle = NULL; } if (GlobalContext.SparseFileHandle != NULL) { ZwClose(GlobalContext.SparseFileHandle); GlobalContext.SparseFileHandle = NULL; } return; } VOID ReinitializationRoutine( __in PDRIVER_OBJECT DriverObject, __in PVOID Context, __in ULONG Count ) { NTSTATUS ns; PDEVICE_OBJECT FilterDevice; PDISK_FLT_DEVICE_EXT DevExt; BOOLEAN PrepareRestore = IsRestoreDisk(); UNREFERENCED_PARAMETER(DriverObject); UNREFERENCED_PARAMETER(Context); UNREFERENCED_PARAMETER(Count); ns = OpenMapping(L"\\??\\D:\\Bitmap.dat", &GlobalContext.FileHandle, &GlobalContext.MapBuffer, &GlobalContext.MapSize); if (!NT_SUCCESS(ns)) { return; } ns = CreateSparseFile(&GlobalContext.SparseFileHandle, L"\\??\\D:\\SpareFile.dat", BootSec.ExBpb.TotalSectors * BootSec.Bpb.BytesPerSector, PrepareRestore); if (!NT_SUCCESS(ns)) { return; } if (PrepareRestore) { FilterDevice = DriverObject->DeviceObject; while (FilterDevice != NULL) { DevExt = FilterDevice->DeviceExtension; if (DevExt != NULL && DevExt->DeviceType == DEVICE_TYPE_FILTER) { RestoreDisk(DevExt); KdBreakPoint(); } FilterDevice = FilterDevice->NextDevice; } } InitFilter = TRUE; return; } NTSTATUS DriverEntry( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath ) { ULONG i; UNREFERENCED_PARAMETER(RegistryPath); KdBreakPoint(); for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) { DriverObject->MajorFunction[i] = DispatchPassThrough; } DriverObject->MajorFunction[IRP_MJ_POWER] = DispatchPower; DriverObject->MajorFunction[IRP_MJ_PNP] = DispatchPnp; DriverObject->MajorFunction[IRP_MJ_READ] = DispatchReadWrite; DriverObject->MajorFunction[IRP_MJ_WRITE] = DispatchReadWrite; DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchDeviceControl; DriverObject->DriverExtension->AddDevice = AddDevice; DriverObject->DriverUnload = Unload; IoRegisterBootDriverReinitialization(DriverObject, ReinitializationRoutine, NULL); return STATUS_SUCCESS; }
C
#ifndef INCLUDES_H #define INCLUDES_H // Application properties #include "Properties.h" /* Common includes for classes */ #include <QApplication> #include <QObject> #include <QDebug> // GUI /*#include <QSplashScreen> #include <QLabel> #include <QMessageBox> #include <QCheckBox> #include <QFileDialog> #include <QIcon> #include <QStyle> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QHeaderView> #include <QComboBox> #include <QScrollbar> #include <QProgressBar> #include <QPalette> // Drag&Drop #include <QMimeData> #include <QDropEvent> #include <QDragEnterEvent>*/ // String stuff #include <QString> #include <QStringList> #include <QByteArray> //#include <QRegExp> //#include <QTextCodec> // File access stuff #include <QFile> #include <QFileInfo> #include <QDir> /*#include <QTextStream> #include <QUrl>*/ // Lists and maps #include <QList> #include <QHash> #include <QMap> // Settings #include <QSettings> #include <QIntValidator> // Network #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QNetworkProxy> #include <QNetworkCookie> #include <QNetworkCookieJar> #include <QTcpServer> #include <QTcpSocket> // Images #include <QImage> #include <QPixmap> // Misc #include <QFlags> #endif // INCLUDES_H
C
#include "Python.h" #include "structmember.h" #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t PyInt_FromLong #define PyInt_AsSsize_t PyInt_AsLong #endif #ifndef Py_IS_FINITE #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) #endif #ifdef __GNUC__ #define UNUSED __attribute__((__unused__)) #else #define UNUSED #endif #define DEFAULT_ENCODING "utf-8" #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType) #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType) #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType) #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType) static PyTypeObject PyScannerType; static PyTypeObject PyEncoderType; typedef struct _PyScannerObject { PyObject_HEAD PyObject *encoding; PyObject *strict; PyObject *object_hook; PyObject *parse_float; PyObject *parse_int; PyObject *parse_constant; } PyScannerObject; static PyMemberDef scanner_members[] = { {"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"}, {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"}, {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"}, {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"}, {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"}, {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"}, {NULL} }; typedef struct _PyEncoderObject { PyObject_HEAD PyObject *markers; PyObject *defaultfn; PyObject *encoder; PyObject *indent; PyObject *key_separator; PyObject *item_separator; PyObject *sort_keys; PyObject *skipkeys; int fast_encode; int allow_nan; } PyEncoderObject; static PyMemberDef encoder_members[] = { {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"}, {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"}, {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"}, {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"}, {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"}, {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"}, {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"}, {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"}, {NULL} }; static Py_ssize_t ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars); static PyObject * ascii_escape_unicode(PyObject *pystr); static PyObject * ascii_escape_str(PyObject *pystr); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr); void init_speedups(void); static PyObject * scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx); static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds); static void scanner_dealloc(PyObject *self); static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds); static void encoder_dealloc(PyObject *self); static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level); static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level); static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level); static PyObject * _encoded_const(PyObject *const); static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end); static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj); static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr); static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr); static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj); #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"') #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r')) #define MIN_EXPANSION 6 #ifdef Py_UNICODE_WIDE #define MAX_EXPANSION (2 * MIN_EXPANSION) #else #define MAX_EXPANSION MIN_EXPANSION #endif static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr) { /* PyObject to Py_ssize_t converter */ *size_ptr = PyInt_AsSsize_t(o); if (*size_ptr == -1 && PyErr_Occurred()); return 1; return 0; } static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr) { /* Py_ssize_t to PyObject converter */ return PyInt_FromSsize_t(*size_ptr); } static Py_ssize_t ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars) { /* Escape unicode code point c to ASCII escape sequences in char *output. output must have at least 12 bytes unused to accommodate an escaped surrogate pair "\uXXXX\uXXXX" */ output[chars++] = '\\'; switch (c) { case '\\': output[chars++] = (char)c; break; case '"': output[chars++] = (char)c; break; case '\b': output[chars++] = 'b'; break; case '\f': output[chars++] = 'f'; break; case '\n': output[chars++] = 'n'; break; case '\r': output[chars++] = 'r'; break; case '\t': output[chars++] = 't'; break; default: #ifdef Py_UNICODE_WIDE if (c >= 0x10000) { /* UTF-16 surrogate pair */ Py_UNICODE v = c - 0x10000; c = 0xd800 | ((v >> 10) & 0x3ff); output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; c = 0xdc00 | (v & 0x3ff); output[chars++] = '\\'; } #endif output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; } return chars; } static PyObject * ascii_escape_unicode(PyObject *pystr) { /* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t max_output_size; Py_ssize_t chars; PyObject *rval; char *output; Py_UNICODE *input_unicode; input_chars = PyUnicode_GET_SIZE(pystr); input_unicode = PyUnicode_AS_UNICODE(pystr); /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; max_output_size = 2 + (input_chars * MAX_EXPANSION); rval = PyString_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyString_AS_STRING(rval); chars = 0; output[chars++] = '"'; for (i = 0; i < input_chars; i++) { Py_UNICODE c = input_unicode[i]; if (S_CHAR(c)) { output[chars++] = (char)c; } else { chars = ascii_escape_char(c, output, chars); } if (output_size - chars < (1 + MAX_EXPANSION)) { /* There's more than four, so let's resize by a lot */ Py_ssize_t new_output_size = output_size * 2; /* This is an upper bound */ if (new_output_size > max_output_size) { new_output_size = max_output_size; } /* Make sure that the output size changed before resizing */ if (new_output_size != output_size) { output_size = new_output_size; if (_PyString_Resize(&rval, output_size) == -1) { return NULL; } output = PyString_AS_STRING(rval); } } } output[chars++] = '"'; if (_PyString_Resize(&rval, chars) == -1) { return NULL; } return rval; } static PyObject * ascii_escape_str(PyObject *pystr) { /* Take a PyString pystr and return a new ASCII-only escaped PyString */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t chars; PyObject *rval; char *output; char *input_str; input_chars = PyString_GET_SIZE(pystr); input_str = PyString_AS_STRING(pystr); /* Fast path for a string that's already ASCII */ for (i = 0; i < input_chars; i++) { Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i]; if (!S_CHAR(c)) { /* If we have to escape something, scan the string for unicode */ Py_ssize_t j; for (j = i; j < input_chars; j++) { c = (Py_UNICODE)(unsigned char)input_str[j]; if (c > 0x7f) { /* We hit a non-ASCII character, bail to unicode mode */ PyObject *uni; uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict"); if (uni == NULL) { return NULL; } rval = ascii_escape_unicode(uni); Py_DECREF(uni); return rval; } } break; } } if (i == input_chars) { /* Input is already ASCII */ output_size = 2 + input_chars; } else { /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; } rval = PyString_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyString_AS_STRING(rval); output[0] = '"'; /* We know that everything up to i is ASCII already */ chars = i + 1; memcpy(&output[1], input_str, i); for (; i < input_chars; i++) { Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i]; if (S_CHAR(c)) { output[chars++] = (char)c; } else { chars = ascii_escape_char(c, output, chars); } /* An ASCII char can't possibly expand to a surrogate! */ if (output_size - chars < (1 + MIN_EXPANSION)) { /* There's more than four, so let's resize by a lot */ output_size *= 2; if (output_size > 2 + (input_chars * MIN_EXPANSION)) { output_size = 2 + (input_chars * MIN_EXPANSION); } if (_PyString_Resize(&rval, output_size) == -1) { return NULL; } output = PyString_AS_STRING(rval); } } output[chars++] = '"'; if (_PyString_Resize(&rval, chars) == -1) { return NULL; } return rval; } static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end) { /* Use the Python function simplejson.decoder.errmsg to raise a nice looking ValueError exception */ static PyObject *errmsg_fn = NULL; PyObject *pymsg; if (errmsg_fn == NULL) { PyObject *decoder = PyImport_ImportModule("simplejson.decoder"); if (decoder == NULL) return; errmsg_fn = PyObject_GetAttrString(decoder, "errmsg"); Py_DECREF(decoder); if (errmsg_fn == NULL) return; } pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end); if (pymsg) { PyErr_SetObject(PyExc_ValueError, pymsg); Py_DECREF(pymsg); } } static PyObject * join_list_unicode(PyObject *lst) { /* return u''.join(lst) */ static PyObject *joinfn = NULL; if (joinfn == NULL) { PyObject *ustr = PyUnicode_FromUnicode(NULL, 0); if (ustr == NULL) return NULL; joinfn = PyObject_GetAttrString(ustr, "join"); Py_DECREF(ustr); if (joinfn == NULL) return NULL; } return PyObject_CallFunctionObjArgs(joinfn, lst, NULL); } static PyObject * join_list_string(PyObject *lst) { /* return ''.join(lst) */ static PyObject *joinfn = NULL; if (joinfn == NULL) { PyObject *ustr = PyString_FromStringAndSize(NULL, 0); if (ustr == NULL) return NULL; joinfn = PyObject_GetAttrString(ustr, "join"); Py_DECREF(ustr); if (joinfn == NULL) return NULL; } return PyObject_CallFunctionObjArgs(joinfn, lst, NULL); } static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) { /* return (rval, idx) tuple, stealing reference to rval */ PyObject *tpl; PyObject *pyidx; /* steal a reference to rval, returns (rval, idx) */ if (rval == NULL) { return NULL; } pyidx = PyInt_FromSsize_t(idx); if (pyidx == NULL) { Py_DECREF(rval); return NULL; } tpl = PyTuple_New(2); if (tpl == NULL) { Py_DECREF(pyidx); Py_DECREF(rval); return NULL; } PyTuple_SET_ITEM(tpl, 0, rval); PyTuple_SET_ITEM(tpl, 1, pyidx); return tpl; } static PyObject * scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyString pystr. end is the index of the first character after the quote. encoding is the encoding of pystr (must be an ASCII superset) if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyString (if ASCII-only) or PyUnicode */ PyObject *rval; Py_ssize_t len = PyString_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next = begin; int has_unicode = 0; char *buf = PyString_AS_STRING(pystr); PyObject *chunks = PyList_New(0); if (chunks == NULL) { goto bail; } if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; PyObject *chunk = NULL; for (next = end; next < len; next++) { c = (unsigned char)buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } else if (c > 0x7f) { has_unicode = 1; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end); if (strchunk == NULL) { goto bail; } if (has_unicode) { chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL); Py_DECREF(strchunk); if (chunk == NULL) { goto bail; } } else { chunk = strchunk; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { c2 <<= 4; Py_UNICODE digit = buf[next]; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } if (c > 0x7f) { has_unicode = 1; } if (has_unicode) { chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } } else { char c_char = Py_CHARMASK(c); chunk = PyString_FromStringAndSize(&c_char, 1); if (chunk == NULL) { goto bail; } } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } rval = join_list_string(chunks); if (rval == NULL) { goto bail; } Py_CLEAR(chunks); *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); return NULL; } static PyObject * scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyUnicode pystr. end is the index of the first character after the quote. encoding is the encoding of pystr (must be an ASCII superset) if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyUnicode */ PyObject *rval; Py_ssize_t len = PyUnicode_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next = begin; const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr); PyObject *chunks = PyList_New(0); if (chunks == NULL) { goto bail; } if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; PyObject *chunk = NULL; for (next = end; next < len; next++) { c = buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { chunk = PyUnicode_FromUnicode(&buf[end], next - end); if (chunk == NULL) { goto bail; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { c2 <<= 4; Py_UNICODE digit = buf[next]; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } rval = join_list_unicode(chunks); if (rval == NULL) { goto bail; } Py_DECREF(chunks); *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); return NULL; } PyDoc_STRVAR(pydoc_scanstring, "scanstring(basestring, end, encoding, strict=True) -> (str, end)\n" "\n" "Scan the string s for a JSON string. End is the index of the\n" "character in s after the quote that started the JSON string.\n" "Unescapes all valid JSON string escape sequences and raises ValueError\n" "on attempt to decode an invalid string. If strict is False then literal\n" "control characters are allowed in the string.\n" "\n" "Returns a tuple of the decoded string and the index of the character in s\n" "after the end quote." ); static PyObject * py_scanstring(PyObject* self UNUSED, PyObject *args) { PyObject *pystr; PyObject *rval; Py_ssize_t end; Py_ssize_t next_end = -1; char *encoding = NULL; int strict = 1; if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) { return NULL; } if (encoding == NULL) { encoding = DEFAULT_ENCODING; } if (PyString_Check(pystr)) { rval = scanstring_str(pystr, end, encoding, strict, &next_end); } else if (PyUnicode_Check(pystr)) { rval = scanstring_unicode(pystr, end, strict, &next_end); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_end); } PyDoc_STRVAR(pydoc_encode_basestring_ascii, "encode_basestring_ascii(basestring) -> str\n" "\n" "Return an ASCII-only JSON representation of a Python string" ); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr) { /* Return an ASCII-only JSON representation of a Python string */ /* METH_O */ if (PyString_Check(pystr)) { return ascii_escape_str(pystr); } else if (PyUnicode_Check(pystr)) { return ascii_escape_unicode(pystr); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } } static void scanner_dealloc(PyObject *self) { /* Deallocate scanner object */ PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; Py_CLEAR(s->encoding); Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); self->ob_type->tp_free(self); } static PyObject * _parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyString pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; PyObject *rval = PyDict_New(); PyObject *key = NULL; PyObject *val = NULL; char *encoding = PyString_AS_STRING(s->encoding); int strict = PyObject_IsTrue(s->strict); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx); if (key == NULL) goto bail; idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON data type */ val = scan_once_str(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyDict_SetItem(rval, key, val) == -1) goto bail; Py_CLEAR(key); Py_CLEAR(val); idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); if (val == NULL) goto bail; Py_DECREF(rval); rval = val; val = NULL; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyUnicode pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyDict_New(); PyObject *key = NULL; int strict = PyObject_IsTrue(s->strict); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_unicode(pystr, idx + 1, strict, &next_idx); if (key == NULL) goto bail; idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyDict_SetItem(rval, key, val) == -1) goto bail; Py_CLEAR(key); Py_CLEAR(val); idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); if (val == NULL) goto bail; Py_DECREF(rval); rval = val; val = NULL; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term and de-tuplefy the (rval, idx) */ val = scan_once_str(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON constant from PyString pystr. constant is the constant string that was found ("NaN", "Infinity", "-Infinity"). idx is the index of the first character of the constant *next_idx_ptr is a return-by-reference index to the first character after the constant. Returns the result of parse_constant */ PyObject *cstr; PyObject *rval; /* constant is "NaN", "Infinity", or "-Infinity" */ cstr = PyString_InternFromString(constant); if (cstr == NULL) return NULL; /* rval = parse_constant(constant) */ rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL); idx += PyString_GET_SIZE(cstr); Py_DECREF(cstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyString pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { /* save the index of the 'e' or 'E' just in case we need to backtrack */ Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } /* copy the section we determined to be a number */ numstr = PyString_FromStringAndSize(&str[start], idx - start); if (numstr == NULL) return NULL; if (is_float) { /* parse as a float using a fast path if available, otherwise call user defined method */ if (s->parse_float != (PyObject *)&PyFloat_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL); } else { rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr))); } } else { /* parse as an int using a fast path if available, otherwise call user defined method */ if (s->parse_int != (PyObject *)&PyInt_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL); } else { rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10); } } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyUnicode pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx < end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } /* copy the section we determined to be a number */ numstr = PyUnicode_FromUnicode(&str[start], idx - start); if (numstr == NULL) return NULL; if (is_float) { /* parse as a float using a fast path if available, otherwise call user defined method */ if (s->parse_float != (PyObject *)&PyFloat_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL); } else { rval = PyFloat_FromString(numstr, NULL); } } else { /* no fast path for unicode -> int, just call */ rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL); } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyString pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ char *str = PyString_AS_STRING(pystr); Py_ssize_t length = PyString_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_str(pystr, idx + 1, PyString_AS_STRING(s->encoding), PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ return _parse_object_str(s, pystr, idx + 1, next_idx_ptr); case '[': /* array */ return _parse_array_str(s, pystr, idx + 1, next_idx_ptr); case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_str(s, pystr, idx, next_idx_ptr); } static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyUnicode pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t length = PyUnicode_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_unicode(pystr, idx + 1, PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr); case '[': /* array */ return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr); case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_unicode(s, pystr, idx, next_idx_ptr); } static PyObject * scanner_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to scan_once_{str,unicode} */ PyObject *pystr; PyObject *rval; Py_ssize_t idx; Py_ssize_t next_idx = -1; static char *kwlist[] = {"string", "idx", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx)) return NULL; if (PyString_Check(pystr)) { rval = scan_once_str(s, pystr, idx, &next_idx); } else if (PyUnicode_Check(pystr)) { rval = scan_once_unicode(s, pystr, idx, &next_idx); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_idx); } static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds) { /* Initialize Scanner object */ PyObject *ctx; static char *kwlist[] = {"context", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx)) return -1; s->encoding = NULL; s->strict = NULL; s->object_hook = NULL; s->parse_float = NULL; s->parse_int = NULL; s->parse_constant = NULL; /* PyString_AS_STRING is used on encoding */ s->encoding = PyObject_GetAttrString(ctx, "encoding"); if (s->encoding == Py_None) { Py_DECREF(Py_None); s->encoding = PyString_InternFromString(DEFAULT_ENCODING); } else if (PyUnicode_Check(s->encoding)) { PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL); Py_DECREF(s->encoding); s->encoding = tmp; } if (s->encoding == NULL || !PyString_Check(s->encoding)) goto bail; /* All of these will fail "gracefully" so we don't need to verify them */ s->strict = PyObject_GetAttrString(ctx, "strict"); if (s->strict == NULL) goto bail; s->object_hook = PyObject_GetAttrString(ctx, "object_hook"); if (s->object_hook == NULL) goto bail; s->parse_float = PyObject_GetAttrString(ctx, "parse_float"); if (s->parse_float == NULL) goto bail; s->parse_int = PyObject_GetAttrString(ctx, "parse_int"); if (s->parse_int == NULL) goto bail; s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant"); if (s->parse_constant == NULL) goto bail; return 0; bail: Py_CLEAR(s->encoding); Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); return -1; } PyDoc_STRVAR(scanner_doc, "JSON scanner object"); static PyTypeObject PyScannerType = { PyObject_HEAD_INIT(0) 0, /* tp_internal */ "Scanner", /* tp_name */ sizeof(PyScannerObject), /* tp_basicsize */ 0, /* tp_itemsize */ scanner_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ scanner_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ scanner_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ scanner_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ scanner_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ 0,/* PyType_GenericNew, */ /* tp_new */ 0,/* _PyObject_Del, */ /* tp_free */ }; static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds) { /* initialize Encoder object */ static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL}; PyEncoderObject *s; PyObject *allow_nan; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; s->markers = NULL; s->defaultfn = NULL; s->encoder = NULL; s->indent = NULL; s->key_separator = NULL; s->item_separator = NULL; s->sort_keys = NULL; s->skipkeys = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist, &s->markers, &s->defaultfn, &s->encoder, &s->indent, &s->key_separator, &s->item_separator, &s->sort_keys, &s->skipkeys, &allow_nan)) return -1; Py_INCREF(s->markers); Py_INCREF(s->defaultfn); Py_INCREF(s->encoder); Py_INCREF(s->indent); Py_INCREF(s->key_separator); Py_INCREF(s->item_separator); Py_INCREF(s->sort_keys); Py_INCREF(s->skipkeys); s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii); s->allow_nan = PyObject_IsTrue(allow_nan); return 0; } static PyObject * encoder_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to encode_listencode_obj */ static char *kwlist[] = {"obj", "_current_indent_level", NULL}; PyObject *obj; PyObject *rval; Py_ssize_t indent_level; PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist, &obj, _convertPyInt_AsSsize_t, &indent_level)) return NULL; rval = PyList_New(0); if (rval == NULL) return NULL; if (encoder_listencode_obj(s, rval, obj, indent_level)) { Py_DECREF(rval); return NULL; } return rval; } static PyObject * _encoded_const(PyObject *obj) { /* Return the JSON string representation of None, True, False */ if (obj == Py_None) { static PyObject *s_null = NULL; if (s_null == NULL) { s_null = PyString_InternFromString("null"); } Py_INCREF(s_null); return s_null; } else if (obj == Py_True) { static PyObject *s_true = NULL; if (s_true == NULL) { s_true = PyString_InternFromString("true"); } Py_INCREF(s_true); return s_true; } else if (obj == Py_False) { static PyObject *s_false = NULL; if (s_false == NULL) { s_false = PyString_InternFromString("false"); } Py_INCREF(s_false); return s_false; } else { PyErr_SetString(PyExc_ValueError, "not a const"); return NULL; } } static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a PyFloat */ double i = PyFloat_AS_DOUBLE(obj); if (!Py_IS_FINITE(i)) { if (!s->allow_nan) { PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant"); return NULL; } if (i > 0) { return PyString_FromString("Infinity"); } else if (i < 0) { return PyString_FromString("-Infinity"); } else { return PyString_FromString("NaN"); } } /* Use a better float format here? */ return PyObject_Repr(obj); } static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a string */ if (s->fast_encode) return py_encode_basestring_ascii(NULL, obj); else return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL); } static int _steal_list_append(PyObject *lst, PyObject *stolen) { /* Append stolen and then decrement its reference count */ int rval = PyList_Append(lst, stolen); Py_DECREF(stolen); return rval; } static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level) { /* Encode Python object obj to a JSON term, rval is a PyList */ PyObject *newobj; int rv; if (obj == Py_None || obj == Py_True || obj == Py_False) { PyObject *cstr = _encoded_const(obj); if (cstr == NULL) return -1; return _steal_list_append(rval, cstr); } else if (PyString_Check(obj) || PyUnicode_Check(obj)) { PyObject *encoded = encoder_encode_string(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyInt_Check(obj) || PyLong_Check(obj)) { PyObject *encoded = PyObject_Str(obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyFloat_Check(obj)) { PyObject *encoded = encoder_encode_float(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyList_Check(obj) || PyTuple_Check(obj)) { return encoder_listencode_list(s, rval, obj, indent_level); } else if (PyDict_Check(obj)) { return encoder_listencode_dict(s, rval, obj, indent_level); } else { PyObject *ident = NULL; if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(obj); if (ident == NULL) return -1; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); Py_DECREF(ident); return -1; } if (PyDict_SetItem(s->markers, ident, obj)) { Py_DECREF(ident); return -1; } } newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL); if (newobj == NULL) { Py_XDECREF(ident); return -1; } rv = encoder_listencode_obj(s, rval, newobj, indent_level); Py_DECREF(newobj); if (rv) { Py_XDECREF(ident); return -1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) { Py_XDECREF(ident); return -1; } Py_XDECREF(ident); } return rv; } } static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level) { /* Encode Python dict dct a JSON term, rval is a PyList */ static PyObject *open_dict = NULL; static PyObject *close_dict = NULL; static PyObject *empty_dict = NULL; PyObject *kstr = NULL; PyObject *ident = NULL; PyObject *key, *value; Py_ssize_t pos; int skipkeys; Py_ssize_t idx; if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) { open_dict = PyString_InternFromString("{"); close_dict = PyString_InternFromString("}"); empty_dict = PyString_InternFromString("{}"); if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) return -1; } if (PyDict_Size(dct) == 0) return PyList_Append(rval, empty_dict); if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(dct); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, dct)) { goto bail; } } if (PyList_Append(rval, open_dict)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } /* TODO: C speedup not implemented for sort_keys */ pos = 0; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; while (PyDict_Next(dct, &pos, &key, &value)) { PyObject *encoded; if (PyString_Check(key) || PyUnicode_Check(key)) { Py_INCREF(key); kstr = key; } else if (PyFloat_Check(key)) { kstr = encoder_encode_float(s, key); if (kstr == NULL) goto bail; } else if (PyInt_Check(key) || PyLong_Check(key)) { kstr = PyObject_Str(key); if (kstr == NULL) goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { kstr = _encoded_const(key); if (kstr == NULL) goto bail; } else if (skipkeys) { continue; } else { /* TODO: include repr of key */ PyErr_SetString(PyExc_ValueError, "keys must be a string"); goto bail; } if (idx) { if (PyList_Append(rval, s->item_separator)) goto bail; } encoded = encoder_encode_string(s, kstr); Py_CLEAR(kstr); if (encoded == NULL) goto bail; if (PyList_Append(rval, encoded)) { Py_DECREF(encoded); goto bail; } Py_DECREF(encoded); if (PyList_Append(rval, s->key_separator)) goto bail; if (encoder_listencode_obj(s, rval, value, indent_level)) goto bail; idx += 1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level -= 1; /* yield '\n' + (' ' * (_indent * _current_indent_level)) */ } if (PyList_Append(rval, close_dict)) goto bail; return 0; bail: Py_XDECREF(kstr); Py_XDECREF(ident); return -1; } static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level) { /* Encode Python list seq to a JSON term, rval is a PyList */ static PyObject *open_array = NULL; static PyObject *close_array = NULL; static PyObject *empty_array = NULL; PyObject *ident = NULL; PyObject *s_fast = NULL; Py_ssize_t num_items; PyObject **seq_items; Py_ssize_t i; if (open_array == NULL || close_array == NULL || empty_array == NULL) { open_array = PyString_InternFromString("["); close_array = PyString_InternFromString("]"); empty_array = PyString_InternFromString("[]"); if (open_array == NULL || close_array == NULL || empty_array == NULL) return -1; } ident = NULL; s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence"); if (s_fast == NULL) return -1; num_items = PySequence_Fast_GET_SIZE(s_fast); if (num_items == 0) { Py_DECREF(s_fast); return PyList_Append(rval, empty_array); } if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(seq); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, seq)) { goto bail; } } seq_items = PySequence_Fast_ITEMS(s_fast); if (PyList_Append(rval, open_array)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } for (i = 0; i < num_items; i++) { PyObject *obj = seq_items[i]; if (i) { if (PyList_Append(rval, s->item_separator)) goto bail; } if (encoder_listencode_obj(s, rval, obj, indent_level)) goto bail; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level -= 1; /* yield '\n' + (' ' * (_indent * _current_indent_level)) */ } if (PyList_Append(rval, close_array)) goto bail; Py_DECREF(s_fast); return 0; bail: Py_XDECREF(ident); Py_DECREF(s_fast); return -1; } static void encoder_dealloc(PyObject *self) { /* Deallocate Encoder */ PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; Py_CLEAR(s->markers); Py_CLEAR(s->defaultfn); Py_CLEAR(s->encoder); Py_CLEAR(s->indent); Py_CLEAR(s->key_separator); Py_CLEAR(s->item_separator); Py_CLEAR(s->sort_keys); Py_CLEAR(s->skipkeys); self->ob_type->tp_free(self); } PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable"); static PyTypeObject PyEncoderType = { PyObject_HEAD_INIT(0) 0, /* tp_internal */ "Encoder", /* tp_name */ sizeof(PyEncoderObject), /* tp_basicsize */ 0, /* tp_itemsize */ encoder_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ encoder_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ encoder_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ encoder_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ encoder_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ 0,/* PyType_GenericNew, */ /* tp_new */ 0,/* _PyObject_Del, */ /* tp_free */ }; static PyMethodDef speedups_methods[] = { {"encode_basestring_ascii", (PyCFunction)py_encode_basestring_ascii, METH_O, pydoc_encode_basestring_ascii}, {"scanstring", (PyCFunction)py_scanstring, METH_VARARGS, pydoc_scanstring}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(module_doc, "simplejson speedups\n"); void init_speedups(void) { PyObject *m; PyScannerType.tp_getattro = PyObject_GenericGetAttr; PyScannerType.tp_setattro = PyObject_GenericSetAttr; PyScannerType.tp_alloc = PyType_GenericAlloc; PyScannerType.tp_new = PyType_GenericNew; PyScannerType.tp_free = _PyObject_Del; if (PyType_Ready(&PyScannerType) < 0) return; PyEncoderType.tp_getattro = PyObject_GenericGetAttr; PyEncoderType.tp_setattro = PyObject_GenericSetAttr; PyEncoderType.tp_alloc = PyType_GenericAlloc; PyEncoderType.tp_new = PyType_GenericNew; PyEncoderType.tp_free = _PyObject_Del; if (PyType_Ready(&PyEncoderType) < 0) return; m = Py_InitModule3("_speedups", speedups_methods, module_doc); Py_INCREF((PyObject*)&PyScannerType); PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType); Py_INCREF((PyObject*)&PyEncoderType); PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType); }
C
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <Windows.h> #define ATL_THUNK_APIHOOK EXCEPTION_DISPOSITION __cdecl _except_handler( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ); typedef EXCEPTION_DISPOSITION (__cdecl *_except_handler_type)( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ); typedef struct tagATL_THUNK_PATTERN { LPBYTE pattern; int pattern_size; (void)(*enumerator)(struct _CONTEXT *); }ATL_THUNK_PATTERN; void InstallAtlThunkEnumeration(); void UninstallAtlThunkEnumeration();
C
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "npapi.h" #include <npfunctions.h> #include <prtypes.h> #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlstr.h> #include <atlcom.h> #include <atlctl.h> #include <varargs.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; //#define NO_REGISTRY_AUTHORIZE #define np_log(instance, level, message, ...) log_activex_logging(instance, level, __FILE__, __LINE__, message, ##__VA_ARGS__) // For catch breakpoints. HRESULT NotImpl(); #define LogNotImplemented(instance) (np_log(instance, 0, "Not Implemented operation!!"), NotImpl()) void log_activex_logging(NPP instance, unsigned int level, const char* file, int line, char *message, ...); NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved); NPError NPP_Destroy(NPP instance, NPSavedData **save); NPError NPP_SetWindow(NPP instance, NPWindow *window); #define REGISTER_MANAGER
C
#pragma once // The following macros define the minimum required platform. The minimum required platform // is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run // your application. The macros work by enabling all features available on platform versions up to and // including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Specifies that the minimum required platform is Windows Vista. #define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. #define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. #endif
C
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once struct ITypeInfo; void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance); void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance); size_t VariantSize(VARTYPE vt); HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest); void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var);
C
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlstr.h> // TODO: reference additional headers your program requires here
C
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by npactivex.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
C
#ifndef _HOOK_H_ #define _HOOK_H_ typedef struct _HOOKINFO_ { PBYTE Stub; DWORD CodeLength; LPVOID FuncAddr; LPVOID FakeAddr; }HOOKINFO, *PHOOKINFO; VOID HEInitHook(PHOOKINFO HookInfo, LPVOID FuncAddr, LPVOID FakeAddr); BOOL HEStartHook(PHOOKINFO HookInfo); BOOL HEStopHook(PHOOKINFO HookInfo); #endif
C
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ BOOL TestAuthorization (NPP Instance, int16 ArgC, char *ArgN[], char *ArgV[], const char *MimeType);
C
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ /* $Id$ */ #include "common.h" #include "log.h" #include "treetype.h" #include "softflowd.h" RCSID("$Id$"); /* * This is the Cisco Netflow(tm) version 5 packet format * Based on: * http://www.cisco.com/univercd/cc/td/doc/product/rtrmgmt/nfc/nfc_3_0/nfc_ug/nfcform.htm */ struct NF5_HEADER { u_int16_t version, flows; u_int32_t uptime_ms, time_sec, time_nanosec, flow_sequence; u_int8_t engine_type, engine_id, reserved1, reserved2; }; struct NF5_FLOW { u_int32_t src_ip, dest_ip, nexthop_ip; u_int16_t if_index_in, if_index_out; u_int32_t flow_packets, flow_octets; u_int32_t flow_start, flow_finish; u_int16_t src_port, dest_port; u_int8_t pad1; u_int8_t tcp_flags, protocol, tos; u_int16_t src_as, dest_as; u_int8_t src_mask, dst_mask; u_int16_t pad2; }; #define NF5_MAXFLOWS 30 #define NF5_MAXPACKET_SIZE (sizeof(struct NF5_HEADER) + \ (NF5_MAXFLOWS * sizeof(struct NF5_FLOW))) /* * Given an array of expired flows, send netflow v5 report packets * Returns number of packets sent or -1 on error */ int send_netflow_v5(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag) { struct timeval now; u_int32_t uptime_ms; u_int8_t packet[NF5_MAXPACKET_SIZE]; /* Maximum allowed packet size (24 flows) */ struct NF5_HEADER *hdr = NULL; struct NF5_FLOW *flw = NULL; int i, j, offset, num_packets, err; socklen_t errsz; gettimeofday(&now, NULL); uptime_ms = timeval_sub_ms(&now, system_boot_time); hdr = (struct NF5_HEADER *)packet; for (num_packets = offset = j = i = 0; i < num_flows; i++) { if (j >= NF5_MAXFLOWS - 1) { if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); *flows_exported += j; j = 0; num_packets++; } if (j == 0) { memset(&packet, '\0', sizeof(packet)); hdr->version = htons(5); hdr->flows = 0; /* Filled in as we go */ hdr->uptime_ms = htonl(uptime_ms); hdr->time_sec = htonl(now.tv_sec); hdr->time_nanosec = htonl(now.tv_usec * 1000); hdr->flow_sequence = htonl(*flows_exported); /* Other fields are left zero */ offset = sizeof(*hdr); } flw = (struct NF5_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); /* NetFlow v.5 doesn't do IPv6 */ if (flows[i]->af != AF_INET) continue; if (flows[i]->octets[0] > 0) { flw->src_ip = flows[i]->addr[0].v4.s_addr; flw->dest_ip = flows[i]->addr[1].v4.s_addr; flw->src_port = flows[i]->port[0]; flw->dest_port = flows[i]->port[1]; flw->flow_packets = htonl(flows[i]->packets[0]); flw->flow_octets = htonl(flows[i]->octets[0]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->tcp_flags = flows[i]->tcp_flags[0]; flw->protocol = flows[i]->protocol; offset += sizeof(*flw); j++; hdr->flows++; } flw = (struct NF5_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); if (flows[i]->octets[1] > 0) { flw->src_ip = flows[i]->addr[1].v4.s_addr; flw->dest_ip = flows[i]->addr[0].v4.s_addr; flw->src_port = flows[i]->port[1]; flw->dest_port = flows[i]->port[0]; flw->flow_packets = htonl(flows[i]->packets[1]); flw->flow_octets = htonl(flows[i]->octets[1]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->tcp_flags = flows[i]->tcp_flags[1]; flw->protocol = flows[i]->protocol; offset += sizeof(*flw); j++; hdr->flows++; } } /* Send any leftovers */ if (j != 0) { if (verbose_flag) logit(LOG_DEBUG, "Sending v5 flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); num_packets++; } *flows_exported += j; return (num_packets); }
C
/* * Copyright (c) 2007 Damien Miller. All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #include "common.h" #include "freelist.h" #include "log.h" #define FREELIST_MAX_ALLOC 0x1000000 #define FREELIST_ALLOC_ALIGN 16 #define FREELIST_INITIAL_ALLOC 16 #ifndef roundup #define roundup(x, y) ((((x) + (y) - 1)/(y))*(y)) #endif /* roundup */ #undef FREELIST_DEBUG #ifdef FREELIST_DEBUG # define FLOGIT(a) logit a #else # define FLOGIT(a) #endif void freelist_init(struct freelist *fl, size_t allocsz) { FLOGIT((LOG_DEBUG, "%s: %s(%p, %zu)", __func__, __func__, fl, allocsz)); bzero(fl, sizeof(fl)); fl->allocsz = roundup(allocsz, FREELIST_ALLOC_ALIGN); fl->free_entries = NULL; } static int freelist_grow(struct freelist *fl) { size_t i, oldnalloc, need; void *p; FLOGIT((LOG_DEBUG, "%s: %s(%p)", __func__, __func__, fl)); FLOGIT((LOG_DEBUG, "%s: nalloc = %zu", __func__, fl->nalloc)); /* Sanity check */ if (fl->nalloc > FREELIST_MAX_ALLOC) return -1; oldnalloc = fl->nalloc; if (fl->nalloc == 0) fl->nalloc = FREELIST_INITIAL_ALLOC; else fl->nalloc <<= 1; if (fl->nalloc > FREELIST_MAX_ALLOC) fl->nalloc = FREELIST_MAX_ALLOC; FLOGIT((LOG_DEBUG, "%s: nalloc now %zu", __func__, fl->nalloc)); /* Check for integer overflow */ if (SIZE_MAX / fl->nalloc < fl->allocsz || SIZE_MAX / fl->nalloc < sizeof(*fl->free_entries)) { FLOGIT((LOG_DEBUG, "%s: integer overflow", __func__)); resize_fail: fl->nalloc = oldnalloc; return -1; } /* Allocate freelist - max size of nalloc */ need = fl->nalloc * sizeof(*fl->free_entries); if ((p = realloc(fl->free_entries, need)) == NULL) { FLOGIT((LOG_DEBUG, "%s: realloc(%zu) failed", __func__, need)); goto resize_fail; } /* Allocate the entries */ fl->free_entries = p; need = (fl->nalloc - oldnalloc) * fl->allocsz; if ((p = malloc(need)) == NULL) { FLOGIT((LOG_DEBUG, "%s: malloc(%zu) failed", __func__, need)); goto resize_fail; } /* * XXX store these malloc ranges in a tree or list, so we can * validate them in _get/_put. Check that r_low <= addr < r_high, and * (addr - r_low) % fl->allocsz == 0 */ fl->navail = fl->nalloc - oldnalloc; for (i = 0; i < fl->navail; i++) fl->free_entries[i] = (u_char *)p + (i * fl->allocsz); for (i = fl->navail; i < fl->nalloc; i++) fl->free_entries[i] = NULL; FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail)); return 0; } void * freelist_get(struct freelist *fl) { void *r; FLOGIT((LOG_DEBUG, "%s: %s(%p)", __func__, __func__, fl)); FLOGIT((LOG_DEBUG, "%s: navail = %zu", __func__, fl->navail)); if (fl->navail == 0) { if (freelist_grow(fl) == -1) return NULL; } /* Sanity check */ if (fl->navail == 0 || fl->navail > FREELIST_MAX_ALLOC || fl->free_entries[fl->navail - 1] == NULL) { logit(LOG_ERR, "%s: invalid navail", __func__); raise(SIGSEGV); } fl->navail--; r = fl->free_entries[fl->navail]; fl->free_entries[fl->navail] = NULL; FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail)); return r; } void freelist_put(struct freelist *fl, void *p) { FLOGIT((LOG_DEBUG, "%s: %s(%p, %zu)", __func__, __func__, fl, p)); FLOGIT((LOG_DEBUG, "%s: navail = %zu", __func__, fl->navail)); FLOGIT((LOG_DEBUG, "%s: nalloc = %zu", __func__, fl->navail)); /* Sanity check */ if (fl->navail >= fl->nalloc) { logit(LOG_ERR, "%s: freelist navail >= nalloc", __func__); raise(SIGSEGV); } if (fl->free_entries[fl->navail] != NULL) { logit(LOG_ERR, "%s: free_entries[%lu] != NULL", __func__, (unsigned long)fl->navail); raise(SIGSEGV); } fl->free_entries[fl->navail] = p; fl->navail++; FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail)); }
C
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ /* $Id$ */ #include "common.h" #include "log.h" #include "treetype.h" #include "softflowd.h" RCSID("$Id$"); /* * This is the Cisco Netflow(tm) version 1 packet format * Based on: * http://www.cisco.com/univercd/cc/td/doc/product/rtrmgmt/nfc/nfc_3_0/nfc_ug/nfcform.htm */ struct NF1_HEADER { u_int16_t version, flows; u_int32_t uptime_ms, time_sec, time_nanosec; }; struct NF1_FLOW { u_int32_t src_ip, dest_ip, nexthop_ip; u_int16_t if_index_in, if_index_out; u_int32_t flow_packets, flow_octets; u_int32_t flow_start, flow_finish; u_int16_t src_port, dest_port; u_int16_t pad1; u_int8_t protocol, tos, tcp_flags; u_int8_t pad2, pad3, pad4; u_int32_t reserved1; #if 0 u_int8_t reserved2; /* XXX: no longer used */ #endif }; /* Maximum of 24 flows per packet */ #define NF1_MAXFLOWS 24 #define NF1_MAXPACKET_SIZE (sizeof(struct NF1_HEADER) + \ (NF1_MAXFLOWS * sizeof(struct NF1_FLOW))) /* * Given an array of expired flows, send netflow v1 report packets * Returns number of packets sent or -1 on error */ int send_netflow_v1(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag) { struct timeval now; u_int32_t uptime_ms; u_int8_t packet[NF1_MAXPACKET_SIZE]; /* Maximum allowed packet size (24 flows) */ struct NF1_HEADER *hdr = NULL; struct NF1_FLOW *flw = NULL; int i, j, offset, num_packets, err; socklen_t errsz; gettimeofday(&now, NULL); uptime_ms = timeval_sub_ms(&now, system_boot_time); hdr = (struct NF1_HEADER *)packet; for(num_packets = offset = j = i = 0; i < num_flows; i++) { if (j >= NF1_MAXFLOWS - 1) { if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); *flows_exported += j; j = 0; num_packets++; } if (j == 0) { memset(&packet, '\0', sizeof(packet)); hdr->version = htons(1); hdr->flows = 0; /* Filled in as we go */ hdr->uptime_ms = htonl(uptime_ms); hdr->time_sec = htonl(now.tv_sec); hdr->time_nanosec = htonl(now.tv_usec * 1000); offset = sizeof(*hdr); } flw = (struct NF1_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); /* NetFlow v.1 doesn't do IPv6 */ if (flows[i]->af != AF_INET) continue; if (flows[i]->octets[0] > 0) { flw->src_ip = flows[i]->addr[0].v4.s_addr; flw->dest_ip = flows[i]->addr[1].v4.s_addr; flw->src_port = flows[i]->port[0]; flw->dest_port = flows[i]->port[1]; flw->flow_packets = htonl(flows[i]->packets[0]); flw->flow_octets = htonl(flows[i]->octets[0]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->protocol = flows[i]->protocol; flw->tcp_flags = flows[i]->tcp_flags[0]; offset += sizeof(*flw); j++; hdr->flows++; } flw = (struct NF1_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); if (flows[i]->octets[1] > 0) { flw->src_ip = flows[i]->addr[1].v4.s_addr; flw->dest_ip = flows[i]->addr[0].v4.s_addr; flw->src_port = flows[i]->port[1]; flw->dest_port = flows[i]->port[0]; flw->flow_packets = htonl(flows[i]->packets[1]); flw->flow_octets = htonl(flows[i]->octets[1]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->protocol = flows[i]->protocol; flw->tcp_flags = flows[i]->tcp_flags[1]; offset += sizeof(*flw); j++; hdr->flows++; } } /* Send any leftovers */ if (j != 0) { if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); num_packets++; } *flows_exported += j; return (num_packets); }
C
/* * Copyright 2004 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ /* $Id$ */ #ifndef _LOG_H #define _LOG_H void loginit(const char *ident, int to_stderr); void logit(int level, const char *fmt,...); #endif /* _LOG_H */
C
/* * Copyright (c) 2001 Kevin Steves. All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #ifndef _SFD_CONVTIME_H /* * Convert a time string into seconds; format is * a sequence of: * time[qualifier] * * Valid time qualifiers are: * <none> seconds * s|S seconds * m|M minutes * h|H hours * d|D days * w|W weeks * * Examples: * 90m 90 minutes * 1h30m 90 minutes * 2d 2 days * 1w 1 week * * Return -1 if time string is invalid. */ long int convtime(const char *s); #endif /* _SFD_CONVTIME_H */
C
/* * Copyright (c) 2002 Damien Miller. All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #ifndef _SFD_COMMON_H #define _SFD_COMMON_H #include "config.h" #define _BSD_SOURCE /* Needed for BSD-style struct ip,tcp,udp on Linux */ #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/poll.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/ip_icmp.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <grp.h> #include <netdb.h> #include <limits.h> #include <pwd.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <time.h> #if defined(HAVE_NET_BPF_H) #include <net/bpf.h> #elif defined(HAVE_PCAP_BPF_H) #include <pcap-bpf.h> #endif #if defined(HAVE_INTTYPES_H) #include <inttypes.h> #endif /* The name of the program */ #define PROGNAME "softflowd" /* The name of the program */ #define PROGVER "0.9.8" /* Default pidfile */ #define DEFAULT_PIDFILE "/var/run/" PROGNAME ".pid" /* Default control socket */ #define DEFAULT_CTLSOCK "/var/run/" PROGNAME ".ctl" #define RCSID(msg) \ static /**/const char *const flowd_rcsid[] = \ { (const char *)flowd_rcsid, "\100(#)" msg } \ #ifndef IP_OFFMASK # define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ #endif #ifndef IPV6_VERSION #define IPV6_VERSION 0x60 #endif #ifndef IPV6_VERSION_MASK #define IPV6_VERSION_MASK 0xf0 #endif #ifndef IPV6_FLOWINFO_MASK #define IPV6_FLOWINFO_MASK ntohl(0x0fffffff) #endif #ifndef IPV6_FLOWLABEL_MASK #define IPV6_FLOWLABEL_MASK ntohl(0x000fffff) #endif #ifndef _PATH_DEVNULL # define _PATH_DEVNULL "/dev/null" #endif #ifndef MIN # define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX # define MAX(a,b) (((a)>(b))?(a):(b)) #endif #ifndef offsetof # define offsetof(type, member) ((size_t) &((type *)0)->member) #endif #if defined(__GNUC__) # ifndef __dead # define __dead __attribute__((__noreturn__)) # endif # ifndef __packed # define __packed __attribute__((__packed__)) # endif #endif #if !defined(HAVE_INT8_T) && defined(OUR_CFG_INT8_T) typedef OUR_CFG_INT8_T int8_t; #endif #if !defined(HAVE_INT16_T) && defined(OUR_CFG_INT16_T) typedef OUR_CFG_INT16_T int16_t; #endif #if !defined(HAVE_INT32_T) && defined(OUR_CFG_INT32_T) typedef OUR_CFG_INT32_T int32_t; #endif #if !defined(HAVE_INT64_T) && defined(OUR_CFG_INT64_T) typedef OUR_CFG_INT64_T int64_t; #endif #if !defined(HAVE_U_INT8_T) && defined(OUR_CFG_U_INT8_T) typedef OUR_CFG_U_INT8_T u_int8_t; #endif #if !defined(HAVE_U_INT16_T) && defined(OUR_CFG_U_INT16_T) typedef OUR_CFG_U_INT16_T u_int16_t; #endif #if !defined(HAVE_U_INT32_T) && defined(OUR_CFG_U_INT32_T) typedef OUR_CFG_U_INT32_T u_int32_t; #endif #if !defined(HAVE_U_INT64_T) && defined(OUR_CFG_U_INT64_T) typedef OUR_CFG_U_INT64_T u_int64_t; #endif #ifndef HAVE_STRLCPY size_t strlcpy(char *dst, const char *src, size_t siz); #endif #ifndef HAVE_STRLCAT size_t strlcat(char *dst, const char *src, size_t siz); #endif #ifndef HAVE_CLOSEFROM void closefrom(int lowfd); #endif #ifndef HAVE_STRUCT_IP6_EXT struct ip6_ext { u_int8_t ip6e_nxt; u_int8_t ip6e_len; } __packed; #endif #endif /* _SFD_COMMON_H */
C
/* OPENBSD ORIGINAL: lib/libc/string/strlcat.c */ /* $OpenBSD: strlcat.c,v 1.11 2003/06/17 21:56:24 millert Exp $ */ /* * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "common.h" #ifndef HAVE_STRLCAT RCSID("$Id$"); #if defined(LIBC_SCCS) && !defined(lint) static char *rcsid = "$OpenBSD: strlcat.c,v 1.11 2003/06/17 21:56:24 millert Exp $"; #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> #include <string.h> /* * Appends src to string dst of size siz (unlike strncat, siz is the * full size of dst, not space left). At most siz-1 characters * will be copied. Always NUL terminates (unless siz <= strlen(dst)). * Returns strlen(src) + MIN(siz, strlen(initial dst)). * If retval >= siz, truncation occurred. */ size_t strlcat(char *dst, const char *src, size_t siz) { register char *d = dst; register const char *s = src; register size_t n = siz; size_t dlen; /* Find the end of dst and adjust bytes left but don't go past end */ while (n-- != 0 && *d != '\0') d++; dlen = d - dst; n = siz - dlen; if (n == 0) return(dlen + strlen(s)); while (*s != '\0') { if (n != 1) { *d++ = *s; n--; } s++; } *d = '\0'; return(dlen + (s - src)); /* count does not include NUL */ } #endif /* !HAVE_STRLCAT */
C
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ /* $Id$ */ #include "common.h" #include "log.h" #include "treetype.h" #include "softflowd.h" RCSID("$Id$"); /* Netflow v.9 */ struct NF9_HEADER { u_int16_t version, flows; u_int32_t uptime_ms, time_sec; u_int32_t package_sequence, source_id; } __packed; struct NF9_FLOWSET_HEADER_COMMON { u_int16_t flowset_id, length; } __packed; struct NF9_TEMPLATE_FLOWSET_HEADER { struct NF9_FLOWSET_HEADER_COMMON c; u_int16_t template_id, count; } __packed; struct NF9_TEMPLATE_FLOWSET_RECORD { u_int16_t type, length; } __packed; struct NF9_DATA_FLOWSET_HEADER { struct NF9_FLOWSET_HEADER_COMMON c; } __packed; #define NF9_TEMPLATE_FLOWSET_ID 0 #define NF9_OPTIONS_FLOWSET_ID 1 #define NF9_MIN_RECORD_FLOWSET_ID 256 /* Flowset record types the we care about */ #define NF9_IN_BYTES 1 #define NF9_IN_PACKETS 2 /* ... */ #define NF9_IN_PROTOCOL 4 /* ... */ #define NF9_TCP_FLAGS 6 #define NF9_L4_SRC_PORT 7 #define NF9_IPV4_SRC_ADDR 8 /* ... */ #define NF9_IF_INDEX_IN 10 #define NF9_L4_DST_PORT 11 #define NF9_IPV4_DST_ADDR 12 /* ... */ #define NF9_IF_INDEX_OUT 14 /* ... */ #define NF9_LAST_SWITCHED 21 #define NF9_FIRST_SWITCHED 22 /* ... */ #define NF9_IPV6_SRC_ADDR 27 #define NF9_IPV6_DST_ADDR 28 /* ... */ #define NF9_IP_PROTOCOL_VERSION 60 /* Stuff pertaining to the templates that softflowd uses */ #define NF9_SOFTFLOWD_TEMPLATE_NRECORDS 11 struct NF9_SOFTFLOWD_TEMPLATE { struct NF9_TEMPLATE_FLOWSET_HEADER h; struct NF9_TEMPLATE_FLOWSET_RECORD r[NF9_SOFTFLOWD_TEMPLATE_NRECORDS]; } __packed; /* softflowd data flowset types */ struct NF9_SOFTFLOWD_DATA_COMMON { u_int32_t last_switched, first_switched; u_int32_t bytes, packets; u_int32_t if_index_in, if_index_out; u_int16_t src_port, dst_port; u_int8_t protocol, tcp_flags, ipproto; } __packed; struct NF9_SOFTFLOWD_DATA_V4 { u_int32_t src_addr, dst_addr; struct NF9_SOFTFLOWD_DATA_COMMON c; } __packed; struct NF9_SOFTFLOWD_DATA_V6 { u_int8_t src_addr[16], dst_addr[16]; struct NF9_SOFTFLOWD_DATA_COMMON c; } __packed; /* Local data: templates and counters */ #define NF9_SOFTFLOWD_MAX_PACKET_SIZE 512 #define NF9_SOFTFLOWD_V4_TEMPLATE_ID 1024 #define NF9_SOFTFLOWD_V6_TEMPLATE_ID 2048 #define NF9_DEFAULT_TEMPLATE_INTERVAL 16 static struct NF9_SOFTFLOWD_TEMPLATE v4_template; static struct NF9_SOFTFLOWD_TEMPLATE v6_template; static int nf9_pkts_until_template = -1; static void nf9_init_template(void) { bzero(&v4_template, sizeof(v4_template)); v4_template.h.c.flowset_id = htons(0); v4_template.h.c.length = htons(sizeof(v4_template)); v4_template.h.template_id = htons(NF9_SOFTFLOWD_V4_TEMPLATE_ID); v4_template.h.count = htons(NF9_SOFTFLOWD_TEMPLATE_NRECORDS); v4_template.r[0].type = htons(NF9_IPV4_SRC_ADDR); v4_template.r[0].length = htons(4); v4_template.r[1].type = htons(NF9_IPV4_DST_ADDR); v4_template.r[1].length = htons(4); v4_template.r[2].type = htons(NF9_LAST_SWITCHED); v4_template.r[2].length = htons(4); v4_template.r[3].type = htons(NF9_FIRST_SWITCHED); v4_template.r[3].length = htons(4); v4_template.r[4].type = htons(NF9_IN_BYTES); v4_template.r[4].length = htons(4); v4_template.r[5].type = htons(NF9_IN_PACKETS); v4_template.r[5].length = htons(4); v4_template.r[6].type = htons(NF9_IF_INDEX_IN); v4_template.r[6].length = htons(4); v4_template.r[7].type = htons(NF9_IF_INDEX_OUT); v4_template.r[7].length = htons(4); v4_template.r[8].type = htons(NF9_L4_SRC_PORT); v4_template.r[8].length = htons(2); v4_template.r[9].type = htons(NF9_L4_DST_PORT); v4_template.r[9].length = htons(2); v4_template.r[10].type = htons(NF9_IN_PROTOCOL); v4_template.r[10].length = htons(1); v4_template.r[11].type = htons(NF9_TCP_FLAGS); v4_template.r[11].length = htons(1); v4_template.r[12].type = htons(NF9_IP_PROTOCOL_VERSION); v4_template.r[12].length = htons(1); bzero(&v6_template, sizeof(v6_template)); v6_template.h.c.flowset_id = htons(0); v6_template.h.c.length = htons(sizeof(v6_template)); v6_template.h.template_id = htons(NF9_SOFTFLOWD_V6_TEMPLATE_ID); v6_template.h.count = htons(NF9_SOFTFLOWD_TEMPLATE_NRECORDS); v6_template.r[0].type = htons(NF9_IPV6_SRC_ADDR); v6_template.r[0].length = htons(16); v6_template.r[1].type = htons(NF9_IPV6_DST_ADDR); v6_template.r[1].length = htons(16); v6_template.r[2].type = htons(NF9_LAST_SWITCHED); v6_template.r[2].length = htons(4); v6_template.r[3].type = htons(NF9_FIRST_SWITCHED); v6_template.r[3].length = htons(4); v6_template.r[4].type = htons(NF9_IN_BYTES); v6_template.r[4].length = htons(4); v6_template.r[5].type = htons(NF9_IN_PACKETS); v6_template.r[5].length = htons(4); v4_template.r[6].type = htons(NF9_IF_INDEX_IN); v4_template.r[6].length = htons(4); v4_template.r[7].type = htons(NF9_IF_INDEX_OUT); v4_template.r[7].length = htons(4); v6_template.r[8].type = htons(NF9_L4_SRC_PORT); v6_template.r[8].length = htons(2); v6_template.r[9].type = htons(NF9_L4_DST_PORT); v6_template.r[9].length = htons(2); v6_template.r[10].type = htons(NF9_IN_PROTOCOL); v6_template.r[10].length = htons(1); v6_template.r[11].type = htons(NF9_TCP_FLAGS); v6_template.r[11].length = htons(1); v6_template.r[12].type = htons(NF9_IP_PROTOCOL_VERSION); v6_template.r[12].length = htons(1); } static int nf_flow_to_flowset(const struct FLOW *flow, u_char *packet, u_int len, u_int16_t ifidx, const struct timeval *system_boot_time, u_int *len_used) { union { struct NF9_SOFTFLOWD_DATA_V4 d4; struct NF9_SOFTFLOWD_DATA_V6 d6; } d[2]; struct NF9_SOFTFLOWD_DATA_COMMON *dc[2]; u_int freclen, ret_len, nflows; bzero(d, sizeof(d)); *len_used = nflows = ret_len = 0; switch (flow->af) { case AF_INET: freclen = sizeof(struct NF9_SOFTFLOWD_DATA_V4); memcpy(&d[0].d4.src_addr, &flow->addr[0].v4, 4); memcpy(&d[0].d4.dst_addr, &flow->addr[1].v4, 4); memcpy(&d[1].d4.src_addr, &flow->addr[1].v4, 4); memcpy(&d[1].d4.dst_addr, &flow->addr[0].v4, 4); dc[0] = &d[0].d4.c; dc[1] = &d[1].d4.c; dc[0]->ipproto = dc[1]->ipproto = 4; break; case AF_INET6: freclen = sizeof(struct NF9_SOFTFLOWD_DATA_V6); memcpy(&d[0].d6.src_addr, &flow->addr[0].v6, 16); memcpy(&d[0].d6.dst_addr, &flow->addr[1].v6, 16); memcpy(&d[1].d6.src_addr, &flow->addr[1].v6, 16); memcpy(&d[1].d6.dst_addr, &flow->addr[0].v6, 16); dc[0] = &d[0].d6.c; dc[1] = &d[1].d6.c; dc[0]->ipproto = dc[1]->ipproto = 6; break; default: return (-1); } dc[0]->first_switched = dc[1]->first_switched = htonl(timeval_sub_ms(&flow->flow_start, system_boot_time)); dc[0]->last_switched = dc[1]->last_switched = htonl(timeval_sub_ms(&flow->flow_last, system_boot_time)); dc[0]->bytes = htonl(flow->octets[0]); dc[1]->bytes = htonl(flow->octets[1]); dc[0]->packets = htonl(flow->packets[0]); dc[1]->packets = htonl(flow->packets[1]); dc[0]->if_index_in = dc[0]->if_index_out = htonl(ifidx); dc[1]->if_index_in = dc[1]->if_index_out = htonl(ifidx); dc[0]->src_port = dc[1]->dst_port = flow->port[0]; dc[1]->src_port = dc[0]->dst_port = flow->port[1]; dc[0]->protocol = dc[1]->protocol = flow->protocol; dc[0]->tcp_flags = flow->tcp_flags[0]; dc[1]->tcp_flags = flow->tcp_flags[1]; if (flow->octets[0] > 0) { if (ret_len + freclen > len) return (-1); memcpy(packet + ret_len, &d[0], freclen); ret_len += freclen; nflows++; } if (flow->octets[1] > 0) { if (ret_len + freclen > len) return (-1); memcpy(packet + ret_len, &d[1], freclen); ret_len += freclen; nflows++; } *len_used = ret_len; return (nflows); } /* * Given an array of expired flows, send netflow v9 report packets * Returns number of packets sent or -1 on error */ int send_netflow_v9(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag) { struct NF9_HEADER *nf9; struct NF9_DATA_FLOWSET_HEADER *dh; struct timeval now; u_int offset, last_af, i, j, num_packets, inc, last_valid; socklen_t errsz; int err, r; u_char packet[NF9_SOFTFLOWD_MAX_PACKET_SIZE]; gettimeofday(&now, NULL); if (nf9_pkts_until_template == -1) { nf9_init_template(); nf9_pkts_until_template = 0; } last_valid = num_packets = 0; for (j = 0; j < num_flows;) { bzero(packet, sizeof(packet)); nf9 = (struct NF9_HEADER *)packet; nf9->version = htons(9); nf9->flows = 0; /* Filled as we go, htons at end */ nf9->uptime_ms = htonl(timeval_sub_ms(&now, system_boot_time)); nf9->time_sec = htonl(time(NULL)); nf9->package_sequence = htonl(*flows_exported + j); nf9->source_id = 0; offset = sizeof(*nf9); /* Refresh template headers if we need to */ if (nf9_pkts_until_template <= 0) { memcpy(packet + offset, &v4_template, sizeof(v4_template)); offset += sizeof(v4_template); memcpy(packet + offset, &v6_template, sizeof(v6_template)); offset += sizeof(v6_template); nf9_pkts_until_template = NF9_DEFAULT_TEMPLATE_INTERVAL; } dh = NULL; last_af = 0; for (i = 0; i + j < num_flows; i++) { if (dh == NULL || flows[i + j]->af != last_af) { if (dh != NULL) { if (offset % 4 != 0) { /* Pad to multiple of 4 */ dh->c.length += 4 - (offset % 4); offset += 4 - (offset % 4); } /* Finalise last header */ dh->c.length = htons(dh->c.length); } if (offset + sizeof(*dh) > sizeof(packet)) { /* Mark header is finished */ dh = NULL; break; } dh = (struct NF9_DATA_FLOWSET_HEADER *) (packet + offset); dh->c.flowset_id = (flows[i + j]->af == AF_INET) ? v4_template.h.template_id : v6_template.h.template_id; last_af = flows[i + j]->af; last_valid = offset; dh->c.length = sizeof(*dh); /* Filled as we go */ offset += sizeof(*dh); } r = nf_flow_to_flowset(flows[i + j], packet + offset, sizeof(packet) - offset, ifidx, system_boot_time, &inc); if (r <= 0) { /* yank off data header, if we had to go back */ if (last_valid) offset = last_valid; break; } offset += inc; dh->c.length += inc; nf9->flows += r; last_valid = 0; /* Don't clobber this header now */ if (verbose_flag) { logit(LOG_DEBUG, "Flow %d/%d: " "r %d offset %d type %04x len %d(0x%04x) " "flows %d", r, i, j, offset, dh->c.flowset_id, dh->c.length, dh->c.length, nf9->flows); } } /* Don't finish header if it has already been done */ if (dh != NULL) { if (offset % 4 != 0) { /* Pad to multiple of 4 */ dh->c.length += 4 - (offset % 4); offset += 4 - (offset % 4); } /* Finalise last header */ dh->c.length = htons(dh->c.length); } nf9->flows = htons(nf9->flows); if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); errsz = sizeof(err); /* Clear ICMP errors */ getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); num_packets++; nf9_pkts_until_template--; j += i; } *flows_exported += j; return (num_packets); } void netflow9_resend_template(void) { if (nf9_pkts_until_template > 0) nf9_pkts_until_template = 0; }
C
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #include "common.h" RCSID("$Id$"); static void usage(void) { fprintf(stderr, "Usage: [-c ctlsock] softflowctl [command]\n"); } int main(int argc, char **argv) { const char *ctlsock_path; char buf[8192], *command; struct sockaddr_un ctl; socklen_t ctllen; int ctlsock, ch; FILE *ctlf; extern char *optarg; extern int optind; ctlsock_path = DEFAULT_CTLSOCK; while ((ch = getopt(argc, argv, "hc:")) != -1) { switch (ch) { case 'h': usage(); return (0); case 'c': ctlsock_path = optarg; break; default: fprintf(stderr, "Invalid commandline option.\n"); usage(); exit(1); } } /* Accept only one argument */ if (optind != argc - 1) { usage(); exit(1); } command = argv[optind]; memset(&ctl, '\0', sizeof(ctl)); if (strlcpy(ctl.sun_path, ctlsock_path, sizeof(ctl.sun_path)) >= sizeof(ctl.sun_path)) { fprintf(stderr, "Control socket path too long.\n"); exit(1); } ctl.sun_path[sizeof(ctl.sun_path) - 1] = '\0'; ctl.sun_family = AF_UNIX; ctllen = offsetof(struct sockaddr_un, sun_path) + strlen(ctlsock_path) + 1; #ifdef SOCK_HAS_LEN ctl.sun_len = ctllen; #endif if ((ctlsock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "ctl socket() error: %s\n", strerror(errno)); exit(1); } if (connect(ctlsock, (struct sockaddr*)&ctl, sizeof(ctl)) == -1) { fprintf(stderr, "ctl connect(\"%s\") error: %s\n", ctl.sun_path, strerror(errno)); exit(1); } if ((ctlf = fdopen(ctlsock, "r+")) == NULL) { fprintf(stderr, "fdopen: %s\n", strerror(errno)); exit(1); } setlinebuf(ctlf); /* Send command */ if (fprintf(ctlf, "%s\n", command) < 0) { fprintf(stderr, "write: %s\n", strerror(errno)); exit(1); } /* Write out reply */ while((fgets(buf, sizeof(buf), ctlf)) != NULL) fputs(buf, stdout); fclose(ctlf); close(ctlsock); exit(0); }
C
/* * Copyright (c) 2007 Damien Miller. All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #ifndef _FREELIST_H #define _FREELIST_H #include "common.h" /* Simple freelist of fixed-sized allocations */ struct freelist { size_t allocsz; size_t nalloc; size_t navail; void **free_entries; }; /* * Initialise a freelist. * allocsz is the size of the individual allocations */ void freelist_init(struct freelist *freelist, size_t allocsz); /* * Get an entry from a freelist. * Will allocate new entries if necessary * Returns pointer to allocated memory or NULL on failure. */ void *freelist_get(struct freelist *freelist); /* * Returns an entry to the freelist. * p must be a pointer to an allocation from the freelist. */ void freelist_put(struct freelist *freelist, void *p); #endif /* FREELIST_H */
C
/* * Copyright 2004 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ /* $Id$ */ #include "common.h" #include "log.h" #include <stdarg.h> RCSID("$Id$"); static int logstderr = 0; void loginit(const char *ident, int to_stderr) { if (to_stderr) logstderr = 1; else openlog(PROGNAME, LOG_PID|LOG_NDELAY, LOG_DAEMON); } void logit(int level, const char *fmt,...) { va_list args; va_start(args, fmt); if (logstderr) { vfprintf(stderr, fmt, args); fputs("\n", stderr); } else vsyslog(level, fmt, args); va_end(args); }
C
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ /* $Id$ */ /* * This is software implementation of Cisco's NetFlow(tm) traffic * reporting system. It operates by listening (via libpcap) on a * promiscuous interface and tracking traffic flows. * * Traffic flows are recorded by source/destination/protocol * IP address or, in the case of TCP and UDP, by * src_addr:src_port/dest_addr:dest_port/protocol * * Flows expire automatically after a period of inactivity (default: 1 * hour) They may also be evicted (in order of age) in situations where * there are more flows than slots available. * * Netflow compatible packets are sent to a specified target host upon * flow expiry. * * As this implementation watches traffic promiscuously, it is likely to * place significant load on hosts or gateways on which it is installed. */ #include "common.h" #include "sys-tree.h" #include "convtime.h" #include "softflowd.h" #include "treetype.h" #include "freelist.h" #include "log.h" #include <pcap.h> RCSID("$Id$"); /* Global variables */ static int verbose_flag = 0; /* Debugging flag */ static u_int16_t if_index = 0; /* "manual" interface index */ /* Signal handler flags */ static volatile sig_atomic_t graceful_shutdown_request = 0; /* Context for libpcap callback functions */ struct CB_CTXT { struct FLOWTRACK *ft; int linktype; int fatal; int want_v6; }; /* Describes a datalink header and how to extract v4/v6 frames from it */ struct DATALINK { int dlt; /* BPF datalink type */ int skiplen; /* Number of bytes to skip datalink header */ int ft_off; /* Datalink frametype offset */ int ft_len; /* Datalink frametype length */ int ft_is_be; /* Set if frametype is big-endian */ u_int32_t ft_mask; /* Mask applied to frametype */ u_int32_t ft_v4; /* IPv4 frametype */ u_int32_t ft_v6; /* IPv6 frametype */ }; /* Datalink types that we know about */ static const struct DATALINK lt[] = { { DLT_EN10MB, 14, 12, 2, 1, 0xffffffff, 0x0800, 0x86dd }, { DLT_PPP, 5, 3, 2, 1, 0xffffffff, 0x0021, 0x0057 }, #ifdef DLT_LINUX_SLL { DLT_LINUX_SLL,16, 14, 2, 1, 0xffffffff, 0x0800, 0x86dd }, #endif { DLT_RAW, 0, 0, 1, 1, 0x000000f0, 0x0040, 0x0060 }, { DLT_NULL, 4, 0, 4, 0, 0xffffffff, AF_INET, AF_INET6 }, #ifdef DLT_LOOP { DLT_LOOP, 4, 0, 4, 1, 0xffffffff, AF_INET, AF_INET6 }, #endif { -1, -1, -1, -1, -1, 0x00000000, 0xffff, 0xffff }, }; /* Netflow send functions */ typedef int (netflow_send_func_t)(struct FLOW **, int, int, u_int16_t, u_int64_t *, struct timeval *, int); struct NETFLOW_SENDER { int version; netflow_send_func_t *func; int v6_capable; }; /* Array of NetFlow export function that we know of. NB. nf[0] is default */ static const struct NETFLOW_SENDER nf[] = { { 5, send_netflow_v5, 0 }, { 1, send_netflow_v1, 0 }, { 9, send_netflow_v9, 1 }, { -1, NULL, 0 }, }; /* Describes a location where we send NetFlow packets to */ struct NETFLOW_TARGET { int fd; const struct NETFLOW_SENDER *dialect; }; /* Signal handlers */ static void sighand_graceful_shutdown(int signum) { graceful_shutdown_request = signum; } static void sighand_other(int signum) { /* XXX: this may not be completely safe */ logit(LOG_WARNING, "Exiting immediately on unexpected signal %d", signum); _exit(0); } /* * This is the flow comparison function. */ static int flow_compare(struct FLOW *a, struct FLOW *b) { /* Be careful to avoid signed vs unsigned issues here */ int r; if (a->af != b->af) return (a->af > b->af ? 1 : -1); if ((r = memcmp(&a->addr[0], &b->addr[0], sizeof(a->addr[0]))) != 0) return (r > 0 ? 1 : -1); if ((r = memcmp(&a->addr[1], &b->addr[1], sizeof(a->addr[1]))) != 0) return (r > 0 ? 1 : -1); #ifdef notyet if (a->ip6_flowlabel[0] != 0 && b->ip6_flowlabel[0] != 0 && a->ip6_flowlabel[0] != b->ip6_flowlabel[0]) return (a->ip6_flowlabel[0] > b->ip6_flowlabel[0] ? 1 : -1); if (a->ip6_flowlabel[1] != 0 && b->ip6_flowlabel[1] != 0 && a->ip6_flowlabel[1] != b->ip6_flowlabel[1]) return (a->ip6_flowlabel[1] > b->ip6_flowlabel[1] ? 1 : -1); #endif if (a->protocol != b->protocol) return (a->protocol > b->protocol ? 1 : -1); if (a->port[0] != b->port[0]) return (ntohs(a->port[0]) > ntohs(b->port[0]) ? 1 : -1); if (a->port[1] != b->port[1]) return (ntohs(a->port[1]) > ntohs(b->port[1]) ? 1 : -1); return (0); } /* Generate functions for flow tree */ FLOW_PROTOTYPE(FLOWS, FLOW, trp, flow_compare); FLOW_GENERATE(FLOWS, FLOW, trp, flow_compare); /* * This is the expiry comparison function. */ static int expiry_compare(struct EXPIRY *a, struct EXPIRY *b) { if (a->expires_at != b->expires_at) return (a->expires_at > b->expires_at ? 1 : -1); /* Make expiry entries unique by comparing flow sequence */ if (a->flow->flow_seq != b->flow->flow_seq) return (a->flow->flow_seq > b->flow->flow_seq ? 1 : -1); return (0); } /* Generate functions for flow tree */ EXPIRY_PROTOTYPE(EXPIRIES, EXPIRY, trp, expiry_compare); EXPIRY_GENERATE(EXPIRIES, EXPIRY, trp, expiry_compare); static struct FLOW * flow_get(struct FLOWTRACK *ft) { return freelist_get(&ft->flow_freelist); } static void flow_put(struct FLOWTRACK *ft, struct FLOW *flow) { return freelist_put(&ft->flow_freelist, flow); } static struct EXPIRY * expiry_get(struct FLOWTRACK *ft) { return freelist_get(&ft->expiry_freelist); } static void expiry_put(struct FLOWTRACK *ft, struct EXPIRY *expiry) { return freelist_put(&ft->expiry_freelist, expiry); } #if 0 /* Dump a packet */ static void dump_packet(const u_int8_t *p, int len) { char buf[1024], tmp[3]; int i; for (*buf = '\0', i = 0; i < len; i++) { snprintf(tmp, sizeof(tmp), "%02x%s", p[i], i % 2 ? " " : ""); if (strlcat(buf, tmp, sizeof(buf) - 4) >= sizeof(buf) - 4) { strlcat(buf, "...", sizeof(buf)); break; } } logit(LOG_INFO, "packet len %d: %s", len, buf); } #endif /* Format a time in an ISOish format */ static const char * format_time(time_t t) { struct tm *tm; static char buf[32]; tm = gmtime(&t); strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", tm); return (buf); } /* Format a flow in a verbose and ugly way */ static const char * format_flow(struct FLOW *flow) { char addr1[64], addr2[64], stime[32], ftime[32]; static char buf[1024]; inet_ntop(flow->af, &flow->addr[0], addr1, sizeof(addr1)); inet_ntop(flow->af, &flow->addr[1], addr2, sizeof(addr2)); snprintf(stime, sizeof(ftime), "%s", format_time(flow->flow_start.tv_sec)); snprintf(ftime, sizeof(ftime), "%s", format_time(flow->flow_last.tv_sec)); snprintf(buf, sizeof(buf), "seq:%llu [%s]:%hu <> [%s]:%hu proto:%u " "octets>:%u packets>:%u octets<:%u packets<:%u " "start:%s.%03ld finish:%s.%03ld tcp>:%02x tcp<:%02x " "flowlabel>:%08x flowlabel<:%08x ", flow->flow_seq, addr1, ntohs(flow->port[0]), addr2, ntohs(flow->port[1]), (int)flow->protocol, flow->octets[0], flow->packets[0], flow->octets[1], flow->packets[1], stime, (flow->flow_start.tv_usec + 500) / 1000, ftime, (flow->flow_last.tv_usec + 500) / 1000, flow->tcp_flags[0], flow->tcp_flags[1], flow->ip6_flowlabel[0], flow->ip6_flowlabel[1]); return (buf); } /* Format a flow in a brief way */ static const char * format_flow_brief(struct FLOW *flow) { char addr1[64], addr2[64]; static char buf[1024]; inet_ntop(flow->af, &flow->addr[0], addr1, sizeof(addr1)); inet_ntop(flow->af, &flow->addr[1], addr2, sizeof(addr2)); snprintf(buf, sizeof(buf), "seq:%llu [%s]:%hu <> [%s]:%hu proto:%u", flow->flow_seq, addr1, ntohs(flow->port[0]), addr2, ntohs(flow->port[1]), (int)flow->protocol); return (buf); } /* Fill in transport-layer (tcp/udp) portions of flow record */ static int transport_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, const size_t caplen, int isfrag, int protocol, int ndx) { const struct tcphdr *tcp = (const struct tcphdr *)pkt; const struct udphdr *udp = (const struct udphdr *)pkt; const struct icmp *icmp = (const struct icmp *)pkt; /* * XXX to keep flow in proper canonical format, it may be necessary to * swap the array slots based on the order of the port numbers does * this matter in practice??? I don't think so - return flows will * always match, because of their symmetrical addr/ports */ switch (protocol) { case IPPROTO_TCP: /* Check for runt packet, but don't error out on short frags */ if (caplen < sizeof(*tcp)) return (isfrag ? 0 : 1); flow->port[ndx] = tcp->th_sport; flow->port[ndx ^ 1] = tcp->th_dport; flow->tcp_flags[ndx] |= tcp->th_flags; break; case IPPROTO_UDP: /* Check for runt packet, but don't error out on short frags */ if (caplen < sizeof(*udp)) return (isfrag ? 0 : 1); flow->port[ndx] = udp->uh_sport; flow->port[ndx ^ 1] = udp->uh_dport; break; case IPPROTO_ICMP: /* * Encode ICMP type * 256 + code into dest port like * Cisco routers */ flow->port[ndx] = 0; flow->port[ndx ^ 1] = htons(icmp->icmp_type * 256 + icmp->icmp_code); break; } return (0); } /* Convert a IPv4 packet to a partial flow record (used for comparison) */ static int ipv4_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, size_t caplen, size_t len, int *isfrag, int af) { const struct ip *ip = (const struct ip *)pkt; int ndx; if (caplen < 20 || caplen < ip->ip_hl * 4) return (-1); /* Runt packet */ if (ip->ip_v != 4) return (-1); /* Unsupported IP version */ /* Prepare to store flow in canonical format */ ndx = memcmp(&ip->ip_src, &ip->ip_dst, sizeof(ip->ip_src)) > 0 ? 1 : 0; flow->af = af; flow->addr[ndx].v4 = ip->ip_src; flow->addr[ndx ^ 1].v4 = ip->ip_dst; flow->protocol = ip->ip_p; flow->octets[ndx] = len; flow->packets[ndx] = 1; *isfrag = (ntohs(ip->ip_off) & (IP_OFFMASK|IP_MF)) ? 1 : 0; /* Don't try to examine higher level headers if not first fragment */ if (*isfrag && (ntohs(ip->ip_off) & IP_OFFMASK) != 0) return (0); return (transport_to_flowrec(flow, pkt + (ip->ip_hl * 4), caplen - (ip->ip_hl * 4), *isfrag, ip->ip_p, ndx)); } /* Convert a IPv6 packet to a partial flow record (used for comparison) */ static int ipv6_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, size_t caplen, size_t len, int *isfrag, int af) { const struct ip6_hdr *ip6 = (const struct ip6_hdr *)pkt; const struct ip6_ext *eh6; const struct ip6_frag *fh6; int ndx, nxt; if (caplen < sizeof(*ip6)) return (-1); /* Runt packet */ if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) return (-1); /* Unsupported IPv6 version */ /* Prepare to store flow in canonical format */ ndx = memcmp(&ip6->ip6_src, &ip6->ip6_dst, sizeof(ip6->ip6_src)) > 0 ? 1 : 0; flow->af = af; flow->ip6_flowlabel[ndx] = ip6->ip6_flow & IPV6_FLOWLABEL_MASK; flow->addr[ndx].v6 = ip6->ip6_src; flow->addr[ndx ^ 1].v6 = ip6->ip6_dst; flow->octets[ndx] = len; flow->packets[ndx] = 1; *isfrag = 0; nxt = ip6->ip6_nxt; pkt += sizeof(*ip6); caplen -= sizeof(*ip6); /* Now loop through headers, looking for transport header */ for (;;) { eh6 = (const struct ip6_ext *)pkt; if (nxt == IPPROTO_HOPOPTS || nxt == IPPROTO_ROUTING || nxt == IPPROTO_DSTOPTS) { if (caplen < sizeof(*eh6) || caplen < (eh6->ip6e_len + 1) << 3) return (1); /* Runt */ nxt = eh6->ip6e_nxt; pkt += (eh6->ip6e_len + 1) << 3; caplen -= (eh6->ip6e_len + 1) << 3; } else if (nxt == IPPROTO_FRAGMENT) { *isfrag = 1; fh6 = (const struct ip6_frag *)eh6; if (caplen < sizeof(*fh6)) return (1); /* Runt */ /* * Don't try to examine higher level headers if * not first fragment */ if ((fh6->ip6f_offlg & IP6F_OFF_MASK) != 0) return (0); nxt = fh6->ip6f_nxt; pkt += sizeof(*fh6); caplen -= sizeof(*fh6); } else break; } flow->protocol = nxt; return (transport_to_flowrec(flow, pkt, caplen, *isfrag, nxt, ndx)); } static void flow_update_expiry(struct FLOWTRACK *ft, struct FLOW *flow) { EXPIRY_REMOVE(EXPIRIES, &ft->expiries, flow->expiry); /* Flows over 2 GiB traffic */ if (flow->octets[0] > (1U << 31) || flow->octets[1] > (1U << 31)) { flow->expiry->expires_at = 0; flow->expiry->reason = R_OVERBYTES; goto out; } /* Flows over maximum life seconds */ if (ft->maximum_lifetime != 0 && flow->flow_last.tv_sec - flow->flow_start.tv_sec > ft->maximum_lifetime) { flow->expiry->expires_at = 0; flow->expiry->reason = R_MAXLIFE; goto out; } if (flow->protocol == IPPROTO_TCP) { /* Reset TCP flows */ if (ft->tcp_rst_timeout != 0 && ((flow->tcp_flags[0] & TH_RST) || (flow->tcp_flags[1] & TH_RST))) { flow->expiry->expires_at = flow->flow_last.tv_sec + ft->tcp_rst_timeout; flow->expiry->reason = R_TCP_RST; goto out; } /* Finished TCP flows */ if (ft->tcp_fin_timeout != 0 && ((flow->tcp_flags[0] & TH_FIN) && (flow->tcp_flags[1] & TH_FIN))) { flow->expiry->expires_at = flow->flow_last.tv_sec + ft->tcp_fin_timeout; flow->expiry->reason = R_TCP_FIN; goto out; } /* TCP flows */ if (ft->tcp_timeout != 0) { flow->expiry->expires_at = flow->flow_last.tv_sec + ft->tcp_timeout; flow->expiry->reason = R_TCP; goto out; } } if (ft->udp_timeout != 0 && flow->protocol == IPPROTO_UDP) { /* UDP flows */ flow->expiry->expires_at = flow->flow_last.tv_sec + ft->udp_timeout; flow->expiry->reason = R_UDP; goto out; } if (ft->icmp_timeout != 0 && ((flow->af == AF_INET && flow->protocol == IPPROTO_ICMP) || ((flow->af == AF_INET6 && flow->protocol == IPPROTO_ICMPV6)))) { /* ICMP flows */ flow->expiry->expires_at = flow->flow_last.tv_sec + ft->icmp_timeout; flow->expiry->reason = R_ICMP; goto out; } /* Everything else */ flow->expiry->expires_at = flow->flow_last.tv_sec + ft->general_timeout; flow->expiry->reason = R_GENERAL; out: if (ft->maximum_lifetime != 0 && flow->expiry->expires_at != 0) { flow->expiry->expires_at = MIN(flow->expiry->expires_at, flow->flow_start.tv_sec + ft->maximum_lifetime); } EXPIRY_INSERT(EXPIRIES, &ft->expiries, flow->expiry); } /* Return values from process_packet */ #define PP_OK 0 #define PP_BAD_PACKET -2 #define PP_MALLOC_FAIL -3 /* * Main per-packet processing function. Take a packet (provided by * libpcap) and attempt to find a matching flow. If no such flow exists, * then create one. * * Also marks flows for fast expiry, based on flow or packet attributes * (the actual expiry is performed elsewhere) */ static int process_packet(struct FLOWTRACK *ft, const u_int8_t *pkt, int af, const u_int32_t caplen, const u_int32_t len, const struct timeval *received_time) { struct FLOW tmp, *flow; int frag; ft->total_packets++; /* Convert the IP packet to a flow identity */ memset(&tmp, 0, sizeof(tmp)); switch (af) { case AF_INET: if (ipv4_to_flowrec(&tmp, pkt, caplen, len, &frag, af) == -1) goto bad; break; case AF_INET6: if (ipv6_to_flowrec(&tmp, pkt, caplen, len, &frag, af) == -1) goto bad; break; default: bad: ft->bad_packets++; return (PP_BAD_PACKET); } if (frag) ft->frag_packets++; /* Zero out bits of the flow that aren't relevant to tracking level */ switch (ft->track_level) { case TRACK_IP_ONLY: tmp.protocol = 0; /* FALLTHROUGH */ case TRACK_IP_PROTO: tmp.port[0] = tmp.port[1] = 0; tmp.tcp_flags[0] = tmp.tcp_flags[1] = 0; /* FALLTHROUGH */ case TRACK_FULL: break; } /* If a matching flow does not exist, create and insert one */ if ((flow = FLOW_FIND(FLOWS, &ft->flows, &tmp)) == NULL) { /* Allocate and fill in the flow */ if ((flow = flow_get(ft)) == NULL) { logit(LOG_ERR, "process_packet: flow_get failed", sizeof(*flow)); return (PP_MALLOC_FAIL); } memcpy(flow, &tmp, sizeof(*flow)); memcpy(&flow->flow_start, received_time, sizeof(flow->flow_start)); flow->flow_seq = ft->next_flow_seq++; FLOW_INSERT(FLOWS, &ft->flows, flow); /* Allocate and fill in the associated expiry event */ if ((flow->expiry = expiry_get(ft)) == NULL) { logit(LOG_ERR, "process_packet: expiry_get failed", sizeof(*flow->expiry)); return (PP_MALLOC_FAIL); } flow->expiry->flow = flow; /* Must be non-zero (0 means expire immediately) */ flow->expiry->expires_at = 1; flow->expiry->reason = R_GENERAL; EXPIRY_INSERT(EXPIRIES, &ft->expiries, flow->expiry); ft->num_flows++; if (verbose_flag) logit(LOG_DEBUG, "ADD FLOW %s", format_flow_brief(flow)); } else { /* Update flow statistics */ flow->packets[0] += tmp.packets[0]; flow->octets[0] += tmp.octets[0]; flow->tcp_flags[0] |= tmp.tcp_flags[0]; flow->packets[1] += tmp.packets[1]; flow->octets[1] += tmp.octets[1]; flow->tcp_flags[1] |= tmp.tcp_flags[1]; } memcpy(&flow->flow_last, received_time, sizeof(flow->flow_last)); if (flow->expiry->expires_at != 0) flow_update_expiry(ft, flow); return (PP_OK); } /* * Subtract two timevals. Returns (t1 - t2) in milliseconds. */ u_int32_t timeval_sub_ms(const struct timeval *t1, const struct timeval *t2) { struct timeval res; res.tv_sec = t1->tv_sec - t2->tv_sec; res.tv_usec = t1->tv_usec - t2->tv_usec; if (res.tv_usec < 0) { res.tv_usec += 1000000L; res.tv_sec--; } return ((u_int32_t)res.tv_sec * 1000 + (u_int32_t)res.tv_usec / 1000); } static void update_statistic(struct STATISTIC *s, double new, double n) { if (n == 1.0) { s->min = s->mean = s->max = new; return; } s->min = MIN(s->min, new); s->max = MAX(s->max, new); s->mean = s->mean + ((new - s->mean) / n); } /* Update global statistics */ static void update_statistics(struct FLOWTRACK *ft, struct FLOW *flow) { double tmp; static double n = 1.0; ft->flows_expired++; ft->flows_pp[flow->protocol % 256]++; tmp = (double)flow->flow_last.tv_sec + ((double)flow->flow_last.tv_usec / 1000000.0); tmp -= (double)flow->flow_start.tv_sec + ((double)flow->flow_start.tv_usec / 1000000.0); if (tmp < 0.0) tmp = 0.0; update_statistic(&ft->duration, tmp, n); update_statistic(&ft->duration_pp[flow->protocol], tmp, (double)ft->flows_pp[flow->protocol % 256]); tmp = flow->octets[0] + flow->octets[1]; update_statistic(&ft->octets, tmp, n); ft->octets_pp[flow->protocol % 256] += tmp; tmp = flow->packets[0] + flow->packets[1]; update_statistic(&ft->packets, tmp, n); ft->packets_pp[flow->protocol % 256] += tmp; n++; } static void update_expiry_stats(struct FLOWTRACK *ft, struct EXPIRY *e) { switch (e->reason) { case R_GENERAL: ft->expired_general++; break; case R_TCP: ft->expired_tcp++; break; case R_TCP_RST: ft->expired_tcp_rst++; break; case R_TCP_FIN: ft->expired_tcp_fin++; break; case R_UDP: ft->expired_udp++; break; case R_ICMP: ft->expired_icmp++; break; case R_MAXLIFE: ft->expired_maxlife++; break; case R_OVERBYTES: ft->expired_overbytes++; break; case R_OVERFLOWS: ft->expired_maxflows++; break; case R_FLUSH: ft->expired_flush++; break; } } /* How long before the next expiry event in millisecond */ static int next_expire(struct FLOWTRACK *ft) { struct EXPIRY *expiry; struct timeval now; u_int32_t expires_at, ret, fudge; gettimeofday(&now, NULL); if ((expiry = EXPIRY_MIN(EXPIRIES, &ft->expiries)) == NULL) return (-1); /* indefinite */ expires_at = expiry->expires_at; /* Don't cluster urgent expiries */ if (expires_at == 0 && (expiry->reason == R_OVERBYTES || expiry->reason == R_OVERFLOWS || expiry->reason == R_FLUSH)) return (0); /* Now */ /* Cluster expiries by expiry_interval */ if (ft->expiry_interval > 1) { if ((fudge = expires_at % ft->expiry_interval) > 0) expires_at += ft->expiry_interval - fudge; } if (expires_at < now.tv_sec) return (0); /* Now */ ret = 999 + (expires_at - now.tv_sec) * 1000; return (ret); } /* * Scan the tree of expiry events and process expired flows. If zap_all * is set, then forcibly expire all flows. */ #define CE_EXPIRE_NORMAL 0 /* Normal expiry processing */ #define CE_EXPIRE_ALL -1 /* Expire all flows immediately */ #define CE_EXPIRE_FORCED 1 /* Only expire force-expired flows */ static int check_expired(struct FLOWTRACK *ft, struct NETFLOW_TARGET *target, int ex) { struct FLOW **expired_flows, **oldexp; int num_expired, i, r; struct timeval now; struct EXPIRY *expiry, *nexpiry; gettimeofday(&now, NULL); r = 0; num_expired = 0; expired_flows = NULL; if (verbose_flag) logit(LOG_DEBUG, "Starting expiry scan: mode %d", ex); for(expiry = EXPIRY_MIN(EXPIRIES, &ft->expiries); expiry != NULL; expiry = nexpiry) { nexpiry = EXPIRY_NEXT(EXPIRIES, &ft->expiries, expiry); if ((expiry->expires_at == 0) || (ex == CE_EXPIRE_ALL) || (ex != CE_EXPIRE_FORCED && (expiry->expires_at < now.tv_sec))) { /* Flow has expired */ if (ft->maximum_lifetime != 0 && expiry->flow->flow_last.tv_sec - expiry->flow->flow_start.tv_sec >= ft->maximum_lifetime) expiry->reason = R_MAXLIFE; if (verbose_flag) logit(LOG_DEBUG, "Queuing flow seq:%llu (%p) for expiry " "reason %d", expiry->flow->flow_seq, expiry->flow, expiry->reason); /* Add to array of expired flows */ oldexp = expired_flows; expired_flows = realloc(expired_flows, sizeof(*expired_flows) * (num_expired + 1)); /* Don't fatal on realloc failures */ if (expired_flows == NULL) expired_flows = oldexp; else { expired_flows[num_expired] = expiry->flow; num_expired++; } if (ex == CE_EXPIRE_ALL) expiry->reason = R_FLUSH; update_expiry_stats(ft, expiry); /* Remove from flow tree, destroy expiry event */ FLOW_REMOVE(FLOWS, &ft->flows, expiry->flow); EXPIRY_REMOVE(EXPIRIES, &ft->expiries, expiry); expiry->flow->expiry = NULL; expiry_put(ft, expiry); ft->num_flows--; } } if (verbose_flag) logit(LOG_DEBUG, "Finished scan %d flow(s) to be evicted", num_expired); /* Processing for expired flows */ if (num_expired > 0) { if (target != NULL && target->fd != -1) { r = target->dialect->func(expired_flows, num_expired, target->fd, if_index, &ft->flows_exported, &ft->system_boot_time, verbose_flag); if (verbose_flag) logit(LOG_DEBUG, "sent %d netflow packets", r); if (r > 0) { ft->packets_sent += r; /* XXX what if r < num_expired * 2 ? */ } else { ft->flows_dropped += num_expired * 2; } } for (i = 0; i < num_expired; i++) { if (verbose_flag) { logit(LOG_DEBUG, "EXPIRED: %s (%p)", format_flow(expired_flows[i]), expired_flows[i]); } update_statistics(ft, expired_flows[i]); flow_put(ft, expired_flows[i]); } free(expired_flows); } return (r == -1 ? -1 : num_expired); } /* * Force expiry of num_to_expire flows (e.g. when flow table overfull) */ static void force_expire(struct FLOWTRACK *ft, u_int32_t num_to_expire) { struct EXPIRY *expiry, **expiryv; int i; /* XXX move all overflow processing here (maybe) */ if (verbose_flag) logit(LOG_INFO, "Forcing expiry of %d flows", num_to_expire); /* * Do this in two steps, as it is dangerous to change a key on * a tree entry without first removing it and then re-adding it. * It is even worse when this has to be done during a FOREACH :) * To get around this, we make a list of expired flows and _then_ * alter them */ if ((expiryv = calloc(num_to_expire, sizeof(*expiryv))) == NULL) { /* * On malloc failure, expire ALL flows. I assume that * setting all the keys in a tree to the same value is * safe. */ logit(LOG_ERR, "Out of memory while expiring flows - " "all flows expired"); EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) { expiry->expires_at = 0; expiry->reason = R_OVERFLOWS; ft->flows_force_expired++; } return; } /* Make the list of flows to expire */ i = 0; EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) { if (i >= num_to_expire) break; expiryv[i++] = expiry; } if (i < num_to_expire) { logit(LOG_ERR, "Needed to expire %d flows, " "but only %d active", num_to_expire, i); num_to_expire = i; } for(i = 0; i < num_to_expire; i++) { EXPIRY_REMOVE(EXPIRIES, &ft->expiries, expiryv[i]); expiryv[i]->expires_at = 0; expiryv[i]->reason = R_OVERFLOWS; EXPIRY_INSERT(EXPIRIES, &ft->expiries, expiryv[i]); } ft->flows_force_expired += num_to_expire; free(expiryv); /* XXX - this is overcomplicated, perhaps use a separate queue */ } /* Delete all flows that we know about without processing */ static int delete_all_flows(struct FLOWTRACK *ft) { struct FLOW *flow, *nflow; int i; i = 0; for(flow = FLOW_MIN(FLOWS, &ft->flows); flow != NULL; flow = nflow) { nflow = FLOW_NEXT(FLOWS, &ft->flows, flow); FLOW_REMOVE(FLOWS, &ft->flows, flow); EXPIRY_REMOVE(EXPIRIES, &ft->expiries, flow->expiry); expiry_put(ft, flow->expiry); ft->num_flows--; flow_put(ft, flow); i++; } return (i); } /* * Log our current status. * Includes summary counters and (in verbose mode) the list of current flows * and the tree of expiry events. */ static int statistics(struct FLOWTRACK *ft, FILE *out, pcap_t *pcap) { int i; struct protoent *pe; char proto[32]; struct pcap_stat ps; fprintf(out, "Number of active flows: %d\n", ft->num_flows); fprintf(out, "Packets processed: %llu\n", ft->total_packets); fprintf(out, "Fragments: %llu\n", ft->frag_packets); fprintf(out, "Ignored packets: %llu (%llu non-IP, %llu too short)\n", ft->non_ip_packets + ft->bad_packets, ft->non_ip_packets, ft->bad_packets); fprintf(out, "Flows expired: %llu (%llu forced)\n", ft->flows_expired, ft->flows_force_expired); fprintf(out, "Flows exported: %llu in %llu packets (%llu failures)\n", ft->flows_exported, ft->packets_sent, ft->flows_dropped); if (pcap_stats(pcap, &ps) == 0) { fprintf(out, "Packets received by libpcap: %lu\n", (unsigned long)ps.ps_recv); fprintf(out, "Packets dropped by libpcap: %lu\n", (unsigned long)ps.ps_drop); fprintf(out, "Packets dropped by interface: %lu\n", (unsigned long)ps.ps_ifdrop); } fprintf(out, "\n"); if (ft->flows_expired != 0) { fprintf(out, "Expired flow statistics: minimum average maximum\n"); fprintf(out, " Flow bytes: %12.0f %12.0f %12.0f\n", ft->octets.min, ft->octets.mean, ft->octets.max); fprintf(out, " Flow packets: %12.0f %12.0f %12.0f\n", ft->packets.min, ft->packets.mean, ft->packets.max); fprintf(out, " Duration: %12.2fs %12.2fs %12.2fs\n", ft->duration.min, ft->duration.mean, ft->duration.max); fprintf(out, "\n"); fprintf(out, "Expired flow reasons:\n"); fprintf(out, " tcp = %9llu tcp.rst = %9llu " "tcp.fin = %9llu\n", ft->expired_tcp, ft->expired_tcp_rst, ft->expired_tcp_fin); fprintf(out, " udp = %9llu icmp = %9llu " "general = %9llu\n", ft->expired_udp, ft->expired_icmp, ft->expired_general); fprintf(out, " maxlife = %9llu\n", ft->expired_maxlife); fprintf(out, "over 2 GiB = %9llu\n", ft->expired_overbytes); fprintf(out, " maxflows = %9llu\n", ft->expired_maxflows); fprintf(out, " flushed = %9llu\n", ft->expired_flush); fprintf(out, "\n"); fprintf(out, "Per-protocol statistics: Octets " "Packets Avg Life Max Life\n"); for(i = 0; i < 256; i++) { if (ft->packets_pp[i]) { pe = getprotobynumber(i); snprintf(proto, sizeof(proto), "%s (%d)", pe != NULL ? pe->p_name : "Unknown", i); fprintf(out, " %17s: %14llu %12llu %8.2fs " "%10.2fs\n", proto, ft->octets_pp[i], ft->packets_pp[i], ft->duration_pp[i].mean, ft->duration_pp[i].max); } } } return (0); } static void dump_flows(struct FLOWTRACK *ft, FILE *out) { struct EXPIRY *expiry; time_t now; now = time(NULL); EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) { fprintf(out, "ACTIVE %s\n", format_flow(expiry->flow)); if ((long int) expiry->expires_at - now < 0) { fprintf(out, "EXPIRY EVENT for flow %llu now%s\n", expiry->flow->flow_seq, expiry->expires_at == 0 ? " (FORCED)": ""); } else { fprintf(out, "EXPIRY EVENT for flow %llu in %ld seconds\n", expiry->flow->flow_seq, (long int) expiry->expires_at - now); } fprintf(out, "\n"); } } /* * Figure out how many bytes to skip from front of packet to get past * datalink headers. If pkt is specified, also check whether determine * whether or not it is one that we are interested in (IPv4 or IPv6 for now) * * Returns number of bytes to skip or -1 to indicate that entire * packet should be skipped */ static int datalink_check(int linktype, const u_int8_t *pkt, u_int32_t caplen, int *af) { int i, j; u_int32_t frametype; static const struct DATALINK *dl = NULL; /* Try to cache last used linktype */ if (dl == NULL || dl->dlt != linktype) { for (i = 0; lt[i].dlt != linktype && lt[i].dlt != -1; i++) ; dl = &lt[i]; } if (dl->dlt == -1 || pkt == NULL) return (dl->dlt); if (caplen <= dl->skiplen) return (-1); /* Suck out the frametype */ frametype = 0; if (dl->ft_is_be) { for (j = 0; j < dl->ft_len; j++) { frametype <<= 8; frametype |= pkt[j + dl->ft_off]; } } else { for (j = dl->ft_len - 1; j >= 0 ; j--) { frametype <<= 8; frametype |= pkt[j + dl->ft_off]; } } frametype &= dl->ft_mask; if (frametype == dl->ft_v4) *af = AF_INET; else if (frametype == dl->ft_v6) *af = AF_INET6; else return (-1); return (dl->skiplen); } /* * Per-packet callback function from libpcap. Pass the packet (if it is IP) * sans datalink headers to process_packet. */ static void flow_cb(u_char *user_data, const struct pcap_pkthdr* phdr, const u_char *pkt) { int s, af; struct CB_CTXT *cb_ctxt = (struct CB_CTXT *)user_data; struct timeval tv; s = datalink_check(cb_ctxt->linktype, pkt, phdr->caplen, &af); if (s < 0 || (!cb_ctxt->want_v6 && af == AF_INET6)) { cb_ctxt->ft->non_ip_packets++; } else { tv.tv_sec = phdr->ts.tv_sec; tv.tv_usec = phdr->ts.tv_usec; if (process_packet(cb_ctxt->ft, pkt + s, af, phdr->caplen - s, phdr->len - s, &tv) == PP_MALLOC_FAIL) cb_ctxt->fatal = 1; } } static void print_timeouts(struct FLOWTRACK *ft, FILE *out) { fprintf(out, " TCP timeout: %ds\n", ft->tcp_timeout); fprintf(out, " TCP post-RST timeout: %ds\n", ft->tcp_rst_timeout); fprintf(out, " TCP post-FIN timeout: %ds\n", ft->tcp_fin_timeout); fprintf(out, " UDP timeout: %ds\n", ft->udp_timeout); fprintf(out, " ICMP timeout: %ds\n", ft->icmp_timeout); fprintf(out, " General timeout: %ds\n", ft->general_timeout); fprintf(out, " Maximum lifetime: %ds\n", ft->maximum_lifetime); fprintf(out, " Expiry interval: %ds\n", ft->expiry_interval); } static int accept_control(int lsock, struct NETFLOW_TARGET *target, struct FLOWTRACK *ft, pcap_t *pcap, int *exit_request, int *stop_collection_flag) { unsigned char buf[64], *p; FILE *ctlf; int fd, ret; if ((fd = accept(lsock, NULL, NULL)) == -1) { logit(LOG_ERR, "ctl accept: %s - exiting", strerror(errno)); return(-1); } if ((ctlf = fdopen(fd, "r+")) == NULL) { logit(LOG_ERR, "fdopen: %s - exiting\n", strerror(errno)); close(fd); return (-1); } setlinebuf(ctlf); if (fgets(buf, sizeof(buf), ctlf) == NULL) { logit(LOG_ERR, "Control socket yielded no data"); return (0); } if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; if (verbose_flag) logit(LOG_DEBUG, "Control socket \"%s\"", buf); /* XXX - use dispatch table */ ret = -1; if (strcmp(buf, "help") == 0) { fprintf(ctlf, "Valid control words are:\n"); fprintf(ctlf, "\tdebug+ debug- delete-all dump-flows exit " "expire-all\n"); fprintf(ctlf, "\tshutdown start-gather statistics stop-gather " "timeouts\n"); fprintf(ctlf, "\tsend-template\n"); ret = 0; } else if (strcmp(buf, "shutdown") == 0) { fprintf(ctlf, "softflowd[%u]: Shutting down gracefully...\n", getpid()); graceful_shutdown_request = 1; ret = 1; } else if (strcmp(buf, "exit") == 0) { fprintf(ctlf, "softflowd[%u]: Exiting now...\n", getpid()); *exit_request = 1; ret = 1; } else if (strcmp(buf, "expire-all") == 0) { netflow9_resend_template(); fprintf(ctlf, "softflowd[%u]: Expired %d flows.\n", getpid(), check_expired(ft, target, CE_EXPIRE_ALL)); ret = 0; } else if (strcmp(buf, "send-template") == 0) { netflow9_resend_template(); fprintf(ctlf, "softflowd[%u]: Template will be sent at " "next flow export\n", getpid()); ret = 0; } else if (strcmp(buf, "delete-all") == 0) { fprintf(ctlf, "softflowd[%u]: Deleted %d flows.\n", getpid(), delete_all_flows(ft)); ret = 0; } else if (strcmp(buf, "statistics") == 0) { fprintf(ctlf, "softflowd[%u]: Accumulated statistics " "since %s UTC:\n", getpid(), format_time(ft->system_boot_time.tv_sec)); statistics(ft, ctlf, pcap); ret = 0; } else if (strcmp(buf, "debug+") == 0) { fprintf(ctlf, "softflowd[%u]: Debug level increased.\n", getpid()); verbose_flag = 1; ret = 0; } else if (strcmp(buf, "debug-") == 0) { fprintf(ctlf, "softflowd[%u]: Debug level decreased.\n", getpid()); verbose_flag = 0; ret = 0; } else if (strcmp(buf, "stop-gather") == 0) { fprintf(ctlf, "softflowd[%u]: Data collection stopped.\n", getpid()); *stop_collection_flag = 1; ret = 0; } else if (strcmp(buf, "start-gather") == 0) { fprintf(ctlf, "softflowd[%u]: Data collection resumed.\n", getpid()); *stop_collection_flag = 0; ret = 0; } else if (strcmp(buf, "dump-flows") == 0) { fprintf(ctlf, "softflowd[%u]: Dumping flow data:\n", getpid()); dump_flows(ft, ctlf); ret = 0; } else if (strcmp(buf, "timeouts") == 0) { fprintf(ctlf, "softflowd[%u]: Printing timeouts:\n", getpid()); print_timeouts(ft, ctlf); ret = 0; } else { fprintf(ctlf, "Unknown control commmand \"%s\"\n", buf); ret = 0; } fclose(ctlf); close(fd); return (ret); } static int connsock(struct sockaddr_storage *addr, socklen_t len, int hoplimit) { int s; unsigned int h6; unsigned char h4; struct sockaddr_in *in4 = (struct sockaddr_in *)addr; struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)addr; if ((s = socket(addr->ss_family, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "socket() error: %s\n", strerror(errno)); exit(1); } if (connect(s, (struct sockaddr*)addr, len) == -1) { fprintf(stderr, "connect() error: %s\n", strerror(errno)); exit(1); } switch (addr->ss_family) { case AF_INET: /* Default to link-local TTL for multicast addresses */ if (hoplimit == -1 && IN_MULTICAST(in4->sin_addr.s_addr)) hoplimit = 1; if (hoplimit == -1) break; h4 = hoplimit; if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &h4, sizeof(h4)) == -1) { fprintf(stderr, "setsockopt(IP_MULTICAST_TTL, " "%u): %s\n", h4, strerror(errno)); exit(1); } break; case AF_INET6: /* Default to link-local hoplimit for multicast addresses */ if (hoplimit == -1 && IN6_IS_ADDR_MULTICAST(&in6->sin6_addr)) hoplimit = 1; if (hoplimit == -1) break; h6 = hoplimit; if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &h6, sizeof(h6)) == -1) { fprintf(stderr, "setsockopt(IPV6_MULTICAST_HOPS, %u): " "%s\n", h6, strerror(errno)); exit(1); } } return(s); } static int unix_listener(const char *path) { struct sockaddr_un addr; socklen_t addrlen; int s; memset(&addr, '\0', sizeof(addr)); addr.sun_family = AF_UNIX; if (strlcpy(addr.sun_path, path, sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) { fprintf(stderr, "control socket path too long\n"); exit(1); } addr.sun_path[sizeof(addr.sun_path) - 1] = '\0'; addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(path) + 1; #ifdef SOCK_HAS_LEN addr.sun_len = addrlen; #endif if ((s = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "unix domain socket() error: %s\n", strerror(errno)); exit(1); } unlink(path); if (bind(s, (struct sockaddr*)&addr, addrlen) == -1) { fprintf(stderr, "unix domain bind(\"%s\") error: %s\n", addr.sun_path, strerror(errno)); exit(1); } if (listen(s, 64) == -1) { fprintf(stderr, "unix domain listen() error: %s\n", strerror(errno)); exit(1); } return (s); } static void setup_packet_capture(struct pcap **pcap, int *linktype, char *dev, char *capfile, char *bpf_prog, int need_v6) { char ebuf[PCAP_ERRBUF_SIZE]; struct bpf_program prog_c; u_int32_t bpf_mask, bpf_net; /* Open pcap */ if (dev != NULL) { if ((*pcap = pcap_open_live(dev, need_v6 ? LIBPCAP_SNAPLEN_V6 : LIBPCAP_SNAPLEN_V4, 1, 0, ebuf)) == NULL) { fprintf(stderr, "pcap_open_live: %s\n", ebuf); exit(1); } if (pcap_lookupnet(dev, &bpf_net, &bpf_mask, ebuf) == -1) bpf_net = bpf_mask = 0; } else { if ((*pcap = pcap_open_offline(capfile, ebuf)) == NULL) { fprintf(stderr, "pcap_open_offline(%s): %s\n", capfile, ebuf); exit(1); } bpf_net = bpf_mask = 0; } *linktype = pcap_datalink(*pcap); if (datalink_check(*linktype, NULL, 0, NULL) == -1) { fprintf(stderr, "Unsupported datalink type %d\n", *linktype); exit(1); } /* Attach BPF filter, if specified */ if (bpf_prog != NULL) { if (pcap_compile(*pcap, &prog_c, bpf_prog, 1, bpf_mask) == -1) { fprintf(stderr, "pcap_compile(\"%s\"): %s\n", bpf_prog, pcap_geterr(*pcap)); exit(1); } if (pcap_setfilter(*pcap, &prog_c) == -1) { fprintf(stderr, "pcap_setfilter: %s\n", pcap_geterr(*pcap)); exit(1); } } #ifdef BIOCLOCK /* * If we are reading from an device (not a file), then * lock the underlying BPF device to prevent changes in the * unprivileged child */ if (dev != NULL && ioctl(pcap_fileno(*pcap), BIOCLOCK) < 0) { fprintf(stderr, "ioctl(BIOCLOCK) failed: %s\n", strerror(errno)); exit(1); } #endif } static void init_flowtrack(struct FLOWTRACK *ft) { /* Set up flow-tracking structure */ memset(ft, '\0', sizeof(*ft)); ft->next_flow_seq = 1; FLOW_INIT(&ft->flows); EXPIRY_INIT(&ft->expiries); freelist_init(&ft->flow_freelist, sizeof(struct FLOW)); freelist_init(&ft->expiry_freelist, sizeof(struct EXPIRY)); ft->max_flows = DEFAULT_MAX_FLOWS; ft->track_level = TRACK_FULL; ft->tcp_timeout = DEFAULT_TCP_TIMEOUT; ft->tcp_rst_timeout = DEFAULT_TCP_RST_TIMEOUT; ft->tcp_fin_timeout = DEFAULT_TCP_FIN_TIMEOUT; ft->udp_timeout = DEFAULT_UDP_TIMEOUT; ft->icmp_timeout = DEFAULT_ICMP_TIMEOUT; ft->general_timeout = DEFAULT_GENERAL_TIMEOUT; ft->maximum_lifetime = DEFAULT_MAXIMUM_LIFETIME; ft->expiry_interval = DEFAULT_EXPIRY_INTERVAL; } static char * argv_join(int argc, char **argv) { int i; size_t ret_len; char *ret; ret_len = 0; ret = NULL; for (i = 0; i < argc; i++) { ret_len += strlen(argv[i]); if ((ret = realloc(ret, ret_len + 2)) == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(1); } if (i == 0) ret[0] = '\0'; else { ret_len++; /* Make room for ' ' */ strlcat(ret, " ", ret_len + 1); } strlcat(ret, argv[i], ret_len + 1); } return (ret); } /* Display commandline usage information */ static void usage(void) { fprintf(stderr, "Usage: %s [options] [bpf_program]\n" "This is %s version %s. Valid commandline options:\n" " -i [idx:]interface Specify interface to listen on\n" " -r pcap_file Specify packet capture file to read\n" " -t timeout=time Specify named timeout\n" " -m max_flows Specify maximum number of flows to track (default %d)\n" " -n host:port Send Cisco NetFlow(tm)-compatible packets to host:port\n" " -p pidfile Record pid in specified file\n" " (default: %s)\n" " -c pidfile Location of control socket\n" " (default: %s)\n" " -v 1|5|9 NetFlow export packet version\n" " -L hoplimit Set TTL/hoplimit for export datagrams\n" " -T full|proto|ip Set flow tracking level (default: full)\n" " -6 Track IPv6 flows, regardless of whether selected \n" " NetFlow export protocol supports it\n" " -d Don't daemonise (run in foreground)\n" " -D Debug mode: foreground + verbosity + track v6 flows\n" " -h Display this help\n" "\n" "Valid timeout names and default values:\n" " tcp (default %6d)" " tcp.rst (default %6d)" " tcp.fin (default %6d)\n" " udp (default %6d)" " icmp (default %6d)" " general (default %6d)\n" " maxlife (default %6d)" " expint (default %6d)\n" "\n" , PROGNAME, PROGNAME, PROGVER, DEFAULT_MAX_FLOWS, DEFAULT_PIDFILE, DEFAULT_CTLSOCK, DEFAULT_TCP_TIMEOUT, DEFAULT_TCP_RST_TIMEOUT, DEFAULT_TCP_FIN_TIMEOUT, DEFAULT_UDP_TIMEOUT, DEFAULT_ICMP_TIMEOUT, DEFAULT_GENERAL_TIMEOUT, DEFAULT_MAXIMUM_LIFETIME, DEFAULT_EXPIRY_INTERVAL); } static void set_timeout(struct FLOWTRACK *ft, const char *to_spec) { char *name, *value; int timeout; if ((name = strdup(to_spec)) == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } if ((value = strchr(name, '=')) == NULL || *(++value) == '\0') { fprintf(stderr, "Invalid -t option \"%s\".\n", name); usage(); exit(1); } *(value - 1) = '\0'; timeout = convtime(value); if (timeout < 0) { fprintf(stderr, "Invalid -t timeout.\n"); usage(); exit(1); } if (strcmp(name, "tcp") == 0) ft->tcp_timeout = timeout; else if (strcmp(name, "tcp.rst") == 0) ft->tcp_rst_timeout = timeout; else if (strcmp(name, "tcp.fin") == 0) ft->tcp_fin_timeout = timeout; else if (strcmp(name, "udp") == 0) ft->udp_timeout = timeout; else if (strcmp(name, "icmp") == 0) ft->icmp_timeout = timeout; else if (strcmp(name, "general") == 0) ft->general_timeout = timeout; else if (strcmp(name, "maxlife") == 0) ft->maximum_lifetime = timeout; else if (strcmp(name, "expint") == 0) ft->expiry_interval = timeout; else { fprintf(stderr, "Invalid -t name.\n"); usage(); exit(1); } if (ft->general_timeout == 0) { fprintf(stderr, "\"general\" flow timeout must be " "greater than zero\n"); exit(1); } free(name); } static void parse_hostport(const char *s, struct sockaddr *addr, socklen_t *len) { char *orig, *host, *port; struct addrinfo hints, *res; int herr; if ((host = orig = strdup(s)) == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } if ((port = strrchr(host, ':')) == NULL || *(++port) == '\0' || *host == '\0') { fprintf(stderr, "Invalid -n argument.\n"); usage(); exit(1); } *(port - 1) = '\0'; /* Accept [host]:port for numeric IPv6 addresses */ if (*host == '[' && *(port - 2) == ']') { host++; *(port - 2) = '\0'; } memset(&hints, '\0', sizeof(hints)); hints.ai_socktype = SOCK_DGRAM; if ((herr = getaddrinfo(host, port, &hints, &res)) == -1) { fprintf(stderr, "Address lookup failed: %s\n", gai_strerror(herr)); exit(1); } if (res == NULL || res->ai_addr == NULL) { fprintf(stderr, "No addresses found for [%s]:%s\n", host, port); exit(1); } if (res->ai_addrlen > *len) { fprintf(stderr, "Address too long\n"); exit(1); } memcpy(addr, res->ai_addr, res->ai_addrlen); free(orig); *len = res->ai_addrlen; } /* * Drop privileges and chroot, will exit on failure */ static void drop_privs(void) { struct passwd *pw; if ((pw = getpwnam(PRIVDROP_USER)) == NULL) { logit(LOG_ERR, "Unable to find unprivileged user \"%s\"", PRIVDROP_USER); exit(1); } if (chdir(PRIVDROP_CHROOT_DIR) != 0) { logit(LOG_ERR, "Unable to chdir to chroot directory \"%s\": %s", PRIVDROP_CHROOT_DIR, strerror(errno)); exit(1); } if (chroot(PRIVDROP_CHROOT_DIR) != 0) { logit(LOG_ERR, "Unable to chroot to directory \"%s\": %s", PRIVDROP_CHROOT_DIR, strerror(errno)); exit(1); } if (chdir("/") != 0) { logit(LOG_ERR, "Unable to chdir to chroot root: %s", strerror(errno)); exit(1); } if (setgroups(1, &pw->pw_gid) != 0) { logit(LOG_ERR, "Couldn't setgroups (%u): %s", (unsigned int)pw->pw_gid, strerror(errno)); exit(1); } #if defined(HAVE_SETRESGID) if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) { #elif defined(HAVE_SETREGID) if (setregid(pw->pw_gid, pw->pw_gid) == -1) { #else if (setegid(pw->pw_gid) == -1 || setgid(pw->pw_gid) == -1) { #endif logit(LOG_ERR, "Couldn't set gid (%u): %s", (unsigned int)pw->pw_gid, strerror(errno)); exit(1); } #if defined(HAVE_SETRESUID) if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) { #elif defined(HAVE_SETREUID) if (setreuid(pw->pw_uid, pw->pw_uid) == -1) { #else if (seteuid(pw->pw_uid) == -1 || setuid(pw->pw_uid) == -1) { #endif logit(LOG_ERR, "Couldn't set uid (%u): %s", (unsigned int)pw->pw_uid, strerror(errno)); exit(1); } } int main(int argc, char **argv) { char *dev, *capfile, *bpf_prog, dest_addr[256], dest_serv[256]; const char *pidfile_path, *ctlsock_path; extern char *optarg; extern int optind; int ch, dontfork_flag, linktype, ctlsock, i, err, always_v6, r; int stop_collection_flag, exit_request, hoplimit; pcap_t *pcap = NULL; struct sockaddr_storage dest; struct FLOWTRACK flowtrack; socklen_t dest_len; struct NETFLOW_TARGET target; struct CB_CTXT cb_ctxt; struct pollfd pl[2]; closefrom(STDERR_FILENO + 1); init_flowtrack(&flowtrack); memset(&dest, '\0', sizeof(dest)); dest_len = 0; memset(&target, '\0', sizeof(target)); target.fd = -1; target.dialect = &nf[0]; hoplimit = -1; bpf_prog = NULL; ctlsock = -1; dev = capfile = NULL; pidfile_path = DEFAULT_PIDFILE; ctlsock_path = DEFAULT_CTLSOCK; dontfork_flag = 0; always_v6 = 0; while ((ch = getopt(argc, argv, "6hdDL:T:i:r:f:t:n:m:p:c:v:")) != -1) { switch (ch) { case '6': always_v6 = 1; break; case 'h': usage(); return (0); case 'D': verbose_flag = 1; always_v6 = 1; /* FALLTHROUGH */ case 'd': dontfork_flag = 1; break; case 'i': if (capfile != NULL || dev != NULL) { fprintf(stderr, "Packet source already " "specified.\n\n"); usage(); exit(1); } dev = strsep(&optarg, ":"); if (optarg != NULL) { if_index = (u_int16_t) atoi(dev); dev = optarg; } if (verbose_flag) fprintf(stderr, "Using %s (idx: %d)\n", dev, if_index); break; case 'r': if (capfile != NULL || dev != NULL) { fprintf(stderr, "Packet source already " "specified.\n\n"); usage(); exit(1); } capfile = optarg; dontfork_flag = 1; ctlsock_path = NULL; break; case 't': /* Will exit on failure */ set_timeout(&flowtrack, optarg); break; case 'T': if (strcasecmp(optarg, "full") == 0) flowtrack.track_level = TRACK_FULL; else if (strcasecmp(optarg, "proto") == 0) flowtrack.track_level = TRACK_IP_PROTO; else if (strcasecmp(optarg, "ip") == 0) flowtrack.track_level = TRACK_IP_ONLY; else { fprintf(stderr, "Unknown flow tracking " "level\n"); usage(); exit(1); } break; case 'L': hoplimit = atoi(optarg); if (hoplimit < 0 || hoplimit > 255) { fprintf(stderr, "Invalid hop limit\n\n"); usage(); exit(1); } break; case 'm': if ((flowtrack.max_flows = atoi(optarg)) < 0) { fprintf(stderr, "Invalid maximum flows\n\n"); usage(); exit(1); } break; case 'n': /* Will exit on failure */ dest_len = sizeof(dest); parse_hostport(optarg, (struct sockaddr *)&dest, &dest_len); break; case 'p': pidfile_path = optarg; break; case 'c': if (strcmp(optarg, "none") == 0) ctlsock_path = NULL; else ctlsock_path = optarg; break; case 'v': for(i = 0, r = atoi(optarg); nf[i].version != -1; i++) { if (nf[i].version == r) break; } if (nf[i].version == -1) { fprintf(stderr, "Invalid NetFlow version\n"); exit(1); } target.dialect = &nf[i]; break; default: fprintf(stderr, "Invalid commandline option.\n"); usage(); exit(1); } } if (capfile == NULL && dev == NULL) { fprintf(stderr, "-i or -r option not specified.\n"); usage(); exit(1); } /* join remaining arguments (if any) into bpf program */ bpf_prog = argv_join(argc - optind, argv + optind); /* Will exit on failure */ setup_packet_capture(&pcap, &linktype, dev, capfile, bpf_prog, target.dialect->v6_capable || always_v6); /* Netflow send socket */ if (dest.ss_family != 0) { if ((err = getnameinfo((struct sockaddr *)&dest, dest_len, dest_addr, sizeof(dest_addr), dest_serv, sizeof(dest_serv), NI_NUMERICHOST)) == -1) { fprintf(stderr, "getnameinfo: %d\n", err); exit(1); } target.fd = connsock(&dest, dest_len, hoplimit); } /* Control socket */ if (ctlsock_path != NULL) ctlsock = unix_listener(ctlsock_path); /* Will exit on fail */ if (dontfork_flag) { loginit(PROGNAME, 1); } else { FILE *pidfile; daemon(0, 0); loginit(PROGNAME, 0); if ((pidfile = fopen(pidfile_path, "w")) == NULL) { fprintf(stderr, "Couldn't open pidfile %s: %s\n", pidfile_path, strerror(errno)); exit(1); } fprintf(pidfile, "%u\n", getpid()); fclose(pidfile); signal(SIGINT, sighand_graceful_shutdown); signal(SIGTERM, sighand_graceful_shutdown); signal(SIGSEGV, sighand_other); setprotoent(1); drop_privs(); } logit(LOG_NOTICE, "%s v%s starting data collection", PROGNAME, PROGVER); if (dest.ss_family != 0) { logit(LOG_NOTICE, "Exporting flows to [%s]:%s", dest_addr, dest_serv); } /* Main processing loop */ gettimeofday(&flowtrack.system_boot_time, NULL); stop_collection_flag = 0; memset(&cb_ctxt, '\0', sizeof(cb_ctxt)); cb_ctxt.ft = &flowtrack; cb_ctxt.linktype = linktype; cb_ctxt.want_v6 = target.dialect->v6_capable || always_v6; for (r = 0; graceful_shutdown_request == 0; r = 0) { /* * Silly libpcap's timeout function doesn't work, so we * do it here (only if we are reading live) */ if (capfile == NULL) { memset(pl, '\0', sizeof(pl)); /* This can only be set via the control socket */ if (!stop_collection_flag) { pl[0].events = POLLIN|POLLERR|POLLHUP; pl[0].fd = pcap_fileno(pcap); } if (ctlsock != -1) { pl[1].fd = ctlsock; pl[1].events = POLLIN|POLLERR|POLLHUP; } r = poll(pl, (ctlsock == -1) ? 1 : 2, next_expire(&flowtrack)); if (r == -1 && errno != EINTR) { logit(LOG_ERR, "Exiting on poll: %s", strerror(errno)); break; } } /* Accept connection on control socket if present */ if (ctlsock != -1 && pl[1].revents != 0) { if (accept_control(ctlsock, &target, &flowtrack, pcap, &exit_request, &stop_collection_flag) != 0) break; } /* If we have data, run it through libpcap */ if (!stop_collection_flag && (capfile != NULL || pl[0].revents != 0)) { r = pcap_dispatch(pcap, flowtrack.max_flows, flow_cb, (void*)&cb_ctxt); if (r == -1) { logit(LOG_ERR, "Exiting on pcap_dispatch: %s", pcap_geterr(pcap)); break; } else if (r == 0) { logit(LOG_NOTICE, "Shutting down after " "pcap EOF"); graceful_shutdown_request = 1; break; } } r = 0; /* Fatal error from per-packet functions */ if (cb_ctxt.fatal) { logit(LOG_WARNING, "Fatal error - exiting immediately"); break; } /* * Expiry processing happens every recheck_rate seconds * or whenever we have exceeded the maximum number of active * flows */ if (flowtrack.num_flows > flowtrack.max_flows || next_expire(&flowtrack) == 0) { expiry_check: /* * If we are reading from a capture file, we never * expire flows based on time - instead we only * expire flows when the flow table is full. */ if (check_expired(&flowtrack, &target, capfile == NULL ? CE_EXPIRE_NORMAL : CE_EXPIRE_FORCED) < 0) logit(LOG_WARNING, "Unable to export flows"); /* * If we are over max_flows, force-expire the oldest * out first and immediately reprocess to evict them */ if (flowtrack.num_flows > flowtrack.max_flows) { force_expire(&flowtrack, flowtrack.num_flows - flowtrack.max_flows); goto expiry_check; } } } /* Flags set by signal handlers or control socket */ if (graceful_shutdown_request) { logit(LOG_WARNING, "Shutting down on user request"); check_expired(&flowtrack, &target, CE_EXPIRE_ALL); } else if (exit_request) logit(LOG_WARNING, "Exiting immediately on user request"); else logit(LOG_ERR, "Exiting immediately on internal error"); if (capfile != NULL && dontfork_flag) statistics(&flowtrack, stdout, pcap); pcap_close(pcap); if (target.fd != -1) close(target.fd); unlink(pidfile_path); if (ctlsock_path != NULL) unlink(ctlsock_path); return(r == 0 ? 0 : 1); }
C
/* * Copyright (c) 2004 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "common.h" #ifndef HAVE_CLOSEFROM #include <sys/types.h> #include <sys/param.h> #include <unistd.h> #include <stdio.h> #include <limits.h> #include <stdlib.h> #include <stddef.h> #ifdef HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # ifdef HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # ifdef HAVE_SYS_DIR_H # include <sys/dir.h> # endif # ifdef HAVE_NDIR_H # include <ndir.h> # endif #endif #ifndef OPEN_MAX # define OPEN_MAX 256 #endif RCSID("$Id$"); #ifndef lint static const char rcsid[] = "$Sudo: closefrom.c,v 1.6 2004/06/01 20:51:56 millert Exp $"; #endif /* lint */ /* * Close all file descriptors greater than or equal to lowfd. */ void closefrom(int lowfd) { long fd, maxfd; #if defined(HAVE_DIRFD) && defined(HAVE_PROC_PID) char fdpath[PATH_MAX], *endp; struct dirent *dent; DIR *dirp; int len; /* Check for a /proc/$$/fd directory. */ len = snprintf(fdpath, sizeof(fdpath), "/proc/%ld/fd", (long)getpid()); if (len != -1 && len <= sizeof(fdpath) && (dirp = opendir(fdpath))) { while ((dent = readdir(dirp)) != NULL) { fd = strtol(dent->d_name, &endp, 10); if (dent->d_name != endp && *endp == '\0' && fd >= 0 && fd < INT_MAX && fd >= lowfd && fd != dirfd(dirp)) (void) close((int) fd); } (void) closedir(dirp); } else #endif { /* * Fall back on sysconf() or getdtablesize(). We avoid checking * resource limits since it is possible to open a file descriptor * and then drop the rlimit such that it is below the open fd. */ #ifdef HAVE_SYSCONF maxfd = sysconf(_SC_OPEN_MAX); #else maxfd = getdtablesize(); #endif /* HAVE_SYSCONF */ if (maxfd < 0) maxfd = OPEN_MAX; for (fd = lowfd; fd < maxfd; fd++) (void) close((int) fd); } } #endif /* HAVE_CLOSEFROM */
C
/* OPENBSD ORIGINAL: lib/libc/string/strlcpy.c */ /* $OpenBSD: strlcpy.c,v 1.8 2003/06/17 21:56:24 millert Exp $ */ /* * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "common.h" #ifndef HAVE_STRLCPY RCSID("$Id$"); #if defined(LIBC_SCCS) && !defined(lint) static char *rcsid = "$OpenBSD: strlcpy.c,v 1.8 2003/06/17 21:56:24 millert Exp $"; #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> #include <string.h> /* * Copy src to string dst of size siz. At most siz-1 characters * will be copied. Always NUL terminates (unless siz == 0). * Returns strlen(src); if retval >= siz, truncation occurred. */ size_t strlcpy(char *dst, const char *src, size_t siz) { register char *d = dst; register const char *s = src; register size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0 && --n != 0) { do { if ((*d++ = *s++) == 0) break; } while (--n != 0); } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) *d = '\0'; /* NUL-terminate dst */ while (*s++) ; } return(s - src - 1); /* count does not include NUL */ } #endif /* !HAVE_STRLCPY */
C
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ /* $Id$ */ /* Select our tree types for various data structures */ #if defined(FLOW_RB) #define FLOW_HEAD RB_HEAD #define FLOW_ENTRY RB_ENTRY #define FLOW_PROTOTYPE RB_PROTOTYPE #define FLOW_GENERATE RB_GENERATE #define FLOW_INSERT RB_INSERT #define FLOW_FIND RB_FIND #define FLOW_REMOVE RB_REMOVE #define FLOW_FOREACH RB_FOREACH #define FLOW_MIN RB_MIN #define FLOW_NEXT RB_NEXT #define FLOW_INIT RB_INIT #elif defined(FLOW_SPLAY) #define FLOW_HEAD SPLAY_HEAD #define FLOW_ENTRY SPLAY_ENTRY #define FLOW_PROTOTYPE SPLAY_PROTOTYPE #define FLOW_GENERATE SPLAY_GENERATE #define FLOW_INSERT SPLAY_INSERT #define FLOW_FIND SPLAY_FIND #define FLOW_REMOVE SPLAY_REMOVE #define FLOW_FOREACH SPLAY_FOREACH #define FLOW_MIN SPLAY_MIN #define FLOW_NEXT SPLAY_NEXT #define FLOW_INIT SPLAY_INIT #else #error No flow tree type defined #endif #if defined(EXPIRY_RB) #define EXPIRY_HEAD RB_HEAD #define EXPIRY_ENTRY RB_ENTRY #define EXPIRY_PROTOTYPE RB_PROTOTYPE #define EXPIRY_GENERATE RB_GENERATE #define EXPIRY_INSERT RB_INSERT #define EXPIRY_FIND RB_FIND #define EXPIRY_REMOVE RB_REMOVE #define EXPIRY_FOREACH RB_FOREACH #define EXPIRY_MIN RB_MIN #define EXPIRY_NEXT RB_NEXT #define EXPIRY_INIT RB_INIT #elif defined(EXPIRY_SPLAY) #define EXPIRY_HEAD SPLAY_HEAD #define EXPIRY_ENTRY SPLAY_ENTRY #define EXPIRY_PROTOTYPE SPLAY_PROTOTYPE #define EXPIRY_GENERATE SPLAY_GENERATE #define EXPIRY_INSERT SPLAY_INSERT #define EXPIRY_FIND SPLAY_FIND #define EXPIRY_REMOVE SPLAY_REMOVE #define EXPIRY_FOREACH SPLAY_FOREACH #define EXPIRY_MIN SPLAY_MIN #define EXPIRY_NEXT SPLAY_NEXT #define EXPIRY_INIT SPLAY_INIT #else #error No expiry tree type defined #endif
C
/* OPENBSD ORIGINAL: lib/libc/gen/daemon.c */ /*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * 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. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #include "common.h" #ifndef HAVE_DAEMON #if defined(LIBC_SCCS) && !defined(lint) static char rcsid[] = "$OpenBSD: daemon.c,v 1.5 2003/07/15 17:32:41 deraadt Exp $"; #endif /* LIBC_SCCS and not lint */ int daemon(int nochdir, int noclose) { int fd; switch (fork()) { case -1: return (-1); case 0: #ifdef HAVE_CYGWIN register_9x_service(); #endif break; default: #ifdef HAVE_CYGWIN /* * This sleep avoids a race condition which kills the * child process if parent is started by a NT/W2K service. */ sleep(1); #endif _exit(0); } if (setsid() == -1) return (-1); if (!nochdir) (void)chdir("/"); if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { (void)dup2(fd, STDIN_FILENO); (void)dup2(fd, STDOUT_FILENO); (void)dup2(fd, STDERR_FILENO); if (fd > 2) (void)close (fd); } return (0); } #endif /* !HAVE_DAEMON */
C
/* * Copyright (c) 2002 Damien Miller. All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #ifndef _SOFTFLOWD_H #define _SOFTFLOWD_H #include "common.h" #include "sys-tree.h" #include "freelist.h" #include "treetype.h" /* User to setuid to and directory to chroot to when we drop privs */ #ifndef PRIVDROP_USER # define PRIVDROP_USER "nobody" #endif #ifndef PRIVDROP_CHROOT_DIR # define PRIVDROP_CHROOT_DIR "/var/empty" #endif /* * Capture length for libpcap: Must fit the link layer header, plus * a maximally sized ip/ipv6 header and most of a TCP header */ #define LIBPCAP_SNAPLEN_V4 96 #define LIBPCAP_SNAPLEN_V6 160 /* * Timeouts */ #define DEFAULT_TCP_TIMEOUT 3600 #define DEFAULT_TCP_RST_TIMEOUT 120 #define DEFAULT_TCP_FIN_TIMEOUT 300 #define DEFAULT_UDP_TIMEOUT 300 #define DEFAULT_ICMP_TIMEOUT 300 #define DEFAULT_GENERAL_TIMEOUT 3600 #define DEFAULT_MAXIMUM_LIFETIME (3600*24*7) #define DEFAULT_EXPIRY_INTERVAL 60 /* * Default maximum number of flow to track simultaneously * 8192 corresponds to just under 1Mb of flow data */ #define DEFAULT_MAX_FLOWS 8192 /* Store a couple of statistics, maybe more in the future */ struct STATISTIC { double min, mean, max; }; /* Flow tracking levels */ #define TRACK_FULL 1 /* src/dst/addr/port/proto 5-tuple */ #define TRACK_IP_PROTO 2 /* src/dst/proto 3-tuple */ #define TRACK_IP_ONLY 3 /* src/dst tuple */ /* * This structure is the root of the flow tracking system. * It holds the root of the tree of active flows and the head of the * tree of expiry events. It also collects miscellaneous statistics */ struct FLOWTRACK { /* The flows and their expiry events */ FLOW_HEAD(FLOWS, FLOW) flows; /* Top of flow tree */ EXPIRY_HEAD(EXPIRIES, EXPIRY) expiries; /* Top of expiries tree */ struct freelist flow_freelist; /* Freelist for flows */ struct freelist expiry_freelist; /* Freelist for expiry events */ unsigned int num_flows; /* # of active flows */ unsigned int max_flows; /* Max # of active flows */ u_int64_t next_flow_seq; /* Next flow ID */ /* Stuff related to flow export */ struct timeval system_boot_time; /* SysUptime */ int track_level; /* See TRACK_* above */ /* Flow timeouts */ int tcp_timeout; /* Open TCP connections */ int tcp_rst_timeout; /* TCP flows after RST */ int tcp_fin_timeout; /* TCP flows after bidi FIN */ int udp_timeout; /* UDP flows */ int icmp_timeout; /* ICMP flows */ int general_timeout; /* Everything else */ int maximum_lifetime; /* Maximum life for flows */ int expiry_interval; /* Interval between expiries */ /* Statistics */ u_int64_t total_packets; /* # of good packets */ u_int64_t frag_packets; /* # of fragmented packets */ u_int64_t non_ip_packets; /* # of not-IP packets */ u_int64_t bad_packets; /* # of bad packets */ u_int64_t flows_expired; /* # expired */ u_int64_t flows_exported; /* # of flows sent */ u_int64_t flows_dropped; /* # of flows dropped */ u_int64_t flows_force_expired; /* # of flows forced out */ u_int64_t packets_sent; /* # netflow packets sent */ struct STATISTIC duration; /* Flow duration */ struct STATISTIC octets; /* Bytes (bidir) */ struct STATISTIC packets; /* Packets (bidir) */ /* Per protocol statistics */ u_int64_t flows_pp[256]; u_int64_t octets_pp[256]; u_int64_t packets_pp[256]; struct STATISTIC duration_pp[256]; /* Timeout statistics */ u_int64_t expired_general; u_int64_t expired_tcp; u_int64_t expired_tcp_rst; u_int64_t expired_tcp_fin; u_int64_t expired_udp; u_int64_t expired_icmp; u_int64_t expired_maxlife; u_int64_t expired_overbytes; u_int64_t expired_maxflows; u_int64_t expired_flush; }; /* * This structure is an entry in the tree of flows that we are * currently tracking. * * Because flows are matched _bi-directionally_, they must be stored in * a canonical format: the numerically lowest address and port number must * be stored in the first address and port array slot respectively. */ struct FLOW { /* Housekeeping */ struct EXPIRY *expiry; /* Pointer to expiry record */ FLOW_ENTRY(FLOW) trp; /* Tree pointer */ /* Flow identity (all are in network byte order) */ int af; /* Address family of flow */ u_int32_t ip6_flowlabel[2]; /* IPv6 Flowlabel */ union { struct in_addr v4; struct in6_addr v6; } addr[2]; /* Endpoint addresses */ u_int16_t port[2]; /* Endpoint ports */ u_int8_t tcp_flags[2]; /* Cumulative OR of flags */ u_int8_t protocol; /* Protocol */ /* Per-flow statistics (all in _host_ byte order) */ u_int64_t flow_seq; /* Flow ID */ struct timeval flow_start; /* Time of creation */ struct timeval flow_last; /* Time of last traffic */ /* Per-endpoint statistics (all in _host_ byte order) */ u_int32_t octets[2]; /* Octets so far */ u_int32_t packets[2]; /* Packets so far */ }; /* * This is an entry in the tree of expiry events. The tree is used to * avoid traversion the whole tree of active flows looking for ones to * expire. "expires_at" is the time at which the flow should be discarded, * or zero if it is scheduled for immediate disposal. * * When a flow which hasn't been scheduled for immediate expiry registers * traffic, it is deleted from its current position in the tree and * re-inserted (subject to its updated timeout). * * Expiry scans operate by starting at the head of the tree and expiring * each entry with expires_at < now * */ struct EXPIRY { EXPIRY_ENTRY(EXPIRY) trp; /* Tree pointer */ struct FLOW *flow; /* pointer to flow */ u_int32_t expires_at; /* time_t */ enum { R_GENERAL, R_TCP, R_TCP_RST, R_TCP_FIN, R_UDP, R_ICMP, R_MAXLIFE, R_OVERBYTES, R_OVERFLOWS, R_FLUSH } reason; }; /* Prototype for functions shared from softflowd.c */ u_int32_t timeval_sub_ms(const struct timeval *t1, const struct timeval *t2); /* Prototypes for functions to send NetFlow packets, from netflow*.c */ int send_netflow_v1(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag); int send_netflow_v5(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag); int send_netflow_v9(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag); /* Force a resend of the flow template */ void netflow9_resend_template(void); #endif /* _SOFTFLOWD_H */
C
/* * Copyright (c) 2001 Kevin Steves. All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #include "common.h" #include "convtime.h" RCSID("$Id$"); #define SECONDS 1 #define MINUTES (SECONDS * 60) #define HOURS (MINUTES * 60) #define DAYS (HOURS * 24) #define WEEKS (DAYS * 7) long int convtime(const char *s) { long total, secs; const char *p; char *endp; errno = 0; total = 0; p = s; if (p == NULL || *p == '\0') return -1; while (*p) { secs = strtol(p, &endp, 10); if (p == endp || (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) || secs < 0) return -1; switch (*endp++) { case '\0': endp--; case 's': case 'S': break; case 'm': case 'M': secs *= MINUTES; break; case 'h': case 'H': secs *= HOURS; break; case 'd': case 'D': secs *= DAYS; break; case 'w': case 'W': secs *= WEEKS; break; default: return -1; } total += secs; if (total < 0) return -1; p = endp; } return total; }
C
/* $OpenBSD: tree.h,v 1.9 2004/11/24 18:10:42 tdeval Exp $ */ /* * Copyright 2002 Niels Provos <provos@citi.umich.edu> * All rights reserved. * * 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 AUTHOR ``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 AUTHOR 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. */ #ifndef _SYS_TREE_H_ #define _SYS_TREE_H_ /* * This file defines data structures for different types of trees: * splay trees and red-black trees. * * A splay tree is a self-organizing data structure. Every operation * on the tree causes a splay to happen. The splay moves the requested * node to the root of the tree and partly rebalances it. * * This has the benefit that request locality causes faster lookups as * the requested nodes move to the top of the tree. On the other hand, * every lookup causes memory writes. * * The Balance Theorem bounds the total access time for m operations * and n inserts on an initially empty tree as O((m + n)lg n). The * amortized cost for a sequence of m accesses to a splay tree is O(lg n); * * A red-black tree is a binary search tree with the node color as an * extra attribute. It fulfills a set of conditions: * - every search path from the root to a leaf consists of the * same number of black nodes, * - each red node (except for the root) has a black parent, * - each leaf node is black. * * Every operation on a red-black tree is bounded as O(lg n). * The maximum height of a red-black tree is 2lg (n+1). */ #define SPLAY_HEAD(name, type) \ struct name { \ struct type *sph_root; /* root of the tree */ \ } #define SPLAY_INITIALIZER(root) \ { NULL } #define SPLAY_INIT(root) do { \ (root)->sph_root = NULL; \ } while (0) #define SPLAY_ENTRY(type) \ struct { \ struct type *spe_left; /* left element */ \ struct type *spe_right; /* right element */ \ } #define SPLAY_LEFT(elm, field) (elm)->field.spe_left #define SPLAY_RIGHT(elm, field) (elm)->field.spe_right #define SPLAY_ROOT(head) (head)->sph_root #define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL) /* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */ #define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ (head)->sph_root = tmp; \ } while (0) #define SPLAY_ROTATE_LEFT(head, tmp, field) do { \ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \ SPLAY_LEFT(tmp, field) = (head)->sph_root; \ (head)->sph_root = tmp; \ } while (0) #define SPLAY_LINKLEFT(head, tmp, field) do { \ SPLAY_LEFT(tmp, field) = (head)->sph_root; \ tmp = (head)->sph_root; \ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \ } while (0) #define SPLAY_LINKRIGHT(head, tmp, field) do { \ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ tmp = (head)->sph_root; \ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \ } while (0) #define SPLAY_ASSEMBLE(head, node, left, right, field) do { \ SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \ SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \ } while (0) /* Generates prototypes and inline functions */ #define SPLAY_PROTOTYPE(name, type, field, cmp) \ void name##_SPLAY(struct name *, struct type *); \ void name##_SPLAY_MINMAX(struct name *, int); \ struct type *name##_SPLAY_INSERT(struct name *, struct type *); \ struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \ \ /* Finds the node with the same key as elm */ \ static __inline struct type * \ name##_SPLAY_FIND(struct name *head, struct type *elm) \ { \ if (SPLAY_EMPTY(head)) \ return(NULL); \ name##_SPLAY(head, elm); \ if ((cmp)(elm, (head)->sph_root) == 0) \ return (head->sph_root); \ return (NULL); \ } \ \ static __inline struct type * \ name##_SPLAY_NEXT(struct name *head, struct type *elm) \ { \ name##_SPLAY(head, elm); \ if (SPLAY_RIGHT(elm, field) != NULL) { \ elm = SPLAY_RIGHT(elm, field); \ while (SPLAY_LEFT(elm, field) != NULL) { \ elm = SPLAY_LEFT(elm, field); \ } \ } else \ elm = NULL; \ return (elm); \ } \ \ static __inline struct type * \ name##_SPLAY_MIN_MAX(struct name *head, int val) \ { \ name##_SPLAY_MINMAX(head, val); \ return (SPLAY_ROOT(head)); \ } /* Main splay operation. * Moves node close to the key of elm to top */ #define SPLAY_GENERATE(name, type, field, cmp) \ struct type * \ name##_SPLAY_INSERT(struct name *head, struct type *elm) \ { \ if (SPLAY_EMPTY(head)) { \ SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \ } else { \ int __comp; \ name##_SPLAY(head, elm); \ __comp = (cmp)(elm, (head)->sph_root); \ if(__comp < 0) { \ SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\ SPLAY_RIGHT(elm, field) = (head)->sph_root; \ SPLAY_LEFT((head)->sph_root, field) = NULL; \ } else if (__comp > 0) { \ SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\ SPLAY_LEFT(elm, field) = (head)->sph_root; \ SPLAY_RIGHT((head)->sph_root, field) = NULL; \ } else \ return ((head)->sph_root); \ } \ (head)->sph_root = (elm); \ return (NULL); \ } \ \ struct type * \ name##_SPLAY_REMOVE(struct name *head, struct type *elm) \ { \ struct type *__tmp; \ if (SPLAY_EMPTY(head)) \ return (NULL); \ name##_SPLAY(head, elm); \ if ((cmp)(elm, (head)->sph_root) == 0) { \ if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\ } else { \ __tmp = SPLAY_RIGHT((head)->sph_root, field); \ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\ name##_SPLAY(head, elm); \ SPLAY_RIGHT((head)->sph_root, field) = __tmp; \ } \ return (elm); \ } \ return (NULL); \ } \ \ void \ name##_SPLAY(struct name *head, struct type *elm) \ { \ struct type __node, *__left, *__right, *__tmp; \ int __comp; \ \ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ __left = __right = &__node; \ \ while ((__comp = (cmp)(elm, (head)->sph_root))) { \ if (__comp < 0) { \ __tmp = SPLAY_LEFT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if ((cmp)(elm, __tmp) < 0){ \ SPLAY_ROTATE_RIGHT(head, __tmp, field); \ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKLEFT(head, __right, field); \ } else if (__comp > 0) { \ __tmp = SPLAY_RIGHT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if ((cmp)(elm, __tmp) > 0){ \ SPLAY_ROTATE_LEFT(head, __tmp, field); \ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKRIGHT(head, __left, field); \ } \ } \ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ } \ \ /* Splay with either the minimum or the maximum element \ * Used to find minimum or maximum element in tree. \ */ \ void name##_SPLAY_MINMAX(struct name *head, int __comp) \ { \ struct type __node, *__left, *__right, *__tmp; \ \ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ __left = __right = &__node; \ \ while (1) { \ if (__comp < 0) { \ __tmp = SPLAY_LEFT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if (__comp < 0){ \ SPLAY_ROTATE_RIGHT(head, __tmp, field); \ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKLEFT(head, __right, field); \ } else if (__comp > 0) { \ __tmp = SPLAY_RIGHT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if (__comp > 0) { \ SPLAY_ROTATE_LEFT(head, __tmp, field); \ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKRIGHT(head, __left, field); \ } \ } \ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ } #define SPLAY_NEGINF -1 #define SPLAY_INF 1 #define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y) #define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y) #define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y) #define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y) #define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \ : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF)) #define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \ : name##_SPLAY_MIN_MAX(x, SPLAY_INF)) #define SPLAY_FOREACH(x, name, head) \ for ((x) = SPLAY_MIN(name, head); \ (x) != NULL; \ (x) = SPLAY_NEXT(name, head, x)) /* Macros that define a red-black tree */ #define RB_HEAD(name, type) \ struct name { \ struct type *rbh_root; /* root of the tree */ \ } #define RB_INITIALIZER(root) \ { NULL } #define RB_INIT(root) do { \ (root)->rbh_root = NULL; \ } while (0) #define RB_BLACK 0 #define RB_RED 1 #define RB_ENTRY(type) \ struct { \ struct type *rbe_left; /* left element */ \ struct type *rbe_right; /* right element */ \ struct type *rbe_parent; /* parent element */ \ int rbe_color; /* node color */ \ } #define RB_LEFT(elm, field) (elm)->field.rbe_left #define RB_RIGHT(elm, field) (elm)->field.rbe_right #define RB_PARENT(elm, field) (elm)->field.rbe_parent #define RB_COLOR(elm, field) (elm)->field.rbe_color #define RB_ROOT(head) (head)->rbh_root #define RB_EMPTY(head) (RB_ROOT(head) == NULL) #define RB_SET(elm, parent, field) do { \ RB_PARENT(elm, field) = parent; \ RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \ RB_COLOR(elm, field) = RB_RED; \ } while (0) #define RB_SET_BLACKRED(black, red, field) do { \ RB_COLOR(black, field) = RB_BLACK; \ RB_COLOR(red, field) = RB_RED; \ } while (0) #ifndef RB_AUGMENT #define RB_AUGMENT(x) #endif #define RB_ROTATE_LEFT(head, elm, tmp, field) do { \ (tmp) = RB_RIGHT(elm, field); \ if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) { \ RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \ } \ RB_AUGMENT(elm); \ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ else \ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ } else \ (head)->rbh_root = (tmp); \ RB_LEFT(tmp, field) = (elm); \ RB_PARENT(elm, field) = (tmp); \ RB_AUGMENT(tmp); \ if ((RB_PARENT(tmp, field))) \ RB_AUGMENT(RB_PARENT(tmp, field)); \ } while (0) #define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \ (tmp) = RB_LEFT(elm, field); \ if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) { \ RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \ } \ RB_AUGMENT(elm); \ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ else \ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ } else \ (head)->rbh_root = (tmp); \ RB_RIGHT(tmp, field) = (elm); \ RB_PARENT(elm, field) = (tmp); \ RB_AUGMENT(tmp); \ if ((RB_PARENT(tmp, field))) \ RB_AUGMENT(RB_PARENT(tmp, field)); \ } while (0) /* Generates prototypes and inline functions */ #define RB_PROTOTYPE(name, type, field, cmp) \ void name##_RB_INSERT_COLOR(struct name *, struct type *); \ void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\ struct type *name##_RB_REMOVE(struct name *, struct type *); \ struct type *name##_RB_INSERT(struct name *, struct type *); \ struct type *name##_RB_FIND(struct name *, struct type *); \ struct type *name##_RB_NEXT(struct type *); \ struct type *name##_RB_MINMAX(struct name *, int); \ \ /* Main rb operation. * Moves node close to the key of elm to top */ #define RB_GENERATE(name, type, field, cmp) \ void \ name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \ { \ struct type *parent, *gparent, *tmp; \ while ((parent = RB_PARENT(elm, field)) && \ RB_COLOR(parent, field) == RB_RED) { \ gparent = RB_PARENT(parent, field); \ if (parent == RB_LEFT(gparent, field)) { \ tmp = RB_RIGHT(gparent, field); \ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ RB_COLOR(tmp, field) = RB_BLACK; \ RB_SET_BLACKRED(parent, gparent, field);\ elm = gparent; \ continue; \ } \ if (RB_RIGHT(parent, field) == elm) { \ RB_ROTATE_LEFT(head, parent, tmp, field);\ tmp = parent; \ parent = elm; \ elm = tmp; \ } \ RB_SET_BLACKRED(parent, gparent, field); \ RB_ROTATE_RIGHT(head, gparent, tmp, field); \ } else { \ tmp = RB_LEFT(gparent, field); \ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ RB_COLOR(tmp, field) = RB_BLACK; \ RB_SET_BLACKRED(parent, gparent, field);\ elm = gparent; \ continue; \ } \ if (RB_LEFT(parent, field) == elm) { \ RB_ROTATE_RIGHT(head, parent, tmp, field);\ tmp = parent; \ parent = elm; \ elm = tmp; \ } \ RB_SET_BLACKRED(parent, gparent, field); \ RB_ROTATE_LEFT(head, gparent, tmp, field); \ } \ } \ RB_COLOR(head->rbh_root, field) = RB_BLACK; \ } \ \ void \ name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \ { \ struct type *tmp; \ while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \ elm != RB_ROOT(head)) { \ if (RB_LEFT(parent, field) == elm) { \ tmp = RB_RIGHT(parent, field); \ if (RB_COLOR(tmp, field) == RB_RED) { \ RB_SET_BLACKRED(tmp, parent, field); \ RB_ROTATE_LEFT(head, parent, tmp, field);\ tmp = RB_RIGHT(parent, field); \ } \ if ((RB_LEFT(tmp, field) == NULL || \ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ (RB_RIGHT(tmp, field) == NULL || \ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ RB_COLOR(tmp, field) = RB_RED; \ elm = parent; \ parent = RB_PARENT(elm, field); \ } else { \ if (RB_RIGHT(tmp, field) == NULL || \ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\ struct type *oleft; \ if ((oleft = RB_LEFT(tmp, field)))\ RB_COLOR(oleft, field) = RB_BLACK;\ RB_COLOR(tmp, field) = RB_RED; \ RB_ROTATE_RIGHT(head, tmp, oleft, field);\ tmp = RB_RIGHT(parent, field); \ } \ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ RB_COLOR(parent, field) = RB_BLACK; \ if (RB_RIGHT(tmp, field)) \ RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\ RB_ROTATE_LEFT(head, parent, tmp, field);\ elm = RB_ROOT(head); \ break; \ } \ } else { \ tmp = RB_LEFT(parent, field); \ if (RB_COLOR(tmp, field) == RB_RED) { \ RB_SET_BLACKRED(tmp, parent, field); \ RB_ROTATE_RIGHT(head, parent, tmp, field);\ tmp = RB_LEFT(parent, field); \ } \ if ((RB_LEFT(tmp, field) == NULL || \ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ (RB_RIGHT(tmp, field) == NULL || \ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ RB_COLOR(tmp, field) = RB_RED; \ elm = parent; \ parent = RB_PARENT(elm, field); \ } else { \ if (RB_LEFT(tmp, field) == NULL || \ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\ struct type *oright; \ if ((oright = RB_RIGHT(tmp, field)))\ RB_COLOR(oright, field) = RB_BLACK;\ RB_COLOR(tmp, field) = RB_RED; \ RB_ROTATE_LEFT(head, tmp, oright, field);\ tmp = RB_LEFT(parent, field); \ } \ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ RB_COLOR(parent, field) = RB_BLACK; \ if (RB_LEFT(tmp, field)) \ RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\ RB_ROTATE_RIGHT(head, parent, tmp, field);\ elm = RB_ROOT(head); \ break; \ } \ } \ } \ if (elm) \ RB_COLOR(elm, field) = RB_BLACK; \ } \ \ struct type * \ name##_RB_REMOVE(struct name *head, struct type *elm) \ { \ struct type *child, *parent, *old = elm; \ int color; \ if (RB_LEFT(elm, field) == NULL) \ child = RB_RIGHT(elm, field); \ else if (RB_RIGHT(elm, field) == NULL) \ child = RB_LEFT(elm, field); \ else { \ struct type *left; \ elm = RB_RIGHT(elm, field); \ while ((left = RB_LEFT(elm, field))) \ elm = left; \ child = RB_RIGHT(elm, field); \ parent = RB_PARENT(elm, field); \ color = RB_COLOR(elm, field); \ if (child) \ RB_PARENT(child, field) = parent; \ if (parent) { \ if (RB_LEFT(parent, field) == elm) \ RB_LEFT(parent, field) = child; \ else \ RB_RIGHT(parent, field) = child; \ RB_AUGMENT(parent); \ } else \ RB_ROOT(head) = child; \ if (RB_PARENT(elm, field) == old) \ parent = elm; \ (elm)->field = (old)->field; \ if (RB_PARENT(old, field)) { \ if (RB_LEFT(RB_PARENT(old, field), field) == old)\ RB_LEFT(RB_PARENT(old, field), field) = elm;\ else \ RB_RIGHT(RB_PARENT(old, field), field) = elm;\ RB_AUGMENT(RB_PARENT(old, field)); \ } else \ RB_ROOT(head) = elm; \ RB_PARENT(RB_LEFT(old, field), field) = elm; \ if (RB_RIGHT(old, field)) \ RB_PARENT(RB_RIGHT(old, field), field) = elm; \ if (parent) { \ left = parent; \ do { \ RB_AUGMENT(left); \ } while ((left = RB_PARENT(left, field))); \ } \ goto color; \ } \ parent = RB_PARENT(elm, field); \ color = RB_COLOR(elm, field); \ if (child) \ RB_PARENT(child, field) = parent; \ if (parent) { \ if (RB_LEFT(parent, field) == elm) \ RB_LEFT(parent, field) = child; \ else \ RB_RIGHT(parent, field) = child; \ RB_AUGMENT(parent); \ } else \ RB_ROOT(head) = child; \ color: \ if (color == RB_BLACK) \ name##_RB_REMOVE_COLOR(head, parent, child); \ return (old); \ } \ \ /* Inserts a node into the RB tree */ \ struct type * \ name##_RB_INSERT(struct name *head, struct type *elm) \ { \ struct type *tmp; \ struct type *parent = NULL; \ int comp = 0; \ tmp = RB_ROOT(head); \ while (tmp) { \ parent = tmp; \ comp = (cmp)(elm, parent); \ if (comp < 0) \ tmp = RB_LEFT(tmp, field); \ else if (comp > 0) \ tmp = RB_RIGHT(tmp, field); \ else \ return (tmp); \ } \ RB_SET(elm, parent, field); \ if (parent != NULL) { \ if (comp < 0) \ RB_LEFT(parent, field) = elm; \ else \ RB_RIGHT(parent, field) = elm; \ RB_AUGMENT(parent); \ } else \ RB_ROOT(head) = elm; \ name##_RB_INSERT_COLOR(head, elm); \ return (NULL); \ } \ \ /* Finds the node with the same key as elm */ \ struct type * \ name##_RB_FIND(struct name *head, struct type *elm) \ { \ struct type *tmp = RB_ROOT(head); \ int comp; \ while (tmp) { \ comp = cmp(elm, tmp); \ if (comp < 0) \ tmp = RB_LEFT(tmp, field); \ else if (comp > 0) \ tmp = RB_RIGHT(tmp, field); \ else \ return (tmp); \ } \ return (NULL); \ } \ \ struct type * \ name##_RB_NEXT(struct type *elm) \ { \ if (RB_RIGHT(elm, field)) { \ elm = RB_RIGHT(elm, field); \ while (RB_LEFT(elm, field)) \ elm = RB_LEFT(elm, field); \ } else { \ if (RB_PARENT(elm, field) && \ (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ elm = RB_PARENT(elm, field); \ else { \ while (RB_PARENT(elm, field) && \ (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\ elm = RB_PARENT(elm, field); \ elm = RB_PARENT(elm, field); \ } \ } \ return (elm); \ } \ \ struct type * \ name##_RB_MINMAX(struct name *head, int val) \ { \ struct type *tmp = RB_ROOT(head); \ struct type *parent = NULL; \ while (tmp) { \ parent = tmp; \ if (val < 0) \ tmp = RB_LEFT(tmp, field); \ else \ tmp = RB_RIGHT(tmp, field); \ } \ return (parent); \ } #define RB_NEGINF -1 #define RB_INF 1 #define RB_INSERT(name, x, y) name##_RB_INSERT(x, y) #define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y) #define RB_FIND(name, x, y) name##_RB_FIND(x, y) #define RB_NEXT(name, x, y) name##_RB_NEXT(y) #define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF) #define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF) #define RB_FOREACH(x, name, head) \ for ((x) = RB_MIN(name, head); \ (x) != NULL; \ (x) = name##_RB_NEXT(x)) #endif /* _SYS_TREE_H_ */
C
#include "Encrypt.h" // if test #if 0 #define SRC_FILE_PATH "test" #define KEY_CODE "123485" #define SHOW_FILE_CMD "" #else #define SRC_FILE_PATH argv[1] #define DST_FILE_PATH argv[1] #define KEY_CODE argv[2] #define SHOW_FILE_CMD argv[3] #endif #define MY_DEBUG printf int main(int argc,char **argv) { struct st_byte_stream *src = NULL; char *src_path = NULL, *encrypt_key_str = NULL; unsigned char *key_buffer; unsigned int key_len = 0; long int file_len = 0; if (SRC_FILE_PATH) { if (KEY_CODE) { encrypt_key_str = KEY_CODE; } else { MY_DEBUG("Param Er @%d\n",__LINE__); return 0; } } else { MY_DEBUG("Param Er @%d\n",__LINE__); return 0; } src = encrypt_open(SRC_FILE_PATH, &src_path); if (!src) { MY_DEBUG("Init Er @%d\n",__LINE__); return 0; } MY_DEBUG("@%s%s @Key: %s\n", src->m_Ew?"Create":"Open", src->m_Type?"File:":"String:\n\t", src_path, encrypt_key_str); //MY_DEBUG("begin...\n"); key_len = STRLEN(KEY_CODE); key_buffer = MALLOC(key_len+1); if (NULL == key_buffer) { MY_DEBUG("Malloc Er @%d\n",__LINE__); encrypt_close(&src); return 0; } MEMCPY(key_buffer,encrypt_key_str,key_len); FILE_SEEK_END(src,0); file_len = FILE_TELL(src); FILE_SEEK_SET(src, 0); encrypt_stream(src, src, file_len, key_buffer, key_len); encrypt_close(&src); //MY_DEBUG("\nOk\n"); FREE(key_buffer); key_buffer = NULL; if (SHOW_FILE_CMD) { char cmdbuffer[256]; MY_DEBUG("\nShow %s:\n",src_path); sprintf(cmdbuffer,"%s %s",SHOW_FILE_CMD,src_path); system(cmdbuffer); //MY_DEBUG("^_^\n"); } return 0; }
C
/* *Copyright (c) 2009,(>WangXi<) *All rights reserved. *File Name:XXByteStrm.h/XXByteStrm.c *Description:This file define a SimClass for ByteStream Operation *version:1.0 *Author:chaoswizard@163.com(>WX<) *Create Date:Dec.14th.2009 */ #ifndef __XBYTESTRM_H__ #define __XBYTESTRM_H__ #include "XXtypeDef.h" #include <stdio.h> #define STRM_BUF_S 0x0 /*Static Alloc Array b000*/ #define STRM_BUF_D 0x4/*Dynamic Alloc Array b100*/ #define STRM_FILE_R 0x5/*Read existed File and Append b101*/ #define STRM_FILE_W 0x7/*Create new File and Append b111*/ struct st_byte_stream {// union { BYTE *Array; FILE *fp; }handle; BYTE m_Type:1;// 1 is file, 0 isArray BYTE m_Ew:1;// 1 is create new,0 is use existed BYTE m_Einc:1;// 1 is Append More,0 is can not //-------member variable----------- DWORD m_Size; long m_Position; //current position FILE *dumpFile; //-------member interface----------- void (*ShowAttri)(struct st_byte_stream *,int line); DWORD (*GetSize)(struct st_byte_stream *); long (*Tell)(struct st_byte_stream *); BOOL (*Eof)(struct st_byte_stream *); void (*Seek)(struct st_byte_stream *,long offset, int origin); int (*ReadByte)(struct st_byte_stream *); int (*Read)(struct st_byte_stream *,void *buffer, int size, int count); BOOL (*PutC)(struct st_byte_stream *stream,int c); int (*Write)(struct st_byte_stream *,const void *buffer, int size, int count); void (*Close)(struct st_byte_stream **,BOOL destoryHandle); void (*Dump)(struct st_byte_stream *,int length); void (*InitDumpFile)(struct st_byte_stream *,BYTE * name); void (*CloseDumpFile)(struct st_byte_stream *); }; //////////////////////////////////////////////////////////// //create one bytestream,MUST judge the return value,0 means failed else means successful. BOOL open_bytestrm(struct st_byte_stream **stream,void *src_data_or_path,DWORD capacity, BYTE mode); //void Print_HexStrm(FILE *dumpFile,BYTE *SrcData,int length); ////////////////////////////////////////////////////////// #endif
C
#ifndef __XTYPEDEF_H__ #define __XTYPEDEF_H__ typedef unsigned char BYTE;//8 bit typedef unsigned short WORD;//16 bit typedef unsigned long DWORD;//32 bit typedef unsigned int UINT; typedef DWORD COLORREF; typedef unsigned int HANDLE; typedef void* HRGN; #ifndef BOOL #define BOOL UINT #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef NULL #define NULL (void *)0 #endif #endif
C
#ifndef __MACRO_PUB_DEFINE_H__ #define __MACRO_PUB_DEFINE_H__ #include "malloc.h" #define MALLOC(size) malloc(size) #define FREE(ptr) free(ptr) //========================================================== #include "XXByteStrm.h" #define FILE_READ(fp, buffer, len) ((fp)->Read(fp, buffer , 1, len)) #define FILE_WRITE(fp, buffer, len) ((fp)->Write(fp, buffer, 1, len)) #define FILE_SEEK_SET(fp, pos) ((fp)->Seek(fp, pos, SEEK_SET)) #define FILE_SEEK_END(fp, pos) ((fp)->Seek(fp, pos, SEEK_END)) #define FILE_TELL(fp) ((fp)->Tell(fp)) #define FILE_CLOSE(fp) ((fp)->Close(&(fp), TRUE)) #include "string.h" #define STRLEN(str) strlen(str) #define MEMCPY(d, s, l) memcpy(d, s, l) #endif
C
#ifndef __MYENCRYPT_H__ #define __MYENCRYPT_H__ #include "macro_pub_define.h" struct st_byte_stream *encrypt_open(const char *path, char **real_path); int encrypt_close(struct st_byte_stream **src_stream); int encrypt_stream(struct st_byte_stream *dest, struct st_byte_stream *src, long int len, const char *key_data, int key_len); #endif
C
/*- * 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 target-subr.c * @brief Target-related subroutines. (ie. determine target type, print target, etc.) */ #include <inttypes.h> #include <nfc/nfc.h> #include "target-subr.h" struct card_atqa { uint16_t atqa; uint16_t mask; char type[128]; // list of up to 8 SAK values compatible with this ATQA int saklist[8]; }; struct card_sak { uint8_t sak; uint8_t mask; char type[128]; }; struct card_atqa const_ca[] = { { 0x0044, 0xffff, "MIFARE Ultralight", {0, -1} }, { 0x0044, 0xffff, "MIFARE Ultralight C", {0, -1} }, { 0x0004, 0xff0f, "MIFARE Mini 0.3K", {1, -1} }, { 0x0004, 0xff0f, "MIFARE Classic 1K", {2, -1} }, { 0x0002, 0xff0f, "MIFARE Classic 4K", {3, -1} }, { 0x0004, 0xffff, "MIFARE Plus (4 Byte UID or 4 Byte RID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0002, 0xffff, "MIFARE Plus (4 Byte UID or 4 Byte RID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0044, 0xffff, "MIFARE Plus (7 Byte UID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0042, 0xffff, "MIFARE Plus (7 Byte UID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0344, 0xffff, "MIFARE DESFire", {10, 11, -1} }, { 0x0044, 0xffff, "P3SR008", { -1} }, // TODO we need SAK info { 0x0004, 0xf0ff, "SmartMX with MIFARE 1K emulation", {12, -1} }, { 0x0002, 0xf0ff, "SmartMX with MIFARE 4K emulation", {12, -1} }, { 0x0048, 0xf0ff, "SmartMX with 7 Byte UID", {12, -1} } }; struct card_sak const_cs[] = { {0x00, 0xff, "" }, // 00 MIFARE Ultralight / Ultralight C {0x09, 0xff, "" }, // 01 MIFARE Mini 0.3K {0x08, 0xff, "" }, // 02 MIFARE Classic 1K {0x18, 0xff, "" }, // 03 MIFARE Classik 4K {0x08, 0xff, " 2K, Security level 1" }, // 04 MIFARE Plus {0x18, 0xff, " 4K, Security level 1" }, // 05 MIFARE Plus {0x10, 0xff, " 2K, Security level 2" }, // 06 MIFARE Plus {0x11, 0xff, " 4K, Security level 2" }, // 07 MIFARE Plus {0x20, 0xff, " 2K, Security level 3" }, // 08 MIFARE Plus {0x20, 0xff, " 4K, Security level 3" }, // 09 MIFARE Plus {0x20, 0xff, " 4K" }, // 10 MIFARE DESFire {0x20, 0xff, " EV1 2K/4K/8K" }, // 11 MIFARE DESFire {0x00, 0x00, "" }, // 12 SmartMX }; int snprint_hex(char *dst, size_t size, const uint8_t *pbtData, const size_t szBytes) { size_t szPos; size_t res = 0; for (szPos = 0; szPos < szBytes; szPos++) { res += snprintf(dst + res, size - res, "%02x ", pbtData[szPos]); } res += snprintf(dst + res, size - res, "\n"); return res; } #define SAK_UID_NOT_COMPLETE 0x04 #define SAK_ISO14443_4_COMPLIANT 0x20 #define SAK_ISO18092_COMPLIANT 0x40 void snprint_nfc_iso14443a_info(char *dst, size_t size, const nfc_iso14443a_info *pnai, bool verbose) { int off = 0; off += snprintf(dst + off, size - off, " ATQA (SENS_RES): "); off += snprint_hex(dst + off, size - off, pnai->abtAtqa, 2); if (verbose) { off += snprintf(dst + off, size - off, "* UID size: "); switch ((pnai->abtAtqa[1] & 0xc0) >> 6) { case 0: off += snprintf(dst + off, size - off, "single\n"); break; case 1: off += snprintf(dst + off, size - off, "double\n"); break; case 2: off += snprintf(dst + off, size - off, "triple\n"); break; case 3: off += snprintf(dst + off, size - off, "RFU\n"); break; } off += snprintf(dst + off, size - off, "* bit frame anticollision "); switch (pnai->abtAtqa[1] & 0x1f) { case 0x01: case 0x02: case 0x04: case 0x08: case 0x10: off += snprintf(dst + off, size - off, "supported\n"); break; default: off += snprintf(dst + off, size - off, "not supported\n"); break; } } off += snprintf(dst + off, size - off, " UID (NFCID%c): ", (pnai->abtUid[0] == 0x08 ? '3' : '1')); off += snprint_hex(dst + off, size - off, pnai->abtUid, pnai->szUidLen); if (verbose) { if (pnai->abtUid[0] == 0x08) { off += snprintf(dst + off, size - off, "* Random UID\n"); } } off += snprintf(dst + off, size - off, " SAK (SEL_RES): "); off += snprint_hex(dst + off, size - off, &pnai->btSak, 1); if (verbose) { if (pnai->btSak & SAK_UID_NOT_COMPLETE) { off += snprintf(dst + off, size - off, "* Warning! Cascade bit set: UID not complete\n"); } if (pnai->btSak & SAK_ISO14443_4_COMPLIANT) { off += snprintf(dst + off, size - off, "* Compliant with ISO/IEC 14443-4\n"); } else { off += snprintf(dst + off, size - off, "* Not compliant with ISO/IEC 14443-4\n"); } if (pnai->btSak & SAK_ISO18092_COMPLIANT) { off += snprintf(dst + off, size - off, "* Compliant with ISO/IEC 18092\n"); } else { off += snprintf(dst + off, size - off, "* Not compliant with ISO/IEC 18092\n"); } } if (pnai->szAtsLen) { off += snprintf(dst + off, size - off, " ATS: "); off += snprint_hex(dst + off, size - off, pnai->abtAts, pnai->szAtsLen); } if (pnai->szAtsLen && verbose) { // Decode ATS according to ISO/IEC 14443-4 (5.2 Answer to select) const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 }; off += snprintf(dst + off, size - off, "* Max Frame Size accepted by PICC: %d bytes\n", iMaxFrameSizes[pnai->abtAts[0] & 0x0F]); size_t offset = 1; if (pnai->abtAts[0] & 0x10) { // TA(1) present uint8_t TA = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, "* Bit Rate Capability:\n"); if (TA == 0) { off += snprintf(dst + off, size - off, " * PICC supports only 106 kbits/s in both directions\n"); } if (TA & 1 << 7) { off += snprintf(dst + off, size - off, " * Same bitrate in both directions mandatory\n"); } if (TA & 1 << 4) { off += snprintf(dst + off, size - off, " * PICC to PCD, DS=2, bitrate 212 kbits/s supported\n"); } if (TA & 1 << 5) { off += snprintf(dst + off, size - off, " * PICC to PCD, DS=4, bitrate 424 kbits/s supported\n"); } if (TA & 1 << 6) { off += snprintf(dst + off, size - off, " * PICC to PCD, DS=8, bitrate 847 kbits/s supported\n"); } if (TA & 1 << 0) { off += snprintf(dst + off, size - off, " * PCD to PICC, DR=2, bitrate 212 kbits/s supported\n"); } if (TA & 1 << 1) { off += snprintf(dst + off, size - off, " * PCD to PICC, DR=4, bitrate 424 kbits/s supported\n"); } if (TA & 1 << 2) { off += snprintf(dst + off, size - off, " * PCD to PICC, DR=8, bitrate 847 kbits/s supported\n"); } if (TA & 1 << 3) { off += snprintf(dst + off, size - off, " * ERROR unknown value\n"); } } if (pnai->abtAts[0] & 0x20) { // TB(1) present uint8_t TB = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, "* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((TB & 0xf0) >> 4)) / 13560.0); if ((TB & 0x0f) == 0) { off += snprintf(dst + off, size - off, "* No Start-up Frame Guard Time required\n"); } else { off += snprintf(dst + off, size - off, "* Start-up Frame Guard Time: %.4g ms\n", 256.0 * 16.0 * (1 << (TB & 0x0f)) / 13560.0); } } if (pnai->abtAts[0] & 0x40) { // TC(1) present uint8_t TC = pnai->abtAts[offset]; offset++; if (TC & 0x1) { off += snprintf(dst + off, size - off, "* Node Address supported\n"); } else { off += snprintf(dst + off, size - off, "* Node Address not supported\n"); } if (TC & 0x2) { off += snprintf(dst + off, size - off, "* Card IDentifier supported\n"); } else { off += snprintf(dst + off, size - off, "* Card IDentifier not supported\n"); } } if (pnai->szAtsLen > offset) { off += snprintf(dst + off, size - off, "* Historical bytes Tk: "); off += snprint_hex(dst + off, size - off, pnai->abtAts + offset, (pnai->szAtsLen - offset)); uint8_t CIB = pnai->abtAts[offset]; offset++; if (CIB != 0x00 && CIB != 0x10 && (CIB & 0xf0) != 0x80) { off += snprintf(dst + off, size - off, " * Proprietary format\n"); if (CIB == 0xc1) { off += snprintf(dst + off, size - off, " * Tag byte: Mifare or virtual cards of various types\n"); uint8_t L = pnai->abtAts[offset]; offset++; if (L != (pnai->szAtsLen - offset)) { off += snprintf(dst + off, size - off, " * Warning: Type Identification Coding length (%i)", L); off += snprintf(dst + off, size - off, " not matching Tk length (%" PRIdPTR ")\n", (pnai->szAtsLen - offset)); } if ((pnai->szAtsLen - offset - 2) > 0) { // Omit 2 CRC bytes uint8_t CTC = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, " * Chip Type: "); switch (CTC & 0xf0) { case 0x00: off += snprintf(dst + off, size - off, "(Multiple) Virtual Cards\n"); break; case 0x10: off += snprintf(dst + off, size - off, "Mifare DESFire\n"); break; case 0x20: off += snprintf(dst + off, size - off, "Mifare Plus\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } off += snprintf(dst + off, size - off, " * Memory size: "); switch (CTC & 0x0f) { case 0x00: off += snprintf(dst + off, size - off, "<1 kbyte\n"); break; case 0x01: off += snprintf(dst + off, size - off, "1 kbyte\n"); break; case 0x02: off += snprintf(dst + off, size - off, "2 kbyte\n"); break; case 0x03: off += snprintf(dst + off, size - off, "4 kbyte\n"); break; case 0x04: off += snprintf(dst + off, size - off, "8 kbyte\n"); break; case 0x0f: off += snprintf(dst + off, size - off, "Unspecified\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } } if ((pnai->szAtsLen - offset) > 0) { // Omit 2 CRC bytes uint8_t CVC = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, " * Chip Status: "); switch (CVC & 0xf0) { case 0x00: off += snprintf(dst + off, size - off, "Engineering sample\n"); break; case 0x20: off += snprintf(dst + off, size - off, "Released\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } off += snprintf(dst + off, size - off, " * Chip Generation: "); switch (CVC & 0x0f) { case 0x00: off += snprintf(dst + off, size - off, "Generation 1\n"); break; case 0x01: off += snprintf(dst + off, size - off, "Generation 2\n"); break; case 0x02: off += snprintf(dst + off, size - off, "Generation 3\n"); break; case 0x0f: off += snprintf(dst + off, size - off, "Unspecified\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } } if ((pnai->szAtsLen - offset) > 0) { // Omit 2 CRC bytes uint8_t VCS = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, " * Specifics (Virtual Card Selection):\n"); if ((VCS & 0x09) == 0x00) { off += snprintf(dst + off, size - off, " * Only VCSL supported\n"); } else if ((VCS & 0x09) == 0x01) { off += snprintf(dst + off, size - off, " * VCS, VCSL and SVC supported\n"); } if ((VCS & 0x0e) == 0x00) { off += snprintf(dst + off, size - off, " * SL1, SL2(?), SL3 supported\n"); } else if ((VCS & 0x0e) == 0x02) { off += snprintf(dst + off, size - off, " * SL3 only card\n"); } else if ((VCS & 0x0f) == 0x0e) { off += snprintf(dst + off, size - off, " * No VCS command supported\n"); } else if ((VCS & 0x0f) == 0x0f) { off += snprintf(dst + off, size - off, " * Unspecified\n"); } else { off += snprintf(dst + off, size - off, " * RFU\n"); } } } } else { if (CIB == 0x00) { off += snprintf(dst + off, size - off, " * Tk after 0x00 consist of optional consecutive COMPACT-TLV data objects\n"); off += snprintf(dst + off, size - off, " followed by a mandatory status indicator (the last three bytes, not in TLV)\n"); off += snprintf(dst + off, size - off, " See ISO/IEC 7816-4 8.1.1.3 for more info\n"); } if (CIB == 0x10) { off += snprintf(dst + off, size - off, " * DIR data reference: %02x\n", pnai->abtAts[offset]); } if (CIB == 0x80) { if (pnai->szAtsLen == offset) { off += snprintf(dst + off, size - off, " * No COMPACT-TLV objects found, no status found\n"); } else { off += snprintf(dst + off, size - off, " * Tk after 0x80 consist of optional consecutive COMPACT-TLV data objects;\n"); off += snprintf(dst + off, size - off, " the last data object may carry a status indicator of one, two or three bytes.\n"); off += snprintf(dst + off, size - off, " See ISO/IEC 7816-4 8.1.1.3 for more info\n"); } } } } } if (verbose) { off += snprintf(dst + off, size - off, "\nFingerprinting based on MIFARE type Identification Procedure:\n"); // AN10833 uint16_t atqa = 0; uint8_t sak = 0; uint8_t i, j; bool found_possible_match = false; atqa = (((uint16_t)pnai->abtAtqa[0] & 0xff) << 8); atqa += (((uint16_t)pnai->abtAtqa[1] & 0xff)); sak = ((uint8_t)pnai->btSak & 0xff); for (i = 0; i < sizeof(const_ca) / sizeof(const_ca[0]); i++) { if ((atqa & const_ca[i].mask) == const_ca[i].atqa) { for (j = 0; (j < sizeof(const_ca[i].saklist) / sizeof(const_ca[i].saklist[0])) && (const_ca[i].saklist[j] >= 0); j++) { int sakindex = const_ca[i].saklist[j]; if ((sak & const_cs[sakindex].mask) == const_cs[sakindex].sak) { off += snprintf(dst + off, size - off, "* %s%s\n", const_ca[i].type, const_cs[sakindex].type); found_possible_match = true; } } } } // Other matches not described in // AN10833 MIFARE Type Identification Procedure // but seen in the field: off += snprintf(dst + off, size - off, "Other possible matches based on ATQA & SAK values:\n"); uint32_t atqasak = 0; atqasak += (((uint32_t)pnai->abtAtqa[0] & 0xff) << 16); atqasak += (((uint32_t)pnai->abtAtqa[1] & 0xff) << 8); atqasak += ((uint32_t)pnai->btSak & 0xff); switch (atqasak) { case 0x000488: off += snprintf(dst + off, size - off, "* Mifare Classic 1K Infineon\n"); found_possible_match = true; break; case 0x000298: off += snprintf(dst + off, size - off, "* Gemplus MPCOS\n"); found_possible_match = true; break; case 0x030428: off += snprintf(dst + off, size - off, "* JCOP31\n"); found_possible_match = true; break; case 0x004820: off += snprintf(dst + off, size - off, "* JCOP31 v2.4.1\n"); off += snprintf(dst + off, size - off, "* JCOP31 v2.2\n"); found_possible_match = true; break; case 0x000428: off += snprintf(dst + off, size - off, "* JCOP31 v2.3.1\n"); found_possible_match = true; break; case 0x000453: off += snprintf(dst + off, size - off, "* Fudan FM1208SH01\n"); found_possible_match = true; break; case 0x000820: off += snprintf(dst + off, size - off, "* Fudan FM1208\n"); found_possible_match = true; break; case 0x000238: off += snprintf(dst + off, size - off, "* MFC 4K emulated by Nokia 6212 Classic\n"); found_possible_match = true; break; case 0x000838: off += snprintf(dst + off, size - off, "* MFC 4K emulated by Nokia 6131 NFC\n"); found_possible_match = true; break; } if (! found_possible_match) { snprintf(dst + off, size - off, "* Unknown card, sorry\n"); } } } void snprint_nfc_felica_info(char *dst, size_t size, const nfc_felica_info *pnfi, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " ID (NFCID2): "); off += snprint_hex(dst + off, size - off, pnfi->abtId, 8); off += snprintf(dst + off, size - off, " Parameter (PAD): "); off += snprint_hex(dst + off, size - off, pnfi->abtPad, 8); off += snprintf(dst + off, size - off, " System Code (SC): "); snprint_hex(dst + off, size - off, pnfi->abtSysCode, 2); } void snprint_nfc_jewel_info(char *dst, size_t size, const nfc_jewel_info *pnji, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " ATQA (SENS_RES): "); off += snprint_hex(dst + off, size - off, pnji->btSensRes, 2); off += snprintf(dst + off, size - off, " 4-LSB JEWELID: "); snprint_hex(dst + off, size - off, pnji->btId, 4); } #define PI_ISO14443_4_SUPPORTED 0x01 #define PI_NAD_SUPPORTED 0x01 #define PI_CID_SUPPORTED 0x02 void snprint_nfc_iso14443b_info(char *dst, size_t size, const nfc_iso14443b_info *pnbi, bool verbose) { int off = 0; off += snprintf(dst + off, size - off, " PUPI: "); off += snprint_hex(dst + off, size - off, pnbi->abtPupi, 4); off += snprintf(dst + off, size - off, " Application Data: "); off += snprint_hex(dst + off, size - off, pnbi->abtApplicationData, 4); off += snprintf(dst + off, size - off, " Protocol Info: "); off += snprint_hex(dst + off, size - off, pnbi->abtProtocolInfo, 3); if (verbose) { off += snprintf(dst + off, size - off, "* Bit Rate Capability:\n"); if (pnbi->abtProtocolInfo[0] == 0) { off += snprintf(dst + off, size - off, " * PICC supports only 106 kbits/s in both directions\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 7) { off += snprintf(dst + off, size - off, " * Same bitrate in both directions mandatory\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 4) { off += snprintf(dst + off, size - off, " * PICC to PCD, 1etu=64/fc, bitrate 212 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 5) { off += snprintf(dst + off, size - off, " * PICC to PCD, 1etu=32/fc, bitrate 424 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 6) { off += snprintf(dst + off, size - off, " * PICC to PCD, 1etu=16/fc, bitrate 847 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 0) { off += snprintf(dst + off, size - off, " * PCD to PICC, 1etu=64/fc, bitrate 212 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 1) { off += snprintf(dst + off, size - off, " * PCD to PICC, 1etu=32/fc, bitrate 424 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 2) { off += snprintf(dst + off, size - off, " * PCD to PICC, 1etu=16/fc, bitrate 847 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 3) { off += snprintf(dst + off, size - off, " * ERROR unknown value\n"); } if ((pnbi->abtProtocolInfo[1] & 0xf0) <= 0x80) { const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 }; off += snprintf(dst + off, size - off, "* Maximum frame sizes: %d bytes\n", iMaxFrameSizes[((pnbi->abtProtocolInfo[1] & 0xf0) >> 4)]); } if ((pnbi->abtProtocolInfo[1] & 0x01) == PI_ISO14443_4_SUPPORTED) { // in principle low nibble could only be 0000 or 0001 and other values are RFU // but in practice we found 0011 so let's use only last bit for -4 compatibility off += snprintf(dst + off, size - off, "* Protocol types supported: ISO/IEC 14443-4\n"); } off += snprintf(dst + off, size - off, "* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((pnbi->abtProtocolInfo[2] & 0xf0) >> 4)) / 13560.0); if ((pnbi->abtProtocolInfo[2] & (PI_NAD_SUPPORTED | PI_CID_SUPPORTED)) != 0) { off += snprintf(dst + off, size - off, "* Frame options supported: "); if ((pnbi->abtProtocolInfo[2] & PI_NAD_SUPPORTED) != 0) off += snprintf(dst + off, size - off, "NAD "); if ((pnbi->abtProtocolInfo[2] & PI_CID_SUPPORTED) != 0) off += snprintf(dst + off, size - off, "CID "); snprintf(dst + off, size - off, "\n"); } } } void snprint_nfc_iso14443bi_info(char *dst, size_t size, const nfc_iso14443bi_info *pnii, bool verbose) { int off = 0; off += snprintf(dst + off, size - off, " DIV: "); off += snprint_hex(dst + off, size - off, pnii->abtDIV, 4); if (verbose) { int version = (pnii->btVerLog & 0x1e) >> 1; off += snprintf(dst + off, size - off, " Software Version: "); if (version == 15) { off += snprintf(dst + off, size - off, "Undefined\n"); } else { off += snprintf(dst + off, size - off, "%i\n", version); } if ((pnii->btVerLog & 0x80) && (pnii->btConfig & 0x80)) { off += snprintf(dst + off, size - off, " Wait Enable: yes"); } } if ((pnii->btVerLog & 0x80) && (pnii->btConfig & 0x40)) { off += snprintf(dst + off, size - off, " ATS: "); snprint_hex(dst + off, size - off, pnii->abtAtr, pnii->szAtrLen); } } void snprint_nfc_iso14443b2sr_info(char *dst, size_t size, const nfc_iso14443b2sr_info *pnsi, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " UID: "); snprint_hex(dst + off, size - off, pnsi->abtUID, 8); } void snprint_nfc_iso14443b2ct_info(char *dst, size_t size, const nfc_iso14443b2ct_info *pnci, bool verbose) { (void) verbose; int off = 0; uint32_t uid; uid = (pnci->abtUID[3] << 24) + (pnci->abtUID[2] << 16) + (pnci->abtUID[1] << 8) + pnci->abtUID[0]; off += snprintf(dst + off, size - off, " UID: "); off += snprint_hex(dst + off, size - off, pnci->abtUID, sizeof(pnci->abtUID)); off += snprintf(dst + off, size - off, " UID (decimal): %010u\n", uid); off += snprintf(dst + off, size - off, " Product Code: %02X\n", pnci->btProdCode); snprintf(dst + off, size - off, " Fab Code: %02X\n", pnci->btFabCode); } void snprint_nfc_dep_info(char *dst, size_t size, const nfc_dep_info *pndi, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " NFCID3: "); off += snprint_hex(dst + off, size - off, pndi->abtNFCID3, 10); off += snprintf(dst + off, size - off, " BS: %02x\n", pndi->btBS); off += snprintf(dst + off, size - off, " BR: %02x\n", pndi->btBR); off += snprintf(dst + off, size - off, " TO: %02x\n", pndi->btTO); off += snprintf(dst + off, size - off, " PP: %02x\n", pndi->btPP); if (pndi->szGB) { off += snprintf(dst + off, size - off, "General Bytes: "); snprint_hex(dst + off, size - off, pndi->abtGB, pndi->szGB); } } void snprint_nfc_target(char *dst, size_t size, const nfc_target *pnt, bool verbose) { if (NULL != pnt) { int off = 0; off += snprintf(dst + off, size - off, "%s (%s%s) target:\n", str_nfc_modulation_type(pnt->nm.nmt), str_nfc_baud_rate(pnt->nm.nbr), (pnt->nm.nmt != NMT_DEP) ? "" : (pnt->nti.ndi.ndm == NDM_ACTIVE) ? "active mode" : "passive mode"); switch (pnt->nm.nmt) { case NMT_ISO14443A: snprint_nfc_iso14443a_info(dst + off, size - off, &pnt->nti.nai, verbose); break; case NMT_JEWEL: snprint_nfc_jewel_info(dst + off, size - off, &pnt->nti.nji, verbose); break; case NMT_FELICA: snprint_nfc_felica_info(dst + off, size - off, &pnt->nti.nfi, verbose); break; case NMT_ISO14443B: snprint_nfc_iso14443b_info(dst + off, size - off, &pnt->nti.nbi, verbose); break; case NMT_ISO14443BI: snprint_nfc_iso14443bi_info(dst + off, size - off, &pnt->nti.nii, verbose); break; case NMT_ISO14443B2SR: snprint_nfc_iso14443b2sr_info(dst + off, size - off, &pnt->nti.nsi, verbose); break; case NMT_ISO14443B2CT: snprint_nfc_iso14443b2ct_info(dst + off, size - off, &pnt->nti.nci, verbose); break; case NMT_DEP: snprint_nfc_dep_info(dst + off, size - off, &pnt->nti.ndi, verbose); break; } } }
C
/*- * 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/> */ #ifndef __LOG_INTERNAL_H__ #define __LOG_INTERNAL_H__ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdarg.h> // Internal methods so different platforms can route the logging // Offering both forms of the variadic function // These are implemented in the log_<platform> specific file void log_put_internal(const char *format, ...); void log_vput_internal(const char *format, va_list args); #endif // __LOG_INTERNAL_H__
C
/*- * 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 mirror-subr.c * @brief Mirror bytes */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include "mirror-subr.h" static const uint8_t ByteMirror[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff }; uint8_t mirror(uint8_t bt) { return ByteMirror[bt]; } static void mirror_bytes(uint8_t *pbts, size_t szLen) { size_t szByteNr; for (szByteNr = 0; szByteNr < szLen; szByteNr++) { *pbts = ByteMirror[*pbts]; pbts++; } } uint32_t mirror32(uint32_t ui32Bits) { mirror_bytes((uint8_t *) & ui32Bits, 4); return ui32Bits; } uint64_t mirror64(uint64_t ui64Bits) { mirror_bytes((uint8_t *) & ui64Bits, 8); return ui64Bits; }
C
/*- * 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/> */ #ifndef __NFC_CONF_H__ #define __NFC_CONF_H__ #include <nfc/nfc-types.h> void conf_load(nfc_context *context); #endif // __NFC_CONF_H__
C
/*- * 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-internal.c * @brief Provide some useful internal functions */ #include <nfc/nfc.h> #include "nfc-internal.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef CONFFILES #include "conf.h" #endif #include <stdlib.h> #include <string.h> #include <inttypes.h> #define LOG_GROUP NFC_LOG_GROUP_GENERAL #define LOG_CATEGORY "libnfc.general" void string_as_boolean(const char *s, bool *value) { if (s) { if (!(*value)) { if ((strcmp(s, "yes") == 0) || (strcmp(s, "true") == 0) || (strcmp(s, "1") == 0)) { *value = true; return; } } else { if ((strcmp(s, "no") == 0) || (strcmp(s, "false") == 0) || (strcmp(s, "0") == 0)) { *value = false; return; } } } } nfc_context * nfc_context_new(void) { nfc_context *res = malloc(sizeof(*res)); if (!res) { return NULL; } // Set default context values res->allow_autoscan = true; res->allow_intrusive_scan = false; #ifdef DEBUG res->log_level = 3; #else res->log_level = 1; #endif // Clear user defined devices array for (int i = 0; i < MAX_USER_DEFINED_DEVICES; i++) { strcpy(res->user_defined_devices[i].name, ""); strcpy(res->user_defined_devices[i].connstring, ""); res->user_defined_devices[i].optional = false; } res->user_defined_device_count = 0; #ifdef ENVVARS // Load user defined device from environment variable at first char *envvar = getenv("LIBNFC_DEFAULT_DEVICE"); if (envvar) { strcpy(res->user_defined_devices[0].name, "user defined default device"); strncpy(res->user_defined_devices[0].connstring, envvar, NFC_BUFSIZE_CONNSTRING); res->user_defined_devices[0].connstring[NFC_BUFSIZE_CONNSTRING - 1] = '\0'; res->user_defined_device_count++; } #endif // ENVVARS #ifdef CONFFILES // Load options from configuration file (ie. /etc/nfc/libnfc.conf) conf_load(res); #endif // CONFFILES #ifdef ENVVARS // Environment variables // Load user defined device from environment variable as the only reader envvar = getenv("LIBNFC_DEVICE"); if (envvar) { strcpy(res->user_defined_devices[0].name, "user defined device"); strncpy(res->user_defined_devices[0].connstring, envvar, NFC_BUFSIZE_CONNSTRING); res->user_defined_devices[0].connstring[NFC_BUFSIZE_CONNSTRING - 1] = '\0'; res->user_defined_device_count = 1; } // Load "auto scan" option envvar = getenv("LIBNFC_AUTO_SCAN"); string_as_boolean(envvar, &(res->allow_autoscan)); // Load "intrusive scan" option envvar = getenv("LIBNFC_INTRUSIVE_SCAN"); string_as_boolean(envvar, &(res->allow_intrusive_scan)); // log level envvar = getenv("LIBNFC_LOG_LEVEL"); if (envvar) { res->log_level = atoi(envvar); } #endif // ENVVARS // Initialize log before use it... log_init(res); // Debug context state #if defined DEBUG log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_NONE, "log_level is set to %"PRIu32, res->log_level); #else log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "log_level is set to %"PRIu32, res->log_level); #endif log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "allow_autoscan is set to %s", (res->allow_autoscan) ? "true" : "false"); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "allow_intrusive_scan is set to %s", (res->allow_intrusive_scan) ? "true" : "false"); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d device(s) defined by user", res->user_defined_device_count); for (uint32_t i = 0; i < res->user_defined_device_count; i++) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, " #%d name: \"%s\", connstring: \"%s\"", i, res->user_defined_devices[i].name, res->user_defined_devices[i].connstring); } return res; } void nfc_context_free(nfc_context *context) { log_exit(); free(context); } void prepare_initiator_data(const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t *pszInitiatorData) { switch (nm.nmt) { case NMT_ISO14443B: { // Application Family Identifier (AFI) must equals 0x00 in order to wakeup all ISO14443-B PICCs (see ISO/IEC 14443-3) *ppbtInitiatorData = (uint8_t *) "\x00"; *pszInitiatorData = 1; } break; case NMT_ISO14443BI: { // APGEN *ppbtInitiatorData = (uint8_t *) "\x01\x0b\x3f\x80"; *pszInitiatorData = 4; } break; case NMT_ISO14443B2SR: { // Get_UID *ppbtInitiatorData = (uint8_t *) "\x0b"; *pszInitiatorData = 1; } break; case NMT_ISO14443B2CT: { // SELECT-ALL *ppbtInitiatorData = (uint8_t *) "\x9F\xFF\xFF"; *pszInitiatorData = 3; } break; case NMT_FELICA: { // polling payload must be present (see ISO/IEC 18092 11.2.2.5) *ppbtInitiatorData = (uint8_t *) "\x00\xff\xff\x01\x00"; *pszInitiatorData = 5; } break; case NMT_ISO14443A: case NMT_JEWEL: case NMT_DEP: *ppbtInitiatorData = NULL; *pszInitiatorData = 0; break; } } int connstring_decode(const nfc_connstring connstring, const char *driver_name, const char *bus_name, char **pparam1, char **pparam2) { if (driver_name == NULL) { driver_name = ""; } if (bus_name == NULL) { bus_name = ""; } int n = strlen(connstring) + 1; char *param0 = malloc(n); if (param0 == NULL) { perror("malloc"); return 0; } char *param1 = malloc(n); if (param1 == NULL) { perror("malloc"); free(param0); return 0; } char *param2 = malloc(n); if (param2 == NULL) { perror("malloc"); free(param0); free(param1); return 0; } char format[32]; snprintf(format, sizeof(format), "%%%i[^:]:%%%i[^:]:%%%i[^:]", n - 1, n - 1, n - 1); int res = sscanf(connstring, format, param0, param1, param2); if (res < 1 || ((0 != strcmp(param0, driver_name)) && (bus_name != NULL) && (0 != strcmp(param0, bus_name)))) { // Driver name does not match. res = 0; } if (pparam1 != NULL) { if (res < 2) { free(param1); *pparam1 = NULL; } else { *pparam1 = param1; } } else { free(param1); } if (pparam2 != NULL) { if (res < 3) { free(param2); *pparam2 = NULL; } else { *pparam2 = param2; } } else { free(param2); } free(param0); return res; }
C
/*- * 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/> */ #ifndef __LOG_H__ #define __LOG_H__ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "nfc-internal.h" #define NFC_LOG_PRIORITY_NONE 0 #define NFC_LOG_PRIORITY_ERROR 1 #define NFC_LOG_PRIORITY_INFO 2 #define NFC_LOG_PRIORITY_DEBUG 3 #define NFC_LOG_GROUP_GENERAL 1 #define NFC_LOG_GROUP_CONFIG 2 #define NFC_LOG_GROUP_CHIP 3 #define NFC_LOG_GROUP_DRIVER 4 #define NFC_LOG_GROUP_COM 5 #define NFC_LOG_GROUP_LIBUSB 6 /* To enable log only for one (or more) group, you can use this formula: log_level = NFC_LOG_PRIORITY(main) + NFC_LOG_PRIORITY(group) * 2 ^ (NFC_LOG_GROUP(group) * 2) Examples: * Main log level is NONE and only communication group log is set to DEBUG verbosity (for rx/tx trace): LIBNFC_LOG_LEVEL=3072 // 0+3072 * Main log level is ERROR and driver layer log is set to DEBUG level: LIBNFC_LOG_LEVEL=769 // 1+768 * Main log level is ERROR, driver layer is set to INFO and communication is set to DEBUG: LIBNFC_LOG_LEVEL=3585 // 1+512+3072 */ //int log_priority_to_int(const char* priority); const char *log_priority_to_str(const int priority); #if defined LOG # ifndef __has_attribute # define __has_attribute(x) 0 # endif # if __has_attribute(format) || defined(__GNUC__) # define __has_attribute_format 1 # endif void log_init(const nfc_context *context); void log_exit(void); void log_put(const uint8_t group, const char *category, const uint8_t priority, const char *format, ...) # if __has_attribute_format __attribute__((format(printf, 4, 5))) # endif ; #else // No logging #define log_init(nfc_context) ((void) 0) #define log_exit() ((void) 0) #define log_put(group, category, priority, format, ...) do {} while (0) #endif // LOG /** * @macro LOG_HEX * @brief Log a byte-array in hexadecimal format * Max values: pcTag of 121 bytes + ": " + 300 bytes of data+ "\0" => acBuf of 1024 bytes */ # ifdef LOG # define LOG_HEX(group, pcTag, pbtData, szBytes) do { \ size_t __szPos; \ char __acBuf[1024]; \ size_t __szBuf = 0; \ if ((int)szBytes < 0) { \ fprintf (stderr, "%s:%d: Attempt to print %d bytes!\n", __FILE__, __LINE__, (int)szBytes); \ log_put (group, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s:%d: Attempt to print %d bytes!\n", __FILE__, __LINE__, (int)szBytes); \ abort(); \ break; \ } \ snprintf (__acBuf + __szBuf, sizeof(__acBuf) - __szBuf, "%s: ", pcTag); \ __szBuf += strlen (pcTag) + 2; \ for (__szPos=0; (__szPos < (size_t)(szBytes)) && (__szBuf < sizeof(__acBuf)); __szPos++) { \ snprintf (__acBuf + __szBuf, sizeof(__acBuf) - __szBuf, "%02x ",((uint8_t *)(pbtData))[__szPos]); \ __szBuf += 3; \ } \ log_put (group, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", __acBuf); \ } while (0); # else # define LOG_HEX(group, pcTag, pbtData, szBytes) do { \ (void) group; \ (void) pcTag; \ (void) pbtData; \ (void) szBytes; \ } while (0); # endif #endif // __LOG_H__
C
/*- * 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/> */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "conf.h" #ifdef CONFFILES #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <regex.h> #include <sys/stat.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "log.h" #define LOG_CATEGORY "libnfc.config" #define LOG_GROUP NFC_LOG_GROUP_CONFIG #ifndef LIBNFC_SYSCONFDIR // If this define does not already exists, we build it using SYSCONFDIR #ifndef SYSCONFDIR #error "SYSCONFDIR is not defined but required." #endif // SYSCONFDIR #define LIBNFC_SYSCONFDIR SYSCONFDIR"/nfc" #endif // LIBNFC_SYSCONFDIR #define LIBNFC_CONFFILE LIBNFC_SYSCONFDIR"/libnfc.conf" #define LIBNFC_DEVICECONFDIR LIBNFC_SYSCONFDIR"/devices.d" static bool conf_parse_file(const char *filename, void (*conf_keyvalue)(void *data, const char *key, const char *value), void *data) { FILE *f = fopen(filename, "r"); if (!f) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Unable to open file: %s", filename); return false; } char line[BUFSIZ]; const char *str_regex = "^[[:space:]]*([[:alnum:]_.]+)[[:space:]]*=[[:space:]]*(\"(.+)\"|([^[:space:]]+))[[:space:]]*$"; regex_t preg; if (regcomp(&preg, str_regex, REG_EXTENDED | REG_NOTEOL) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Regular expression used for configuration file parsing is not valid."); fclose(f); return false; } size_t nmatch = preg.re_nsub + 1; regmatch_t *pmatch = malloc(sizeof(*pmatch) * nmatch); if (!pmatch) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Not enough memory: malloc failed."); regfree(&preg); fclose(f); return false; } int lineno = 0; while (fgets(line, BUFSIZ, f) != NULL) { lineno++; switch (line[0]) { case '#': case '\n': break; default: { int match; if ((match = regexec(&preg, line, nmatch, pmatch, 0)) == 0) { const size_t key_size = pmatch[1].rm_eo - pmatch[1].rm_so; const off_t value_pmatch = pmatch[3].rm_eo != -1 ? 3 : 4; const size_t value_size = pmatch[value_pmatch].rm_eo - pmatch[value_pmatch].rm_so; char key[key_size + 1]; char value[value_size + 1]; strncpy(key, line + (pmatch[1].rm_so), key_size); key[key_size] = '\0'; strncpy(value, line + (pmatch[value_pmatch].rm_so), value_size); value[value_size] = '\0'; conf_keyvalue(data, key, value); } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Parse error on line #%d: %s", lineno, line); } } break; } } free(pmatch); regfree(&preg); fclose(f); return false; } static void conf_keyvalue_context(void *data, const char *key, const char *value) { nfc_context *context = (nfc_context *)data; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "key: [%s], value: [%s]", key, value); if (strcmp(key, "allow_autoscan") == 0) { string_as_boolean(value, &(context->allow_autoscan)); } else if (strcmp(key, "allow_intrusive_scan") == 0) { string_as_boolean(value, &(context->allow_intrusive_scan)); } else if (strcmp(key, "log_level") == 0) { context->log_level = atoi(value); } else if (strcmp(key, "device.name") == 0) { if ((context->user_defined_device_count == 0) || strcmp(context->user_defined_devices[context->user_defined_device_count - 1].name, "") != 0) { if (context->user_defined_device_count >= MAX_USER_DEFINED_DEVICES) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Configuration exceeded maximum user-defined devices."); return; } context->user_defined_device_count++; } strncpy(context->user_defined_devices[context->user_defined_device_count - 1].name, value, DEVICE_NAME_LENGTH - 1); context->user_defined_devices[context->user_defined_device_count - 1].name[DEVICE_NAME_LENGTH - 1] = '\0'; } else if (strcmp(key, "device.connstring") == 0) { if ((context->user_defined_device_count == 0) || strcmp(context->user_defined_devices[context->user_defined_device_count - 1].connstring, "") != 0) { if (context->user_defined_device_count >= MAX_USER_DEFINED_DEVICES) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Configuration exceeded maximum user-defined devices."); return; } context->user_defined_device_count++; } strncpy(context->user_defined_devices[context->user_defined_device_count - 1].connstring, value, NFC_BUFSIZE_CONNSTRING - 1); context->user_defined_devices[context->user_defined_device_count - 1].connstring[NFC_BUFSIZE_CONNSTRING - 1] = '\0'; } else if (strcmp(key, "device.optional") == 0) { if ((context->user_defined_device_count == 0) || context->user_defined_devices[context->user_defined_device_count - 1].optional) { if (context->user_defined_device_count >= MAX_USER_DEFINED_DEVICES) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Configuration exceeded maximum user-defined devices."); return; } context->user_defined_device_count++; } if ((strcmp(value, "true") == 0) || (strcmp(value, "True") == 0) || (strcmp(value, "1") == 0)) //optional context->user_defined_devices[context->user_defined_device_count - 1].optional = true; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Unknown key in config line: %s = %s", key, value); } } static void conf_keyvalue_device(void *data, const char *key, const char *value) { char newkey[BUFSIZ]; sprintf(newkey, "device.%s", key); conf_keyvalue_context(data, newkey, value); } static void conf_devices_load(const char *dirname, nfc_context *context) { DIR *d = opendir(dirname); if (!d) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Unable to open directory: %s", dirname); } else { struct dirent *de; #ifdef WIN32 while ((de = readdir(d)) != NULL) { #else struct dirent entry; struct dirent *result; while ((readdir_r(d, &entry, &result) == 0) && (result != NULL)) { de = &entry; #endif if (de->d_name[0] != '.') { const size_t filename_len = strlen(de->d_name); const size_t extension_len = strlen(".conf"); if ((filename_len > extension_len) && (strncmp(".conf", de->d_name + (filename_len - extension_len), extension_len) == 0)) { char filename[BUFSIZ] = LIBNFC_DEVICECONFDIR"/"; strcat(filename, de->d_name); struct stat s; if (stat(filename, &s) == -1) { perror("stat"); continue; } if (S_ISREG(s.st_mode)) { conf_parse_file(filename, conf_keyvalue_device, context); } } } } closedir(d); } } void conf_load(nfc_context *context) { conf_parse_file(LIBNFC_CONFFILE, conf_keyvalue_context, context); conf_devices_load(LIBNFC_DEVICECONFDIR, context); } #endif // CONFFILES
C
/*- * 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-internal.h * @brief Internal defines and macros */ #ifndef __NFC_INTERNAL_H__ #define __NFC_INTERNAL_H__ #include <stdbool.h> #include <err.h> # include <sys/time.h> #include "nfc/nfc.h" #include "log.h" /** * @macro HAL * @brief Execute corresponding driver function if exists. */ #define HAL( FUNCTION, ... ) pnd->last_error = 0; \ if (pnd->driver->FUNCTION) { \ return pnd->driver->FUNCTION( __VA_ARGS__ ); \ } else { \ pnd->last_error = NFC_EDEVNOTSUPP; \ return false; \ } #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif /* * Buffer management macros. * * The following macros ease setting-up and using buffers: * BUFFER_INIT (data, 5); // data -> [ xx, xx, xx, xx, xx ] * BUFFER_SIZE (data); // size -> 0 * BUFFER_APPEND (data, 0x12); // data -> [ 12, xx, xx, xx, xx ] * BUFFER_SIZE (data); // size -> 1 * uint16_t x = 0x3456; // We suppose we are little endian * BUFFER_APPEND_BYTES (data, x, 2); * // data -> [ 12, 56, 34, xx, xx ] * BUFFER_SIZE (data); // size -> 3 * BUFFER_APPEND_LE (data, x, 2, sizeof (x)); * // data -> [ 12, 56, 34, 34, 56 ] * BUFFER_SIZE (data); // size -> 5 */ /* * Initialise a buffer named buffer_name of size bytes. */ #define BUFFER_INIT(buffer_name, size) \ uint8_t buffer_name[size]; \ size_t __##buffer_name##_n = 0 /* * Create a wrapper for an existing buffer. * BEWARE! It eats children! */ #define BUFFER_ALIAS(buffer_name, origin) \ uint8_t *buffer_name = (void *)origin; \ size_t __##buffer_name##_n = 0; #define BUFFER_SIZE(buffer_name) (__##buffer_name##_n) #define BUFFER_CLEAR(buffer_name) (__##buffer_name##_n = 0) /* * Append one byte of data to the buffer buffer_name. */ #define BUFFER_APPEND(buffer_name, data) \ do { \ buffer_name[__##buffer_name##_n++] = data; \ } while (0) /* * Append size bytes of data to the buffer buffer_name. */ #define BUFFER_APPEND_BYTES(buffer_name, data, size) \ do { \ size_t __n = 0; \ while (__n < size) { \ buffer_name[__##buffer_name##_n++] = ((uint8_t *)data)[__n++]; \ } \ } while (0) typedef enum { NOT_INTRUSIVE, INTRUSIVE, NOT_AVAILABLE, } scan_type_enum; struct nfc_driver { const char *name; const scan_type_enum scan_type; size_t (*scan)(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len); struct nfc_device *(*open)(const nfc_context *context, const nfc_connstring connstring); void (*close)(struct nfc_device *pnd); const char *(*strerror)(const struct nfc_device *pnd); int (*initiator_init)(struct nfc_device *pnd); int (*initiator_init_secure_element)(struct nfc_device *pnd); int (*initiator_select_passive_target)(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt); int (*initiator_poll_target)(struct nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t btPeriod, nfc_target *pnt); int (*initiator_select_dep_target)(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout); int (*initiator_deselect_target)(struct nfc_device *pnd); int (*initiator_transceive_bytes)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout); int (*initiator_transceive_bits)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar); int (*initiator_transceive_bytes_timed)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, uint32_t *cycles); int (*initiator_transceive_bits_timed)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles); int (*initiator_target_is_present)(struct nfc_device *pnd, const nfc_target *pnt); int (*target_init)(struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout); int (*target_send_bytes)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout); int (*target_receive_bytes)(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout); int (*target_send_bits)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar); int (*target_receive_bits)(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar); int (*device_set_property_bool)(struct nfc_device *pnd, const nfc_property property, const bool bEnable); int (*device_set_property_int)(struct nfc_device *pnd, const nfc_property property, const int value); int (*get_supported_modulation)(struct nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt); int (*get_supported_baud_rate)(struct nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); int (*device_get_information_about)(struct nfc_device *pnd, char **buf); int (*abort_command)(struct nfc_device *pnd); int (*idle)(struct nfc_device *pnd); int (*powerdown)(struct nfc_device *pnd); }; # define DEVICE_NAME_LENGTH 256 # define DEVICE_PORT_LENGTH 64 #define MAX_USER_DEFINED_DEVICES 4 struct nfc_user_defined_device { char name[DEVICE_NAME_LENGTH]; nfc_connstring connstring; bool optional; }; /** * @struct nfc_context * @brief NFC library context * Struct which contains internal options, references, pointers, etc. used by library */ struct nfc_context { bool allow_autoscan; bool allow_intrusive_scan; uint32_t log_level; struct nfc_user_defined_device user_defined_devices[MAX_USER_DEFINED_DEVICES]; unsigned int user_defined_device_count; }; nfc_context *nfc_context_new(void); void nfc_context_free(nfc_context *context); /** * @struct nfc_device * @brief NFC device information */ struct nfc_device { const nfc_context *context; const struct nfc_driver *driver; void *driver_data; void *chip_data; /** Device name string, including device wrapper firmware */ char name[DEVICE_NAME_LENGTH]; /** Device connection string */ nfc_connstring connstring; /** Is the CRC automaticly added, checked and removed from the frames */ bool bCrc; /** Does the chip handle parity bits, all parities are handled as data */ bool bPar; /** Should the chip handle frames encapsulation and chaining */ bool bEasyFraming; /** Should the chip try forever on select? */ bool bInfiniteSelect; /** Should the chip switch automatically activate ISO14443-4 when selecting tags supporting it? */ bool bAutoIso14443_4; /** Supported modulation encoded in a byte */ uint8_t btSupportByte; /** Last reported error */ int last_error; }; nfc_device *nfc_device_new(const nfc_context *context, const nfc_connstring connstring); void nfc_device_free(nfc_device *dev); void string_as_boolean(const char *s, bool *value); void iso14443_cascade_uid(const uint8_t abtUID[], const size_t szUID, uint8_t *pbtCascadedUID, size_t *pszCascadedUID); void prepare_initiator_data(const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t *pszInitiatorData); int connstring_decode(const nfc_connstring connstring, const char *driver_name, const char *bus_name, char **pparam1, char **pparam2); #endif // __NFC_INTERNAL_H__
C
/*- * 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.c * @brief NFC library implementation */ /** * @defgroup lib Library initialization/deinitialization * This page details how to initialize and deinitialize libnfc. Initialization * must be performed before using any libnfc functionality, and similarly you * must not call any libnfc functions after deinitialization. */ /** * @defgroup dev NFC Device/Hardware manipulation * The functionality documented below is designed to help with the following * operations: * - Enumerating the NFC devices currently attached to the system * - Opening and closing the chosen device */ /** * @defgroup initiator NFC initiator * This page details how to act as "reader". */ /** * @defgroup target NFC target * This page details how to act as tag (i.e. MIFARE Classic) or NFC target device. */ /** * @defgroup error Error reporting * Most libnfc functions return 0 on success or one of error codes defined on failure. */ /** * @defgroup data Special data accessors * The functionnality documented below allow to access to special data as device name or device connstring. */ /** * @defgroup properties Properties accessors * The functionnality documented below allow to configure parameters and registers. */ /** * @defgroup misc Miscellaneous * */ /** * @defgroup string-converter To-string converters * The functionnality documented below allow to retreive some information in text format. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "target-subr.h" #include "drivers.h" #if defined (DRIVER_ACR122_PCSC_ENABLED) # include "drivers/acr122_pcsc.h" #endif /* DRIVER_ACR122_PCSC_ENABLED */ #if defined (DRIVER_ACR122_USB_ENABLED) # include "drivers/acr122_usb.h" #endif /* DRIVER_ACR122_USB_ENABLED */ #if defined (DRIVER_ACR122S_ENABLED) # include "drivers/acr122s.h" #endif /* DRIVER_ACR122S_ENABLED */ #if defined (DRIVER_PN53X_USB_ENABLED) # include "drivers/pn53x_usb.h" #endif /* DRIVER_PN53X_USB_ENABLED */ #if defined (DRIVER_ARYGON_ENABLED) # include "drivers/arygon.h" #endif /* DRIVER_ARYGON_ENABLED */ #if defined (DRIVER_PN532_UART_ENABLED) # include "drivers/pn532_uart.h" #endif /* DRIVER_PN532_UART_ENABLED */ #if defined (DRIVER_PN532_SPI_ENABLED) # include "drivers/pn532_spi.h" #endif /* DRIVER_PN532_SPI_ENABLED */ #if defined (DRIVER_PN532_I2C_ENABLED) # include "drivers/pn532_i2c.h" #endif /* DRIVER_PN532_I2C_ENABLED */ #define LOG_CATEGORY "libnfc.general" #define LOG_GROUP NFC_LOG_GROUP_GENERAL struct nfc_driver_list { const struct nfc_driver_list *next; const struct nfc_driver *driver; }; const struct nfc_driver_list *nfc_drivers = NULL; static void nfc_drivers_init(void) { #if defined (DRIVER_PN53X_USB_ENABLED) nfc_register_driver(&pn53x_usb_driver); #endif /* DRIVER_PN53X_USB_ENABLED */ #if defined (DRIVER_ACR122_PCSC_ENABLED) nfc_register_driver(&acr122_pcsc_driver); #endif /* DRIVER_ACR122_PCSC_ENABLED */ #if defined (DRIVER_ACR122_USB_ENABLED) nfc_register_driver(&acr122_usb_driver); #endif /* DRIVER_ACR122_USB_ENABLED */ #if defined (DRIVER_ACR122S_ENABLED) nfc_register_driver(&acr122s_driver); #endif /* DRIVER_ACR122S_ENABLED */ #if defined (DRIVER_PN532_UART_ENABLED) nfc_register_driver(&pn532_uart_driver); #endif /* DRIVER_PN532_UART_ENABLED */ #if defined (DRIVER_PN532_SPI_ENABLED) nfc_register_driver(&pn532_spi_driver); #endif /* DRIVER_PN532_SPI_ENABLED */ #if defined (DRIVER_PN532_I2C_ENABLED) nfc_register_driver(&pn532_i2c_driver); #endif /* DRIVER_PN532_I2C_ENABLED */ #if defined (DRIVER_ARYGON_ENABLED) nfc_register_driver(&arygon_driver); #endif /* DRIVER_ARYGON_ENABLED */ } static int nfc_device_validate_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation *nm); /** @ingroup lib * @brief Register an NFC device driver with libnfc. * This function registers a driver with libnfc, the caller is responsible of managing the lifetime of the * driver and make sure that any resources associated with the driver are available after registration. * @param pnd Pointer to an NFC device driver to be registered. * @retval NFC_SUCCESS If the driver registration succeeds. */ int nfc_register_driver(const struct nfc_driver *ndr) { if (!ndr) return NFC_EINVARG; struct nfc_driver_list *pndl = (struct nfc_driver_list *)malloc(sizeof(struct nfc_driver_list)); if (!pndl) return NFC_ESOFT; pndl->driver = ndr; pndl->next = nfc_drivers; nfc_drivers = pndl; return NFC_SUCCESS; } /** @ingroup lib * @brief Initialize libnfc. * This function must be called before calling any other libnfc function * @param context Output location for nfc_context */ void nfc_init(nfc_context **context) { *context = nfc_context_new(); if (!*context) { perror("malloc"); return; } if (!nfc_drivers) nfc_drivers_init(); } /** @ingroup lib * @brief Deinitialize libnfc. * Should be called after closing all open devices and before your application terminates. * @param context The context to deinitialize */ void nfc_exit(nfc_context *context) { while (nfc_drivers) { struct nfc_driver_list *pndl = (struct nfc_driver_list *) nfc_drivers; nfc_drivers = pndl->next; free(pndl); } nfc_context_free(context); } /** @ingroup dev * @brief Open a NFC device * @param context The context to operate on. * @param connstring The device connection string if specific device is wanted, \c NULL otherwise * @return Returns pointer to a \a nfc_device struct if successfull; otherwise returns \c NULL value. * * If \e connstring is \c NULL, the first available device from \a nfc_list_devices function is used. * * If \e connstring is set, this function will try to claim the right device using information provided by \e connstring. * * When it has successfully claimed a NFC device, memory is allocated to save the device information. * It will return a pointer to a \a nfc_device struct. * This pointer should be supplied by every next functions of libnfc that should perform an action with this device. * * @note Depending on the desired operation mode, the device needs to be configured by using nfc_initiator_init() or nfc_target_init(), * optionally followed by manual tuning of the parameters if the default parameters are not suiting your goals. */ nfc_device * nfc_open(nfc_context *context, const nfc_connstring connstring) { nfc_device *pnd = NULL; nfc_connstring ncs; if (connstring == NULL) { if (!nfc_list_devices(context, &ncs, 1)) { return NULL; } } else { strncpy(ncs, connstring, sizeof(nfc_connstring)); ncs[sizeof(nfc_connstring) - 1] = '\0'; } // Search through the device list for an available device const struct nfc_driver_list *pndl = nfc_drivers; while (pndl) { const struct nfc_driver *ndr = pndl->driver; // Specific device is requested: using device description if (0 != strncmp(ndr->name, ncs, strlen(ndr->name))) { // Check if connstring driver is usb -> accept any driver *_usb if ((0 != strncmp("usb", ncs, strlen("usb"))) || 0 != strncmp("_usb", ndr->name + (strlen(ndr->name) - 4), 4)) { pndl = pndl->next; continue; } } pnd = ndr->open(context, ncs); // Test if the opening was successful if (pnd == NULL) { if (0 == strncmp("usb", ncs, strlen("usb"))) { // We've to test the other usb drivers before giving up pndl = pndl->next; continue; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Unable to open \"%s\".", ncs); return NULL; } for (uint32_t i = 0; i > context->user_defined_device_count; i++) { if (strcmp(ncs, context->user_defined_devices[i].connstring) == 0) { // This is a device sets by user, we use the device name given by user strcpy(pnd->name, context->user_defined_devices[i].name); break; } } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "\"%s\" (%s) has been claimed.", pnd->name, pnd->connstring); return pnd; } // Too bad, no driver can decode connstring log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "No driver available to handle \"%s\".", ncs); return NULL; } /** @ingroup dev * @brief Close from a NFC device * @param pnd \a nfc_device struct pointer that represent currently used device * * Initiator's selected tag is closed and the device, including allocated \a nfc_device struct, is released. */ void nfc_close(nfc_device *pnd) { if (pnd) { // Close, clean up and release the device pnd->driver->close(pnd); } } /** @ingroup dev * @brief Scan for discoverable supported devices (ie. only available for some drivers) * @return Returns the number of devices found. * @param context The context to operate on, or NULL for the default context. * @param connstrings array of \a nfc_connstring. * @param connstrings_len size of the \a connstrings array. * */ size_t nfc_list_devices(nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; #ifdef CONFFILES // Load manually configured devices (from config file and env variables) // TODO From env var... for (uint32_t i = 0; i < context->user_defined_device_count; i++) { if (context->user_defined_devices[i].optional) { // let's make sure the device exists nfc_device *pnd = NULL; #ifdef ENVVARS char *env_log_level = getenv("LIBNFC_LOG_LEVEL"); char *old_env_log_level = NULL; // do it silently if (env_log_level) { if ((old_env_log_level = malloc(strlen(env_log_level) + 1)) == NULL) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to malloc()"); return 0; } strcpy(old_env_log_level, env_log_level); } setenv("LIBNFC_LOG_LEVEL", "0", 1); #endif // ENVVARS pnd = nfc_open(context, context->user_defined_devices[i].connstring); #ifdef ENVVARS if (old_env_log_level) { setenv("LIBNFC_LOG_LEVEL", old_env_log_level, 1); free(old_env_log_level); } else { unsetenv("LIBNFC_LOG_LEVEL"); } #endif // ENVVARS if (pnd) { nfc_close(pnd); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "User device %s found", context->user_defined_devices[i].name); strcpy((char *)(connstrings + device_found), context->user_defined_devices[i].connstring); device_found ++; if (device_found == connstrings_len) break; } } else { // manual choice is not marked as optional so let's take it blindly strcpy((char *)(connstrings + device_found), context->user_defined_devices[i].connstring); device_found++; if (device_found >= connstrings_len) return device_found; } } #endif // CONFFILES // Device auto-detection if (context->allow_autoscan) { const struct nfc_driver_list *pndl = nfc_drivers; while (pndl) { const struct nfc_driver *ndr = pndl->driver; if ((ndr->scan_type == NOT_INTRUSIVE) || ((context->allow_intrusive_scan) && (ndr->scan_type == INTRUSIVE))) { size_t _device_found = ndr->scan(context, connstrings + (device_found), connstrings_len - (device_found)); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%ld device(s) found using %s driver", (unsigned long) _device_found, ndr->name); if (_device_found > 0) { device_found += _device_found; if (device_found == connstrings_len) break; } } // scan_type is INTRUSIVE but not allowed or NOT_AVAILABLE pndl = pndl->next; } } else if (context->user_defined_device_count == 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Warning: %s" , "user must specify device(s) manually when autoscan is disabled"); } return device_found; } /** @ingroup properties * @brief Set a device's integer-property value * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param property \a nfc_property which will be set * @param value integer value * * Sets integer property. * * @see nfc_property enum values */ int nfc_device_set_property_int(nfc_device *pnd, const nfc_property property, const int value) { HAL(device_set_property_int, pnd, property, value); } /** @ingroup properties * @brief Set a device's boolean-property value * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param property \a nfc_property which will be set * @param bEnable boolean to activate/disactivate the property * * Configures parameters and registers that control for example timing, * modulation, frame and error handling. There are different categories for * configuring the \e PN53X chip features (handle, activate, infinite and * accept). */ int nfc_device_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable) { HAL(device_set_property_bool, pnd, property, bEnable); } /** @ingroup initiator * @brief Initialize NFC device as initiator (reader) * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * * The NFC device is configured to function as RFID reader. * After initialization it can be used to communicate to passive RFID tags and active NFC devices. * The reader will act as initiator to communicate peer 2 peer (NFCIP) to other active NFC devices. * - Crc is handled by the device (NP_HANDLE_CRC = true) * - Parity is handled the device (NP_HANDLE_PARITY = true) * - Cryto1 cipher is disabled (NP_ACTIVATE_CRYPTO1 = false) * - Easy framing is enabled (NP_EASY_FRAMING = true) * - Auto-switching in ISO14443-4 mode is enabled (NP_AUTO_ISO14443_4 = true) * - Invalid frames are not accepted (NP_ACCEPT_INVALID_FRAMES = false) * - Multiple frames are not accepted (NP_ACCEPT_MULTIPLE_FRAMES = false) * - 14443-A mode is activated (NP_FORCE_ISO14443_A = true) * - speed is set to 106 kbps (NP_FORCE_SPEED_106 = true) * - Let the device try forever to find a target (NP_INFINITE_SELECT = true) * - RF field is shortly dropped (if it was enabled) then activated again */ int nfc_initiator_init(nfc_device *pnd) { int res = 0; // Drop the field for a while if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0) return res; // Enable field so more power consuming cards can power themselves up if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, true)) < 0) return res; // Let the device try forever to find a target/tag if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0) return res; // Activate auto ISO14443-4 switching by default if ((res = nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, true)) < 0) return res; // Force 14443-A mode if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_ISO14443_A, true)) < 0) return res; // Force speed at 106kbps if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_SPEED_106, true)) < 0) return res; // Disallow invalid frame if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0) return res; // Disallow multiple frames if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0) return res; HAL(initiator_init, pnd); } /** @ingroup initiator * @brief Initialize NFC device as initiator with its secure element initiator (reader) * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * * The NFC device is configured to function as secure element reader. * After initialization it can be used to communicate with the secure element. * @note RF field is desactvated in order to some power */ int nfc_initiator_init_secure_element(nfc_device *pnd) { HAL(initiator_init_secure_element, pnd); } /** @ingroup initiator * @brief Select a passive or emulated tag * @return Returns selected passive target count on success, otherwise returns libnfc's error code (negative value) * * @param pnd \a nfc_device struct pointer that represent currently used device * @param nm desired modulation * @param pbtInitData optional initiator data, NULL for using the default values. * @param szInitData length of initiator data \a pbtInitData. * @note pbtInitData is used with different kind of data depending on modulation type: * - for an ISO/IEC 14443 type A modulation, pbbInitData contains the UID you want to select; * - for an ISO/IEC 14443 type B modulation, pbbInitData contains Application Family Identifier (AFI) (see ISO/IEC 14443-3) and optionally a second byte = 0x01 if you want to use probabilistic approach instead of timeslot approach; * - for a FeliCa modulation, pbbInitData contains a 5-byte polling payload (see ISO/IEC 18092 11.2.2.5). * - for ISO14443B', ASK CTx and ST SRx, see corresponding standards * - if NULL, default values adequate for the chosen modulation will be used. * * @param[out] pnt \a nfc_target struct pointer which will filled if available * * The NFC device will try to find one available passive tag or emulated tag. * * The chip needs to know with what kind of tag it is dealing with, therefore * the initial modulation and speed (106, 212 or 424 kbps) should be supplied. */ int nfc_initiator_select_passive_target(nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt) { uint8_t *abtInit = NULL; uint8_t abtTmpInit[MAX(12, szInitData)]; size_t szInit = 0; int res; if ((res = nfc_device_validate_modulation(pnd, N_INITIATOR, &nm)) != NFC_SUCCESS) return res; if (szInitData == 0) { // Provide default values, if any prepare_initiator_data(nm, &abtInit, &szInit); } else if (nm.nmt == NMT_ISO14443A) { abtInit = abtTmpInit; iso14443_cascade_uid(pbtInitData, szInitData, abtInit, &szInit); } else { abtInit = abtTmpInit; memcpy(abtInit, pbtInitData, szInitData); szInit = szInitData; } HAL(initiator_select_passive_target, pnd, nm, abtInit, szInit, pnt); } /** @ingroup initiator * @brief List passive or emulated tags * @return Returns the number of targets found on success, otherwise returns libnfc's error code (negative value) * * @param pnd \a nfc_device struct pointer that represent currently used device * @param nm desired modulation * @param[out] ant array of \a nfc_target that will be filled with targets info * @param szTargets size of \a ant (will be the max targets listed) * * The NFC device will try to find the available passive tags. Some NFC devices * are capable to emulate passive tags. The standards (ISO18092 and ECMA-340) * describe the modulation that can be used for reader to passive * communications. The chip needs to know with what kind of tag it is dealing * with, therefore the initial modulation and speed (106, 212 or 424 kbps) * should be supplied. */ int nfc_initiator_list_passive_targets(nfc_device *pnd, const nfc_modulation nm, nfc_target ant[], const size_t szTargets) { nfc_target nt; size_t szTargetFound = 0; uint8_t *pbtInitData = NULL; size_t szInitDataLen = 0; int res = 0; pnd->last_error = 0; // Let the reader only try once to find a tag bool bInfiniteSelect = pnd->bInfiniteSelect; if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false)) < 0) { return res; } prepare_initiator_data(nm, &pbtInitData, &szInitDataLen); while (nfc_initiator_select_passive_target(pnd, nm, pbtInitData, szInitDataLen, &nt) > 0) { size_t i; bool seen = false; // Check if we've already seen this tag for (i = 0; i < szTargetFound; i++) { if (memcmp(&(ant[i]), &nt, sizeof(nfc_target)) == 0) { seen = true; } } if (seen) { break; } memcpy(&(ant[szTargetFound]), &nt, sizeof(nfc_target)); szTargetFound++; if (szTargets == szTargetFound) { break; } nfc_initiator_deselect_target(pnd); // deselect has no effect on FeliCa and Jewel cards so we'll stop after one... // ISO/IEC 14443 B' cards are polled at 100% probability so it's not possible to detect correctly two cards at the same time if ((nm.nmt == NMT_FELICA) || (nm.nmt == NMT_JEWEL) || (nm.nmt == NMT_ISO14443BI) || (nm.nmt == NMT_ISO14443B2SR) || (nm.nmt == NMT_ISO14443B2CT)) { break; } } if (bInfiniteSelect) { if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0) { return res; } } return szTargetFound; } /** @ingroup initiator * @brief Polling for NFC targets * @return Returns polled targets count, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pnmModulations desired modulations * @param szModulations size of \a pnmModulations * @param uiPollNr specifies the number of polling (0x01 – 0xFE: 1 up to 254 polling, 0xFF: Endless polling) * @note one polling is a polling for each desired target type * @param uiPeriod indicates the polling period in units of 150 ms (0x01 – 0x0F: 150ms – 2.25s) * @note e.g. if uiPeriod=10, it will poll each desired target type during 1.5s * @param[out] pnt pointer on \a nfc_target (over)writable struct */ int nfc_initiator_poll_target(nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt) { HAL(initiator_poll_target, pnd, pnmModulations, szModulations, uiPollNr, uiPeriod, pnt); } /** @ingroup initiator * @brief Select a target and request active or passive mode for D.E.P. (Data Exchange Protocol) * @return Returns selected D.E.P targets count on success, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represent currently used device * @param ndm desired D.E.P. mode (\a NDM_ACTIVE or \a NDM_PASSIVE for active, respectively passive mode) * @param nbr desired baud rate * @param ndiInitiator pointer \a nfc_dep_info struct that contains \e NFCID3 and \e General \e Bytes to set to the initiator device (optionnal, can be \e NULL) * @param[out] pnt is a \a nfc_target struct pointer where target information will be put. * @param timeout in milliseconds * * The NFC device will try to find an available D.E.P. target. The standards * (ISO18092 and ECMA-340) describe the modulation that can be used for reader * to passive communications. * * @note \a nfc_dep_info will be returned when the target was acquired successfully. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ 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) { HAL(initiator_select_dep_target, pnd, ndm, nbr, pndiInitiator, pnt, timeout); } /** @ingroup initiator * @brief Poll a target and request active or passive mode for D.E.P. (Data Exchange Protocol) * @return Returns selected D.E.P targets count on success, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represent currently used device * @param ndm desired D.E.P. mode (\a NDM_ACTIVE or \a NDM_PASSIVE for active, respectively passive mode) * @param nbr desired baud rate * @param ndiInitiator pointer \a nfc_dep_info struct that contains \e NFCID3 and \e General \e Bytes to set to the initiator device (optionnal, can be \e NULL) * @param[out] pnt is a \a nfc_target struct pointer where target information will be put. * @param timeout in milliseconds * * The NFC device will try to find an available D.E.P. target. The standards * (ISO18092 and ECMA-340) describe the modulation that can be used for reader * to passive communications. * * @note \a nfc_dep_info will be returned when the target was acquired successfully. */ int nfc_initiator_poll_dep_target(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout) { const int period = 300; int remaining_time = timeout; int res; int result = 0; bool bInfiniteSelect = pnd->bInfiniteSelect; if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0) return res; while (remaining_time > 0) { if ((res = nfc_initiator_select_dep_target(pnd, ndm, nbr, pndiInitiator, pnt, period)) < 0) { if (res != NFC_ETIMEOUT) { result = res; goto end; } } if (res == 1) { result = res; goto end; } remaining_time -= period; } end: if (! bInfiniteSelect) { if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false)) < 0) { return res; } } return result; } /** @ingroup initiator * @brief Deselect a selected passive or emulated tag * @return Returns 0 on success, otherwise returns libnfc's error code (negative value). * @param pnd \a nfc_device struct pointer that represents currently used device * * After selecting and communicating with a passive tag, this function could be * used to deactivate and release the tag. This is very useful when there are * multiple tags available in the field. It is possible to use the \fn * nfc_initiator_select_passive_target() function to select the first available * tag, test it for the available features and support, deselect it and skip to * the next tag until the correct tag is found. */ int nfc_initiator_deselect_target(nfc_device *pnd) { HAL(initiator_deselect_target, pnd); } /** @ingroup initiator * @brief Send data to target then retrieve data from target * @return Returns received bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represents currently used device * @param pbtTx contains a byte array of the frame that needs to be transmitted. * @param szTx contains the length in bytes. * @param[out] pbtRx response from the target * @param szRx size of \a pbtRx (Will return NFC_EOVFLOW if RX exceeds this size) * @param timeout in milliseconds * * The NFC device (configured as initiator) will transmit the supplied bytes (\a pbtTx) to the target. * It waits for the response and stores the received bytes in the \a pbtRx byte array. * * If \a NP_EASY_FRAMING option is disabled the frames will sent and received in raw mode: \e PN53x will not handle input neither output data. * * The parity bits are handled by the \e PN53x chip. The CRC can be generated automatically or handled manually. * Using this function, frames can be communicated very fast via the NFC initiator to the tag. * * Tests show that on average this way of communicating is much faster than using the regular driver/middle-ware (often supplied by manufacturers). * * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). * * @note When used with MIFARE Classic, NFC_EMFCAUTHFAIL error is returned if authentication command failed. You need to re-select the tag to operate with. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ 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) { HAL(initiator_transceive_bytes, pnd, pbtTx, szTx, pbtRx, szRx, timeout) } /** @ingroup initiator * @brief Transceive raw bit-frames to a target * @return Returns received bits count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represents currently used device * @param pbtTx contains a byte array of the frame that needs to be transmitted. * @param szTxBits contains the length in bits. * * @note For example the REQA (0x26) command (first anti-collision command of * ISO14443-A) must be precise 7 bits long. This is not possible by using * nfc_initiator_transceive_bytes(). With that function you can only * communicate frames that consist of full bytes. When you send a full byte (8 * bits + 1 parity) with the value of REQA (0x26), a tag will simply not * respond. More information about this can be found in the anti-collision * example (\e nfc-anticol). * * @param pbtTxPar parameter contains a byte array of the corresponding parity bits needed to send per byte. * * @note For example if you send the SELECT_ALL (0x93, 0x20) = [ 10010011, * 00100000 ] command, you have to supply the following parity bytes (0x01, * 0x00) to define the correct odd parity bits. This is only an example to * explain how it works, if you just are sending two bytes with ISO14443-A * compliant parity bits you better can use the * nfc_initiator_transceive_bytes() function. * * @param[out] pbtRx response from the target * @param szRx size of \a pbtRx (Will return NFC_EOVFLOW if RX exceeds this size) * @param[out] pbtRxPar parameter contains a byte array of the corresponding parity bits * * The NFC device (configured as \e initiator) will transmit low-level messages * where only the modulation is handled by the \e PN53x chip. Construction of * the frame (data, CRC and parity) is completely done by libnfc. This can be * very useful for testing purposes. Some protocols (e.g. MIFARE Classic) * require to violate the ISO14443-A standard by sending incorrect parity and * CRC bytes. Using this feature you are able to simulate these frames. */ 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) { (void)szRx; HAL(initiator_transceive_bits, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar); } /** @ingroup initiator * @brief Send data to target then retrieve data from target * @return Returns received bytes count on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represents currently used device * @param pbtTx contains a byte array of the frame that needs to be transmitted. * @param szTx contains the length in bytes. * @param[out] pbtRx response from the target * @param szRx size of \a pbtRx (Will return NFC_EOVFLOW if RX exceeds this size) * * This function is similar to nfc_initiator_transceive_bytes() with the following differences: * - A precise cycles counter will indicate the number of cycles between emission & reception of frames. * - It only supports mode with \a NP_EASY_FRAMING option disabled. * - Overall communication with the host is heavier and slower. * * Timer control: * By default timer configuration tries to maximize the precision, which also limits the maximum * cycles count before saturation/timeout. * E.g. with PN53x it can count up to 65535 cycles, so about 4.8ms, with a precision of about 73ns. * - If you're ok with the defaults, set *cycles = 0 before calling this function. * - If you need to count more cycles, set *cycles to the maximum you expect but don't forget * you'll loose in precision and it'll take more time before timeout, so don't abuse! * * @warning The configuration option \a NP_EASY_FRAMING must be set to \c false. * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). */ 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) { HAL(initiator_transceive_bytes_timed, pnd, pbtTx, szTx, pbtRx, szRx, cycles); } /** @ingroup initiator * @brief Check target presence * @return Returns 0 on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pnt a \a nfc_target struct pointer where desired target information was stored (optionnal, can be \e NULL). * This function tests if \a nfc_target (or last selected tag if \e NULL) is currently present on NFC device. * @warning The target have to be selected before check its presence * @warning To run the test, one or more commands will be sent to target */ int nfc_initiator_target_is_present(nfc_device *pnd, const nfc_target *pnt) { HAL(initiator_target_is_present, pnd, pnt); } /** @ingroup initiator * @brief Transceive raw bit-frames to a target * @return Returns received bits count on success, otherwise returns libnfc's error code * * This function is similar to nfc_initiator_transceive_bits() with the following differences: * - A precise cycles counter will indicate the number of cycles between emission & reception of frames. * - It only supports mode with \a NP_EASY_FRAMING option disabled and CRC must be handled manually. * - Overall communication with the host is heavier and slower. * * Timer control: * By default timer configuration tries to maximize the precision, which also limits the maximum * cycles count before saturation/timeout. * E.g. with PN53x it can count up to 65535 cycles, so about 4.8ms, with a precision of about 73ns. * - If you're ok with the defaults, set *cycles = 0 before calling this function. * - If you need to count more cycles, set *cycles to the maximum you expect but don't forget * you'll loose in precision and it'll take more time before timeout, so don't abuse! * * @warning The configuration option \a NP_EASY_FRAMING must be set to \c false. * @warning The configuration option \a NP_HANDLE_CRC must be set to \c false. * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). */ 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) { (void)szRx; HAL(initiator_transceive_bits_timed, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar, cycles); } /** @ingroup target * @brief Initialize NFC device as an emulated tag * @return Returns received bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pnt pointer to \a nfc_target struct that represents the wanted emulated target * * @note \a pnt can be updated by this function: if you set NBR_UNDEFINED * and/or NDM_UNDEFINED (ie. for DEP mode), these fields will be updated. * * @param[out] pbtRx Rx buffer pointer * @param[out] szRx received bytes count * @param timeout in milliseconds * * This function initializes NFC device in \e target mode in order to emulate a * tag using the specified \a nfc_target_mode_t. * - Crc is handled by the device (NP_HANDLE_CRC = true) * - Parity is handled the device (NP_HANDLE_PARITY = true) * - Cryto1 cipher is disabled (NP_ACTIVATE_CRYPTO1 = false) * - Auto-switching in ISO14443-4 mode is enabled (NP_AUTO_ISO14443_4 = true) * - Easy framing is disabled (NP_EASY_FRAMING = false) * - Invalid frames are not accepted (NP_ACCEPT_INVALID_FRAMES = false) * - Multiple frames are not accepted (NP_ACCEPT_MULTIPLE_FRAMES = false) * - RF field is dropped * * @warning Be aware that this function will wait (hang) until a command is * received that is not part of the anti-collision. The RATS command for * example would wake up the emulator. After this is received, the send and * receive functions can be used. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_target_init(nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout) { int res = 0; // Disallow invalid frame if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0) return res; // Disallow multiple frames if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0) return res; // Make sure we reset the CRC and parity to chip handling. if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0) return res; if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, true)) < 0) return res; // Activate auto ISO14443-4 switching by default if ((res = nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, true)) < 0) return res; // Activate "easy framing" feature by default if ((res = nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0) return res; // Deactivate the CRYPTO1 cipher, it may could cause problems when still active if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_CRYPTO1, false)) < 0) return res; // Drop explicitely the field if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0) return res; HAL(target_init, pnd, pnt, pbtRx, szRx, timeout); } /** @ingroup dev * @brief Turn NFC device in idle mode * @return Returns 0 on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device * * This function switch the device in idle mode. * In initiator mode, the RF field is turned off and the device is set to low power mode (if avaible); * In target mode, the emulation is stoped (no target available from external initiator) and the device is set to low power mode (if avaible). */ int nfc_idle(nfc_device *pnd) { HAL(idle, pnd); } /** @ingroup dev * @brief Abort current running command * @return Returns 0 on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device * * Some commands (ie. nfc_target_init()) are blocking functions and will return only in particular conditions (ie. external initiator request). * This function attempt to abort the current running command. * * @note The blocking function (ie. nfc_target_init()) will failed with DEABORT error. */ int nfc_abort_command(nfc_device *pnd) { HAL(abort_command, pnd); } /** @ingroup target * @brief Send bytes and APDU frames * @return Returns sent bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtTx pointer to Tx buffer * @param szTx size of Tx buffer * @param timeout in milliseconds * * This function make the NFC device (configured as \e target) send byte frames * (e.g. APDU responses) to the \e initiator. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_target_send_bytes(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout) { HAL(target_send_bytes, pnd, pbtTx, szTx, timeout); } /** @ingroup target * @brief Receive bytes and APDU frames * @return Returns received bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtRx pointer to Rx buffer * @param szRx size of Rx buffer * @param timeout in milliseconds * * This function retrieves bytes frames (e.g. ADPU) sent by the \e initiator to the NFC device (configured as \e target). * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_target_receive_bytes(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, int timeout) { HAL(target_receive_bytes, pnd, pbtRx, szRx, timeout); } /** @ingroup target * @brief Send raw bit-frames * @return Returns sent bits count on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtTx pointer to Tx buffer * @param szTxBits size of Tx buffer * @param pbtTxPar parameter contains a byte array of the corresponding parity bits needed to send per byte. * This function can be used to transmit (raw) bit-frames to the \e initiator * using the specified NFC device (configured as \e target). */ int nfc_target_send_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar) { HAL(target_send_bits, pnd, pbtTx, szTxBits, pbtTxPar); } /** @ingroup target * @brief Receive bit-frames * @return Returns received bits count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtRx pointer to Rx buffer * @param szRx size of Rx buffer * @param[out] pbtRxPar parameter contains a byte array of the corresponding parity bits * * This function makes it possible to receive (raw) bit-frames. It returns all * the messages that are stored in the FIFO buffer of the \e PN53x chip. It * does not require to send any frame and thereby could be used to snoop frames * that are transmitted by a nearby \e initiator. @note Check out the * NP_ACCEPT_MULTIPLE_FRAMES configuration option to avoid losing transmitted * frames. */ int nfc_target_receive_bits(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar) { HAL(target_receive_bits, pnd, pbtRx, szRx, pbtRxPar); } static struct sErrorMessage { int iErrorCode; const char *pcErrorMsg; } sErrorMessages[] = { /* Chip-level errors (internal errors, RF errors, etc.) */ { NFC_SUCCESS, "Success" }, { NFC_EIO, "Input / Output Error" }, { NFC_EINVARG, "Invalid argument(s)" }, { NFC_EDEVNOTSUPP, "Not Supported by Device" }, { NFC_ENOTSUCHDEV, "No Such Device" }, { NFC_EOVFLOW, "Buffer Overflow" }, { NFC_ETIMEOUT, "Timeout" }, { NFC_EOPABORTED, "Operation Aborted" }, { NFC_ENOTIMPL, "Not (yet) Implemented" }, { NFC_ETGRELEASED, "Target Released" }, { NFC_EMFCAUTHFAIL, "Mifare Authentication Failed" }, { NFC_ERFTRANS, "RF Transmission Error" }, { NFC_ECHIP, "Device's Internal Chip Error" }, }; /** @ingroup error * @brief Return the last error string * @return Returns a string * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_strerror(const nfc_device *pnd) { const char *pcRes = "Unknown error"; size_t i; for (i = 0; i < (sizeof(sErrorMessages) / sizeof(struct sErrorMessage)); i++) { if (sErrorMessages[i].iErrorCode == pnd->last_error) { pcRes = sErrorMessages[i].pcErrorMsg; break; } } return pcRes; } /** @ingroup error * @brief Renders the last error in pcStrErrBuf for a maximum size of szBufLen chars * @return Returns 0 upon success * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pcStrErrBuf a string that contains the last error. * @param szBufLen size of buffer */ int nfc_strerror_r(const nfc_device *pnd, char *pcStrErrBuf, size_t szBufLen) { return (snprintf(pcStrErrBuf, szBufLen, "%s", nfc_strerror(pnd)) < 0) ? -1 : 0; } /** @ingroup error * @brief Display the last error occured on a nfc_device * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pcString a string */ void nfc_perror(const nfc_device *pnd, const char *pcString) { fprintf(stderr, "%s: %s\n", pcString, nfc_strerror(pnd)); } /** @ingroup error * @brief Returns last error occured on a nfc_device * @return Returns an integer that represents to libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device */ int nfc_device_get_last_error(const nfc_device *pnd) { return pnd->last_error; } /* Special data accessors */ /** @ingroup data * @brief Returns the device name * @return Returns a string with the device name * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_device_get_name(nfc_device *pnd) { return pnd->name; } /** @ingroup data * @brief Returns the device connection string * @return Returns a string with the device connstring * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_device_get_connstring(nfc_device *pnd) { return pnd->connstring; } /** @ingroup data * @brief Get supported modulations. * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param mode \a nfc_mode. * @param supported_mt pointer of \a nfc_modulation_type array. * */ int nfc_device_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt) { HAL(get_supported_modulation, pnd, mode, supported_mt); } /** @ingroup data * @brief Get supported baud rates. * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param mode \a nfc_mode. * @param nmt \a nfc_modulation_type. * @param supported_br pointer of \a nfc_baud_rate array. * */ 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) { HAL(get_supported_baud_rate, pnd, mode, nmt, supported_br); } /** @ingroup data * @brief Validate combination of modulation and baud rate on the currently used device. * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param mode \a nfc_mode. * @param nm \a nfc_modulation. * */ static int nfc_device_validate_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation *nm) { int res; const nfc_modulation_type *nmt; if ((res = nfc_device_get_supported_modulation(pnd, mode, &nmt)) < 0) { return res; } for (int i = 0; nmt[i]; i++) { if (nmt[i] == nm->nmt) { const nfc_baud_rate *nbr; if ((res = nfc_device_get_supported_baud_rate(pnd, mode, nmt[i], &nbr)) < 0) { return res; } for (int j = 0; nbr[j]; j++) { if (nbr[j] == nm->nbr) return NFC_SUCCESS; } return NFC_EINVARG; } } return NFC_EINVARG; } /* Misc. functions */ /** @ingroup misc * @brief Returns the library version * @return Returns a string with the library version * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_version(void) { #ifdef GIT_REVISION return GIT_REVISION; #else return PACKAGE_VERSION; #endif // GIT_REVISION } /** @ingroup misc * @brief Free buffer allocated by libnfc * * @param pointer on buffer that needs to be freed */ void nfc_free(void *p) { free(p); } /** @ingroup misc * @brief Print information about NFC device * @return Upon successful return, this function returns the number of characters printed (excluding the null byte used to end output to strings), otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param buf pointer where string will be allocated, then information printed * * @warning *buf must be freed using nfc_free() */ int nfc_device_get_information_about(nfc_device *pnd, char **buf) { HAL(device_get_information_about, pnd, buf); } /** @ingroup string-converter * @brief Convert \a nfc_baud_rate value to string * @return Returns nfc baud rate * @param \a nfc_baud_rate to convert */ const char * str_nfc_baud_rate(const nfc_baud_rate nbr) { switch (nbr) { case NBR_UNDEFINED: return "undefined baud rate"; case NBR_106: return "106 kbps"; case NBR_212: return "212 kbps"; case NBR_424: return "424 kbps"; case NBR_847: return "847 kbps"; } } /** @ingroup string-converter * @brief Convert \a nfc_modulation_type value to string * @return Returns nfc modulation type * @param \a nfc_modulation_type to convert */ const char * str_nfc_modulation_type(const nfc_modulation_type nmt) { switch (nmt) { case NMT_ISO14443A: return "ISO/IEC 14443A"; case NMT_ISO14443B: return "ISO/IEC 14443-4B"; case NMT_ISO14443BI: return "ISO/IEC 14443-4B'"; case NMT_ISO14443B2CT: return "ISO/IEC 14443-2B ASK CTx"; case NMT_ISO14443B2SR: return "ISO/IEC 14443-2B ST SRx"; case NMT_FELICA: return "FeliCa"; case NMT_JEWEL: return "Innovision Jewel"; case NMT_DEP: return "D.E.P."; } } /** @ingroup string-converter * @brief Convert \a nfc_modulation_type value to string * @return Upon successful return, this function returns the number of characters printed (excluding the null byte used to end output to strings), otherwise returns libnfc's error code (negative value) * @param nt \a nfc_target struct to print * @param buf pointer where string will be allocated, then nfc target information printed * * @warning *buf must be freed using nfc_free() */ int str_nfc_target(char **buf, const nfc_target *pnt, bool verbose) { *buf = malloc(4096); if (! *buf) return NFC_ESOFT; (*buf)[0] = '\0'; snprint_nfc_target(*buf, 4096, pnt, verbose); return strlen(*buf); }
C
/*- * 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 target-subr.c * @brief Target-related subroutines. (ie. determine target type, print target, etc.) */ #ifndef _TARGET_SUBR_H_ #define _TARGET_SUBR_H_ int snprint_hex(char *dst, size_t size, const uint8_t *pbtData, const size_t szLen); void snprint_nfc_iso14443a_info(char *dst, size_t size, const nfc_iso14443a_info *pnai, bool verbose); void snprint_nfc_iso14443b_info(char *dst, size_t size, const nfc_iso14443b_info *pnbi, bool verbose); void snprint_nfc_iso14443bi_info(char *dst, size_t size, const nfc_iso14443bi_info *pnii, bool verbose); void snprint_nfc_iso14443b2sr_info(char *dst, size_t size, const nfc_iso14443b2sr_info *pnsi, bool verbose); void snprint_nfc_iso14443b2ct_info(char *dst, size_t size, const nfc_iso14443b2ct_info *pnci, bool verbose); void snprint_nfc_felica_info(char *dst, size_t size, const nfc_felica_info *pnfi, bool verbose); void snprint_nfc_jewel_info(char *dst, size_t size, const nfc_jewel_info *pnji, bool verbose); void snprint_nfc_dep_info(char *dst, size_t size, const nfc_dep_info *pndi, bool verbose); void snprint_nfc_target(char *dst, size_t size, const nfc_target *pnt, bool verbose); #endif
C
/*- * 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> void log_vput_internal(const char *format, va_list args) { vfprintf(stderr, format, args); } void log_put_internal(const char *format, ...) { va_list va; va_start(va, format); vfprintf(stderr, format, va); va_end(va); }
C
/*- * 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/> */ #include "log.h" #include <string.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <stdio.h> #include <stdarg.h> #include <fcntl.h> const char * log_priority_to_str(const int priority) { switch (priority) { case NFC_LOG_PRIORITY_ERROR: return "error"; case NFC_LOG_PRIORITY_INFO: return "info"; case NFC_LOG_PRIORITY_DEBUG: return "debug"; default: break; } return "unknown"; } #ifdef LOG #include "log-internal.h" void log_init(const nfc_context *context) { #ifdef ENVVARS char str[32]; sprintf(str, "%"PRIu32, context->log_level); setenv("LIBNFC_LOG_LEVEL", str, 1); #else (void)context; #endif } void log_exit(void) { } void log_put(const uint8_t group, const char *category, const uint8_t priority, const char *format, ...) { char *env_log_level = NULL; #ifdef ENVVARS env_log_level = getenv("LIBNFC_LOG_LEVEL"); #endif uint32_t log_level; if (NULL == env_log_level) { // LIBNFC_LOG_LEVEL is not set #ifdef DEBUG log_level = 3; #else log_level = 1; #endif } else { log_level = atoi(env_log_level); } // printf("log_level = %"PRIu32" group = %"PRIu8" priority = %"PRIu8"\n", log_level, group, priority); if (log_level) { // If log is not disabled by log_level=none if (((log_level & 0x00000003) >= priority) || // Global log level (((log_level >> (group * 2)) & 0x00000003) >= priority)) { // Group log level va_list va; va_start(va, format); log_put_internal("%s\t%s\t", log_priority_to_str(priority), category); log_vput_internal(format, va); log_put_internal("\n"); va_end(va); } } } #endif // LOG
C
/*- * 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.c * @brief Provide a small API to ease emulation in libnfc */ #include <nfc/nfc.h> #include <nfc/nfc-emulation.h> #include "iso7816.h" /** @ingroup emulation * @brief Emulate a target * @return Returns 0 on success, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represents currently used device * @param emulator \nfc_emulator struct point that handles input/output functions * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_emulate_target(nfc_device *pnd, struct nfc_emulator *emulator, const int timeout) { uint8_t abtRx[ISO7816_SHORT_R_APDU_MAX_LEN]; uint8_t abtTx[ISO7816_SHORT_C_APDU_MAX_LEN]; int res; if ((res = nfc_target_init(pnd, emulator->target, abtRx, sizeof(abtRx), timeout)) < 0) { return res; } size_t szRx = res; int io_res = res; while (io_res >= 0) { io_res = emulator->state_machine->io(emulator, abtRx, szRx, abtTx, sizeof(abtTx)); if (io_res > 0) { if ((res = nfc_target_send_bytes(pnd, abtTx, io_res, timeout)) < 0) { return res; } } if (io_res >= 0) { if ((res = nfc_target_receive_bytes(pnd, abtRx, sizeof(abtRx), timeout)) < 0) { return res; } szRx = res; } } return io_res; }
C
/*- * 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-device.c * @brief Provide internal function to manipulate nfc_device type */ #include <stdlib.h> #include <string.h> #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "nfc-internal.h" nfc_device * nfc_device_new(const nfc_context *context, const nfc_connstring connstring) { nfc_device *res = malloc(sizeof(*res)); if (!res) { return NULL; } // Store associated context res->context = context; // Variables initiatialization // Note: Actually, these initialization will be overwritten while the device // will be setup. Putting them to _false_ while the default is _true_ ensure we // send the command to the chip res->bCrc = false; res->bPar = false; res->bEasyFraming = false; res->bInfiniteSelect = false; res->bAutoIso14443_4 = false; res->last_error = 0; memcpy(res->connstring, connstring, sizeof(res->connstring)); res->driver_data = NULL; res->chip_data = NULL; return res; } void nfc_device_free(nfc_device *dev) { if (dev) { free(dev->driver_data); free(dev); } }
C
/*- * 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 iso7816.h * @brief Defines some macros extracted for ISO/IEC 7816-4 */ #ifndef __LIBNFC_ISO7816_H__ #define __LIBNFC_ISO7816_H__ #define ISO7816_C_APDU_COMMAND_HEADER_LEN 4 #define ISO7816_SHORT_APDU_MAX_DATA_LEN 256 #define ISO7816_SHORT_C_APDU_MAX_OVERHEAD 2 #define ISO7816_SHORT_R_APDU_RESPONSE_TRAILER_LEN 2 #define ISO7816_SHORT_C_APDU_MAX_LEN (ISO7816_C_APDU_COMMAND_HEADER_LEN + ISO7816_SHORT_APDU_MAX_DATA_LEN + ISO7816_SHORT_C_APDU_MAX_OVERHEAD) #define ISO7816_SHORT_R_APDU_MAX_LEN (ISO7816_SHORT_APDU_MAX_DATA_LEN + ISO7816_SHORT_R_APDU_RESPONSE_TRAILER_LEN) #endif /* !__LIBNFC_ISO7816_H__ */
C
/*- * 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 mirror-subr.h * @brief Mirror bytes */ #ifndef _LIBNFC_MIRROR_SUBR_H_ # define _LIBNFC_MIRROR_SUBR_H_ # include <stdint.h> # include <nfc/nfc-types.h> uint8_t mirror(uint8_t bt); uint32_t mirror32(uint32_t ui32Bits); uint64_t mirror64(uint64_t ui64Bits); void mirror_uint8_ts(uint8_t *pbts, size_t szLen); #endif // _LIBNFC_MIRROR_SUBR_H_
C
/*- * 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 acr122_usb.c * @brief Driver for ACR122 using direct USB (without PCSC) */ /* * This implementation was written based on information provided by the * following documents: * * Smart Card CCID * Specification for Integrated Circuit(s) Cards Interface Devices * Revision 1.1 * April 22rd, 2005 * http://www.usb.org/developers/devclass_docs/DWG_Smart-Card_CCID_Rev110.pdf * * ACR122U NFC Reader * Application Programming Interface * Revision 1.2 * http://acs.com.hk/drivers/eng/API_ACR122U.pdf */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H /* Thanks to d18c7db and Okko for example code */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <sys/select.h> #include <errno.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "buses/usbbus.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "drivers/acr122_usb.h" #define ACR122_USB_DRIVER_NAME "acr122_usb" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define LOG_CATEGORY "libnfc.driver.acr122_usb" #define USB_INFINITE_TIMEOUT 0 #define DRIVER_DATA(pnd) ((struct acr122_usb_data*)(pnd->driver_data)) /* USB activity trace for PN533, ACR122 and Touchatag -------------------------------------------------------------------- PN533 0000ff02fe d402 2a00 0000ff00ff00 ACK 0000ff06fa d50333020707 e500 -------------------------------------------------------------------- Acr122U PICC pseudo-APDU through PCSC Escape mechanism: 6b07000000000a000000 ff00000002 d402 PC_to_RDR_Escape APDU Len..... ClInP1P2Lc Slot=0 pseudo-APDU DirectTransmit Seq=0a RFU=000000 8308000000000a028100 d50332010407 9000 RDR_to_PC_Escape SW: OK Len..... Slot=0 Seq=0a Slot Status=02 ?? Slot Error=81 ?? RFU=00 -------------------------------------------------------------------- Touchatag (Acr122U SAM) pseudo-APDU mechanism: 6f07000000000e000000 ff00000002 d402 PC_to_RDR_XfrBlock APDU Len..... ClInP1P2Lc Slot=0 pseudo-APDU DirectTransmit Seq=0e BWI=00 RFU=0000 8002000000000e000000 6108 RDR_to_PC_DataBlock SW: more data: 8 bytes Slot=0 Seq=0e Slot Status=00 Slot Error=00 RFU=00 6f05000000000f000000 ffc0000008 pseudo-ADPU GetResponse 8008000000000f000000 d50332010407 9000 SW: OK -------------------------------------------------------------------- Apparently Acr122U PICC can also work without Escape (even if there is no card): 6f070000000000000000 ff00000002 d402 PC_to_RDR_XfrBlock APDU Len..... ClInP1P2Lc Slot=0 pseudo-APDU DirectTransmit Seq=00 BWI=00 RFU=0000 80080000000000008100 d50332010407 9000 SW: OK */ #pragma pack(1) struct ccid_header { uint8_t bMessageType; uint32_t dwLength; uint8_t bSlot; uint8_t bSeq; uint8_t bMessageSpecific[3]; }; struct apdu_header { uint8_t bClass; uint8_t bIns; uint8_t bP1; uint8_t bP2; uint8_t bLen; }; struct acr122_usb_tama_frame { struct ccid_header ccid_header; struct apdu_header apdu_header; uint8_t tama_header; uint8_t tama_payload[254]; // According to ACR122U manual: Pseudo APDUs (Section 6.0), Lc is 1-byte long (Data In: 255-bytes). }; struct acr122_usb_apdu_frame { struct ccid_header ccid_header; struct apdu_header apdu_header; uint8_t apdu_payload[255]; // APDU Lc is 1-byte long }; #pragma pack() // Internal data struct struct acr122_usb_data { usb_dev_handle *pudh; uint32_t uiEndPointIn; uint32_t uiEndPointOut; uint32_t uiMaxPacketSize; volatile bool abort_flag; // Keep some buffers to reduce memcpy() usage struct acr122_usb_tama_frame tama_frame; struct acr122_usb_apdu_frame apdu_frame; }; // CCID Bulk-Out messages type #define PC_to_RDR_IccPowerOn 0x62 #define PC_to_RDR_XfrBlock 0x6f #define RDR_to_PC_DataBlock 0x80 // ISO 7816-4 #define SW1_More_Data_Available 0x61 #define SW1_Warning_with_NV_changed 0x63 #define PN53x_Specific_Application_Level_Error_Code 0x7f // This frame template is copied at init time // Its designed for TAMA sending but is also used for simple ADPU frame: acr122_build_frame_from_apdu() will overwrite needed bytes const uint8_t acr122_usb_frame_template[] = { PC_to_RDR_XfrBlock, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // CCID header 0xff, 0x00, 0x00, 0x00, 0x00, // ADPU header 0xd4, // PN532 direction }; // APDUs instructions #define APDU_GetAdditionnalData 0xc0 // Internal io struct const struct pn53x_io acr122_usb_io; // Prototypes static int acr122_usb_init(nfc_device *pnd); static int acr122_usb_ack(nfc_device *pnd); static int acr122_usb_send_apdu(nfc_device *pnd, const uint8_t ins, const uint8_t p1, const uint8_t p2, const uint8_t *const data, size_t data_len, const uint8_t le, uint8_t *out, const size_t out_size); static int acr122_usb_bulk_read(struct acr122_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout) { int res = usb_bulk_read(data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout); if (res > 0) { LOG_HEX(NFC_LOG_GROUP_COM, "RX", abtRx, res); } else if (res < 0) { if (res != -USB_TIMEDOUT) { res = NFC_EIO; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror(res)); } else { res = NFC_ETIMEOUT; } } return res; } static int acr122_usb_bulk_write(struct acr122_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout) { LOG_HEX(NFC_LOG_GROUP_COM, "TX", abtTx, szTx); int res = usb_bulk_write(data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout); if (res > 0) { // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details if ((res % data->uiMaxPacketSize) == 0) { usb_bulk_write(data->pudh, data->uiEndPointOut, "\0", 0, timeout); } } else if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror(res)); if (res == -USB_TIMEDOUT) { res = NFC_ETIMEOUT; } else { res = NFC_EIO; } } return res; } struct acr122_usb_supported_device { uint16_t vendor_id; uint16_t product_id; const char *name; }; const struct acr122_usb_supported_device acr122_usb_supported_devices[] = { { 0x072F, 0x2200, "ACS ACR122" }, { 0x072F, 0x90CC, "Touchatag" }, }; // Find transfer endpoints for bulk transfers static void acr122_usb_get_end_points(struct usb_device *dev, struct acr122_usb_data *data) { uint32_t uiIndex; uint32_t uiEndPoint; struct usb_interface_descriptor *puid = dev->config->interface->altsetting; // 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out for (uiIndex = 0; uiIndex < puid->bNumEndpoints; uiIndex++) { // Only accept bulk transfer endpoints (ignore interrupt endpoints) if (puid->endpoint[uiIndex].bmAttributes != USB_ENDPOINT_TYPE_BULK) continue; // Copy the endpoint to a local var, makes it more readable code uiEndPoint = puid->endpoint[uiIndex].bEndpointAddress; // Test if we dealing with a bulk IN endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_IN) { data->uiEndPointIn = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } // Test if we dealing with a bulk OUT endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_OUT) { data->uiEndPointOut = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } } } static size_t acr122_usb_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { (void)context; usb_prepare(); size_t device_found = 0; uint32_t uiBusIndex = 0; struct usb_bus *bus; for (bus = usb_get_busses(); bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) { for (size_t n = 0; n < sizeof(acr122_usb_supported_devices) / sizeof(struct acr122_usb_supported_device); n++) { if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { // Make sure there are 2 endpoints available // with libusb-win32 we got some null pointers so be robust before looking at endpoints: if (dev->config == NULL || dev->config->interface == NULL || dev->config->interface->altsetting == NULL) { // Nope, we maybe want the next one, let's try to find another continue; } if (dev->config->interface->altsetting->bNumEndpoints < 2) { // Nope, we maybe want the next one, let's try to find another continue; } usb_dev_handle *udev = usb_open(dev); if (udev == NULL) continue; // Set configuration // acr122_usb_get_usb_device_name (dev, udev, pnddDevices[device_found].acDevice, sizeof (pnddDevices[device_found].acDevice)); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "device found: Bus %s Device %s Name %s", bus->dirname, dev->filename, acr122_usb_supported_devices[n].name); usb_close(udev); snprintf(connstrings[device_found], sizeof(nfc_connstring), "%s:%s:%s", ACR122_USB_DRIVER_NAME, bus->dirname, dev->filename); device_found++; // Test if we reach the maximum "wanted" devices if (device_found == connstrings_len) { return device_found; } } } } } return device_found; } struct acr122_usb_descriptor { char *dirname; char *filename; }; static bool acr122_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len) { *buffer = '\0'; if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) { if (udev) { usb_get_string_simple(udev, dev->descriptor.iManufacturer, buffer, len); if (strlen(buffer) > 0) strcpy(buffer + strlen(buffer), " / "); usb_get_string_simple(udev, dev->descriptor.iProduct, buffer + strlen(buffer), len - strlen(buffer)); } } if (!*buffer) { for (size_t n = 0; n < sizeof(acr122_usb_supported_devices) / sizeof(struct acr122_usb_supported_device); n++) { if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { strncpy(buffer, acr122_usb_supported_devices[n].name, len); buffer[len - 1] = '\0'; return true; } } } return false; } static nfc_device * acr122_usb_open(const nfc_context *context, const nfc_connstring connstring) { nfc_device *pnd = NULL; struct acr122_usb_descriptor desc = { NULL, NULL }; int connstring_decode_level = connstring_decode(connstring, ACR122_USB_DRIVER_NAME, "usb", &desc.dirname, &desc.filename); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); if (connstring_decode_level < 1) { goto free_mem; } struct acr122_usb_data data = { .pudh = NULL, .uiEndPointIn = 0, .uiEndPointOut = 0, }; struct usb_bus *bus; struct usb_device *dev; usb_prepare(); for (bus = usb_get_busses(); bus; bus = bus->next) { if (connstring_decode_level > 1) { // A specific bus have been specified if (0 != strcmp(bus->dirname, desc.dirname)) continue; } for (dev = bus->devices; dev; dev = dev->next) { if (connstring_decode_level > 2) { // A specific dev have been specified if (0 != strcmp(dev->filename, desc.filename)) continue; } // Open the USB device if ((data.pudh = usb_open(dev)) == NULL) continue; // Reset device usb_reset(data.pudh); // Retrieve end points acr122_usb_get_end_points(dev, &data); // Claim interface int res = usb_claim_interface(data.pudh, 0); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror(res)); usb_close(data.pudh); // we failed to use the specified device goto free_mem; } res = usb_set_altinterface(data.pudh, 0); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set alternate setting on USB interface (%s)", _usb_strerror(res)); usb_close(data.pudh); // we failed to use the specified device goto free_mem; } // Allocate memory for the device info and specification, fill it and return the info pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); goto error; } acr122_usb_get_usb_device_name(dev, data.pudh, pnd->name, sizeof(pnd->name)); pnd->driver_data = malloc(sizeof(struct acr122_usb_data)); if (!pnd->driver_data) { perror("malloc"); goto error; } *DRIVER_DATA(pnd) = data; // Alloc and init chip's data if (pn53x_data_new(pnd, &acr122_usb_io) == NULL) { perror("malloc"); goto error; } memcpy(&(DRIVER_DATA(pnd)->tama_frame), acr122_usb_frame_template, sizeof(acr122_usb_frame_template)); memcpy(&(DRIVER_DATA(pnd)->apdu_frame), acr122_usb_frame_template, sizeof(acr122_usb_frame_template)); CHIP_DATA(pnd)->timer_correction = 46; // empirical tuning pnd->driver = &acr122_usb_driver; if (acr122_usb_init(pnd) < 0) { usb_close(data.pudh); goto error; } DRIVER_DATA(pnd)->abort_flag = false; goto free_mem; } } // We ran out of devices before the index required goto free_mem; error: // Free allocated structure on error. nfc_device_free(pnd); pnd = NULL; free_mem: free(desc.dirname); free(desc.filename); return pnd; } static void acr122_usb_close(nfc_device *pnd) { acr122_usb_ack(pnd); pn53x_idle(pnd); int res; if ((res = usb_release_interface(DRIVER_DATA(pnd)->pudh, 0)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror(res)); } if ((res = usb_close(DRIVER_DATA(pnd)->pudh)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror(res)); } pn53x_data_free(pnd); nfc_device_free(pnd); } #if !defined(htole32) uint32_t htole32(uint32_t u32); uint32_t htole32(uint32_t u32) { union { uint8_t arr[4]; uint32_t u32; } u; for (int i = 0; i < 4; i++) { u.arr[i] = (u32 & 0xff); u32 >>= 8; } return u.u32; } #endif /* !defined(htole32) */ static int acr122_build_frame_from_apdu(nfc_device *pnd, const uint8_t ins, const uint8_t p1, const uint8_t p2, const uint8_t *data, const size_t data_len, const uint8_t le) { if (data_len > sizeof(DRIVER_DATA(pnd)->apdu_frame.apdu_payload)) return NFC_EINVARG; if ((data == NULL) && (data_len != 0)) return NFC_EINVARG; DRIVER_DATA(pnd)->apdu_frame.ccid_header.dwLength = htole32(data_len + sizeof(struct apdu_header)); DRIVER_DATA(pnd)->apdu_frame.apdu_header.bIns = ins; DRIVER_DATA(pnd)->apdu_frame.apdu_header.bP1 = p1; DRIVER_DATA(pnd)->apdu_frame.apdu_header.bP2 = p2; if (data) { // bLen is Lc when data != NULL DRIVER_DATA(pnd)->apdu_frame.apdu_header.bLen = data_len; memcpy(DRIVER_DATA(pnd)->apdu_frame.apdu_payload, data, data_len); } else { // bLen is Le when no data. DRIVER_DATA(pnd)->apdu_frame.apdu_header.bLen = le; } return (sizeof(struct ccid_header) + sizeof(struct apdu_header) + data_len); } static int acr122_build_frame_from_tama(nfc_device *pnd, const uint8_t *tama, const size_t tama_len) { if (tama_len > sizeof(DRIVER_DATA(pnd)->tama_frame.tama_payload)) return NFC_EINVARG; DRIVER_DATA(pnd)->tama_frame.ccid_header.dwLength = htole32(tama_len + sizeof(struct apdu_header) + 1); DRIVER_DATA(pnd)->tama_frame.apdu_header.bLen = tama_len + 1; memcpy(DRIVER_DATA(pnd)->tama_frame.tama_payload, tama, tama_len); return (sizeof(struct ccid_header) + sizeof(struct apdu_header) + 1 + tama_len); } static int acr122_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) { int res; if ((res = acr122_build_frame_from_tama(pnd, pbtData, szData)) < 0) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), (unsigned char *) & (DRIVER_DATA(pnd)->tama_frame), res, timeout)) < 0) { pnd->last_error = res; return pnd->last_error; } return NFC_SUCCESS; } #define USB_TIMEOUT_PER_PASS 200 static int acr122_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) { off_t offset = 0; uint8_t abtRxBuf[255 + sizeof(struct ccid_header)]; int res; /* * If no timeout is specified but the command is blocking, force a 200ms (USB_TIMEOUT_PER_PASS) * timeout to allow breaking the loop if the user wants to stop it. */ int usb_timeout; int remaining_time = timeout; read: if (timeout == USB_INFINITE_TIMEOUT) { usb_timeout = USB_TIMEOUT_PER_PASS; } else { // A user-provided timeout is set, we have to cut it in multiple chunk to be able to keep an nfc_abort_command() mecanism remaining_time -= USB_TIMEOUT_PER_PASS; if (remaining_time <= 0) { pnd->last_error = NFC_ETIMEOUT; return pnd->last_error; } else { usb_timeout = MIN(remaining_time, USB_TIMEOUT_PER_PASS); } } res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), usb_timeout); uint8_t attempted_response = RDR_to_PC_DataBlock; size_t len; if (res == NFC_ETIMEOUT) { if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; acr122_usb_ack(pnd); pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } else { goto read; } } if (res < 12) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Invalid RDR_to_PC_DataBlock frame"); // try to interrupt current device state acr122_usb_ack(pnd); pnd->last_error = NFC_EIO; return pnd->last_error; } if (abtRxBuf[offset] != attempted_response) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame header mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset++; len = abtRxBuf[offset++]; if (!((len > 1) && (abtRxBuf[10] == 0xd5))) { // In case we didn't get an immediate answer: if (len != 2) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Wrong reply"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (abtRxBuf[10] != SW1_More_Data_Available) { if ((abtRxBuf[10] == SW1_Warning_with_NV_changed) && (abtRxBuf[11] == PN53x_Specific_Application_Level_Error_Code)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "PN532 has detected an error at the application level"); } else if ((abtRxBuf[10] == SW1_Warning_with_NV_changed) && (abtRxBuf[11] == 0x00)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "PN532 didn't reply"); } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unexpected Status Word (SW1: %02x SW2: %02x)", abtRxBuf[10], abtRxBuf[11]); } pnd->last_error = NFC_EIO; return pnd->last_error; } res = acr122_usb_send_apdu(pnd, APDU_GetAdditionnalData, 0x00, 0x00, NULL, 0, abtRxBuf[11], abtRxBuf, sizeof(abtRxBuf)); if (res == NFC_ETIMEOUT) { if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; acr122_usb_ack(pnd); pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } else { goto read; // FIXME May cause some trouble on Touchatag, right ? } } if (res < 12) { // try to interrupt current device state acr122_usb_ack(pnd); pnd->last_error = NFC_EIO; return pnd->last_error; } } offset = 0; if (abtRxBuf[offset] != attempted_response) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame header mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset++; // XXX In CCID specification, len is a 32-bits (dword), do we need to decode more than 1 byte ? (0-255 bytes for PN532 reply) len = abtRxBuf[offset++]; if ((abtRxBuf[offset] != 0x00) && (abtRxBuf[offset + 1] != 0x00) && (abtRxBuf[offset + 2] != 0x00)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Not implemented: only 1-byte length is supported, please report this bug with a full trace."); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 3; if (len < 4) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Too small reply"); pnd->last_error = NFC_EIO; return pnd->last_error; } len -= 4; // We skip 2 bytes for PN532 direction byte (D5) and command byte (CMD+1), then 2 bytes for APDU status (90 00). if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EOVFLOW; return pnd->last_error; } // Skip CCID remaining bytes offset += 2; // bSlot and bSeq are not used offset += 2; // XXX bStatus and bError should maybe checked ? offset += 1; // bRFU should be 0x00 // TFI + PD0 (CC+1) if (abtRxBuf[offset] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; if (abtRxBuf[offset] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; memcpy(pbtData, abtRxBuf + offset, len); return len; } int acr122_usb_ack(nfc_device *pnd) { (void) pnd; int res = 0; uint8_t acr122_ack_frame[] = { GetFirmwareVersion }; // We can't send a PN532's ACK frame, so we use a normal command to cancel current command log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ACR122 Abort"); if ((res = acr122_build_frame_from_tama(pnd, acr122_ack_frame, sizeof(acr122_ack_frame))) < 0) return res; if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), (unsigned char *) & (DRIVER_DATA(pnd)->tama_frame), res, 1000)) < 0) return res; uint8_t abtRxBuf[255 + sizeof(struct ccid_header)]; res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), 1000); return res; } static int acr122_usb_send_apdu(nfc_device *pnd, const uint8_t ins, const uint8_t p1, const uint8_t p2, const uint8_t *const data, size_t data_len, const uint8_t le, uint8_t *out, const size_t out_size) { int res; size_t frame_len = acr122_build_frame_from_apdu(pnd, ins, p1, p2, data, data_len, le); if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), (unsigned char *) & (DRIVER_DATA(pnd)->apdu_frame), frame_len, 1000)) < 0) return res; if ((res = acr122_usb_bulk_read(DRIVER_DATA(pnd), out, out_size, 1000)) < 0) return res; return res; } int acr122_usb_init(nfc_device *pnd) { int res = 0; int i; uint8_t abtRxBuf[255 + sizeof(struct ccid_header)]; /* // See ACR122 manual: "Bi-Color LED and Buzzer Control" section uint8_t acr122u_get_led_state_frame[] = { 0x6b, // CCID 0x09, // lenght of frame 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding // frame: 0xff, // Class 0x00, // INS 0x40, // P1: Get LED state command 0x00, // P2: LED state control 0x04, // Lc 0x00, 0x00, 0x00, 0x00, // Blinking duration control }; log_put (LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ACR122 Get LED state"); if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *) acr122u_get_led_state_frame, sizeof (acr122u_get_led_state_frame), 1000)) < 0) return res; if ((res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), 1000)) < 0) return res; */ if ((res = pn53x_set_property_int(pnd, NP_TIMEOUT_COMMAND, 1000)) < 0) return res; // Power On ICC uint8_t ccid_frame[] = { PC_to_RDR_IccPowerOn, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00 }; if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), ccid_frame, sizeof(struct ccid_header), 1000)) < 0) return res; if ((res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), 1000)) < 0) return res; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ACR122 PICC Operating Parameters"); if ((res = acr122_usb_send_apdu(pnd, 0x00, 0x51, 0x00, NULL, 0, 0, abtRxBuf, sizeof(abtRxBuf))) < 0) return res; res = 0; for (i = 0; i < 3; i++) { if (res < 0) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "PN532 init failed, trying again..."); if ((res = pn53x_init(pnd)) >= 0) break; } if (res < 0) return res; return NFC_SUCCESS; } static int acr122_usb_abort_command(nfc_device *pnd) { DRIVER_DATA(pnd)->abort_flag = true; return NFC_SUCCESS; } const struct pn53x_io acr122_usb_io = { .send = acr122_usb_send, .receive = acr122_usb_receive, }; const struct nfc_driver acr122_usb_driver = { .name = ACR122_USB_DRIVER_NAME, .scan_type = NOT_INTRUSIVE, .scan = acr122_usb_scan, .open = acr122_usb_open, .close = acr122_usb_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = acr122_usb_abort_command, .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
C
/*- * 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 arygon.h * @brief Driver for PN53x-equipped ARYGON device connected using UART */ #ifndef __NFC_DRIVER_ARYGON_H__ #define __NFC_DRIVER_ARYGON_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver arygon_driver; #endif // ! __NFC_DRIVER_ARYGON_H__
C
/*- * 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 pn532_uart.h * @brief Driver for PN532 connected in UART (HSU) */ #ifndef __NFC_DRIVER_PN532_UART_H__ #define __NFC_DRIVER_PN532_UART_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver pn532_uart_driver; #endif // ! __NFC_DRIVER_PN532_UART_H__
C
/*- * 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 pn532_i2c.h * @brief Driver for PN532 connected through I2C bus */ #ifndef __NFC_DRIVER_PN532_I2C_H__ #define __NFC_DRIVER_PN532_I2C_H__ #include <nfc/nfc-types.h> /* Reference to the I2C driver structure */ extern const struct nfc_driver pn532_i2c_driver; #endif // ! __NFC_DRIVER_I2C_H__
C
/*- * 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 pn532_spi.c * @brief PN532 driver using SPI bus */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "pn532_spi.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "spi.h" #define PN532_SPI_DEFAULT_SPEED 1000000 // 1 MHz #define PN532_SPI_DRIVER_NAME "pn532_spi" #define PN532_SPI_MODE SPI_MODE_0 #define LOG_CATEGORY "libnfc.driver.pn532_spi" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #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 // Internal data structs const struct pn53x_io pn532_spi_io; struct pn532_spi_data { spi_port port; volatile bool abort_flag; }; static const uint8_t pn532_spi_cmd_dataread = 0x03; static const uint8_t pn532_spi_cmd_datawrite = 0x01; // Prototypes int pn532_spi_ack(nfc_device *pnd); int pn532_spi_wakeup(nfc_device *pnd); #define DRIVER_DATA(pnd) ((struct pn532_spi_data*)(pnd->driver_data)) static size_t pn532_spi_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; spi_port sp; char **acPorts = spi_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = spi_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find PN532 device on SPI port: %s at %d Hz.", acPort, PN532_SPI_DEFAULT_SPEED); if ((sp != INVALID_SPI_PORT) && (sp != CLAIMED_SPI_PORT)) { // Serial port claimed but we need to check if a PN532_SPI is opened. spi_set_speed(sp, PN532_SPI_DEFAULT_SPEED); spi_set_mode(sp, PN532_SPI_MODE); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, PN532_SPI_DRIVER_NAME, acPort, PN532_SPI_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); spi_close(sp); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } pnd->driver = &pn532_spi_driver; pnd->driver_data = malloc(sizeof(struct pn532_spi_data)); if (!pnd->driver_data) { perror("malloc"); spi_close(sp); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_spi_io) == NULL) { perror("malloc"); spi_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat power mode CHIP_DATA(pnd)->power_mode = LOWVBAT; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) int res = pn53x_check_communication(pnd); spi_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } struct pn532_spi_descriptor { char *port; uint32_t speed; }; static void pn532_spi_close(nfc_device *pnd) { pn53x_idle(pnd); // Release SPI port spi_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); } static nfc_device * pn532_spi_open(const nfc_context *context, const nfc_connstring connstring) { struct pn532_spi_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, PN532_SPI_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = PN532_SPI_DEFAULT_SPEED; } spi_port sp; nfc_device *pnd = NULL; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open: %s at %d Hz.", ndd.port, ndd.speed); sp = spi_open(ndd.port); if (sp == INVALID_SPI_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid SPI port: %s", ndd.port); if (sp == CLAIMED_SPI_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "SPI port already claimed: %s", ndd.port); if ((sp == CLAIMED_SPI_PORT) || (sp == INVALID_SPI_PORT)) { free(ndd.port); return NULL; } spi_set_speed(sp, ndd.speed); spi_set_mode(sp, PN532_SPI_MODE); // We have a connection pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); spi_close(sp); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", PN532_SPI_DRIVER_NAME, ndd.port); free(ndd.port); pnd->driver_data = malloc(sizeof(struct pn532_spi_data)); if (!pnd->driver_data) { perror("malloc"); spi_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_spi_io) == NULL) { perror("malloc"); spi_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat mode CHIP_DATA(pnd)->power_mode = LOWVBAT; // empirical tuning CHIP_DATA(pnd)->timer_correction = 48; pnd->driver = &pn532_spi_driver; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) if (pn53x_check_communication(pnd) < 0) { nfc_perror(pnd, "pn53x_check_communication"); pn532_spi_close(pnd); return NULL; } pn53x_init(pnd); return pnd; } static int pn532_spi_read_spi_status(nfc_device *pnd) { static const uint8_t pn532_spi_statread_cmd = 0x02; uint8_t spi_status = 0; int res = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_statread_cmd, 1, &spi_status, 1, true); if (res != NFC_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to read SPI status"); return res; } return spi_status; } int pn532_spi_wakeup(nfc_device *pnd) { /* SPI wakeup is basically activating chipselect for several ms. * To do so, we are sending harmless command at very low speed */ int res; const uint32_t prev_port_speed = spi_get_speed(DRIVER_DATA(pnd)->port); // Try to get byte from the SPI line. If PN532 is powered down, the byte will be 0xff (MISO line is high) uint8_t spi_byte = 0; res = spi_receive(DRIVER_DATA(pnd)->port, &spi_byte, 1, true); if (res != NFC_SUCCESS) { return res; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Got %x byte from SPI line before wakeup", spi_byte); CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 will be awake soon msleep(1); if (spi_byte == 0xff) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Wakeup is needed"); spi_set_speed(DRIVER_DATA(pnd)->port, 5000); // set slow speed res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000); // wakeup by sending SAMConfiguration, which works just fine spi_set_speed(DRIVER_DATA(pnd)->port, prev_port_speed); } return res; } #define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int pn532_spi_wait_for_data(nfc_device *pnd, int timeout) { static const uint8_t pn532_spi_ready = 0x01; static const int pn532_spi_poll_interval = 10; //ms int timer = 0; int ret; while ((ret = pn532_spi_read_spi_status(pnd)) != pn532_spi_ready) { if (ret < 0) { return ret; } if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; return NFC_EOPABORTED; } if (timeout > 0) { timer += pn532_spi_poll_interval; if (timer > timeout) { return NFC_ETIMEOUT; } msleep(pn532_spi_poll_interval); } } return NFC_SUCCESS; } static int pn532_spi_receive_next_chunk(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen) { // According to datasheet, the entire read operation should be done at once // However, it seems impossible to do since the length of the frame is stored in the frame // itself and it's impossible to manually set CS to low between two read operations // It's possible to read the response frame in a series of read operations, provided // each read operation is preceded by SPI_DATAREAD byte from the host. // Unfortunately, the PN532 sends first byte of the second and successive response chunks // at the same time as host sends SPI_DATAREAD byte // Many hardware SPI implementations are half-duplex, so it's became impossible to read this // first response byte // The following hack is used here: we first try to receive data from PN532 without SPI_DATAREAD // and then begin full-featured read operation // The PN532 does not shift the internal register on the receive operation, which allows us to read the whole response // The example transfer log is as follows: // CS ..._/---\___________________________/---\________/------\_____________/-----\_________/---\____________/---... // MOSI (host=>pn532) ... 0x03 0x00 0x00 0x00 0x00 0x00 0x03 0x00 0x00 0x03 0x00 // MISO (pn532<=host) ... 0x01 0x00 0xff 0x02 0xfe 0xd5 0xd5 0x15 0x16 0x16 0x00 // linux send/receive s r r r r r s r r s r // |<-- data -->| |<-data->| |<-data->| |<-data->| |<-data->| // |<-- first chunk -->| |<-- second chunk -->| |<-- third chunk -->| // The response frame is 0x00 0xff 0x02 0xfe 0xd5 0x15 0x16 0x00 int res = spi_receive(DRIVER_DATA(pnd)->port, pbtData, 1, true); if (res != NFC_SUCCESS) { return res; } res = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_cmd_dataread, 1, pbtData + 1, szDataLen - 1, true); return res; } static int pn532_spi_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t abtRxBuf[5]; size_t len; pnd->last_error = pn532_spi_wait_for_data(pnd, timeout); if (NFC_EOPABORTED == pnd->last_error) { return pn532_spi_ack(pnd); } if (pnd->last_error != NFC_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to wait for SPI data. (RX)"); goto error; } pnd->last_error = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_cmd_dataread, 1, abtRxBuf , 4, true); if (pnd->last_error < 0) { goto error; } const uint8_t pn53x_long_preamble[3] = { 0x00, 0x00, 0xff }; if (0 == (memcmp(abtRxBuf, pn53x_long_preamble, 3))) { // long preamble // omit first byte for (size_t i = 0; i < 3; ++i) { abtRxBuf[i] = abtRxBuf[i + 1]; } // need one more byte pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf + 3, 1); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive one more byte for long preamble frame. (RX)"); goto error; } } const uint8_t pn53x_preamble[2] = { 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 2))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", " preamble+start code mismatch"); pnd->last_error = NFC_EIO; goto error; } if ((0x01 == abtRxBuf[2]) && (0xff == abtRxBuf[3])) { // Error frame pn532_spi_receive_next_chunk(pnd, abtRxBuf, 3); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; goto error; } else if ((0xff == abtRxBuf[2]) && (0xff == abtRxBuf[3])) { // Extended frame pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf, 3); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } // (abtRxBuf[0] << 8) + abtRxBuf[1] (LEN) include TFI + (CC+1) len = (abtRxBuf[0] << 8) + abtRxBuf[1] - 2; if (((abtRxBuf[0] + abtRxBuf[1] + abtRxBuf[2]) % 256) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } } else { // Normal frame if (256 != (abtRxBuf[2] + abtRxBuf[3])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[2] - 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); pnd->last_error = NFC_EIO; goto error; } // TFI + PD0 (CC+1) pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf, 2); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } if (abtRxBuf[0] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; goto error; } if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; goto error; } if (len) { pnd->last_error = pn532_spi_receive_next_chunk(pnd, pbtData, len); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } } pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf, 2); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[0]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } if (0x00 != abtRxBuf[1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; goto error; } // The PN53x command is done and we successfully received the reply return len; error: return pnd->last_error; } static int pn532_spi_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; switch (CHIP_DATA(pnd)->power_mode) { case LOWVBAT: { /** PN532C106 wakeup. */ if ((res = pn532_spi_wakeup(pnd)) < 0) { return res; } // According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000)) < 0) { return res; } } break; case POWERDOWN: { if ((res = pn532_spi_wakeup(pnd)) < 0) { return res; } } break; case NORMAL: // Nothing to do :) break; }; uint8_t abtFrame[PN532_BUFFER_LEN + 1] = { pn532_spi_cmd_datawrite, 0x00, 0x00, 0xff }; // SPI data transfer starts with DATAWRITE (0x01) byte, Every packet must start with "00 00 ff" size_t szFrame = 0; if ((res = pn53x_build_frame(abtFrame + 1, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } res = spi_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame, true); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } res = pn532_spi_wait_for_data(pnd, timeout); if (res != NFC_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to wait for SPI data. (RX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; res = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_cmd_dataread, 1, abtRxBuf, sizeof(abtRxBuf), true); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to read ACK"); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { // The PN53x is running the sent command } else { return pnd->last_error; } return NFC_SUCCESS; } int pn532_spi_ack(nfc_device *pnd) { const size_t ack_frame_len = (sizeof(pn53x_ack_frame) / sizeof(pn53x_ack_frame[0])); uint8_t ack_tx_buf [1 + ack_frame_len]; ack_tx_buf[0] = pn532_spi_cmd_datawrite; memcpy(ack_tx_buf + 1, pn53x_ack_frame, ack_frame_len); int res = spi_send(DRIVER_DATA(pnd)->port, ack_tx_buf, ack_frame_len + 1, true); return res; } static int pn532_spi_abort_command(nfc_device *pnd) { if (pnd) { DRIVER_DATA(pnd)->abort_flag = true; } return NFC_SUCCESS; } const struct pn53x_io pn532_spi_io = { .send = pn532_spi_send, .receive = pn532_spi_receive, }; const struct nfc_driver pn532_spi_driver = { .name = PN532_SPI_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = pn532_spi_scan, .open = pn532_spi_open, .close = pn532_spi_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = pn532_initiator_init_secure_element, .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn532_spi_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
C
/*- * 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 arygon.c * @brief ARYGON readers driver * * This driver can handle ARYGON readers that use UART as bus. * UART connection can be direct (host<->arygon_uc) or could be provided by internal USB to serial interface (e.g. host<->ftdi_chip<->arygon_uc) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "arygon.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <string.h> #include <unistd.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "uart.h" /** @def DEV_ARYGON_PROTOCOL_ARYGON_ASCII * @brief High level language in ASCII format. (Common µC commands and Mifare® commands) */ #define DEV_ARYGON_PROTOCOL_ARYGON_ASCII '0' /** @def DEV_ARYGON_MODE_HL_ASCII * @brief High level language in Binary format With AddressingByte for party line. (Common µC commands and Mifare® commands) */ #define DEV_ARYGON_PROTOCOL_ARYGON_BINARY_WAB '1' /** @def DEV_ARYGON_PROTOCOL_TAMA * @brief Philips protocol (TAMA language) in binary format. */ #define DEV_ARYGON_PROTOCOL_TAMA '2' /** @def DEV_ARYGON_PROTOCOL_TAMA_WAB * @brief Philips protocol (TAMA language) in binary With AddressingByte for party line. */ #define DEV_ARYGON_PROTOCOL_TAMA_WAB '3' #define ARYGON_DEFAULT_SPEED 9600 #define ARYGON_DRIVER_NAME "arygon" #define LOG_CATEGORY "libnfc.driver.arygon" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define DRIVER_DATA(pnd) ((struct arygon_data*)(pnd->driver_data)) // Internal data structs const struct pn53x_io arygon_tama_io; struct arygon_data { serial_port port; #ifndef WIN32 int iAbortFds[2]; #else volatile bool abort_flag; #endif }; // ARYGON frames static const uint8_t arygon_error_none[] = "FF000000\x0d\x0a"; static const uint8_t arygon_error_incomplete_command[] = "FF0C0000\x0d\x0a"; static const uint8_t arygon_error_unknown_mode[] = "FF060000\x0d\x0a"; // Prototypes int arygon_reset_tama(nfc_device *pnd); void arygon_firmware(nfc_device *pnd, char *str); static size_t arygon_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; serial_port sp; char **acPorts = uart_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = uart_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find ARYGON device on serial port: %s at %d baud.", acPort, ARYGON_DEFAULT_SPEED); if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp, true); uart_set_speed(sp, ARYGON_DEFAULT_SPEED); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ARYGON_DRIVER_NAME, acPort, ARYGON_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); uart_close(sp); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } pnd->driver = &arygon_driver; pnd->driver_data = malloc(sizeof(struct arygon_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &arygon_tama_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif int res = arygon_reset_tama(pnd); uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } // ARYGON reader is found memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } struct arygon_descriptor { char *port; uint32_t speed; }; static void arygon_close_step2(nfc_device *pnd) { // Release UART port uart_close(DRIVER_DATA(pnd)->port); #ifndef WIN32 // Release file descriptors used for abort mecanism close(DRIVER_DATA(pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[1]); #endif pn53x_data_free(pnd); nfc_device_free(pnd); } static void arygon_close(nfc_device *pnd) { pn53x_idle(pnd); arygon_close_step2(pnd); } static nfc_device * arygon_open(const nfc_context *context, const nfc_connstring connstring) { struct arygon_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, ARYGON_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = ARYGON_DEFAULT_SPEED; } serial_port sp; nfc_device *pnd = NULL; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open: %s at %d baud.", ndd.port, ndd.speed); sp = uart_open(ndd.port); if (sp == INVALID_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); if (sp == CLAIMED_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT)) { free(ndd.port); return NULL; } // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp, true); uart_set_speed(sp, ndd.speed); // We have a connection pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); uart_close(sp); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", ARYGON_DRIVER_NAME, ndd.port); free(ndd.port); pnd->driver_data = malloc(sizeof(struct arygon_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &arygon_tama_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } // The PN53x chip opened to ARYGON MCU doesn't seems to be in LowVBat mode CHIP_DATA(pnd)->power_mode = NORMAL; // empirical tuning CHIP_DATA(pnd)->timer_correction = 46; pnd->driver = &arygon_driver; #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); return NULL; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif // Check communication using "Reset TAMA" command if (arygon_reset_tama(pnd) < 0) { arygon_close_step2(pnd); return NULL; } char arygon_firmware_version[10]; arygon_firmware(pnd, arygon_firmware_version); char *pcName; pcName = strdup(pnd->name); snprintf(pnd->name, sizeof(pnd->name), "%s %s", pcName, arygon_firmware_version); free(pcName); pn53x_init(pnd); return pnd; } #define ARYGON_TX_BUFFER_LEN (PN53x_NORMAL_FRAME__DATA_MAX_LEN + PN53x_NORMAL_FRAME__OVERHEAD + 1) #define ARYGON_RX_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int arygon_tama_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; // Before sending anything, we need to discard from any junk bytes uart_flush_input(DRIVER_DATA(pnd)->port, false); uint8_t abtFrame[ARYGON_TX_BUFFER_LEN] = { DEV_ARYGON_PROTOCOL_TAMA, 0x00, 0x00, 0xff }; // Every packet must start with "0x32 0x00 0x00 0xff" size_t szFrame = 0; if (szData > PN53x_NORMAL_FRAME__DATA_MAX_LEN) { // ARYGON Reader with PN532 equipped does not support extended frame (bug in ARYGON firmware?) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "ARYGON device does not support more than %d bytes as payload (requested: %" PRIdPTR ")", PN53x_NORMAL_FRAME__DATA_MAX_LEN, szData); pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } if ((res = pn53x_build_frame(abtFrame + 1, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } if ((res = uart_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame + 1, timeout)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; if ((res = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, sizeof(abtRxBuf), 0, timeout)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to read ACK"); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { // The PN53x is running the sent command } else if (0 == memcmp(arygon_error_unknown_mode, abtRxBuf, sizeof(abtRxBuf))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Bad frame format."); // We have already read 6 bytes and arygon_error_unknown_mode is 10 bytes long // so we have to read 4 remaining bytes to be synchronized at the next receiving pass. pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 4, 0, timeout); return pnd->last_error; } else { return pnd->last_error; } return NFC_SUCCESS; } static int arygon_abort(nfc_device *pnd) { // Send a valid TAMA packet to wakup the PN53x (we will not have an answer, according to Arygon manual) uint8_t dummy[] = { 0x32, 0x00, 0x00, 0xff, 0x09, 0xf7, 0xd4, 0x00, 0x00, 0x6c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0xbe, 0x00 }; uart_send(DRIVER_DATA(pnd)->port, dummy, sizeof(dummy), 0); // Using Arygon device we can't send ACK frame to abort the running command return pn53x_check_communication(pnd); } static int arygon_tama_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t abtRxBuf[5]; size_t len; void *abort_p = NULL; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->iAbortFds[1]); #else abort_p = (void *) & (DRIVER_DATA(pnd)->abort_flag); #endif pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 5, abort_p, timeout); if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { arygon_abort(pnd); /* last_error got reset by arygon_abort() */ pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Error frame uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; return pnd->last_error; } else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Extended frame // ARYGON devices does not support extended frame sending abort(); } else { // Normal frame if (256 != (abtRxBuf[3] + abtRxBuf[4])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[3] - 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; return pnd->last_error; } // TFI + PD0 (CC+1) pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } if (abtRxBuf[0] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (len) { pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, pbtData, len, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } } pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[0]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (0x00 != abtRxBuf[1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // The PN53x command is done and we successfully received the reply return len; } void arygon_firmware(nfc_device *pnd, char *str) { const uint8_t arygon_firmware_version_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'v' }; uint8_t abtRx[16]; size_t szRx = sizeof(abtRx); int res = uart_send(DRIVER_DATA(pnd)->port, arygon_firmware_version_cmd, sizeof(arygon_firmware_version_cmd), 0); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to send ARYGON firmware command."); return; } res = uart_receive(DRIVER_DATA(pnd)->port, abtRx, szRx, 0, 0); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to retrieve ARYGON firmware version."); return; } if (0 == memcmp(abtRx, arygon_error_none, 6)) { uint8_t *p = abtRx + 6; unsigned int szData; sscanf((const char *)p, "%02x%9s", &szData, p); if (szData > 9) szData = 9; memcpy(str, p, szData); *(str + szData) = '\0'; } } int arygon_reset_tama(nfc_device *pnd) { const uint8_t arygon_reset_tama_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'r' }; uint8_t abtRx[10]; // Attempted response is 10 bytes long size_t szRx = sizeof(abtRx); int res; uart_send(DRIVER_DATA(pnd)->port, arygon_reset_tama_cmd, sizeof(arygon_reset_tama_cmd), 500); // Two reply are possible from ARYGON device: arygon_error_none (ie. in case the byte is well-sent) // or arygon_error_unknown_mode (ie. in case of the first byte was bad-transmitted) res = uart_receive(DRIVER_DATA(pnd)->port, abtRx, szRx, 0, 1000); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "No reply to 'reset TAMA' command."); pnd->last_error = res; return pnd->last_error; } if (0 != memcmp(abtRx, arygon_error_none, sizeof(arygon_error_none) - 1)) { pnd->last_error = NFC_EIO; return pnd->last_error; } return NFC_SUCCESS; } static int arygon_abort_command(nfc_device *pnd) { if (pnd) { #ifndef WIN32 close(DRIVER_DATA(pnd)->iAbortFds[0]); if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { return NFC_ESOFT; } #else DRIVER_DATA(pnd)->abort_flag = true; #endif } return NFC_SUCCESS; } const struct pn53x_io arygon_tama_io = { .send = arygon_tama_send, .receive = arygon_tama_receive, }; const struct nfc_driver arygon_driver = { .name = ARYGON_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = arygon_scan, .open = arygon_open, .close = arygon_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = arygon_abort_command, .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
C
/*- * 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 pn532_spi.h * @brief Driver for PN532 connected in SPI */ #ifndef __NFC_DRIVER_PN532_SPI_H__ #define __NFC_DRIVER_PN532_SPI_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver pn532_spi_driver; #endif // ! __NFC_DRIVER_PN532_SPI_H__
C
/*- * 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 acr122_pcsc.c * @brief Driver for ACR122 devices (e.g. Tikitag, Touchatag, ACS ACR122) behind PC/SC */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <nfc/nfc.h> #include "chips/pn53x.h" #include "drivers/acr122_pcsc.h" #include "nfc-internal.h" // Bus #ifdef __APPLE__ #include <PCSC/winscard.h> #include <PCSC/wintypes.h> #else #include <winscard.h> #endif #define ACR122_PCSC_DRIVER_NAME "acr122_pcsc" #if defined (_WIN32) # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE SCARD_CTL_CODE(3500) #elif defined(__APPLE__) # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE (((0x31) << 16) | ((3500) << 2)) #elif defined (__FreeBSD__) || defined (__OpenBSD__) # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE (((0x31) << 16) | ((3500) << 2)) #elif defined (__linux__) # include <reader.h> // Escape IOCTL tested successfully: # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE SCARD_CTL_CODE(1) #else # error "Can't determine serial string for your system" #endif #include <nfc/nfc.h> #define SCARD_OPERATION_SUCCESS 0x61 #define SCARD_OPERATION_ERROR 0x63 #ifndef SCARD_PROTOCOL_UNDEFINED # define SCARD_PROTOCOL_UNDEFINED SCARD_PROTOCOL_UNSET #endif #define FIRMWARE_TEXT "ACR122U" // Tested on: ACR122U101(ACS), ACR122U102(Tikitag), ACR122U203(ACS) #define ACR122_PCSC_WRAP_LEN 6 #define ACR122_PCSC_COMMAND_LEN 266 #define ACR122_PCSC_RESPONSE_LEN 268 #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define LOG_CATEGORY "libnfc.driver.acr122_pcsc" // Internal data struct const struct pn53x_io acr122_pcsc_io; // Prototypes char *acr122_pcsc_firmware(nfc_device *pnd); const char *supported_devices[] = { "ACS ACR122", // ACR122U & Touchatag, last version "ACS ACR 38U-CCID", // Touchatag, early version "ACS ACR38U-CCID", // Touchatag, early version, under MacOSX "ACS AET65", // Touchatag using CCID driver version >= 1.4.6 " CCID USB", // ?? NULL }; struct acr122_pcsc_data { SCARDHANDLE hCard; SCARD_IO_REQUEST ioCard; uint8_t abtRx[ACR122_PCSC_RESPONSE_LEN]; size_t szRx; }; #define DRIVER_DATA(pnd) ((struct acr122_pcsc_data*)(pnd->driver_data)) static SCARDCONTEXT _SCardContext; static int _iSCardContextRefCount = 0; static SCARDCONTEXT * acr122_pcsc_get_scardcontext(void) { if (_iSCardContextRefCount == 0) { if (SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &_SCardContext) != SCARD_S_SUCCESS) return NULL; } _iSCardContextRefCount++; return &_SCardContext; } static void acr122_pcsc_free_scardcontext(void) { if (_iSCardContextRefCount) { _iSCardContextRefCount--; if (!_iSCardContextRefCount) { SCardReleaseContext(_SCardContext); } } } #define PCSC_MAX_DEVICES 16 /** * @brief List opened devices * * Probe PCSC to find ACR122 devices (ACR122U and Touchatag/Tikitag). * * @param connstring array of nfc_connstring where found device's connection strings will be stored. * @param connstrings_len size of connstrings array. * @return number of devices found. */ static size_t acr122_pcsc_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { (void) context; size_t szPos = 0; char acDeviceNames[256 + 64 * PCSC_MAX_DEVICES]; size_t szDeviceNamesLen = sizeof(acDeviceNames); SCARDCONTEXT *pscc; int i; // Clear the reader list memset(acDeviceNames, '\0', szDeviceNamesLen); // Test if context succeeded if (!(pscc = acr122_pcsc_get_scardcontext())) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Warning: %s", "PCSC context not found (make sure PCSC daemon is running)."); return 0; } // Retrieve the string array of all available pcsc readers DWORD dwDeviceNamesLen = szDeviceNamesLen; if (SCardListReaders(*pscc, NULL, acDeviceNames, &dwDeviceNamesLen) != SCARD_S_SUCCESS) return 0; size_t device_found = 0; while ((acDeviceNames[szPos] != '\0') && (device_found < connstrings_len)) { bool bSupported = false; for (i = 0; supported_devices[i] && !bSupported; i++) { int l = strlen(supported_devices[i]); bSupported = 0 == strncmp(supported_devices[i], acDeviceNames + szPos, l); } if (bSupported) { // Supported ACR122 device found snprintf(connstrings[device_found], sizeof(nfc_connstring), "%s:%s", ACR122_PCSC_DRIVER_NAME, acDeviceNames + szPos); device_found++; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "PCSC device [%s] is not NFC capable or not supported by libnfc.", acDeviceNames + szPos); } // Find next device name position while (acDeviceNames[szPos++] != '\0'); } acr122_pcsc_free_scardcontext(); return device_found; } struct acr122_pcsc_descriptor { char *pcsc_device_name; }; static nfc_device * acr122_pcsc_open(const nfc_context *context, const nfc_connstring connstring) { struct acr122_pcsc_descriptor ndd; int connstring_decode_level = connstring_decode(connstring, ACR122_PCSC_DRIVER_NAME, "pcsc", &ndd.pcsc_device_name, NULL); if (connstring_decode_level < 1) { return NULL; } nfc_connstring fullconnstring; if (connstring_decode_level == 1) { // Device was not specified, take the first one we can find size_t szDeviceFound = acr122_pcsc_scan(context, &fullconnstring, 1); if (szDeviceFound < 1) return NULL; connstring_decode_level = connstring_decode(fullconnstring, ACR122_PCSC_DRIVER_NAME, "pcsc", &ndd.pcsc_device_name, NULL); if (connstring_decode_level < 2) { return NULL; } } else { memcpy(fullconnstring, connstring, sizeof(nfc_connstring)); } if (strlen(ndd.pcsc_device_name) < 5) { // We can assume it's a reader ID as pcsc_name always ends with "NN NN" // Device was not specified, only ID, retrieve it size_t index; if (sscanf(ndd.pcsc_device_name, "%4" SCNuPTR, &index) != 1) { free(ndd.pcsc_device_name); return NULL; } nfc_connstring *ncs = malloc(sizeof(nfc_connstring) * (index + 1)); if (!ncs) { perror("malloc"); free(ndd.pcsc_device_name); return NULL; } size_t szDeviceFound = acr122_pcsc_scan(context, ncs, index + 1); if (szDeviceFound < index + 1) { free(ncs); free(ndd.pcsc_device_name); return NULL; } strncpy(fullconnstring, ncs[index], sizeof(nfc_connstring)); fullconnstring[sizeof(nfc_connstring) - 1] = '\0'; free(ncs); connstring_decode_level = connstring_decode(fullconnstring, ACR122_PCSC_DRIVER_NAME, "pcsc", &ndd.pcsc_device_name, NULL); if (connstring_decode_level < 2) { free(ndd.pcsc_device_name); return NULL; } } char *pcFirmware; nfc_device *pnd = nfc_device_new(context, fullconnstring); if (!pnd) { perror("malloc"); goto error; } pnd->driver_data = malloc(sizeof(struct acr122_pcsc_data)); if (!pnd->driver_data) { perror("malloc"); goto error; } // Alloc and init chip's data if (pn53x_data_new(pnd, &acr122_pcsc_io) == NULL) { perror("malloc"); goto error; } SCARDCONTEXT *pscc; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open %s", ndd.pcsc_device_name); // Test if context succeeded if (!(pscc = acr122_pcsc_get_scardcontext())) goto error; // Test if we were able to connect to the "emulator" card if (SCardConnect(*pscc, ndd.pcsc_device_name, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &(DRIVER_DATA(pnd)->hCard), (void *) & (DRIVER_DATA(pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { // Connect to ACR122 firmware version >2.0 if (SCardConnect(*pscc, ndd.pcsc_device_name, SCARD_SHARE_DIRECT, 0, &(DRIVER_DATA(pnd)->hCard), (void *) & (DRIVER_DATA(pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { // We can not connect to this device. log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "PCSC connect failed"); goto error; } } // Configure I/O settings for card communication DRIVER_DATA(pnd)->ioCard.cbPciLength = sizeof(SCARD_IO_REQUEST); // Retrieve the current firmware version pcFirmware = acr122_pcsc_firmware(pnd); if (strstr(pcFirmware, FIRMWARE_TEXT) != NULL) { // Done, we found the reader we are looking for snprintf(pnd->name, sizeof(pnd->name), "%s / %s", ndd.pcsc_device_name, pcFirmware); // 50: empirical tuning on Touchatag // 46: empirical tuning on ACR122U CHIP_DATA(pnd)->timer_correction = 50; pnd->driver = &acr122_pcsc_driver; pn53x_init(pnd); free(ndd.pcsc_device_name); return pnd; } error: free(ndd.pcsc_device_name); nfc_device_free(pnd); return NULL; } static void acr122_pcsc_close(nfc_device *pnd) { pn53x_idle(pnd); SCardDisconnect(DRIVER_DATA(pnd)->hCard, SCARD_LEAVE_CARD); acr122_pcsc_free_scardcontext(); pn53x_data_free(pnd); nfc_device_free(pnd); } static int acr122_pcsc_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { // FIXME: timeout is not handled (void) timeout; // Make sure the command does not overflow the send buffer if (szData > ACR122_PCSC_COMMAND_LEN) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } // Prepare and transmit the send buffer const size_t szTxBuf = szData + 6; uint8_t abtTxBuf[ACR122_PCSC_WRAP_LEN + ACR122_PCSC_COMMAND_LEN] = { 0xFF, 0x00, 0x00, 0x00, szData + 1, 0xD4 }; memcpy(abtTxBuf + ACR122_PCSC_WRAP_LEN, pbtData, szData); LOG_HEX(NFC_LOG_GROUP_COM, "TX", abtTxBuf, szTxBuf); DRIVER_DATA(pnd)->szRx = 0; DWORD dwRxLen = sizeof(DRIVER_DATA(pnd)->abtRx); if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { /* * In this communication mode, we directly have the response from the * PN532. Save it in the driver data structure so that it can be retrieved * in ac122_receive(). * * Some devices will never enter this state (e.g. Touchatag) but are still * supported through SCardTransmit calls (see bellow). * * This state is generaly reached when the ACR122 has no target in it's * field. */ if (SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtTxBuf, szTxBuf, DRIVER_DATA(pnd)->abtRx, ACR122_PCSC_RESPONSE_LEN, &dwRxLen) != SCARD_S_SUCCESS) { pnd->last_error = NFC_EIO; return pnd->last_error; } } else { /* * In T=0 mode, we receive an acknoledge from the MCU, in T=1 mode, we * receive the response from the PN532. */ if (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtTxBuf, szTxBuf, NULL, DRIVER_DATA(pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { pnd->last_error = NFC_EIO; return pnd->last_error; } } if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { /* * Check the MCU response */ // Make sure we received the byte-count we expected if (dwRxLen != 2) { pnd->last_error = NFC_EIO; return pnd->last_error; } // Check if the operation was successful, so an answer is available if (DRIVER_DATA(pnd)->abtRx[0] == SCARD_OPERATION_ERROR) { pnd->last_error = NFC_EIO; return pnd->last_error; } } else { DRIVER_DATA(pnd)->szRx = dwRxLen; } return NFC_SUCCESS; } static int acr122_pcsc_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout) { // FIXME: timeout is not handled (void) timeout; int len; uint8_t abtRxCmd[5] = { 0xFF, 0xC0, 0x00, 0x00 }; if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { /* * Retrieve the PN532 response. */ DWORD dwRxLen = sizeof(DRIVER_DATA(pnd)->abtRx); abtRxCmd[4] = DRIVER_DATA(pnd)->abtRx[1]; if (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtRxCmd, sizeof(abtRxCmd), NULL, DRIVER_DATA(pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { pnd->last_error = NFC_EIO; return pnd->last_error; } DRIVER_DATA(pnd)->szRx = dwRxLen; } else { /* * We already have the PN532 answer, it was saved by acr122_pcsc_send(). */ } LOG_HEX(NFC_LOG_GROUP_COM, "RX", DRIVER_DATA(pnd)->abtRx, DRIVER_DATA(pnd)->szRx); // Make sure we have an emulated answer that fits the return buffer if (DRIVER_DATA(pnd)->szRx < 4 || (DRIVER_DATA(pnd)->szRx - 4) > szData) { pnd->last_error = NFC_EIO; return pnd->last_error; } // Wipe out the 4 APDU emulation bytes: D5 4B .. .. .. 90 00 len = DRIVER_DATA(pnd)->szRx - 4; memcpy(pbtData, DRIVER_DATA(pnd)->abtRx + 2, len); return len; } char * acr122_pcsc_firmware(nfc_device *pnd) { uint8_t abtGetFw[5] = { 0xFF, 0x00, 0x48, 0x00, 0x00 }; uint32_t uiResult; static char abtFw[11]; DWORD dwFwLen = sizeof(abtFw); memset(abtFw, 0x00, sizeof(abtFw)); if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { uiResult = SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtGetFw, sizeof(abtGetFw), (uint8_t *) abtFw, dwFwLen - 1, &dwFwLen); } else { uiResult = SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtGetFw, sizeof(abtGetFw), NULL, (uint8_t *) abtFw, &dwFwLen); } if (uiResult != SCARD_S_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "No ACR122 firmware received, Error: %08x", uiResult); } return abtFw; } #if 0 bool acr122_pcsc_led_red(nfc_device *pnd, bool bOn) { uint8_t abtLed[9] = { 0xFF, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x00 }; uint8_t abtBuf[2]; DWORD dwBufLen = sizeof(abtBuf); (void) bOn; if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { return (SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtLed, sizeof(abtLed), abtBuf, dwBufLen, &dwBufLen) == SCARD_S_SUCCESS); } else { return (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtLed, sizeof(abtLed), NULL, abtBuf, &dwBufLen) == SCARD_S_SUCCESS); } } #endif const struct pn53x_io acr122_pcsc_io = { .send = acr122_pcsc_send, .receive = acr122_pcsc_receive, }; const struct nfc_driver acr122_pcsc_driver = { .name = ACR122_PCSC_DRIVER_NAME, .scan = acr122_pcsc_scan, .open = acr122_pcsc_open, .close = acr122_pcsc_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = NULL, // Abort is not supported in this driver .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
C
/*- * 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 pn53x_usb.c * @brief Driver for PN53x using USB */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H /* Thanks to d18c7db and Okko for example code */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <sys/select.h> #include <errno.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "buses/usbbus.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "drivers/pn53x_usb.h" #define PN53X_USB_DRIVER_NAME "pn53x_usb" #define LOG_CATEGORY "libnfc.driver.pn53x_usb" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define USB_INFINITE_TIMEOUT 0 #define DRIVER_DATA(pnd) ((struct pn53x_usb_data*)(pnd->driver_data)) const nfc_modulation_type no_target_support[] = {0}; typedef enum { UNKNOWN, NXP_PN531, SONY_PN531, NXP_PN533, ASK_LOGO, SCM_SCL3711, SONY_RCS360 } pn53x_usb_model; // Internal data struct struct pn53x_usb_data { usb_dev_handle *pudh; pn53x_usb_model model; uint32_t uiEndPointIn; uint32_t uiEndPointOut; uint32_t uiMaxPacketSize; volatile bool abort_flag; }; // Internal io struct const struct pn53x_io pn53x_usb_io; // Prototypes bool pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len); int pn53x_usb_init(nfc_device *pnd); static int pn53x_usb_bulk_read(struct pn53x_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout) { int res = usb_bulk_read(data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout); if (res > 0) { LOG_HEX(NFC_LOG_GROUP_COM, "RX", abtRx, res); } else if (res < 0) { if (res != -USB_TIMEDOUT) log_put(NFC_LOG_GROUP_COM, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror(res)); } return res; } static int pn53x_usb_bulk_write(struct pn53x_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout) { LOG_HEX(NFC_LOG_GROUP_COM, "TX", abtTx, szTx); int res = usb_bulk_write(data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout); if (res > 0) { // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details if ((res % data->uiMaxPacketSize) == 0) { usb_bulk_write(data->pudh, data->uiEndPointOut, "\0", 0, timeout); } } else { log_put(NFC_LOG_GROUP_COM, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror(res)); } return res; } struct pn53x_usb_supported_device { uint16_t vendor_id; uint16_t product_id; pn53x_usb_model model; const char *name; }; const struct pn53x_usb_supported_device pn53x_usb_supported_devices[] = { { 0x04CC, 0x0531, NXP_PN531, "Philips / PN531" }, { 0x04CC, 0x2533, NXP_PN533, "NXP / PN533" }, { 0x04E6, 0x5591, SCM_SCL3711, "SCM Micro / SCL3711-NFC&RW" }, { 0x054c, 0x0193, SONY_PN531, "Sony / PN531" }, { 0x1FD3, 0x0608, ASK_LOGO, "ASK / LoGO" }, { 0x054C, 0x02E1, SONY_RCS360, "Sony / FeliCa S360 [PaSoRi]" } }; static pn53x_usb_model pn53x_usb_get_device_model(uint16_t vendor_id, uint16_t product_id) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) { if ((vendor_id == pn53x_usb_supported_devices[n].vendor_id) && (product_id == pn53x_usb_supported_devices[n].product_id)) return pn53x_usb_supported_devices[n].model; } return UNKNOWN; } int pn53x_usb_ack(nfc_device *pnd); // Find transfer endpoints for bulk transfers static void pn53x_usb_get_end_points(struct usb_device *dev, struct pn53x_usb_data *data) { uint32_t uiIndex; uint32_t uiEndPoint; struct usb_interface_descriptor *puid = dev->config->interface->altsetting; // 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out for (uiIndex = 0; uiIndex < puid->bNumEndpoints; uiIndex++) { // Only accept bulk transfer endpoints (ignore interrupt endpoints) if (puid->endpoint[uiIndex].bmAttributes != USB_ENDPOINT_TYPE_BULK) continue; // Copy the endpoint to a local var, makes it more readable code uiEndPoint = puid->endpoint[uiIndex].bEndpointAddress; // Test if we dealing with a bulk IN endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_IN) { data->uiEndPointIn = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } // Test if we dealing with a bulk OUT endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_OUT) { data->uiEndPointOut = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } } } static size_t pn53x_usb_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { (void)context; usb_prepare(); size_t device_found = 0; uint32_t uiBusIndex = 0; struct usb_bus *bus; for (bus = usb_get_busses(); bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) { if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { // Make sure there are 2 endpoints available // with libusb-win32 we got some null pointers so be robust before looking at endpoints: if (dev->config == NULL || dev->config->interface == NULL || dev->config->interface->altsetting == NULL) { // Nope, we maybe want the next one, let's try to find another continue; } if (dev->config->interface->altsetting->bNumEndpoints < 2) { // Nope, we maybe want the next one, let's try to find another continue; } usb_dev_handle *udev = usb_open(dev); if (udev == NULL) continue; // Set configuration int res = usb_set_configuration(udev, 1); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res)); usb_close(udev); // we failed to use the device continue; } // pn53x_usb_get_usb_device_name (dev, udev, pnddDevices[device_found].acDevice, sizeof (pnddDevices[device_found].acDevice)); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "device found: Bus %s Device %s", bus->dirname, dev->filename); usb_close(udev); snprintf(connstrings[device_found], sizeof(nfc_connstring), "%s:%s:%s", PN53X_USB_DRIVER_NAME, bus->dirname, dev->filename); device_found++; // Test if we reach the maximum "wanted" devices if (device_found == connstrings_len) { return device_found; } } } } } return device_found; } struct pn53x_usb_descriptor { char *dirname; char *filename; }; bool pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len) { *buffer = '\0'; if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) { if (udev) { usb_get_string_simple(udev, dev->descriptor.iManufacturer, buffer, len); if (strlen(buffer) > 0) strcpy(buffer + strlen(buffer), " / "); usb_get_string_simple(udev, dev->descriptor.iProduct, buffer + strlen(buffer), len - strlen(buffer)); } } if (!*buffer) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) { if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { strncpy(buffer, pn53x_usb_supported_devices[n].name, len); buffer[len - 1] = '\0'; return true; } } } return false; } static nfc_device * pn53x_usb_open(const nfc_context *context, const nfc_connstring connstring) { nfc_device *pnd = NULL; struct pn53x_usb_descriptor desc = { NULL, NULL }; int connstring_decode_level = connstring_decode(connstring, PN53X_USB_DRIVER_NAME, "usb", &desc.dirname, &desc.filename); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); if (connstring_decode_level < 1) { goto free_mem; } struct pn53x_usb_data data = { .pudh = NULL, .uiEndPointIn = 0, .uiEndPointOut = 0, }; struct usb_bus *bus; struct usb_device *dev; usb_prepare(); for (bus = usb_get_busses(); bus; bus = bus->next) { if (connstring_decode_level > 1) { // A specific bus have been specified if (0 != strcmp(bus->dirname, desc.dirname)) continue; } for (dev = bus->devices; dev; dev = dev->next) { if (connstring_decode_level > 2) { // A specific dev have been specified if (0 != strcmp(dev->filename, desc.filename)) continue; } // Open the USB device if ((data.pudh = usb_open(dev)) == NULL) continue; // Retrieve end points pn53x_usb_get_end_points(dev, &data); // Set configuration int res = usb_set_configuration(data.pudh, 1); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res)); if (EPERM == -res) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Warning: Please double check USB permissions for device %04x:%04x", dev->descriptor.idVendor, dev->descriptor.idProduct); } usb_close(data.pudh); // we failed to use the specified device goto free_mem; } res = usb_claim_interface(data.pudh, 0); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror(res)); usb_close(data.pudh); // we failed to use the specified device goto free_mem; } data.model = pn53x_usb_get_device_model(dev->descriptor.idVendor, dev->descriptor.idProduct); // Allocate memory for the device info and specification, fill it and return the info pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); goto error; } pn53x_usb_get_usb_device_name(dev, data.pudh, pnd->name, sizeof(pnd->name)); pnd->driver_data = malloc(sizeof(struct pn53x_usb_data)); if (!pnd->driver_data) { perror("malloc"); goto error; } *DRIVER_DATA(pnd) = data; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn53x_usb_io) == NULL) { perror("malloc"); goto error; } switch (DRIVER_DATA(pnd)->model) { // empirical tuning case ASK_LOGO: CHIP_DATA(pnd)->timer_correction = 50; break; case SCM_SCL3711: case NXP_PN533: CHIP_DATA(pnd)->timer_correction = 46; break; case NXP_PN531: CHIP_DATA(pnd)->timer_correction = 50; break; case SONY_PN531: CHIP_DATA(pnd)->timer_correction = 54; break; case SONY_RCS360: case UNKNOWN: CHIP_DATA(pnd)->timer_correction = 0; // TODO: allow user to know if timed functions are available break; } pnd->driver = &pn53x_usb_driver; // HACK1: Send first an ACK as Abort command, to reset chip before talking to it: pn53x_usb_ack(pnd); // HACK2: Then send a GetFirmware command to resync USB toggle bit between host & device // in case host used set_configuration and expects the device to have reset its toggle bit, which PN53x doesn't do if (pn53x_usb_init(pnd) < 0) { usb_close(data.pudh); goto error; } DRIVER_DATA(pnd)->abort_flag = false; goto free_mem; } } // We ran out of devices before the index required goto free_mem; error: // Free allocated structure on error. nfc_device_free(pnd); pnd = NULL; free_mem: free(desc.dirname); free(desc.filename); return pnd; } static void pn53x_usb_close(nfc_device *pnd) { pn53x_usb_ack(pnd); if (DRIVER_DATA(pnd)->model == ASK_LOGO) { /* Set P30, P31, P32, P33, P35 to logic 1 and P34 to 0 logic */ /* ie. Switch all LEDs off and turn off progressive field */ pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P32) | _BV(P33) | _BV(P35)); } pn53x_idle(pnd); int res; if ((res = usb_release_interface(DRIVER_DATA(pnd)->pudh, 0)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror(res)); } if ((res = usb_close(DRIVER_DATA(pnd)->pudh)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror(res)); } pn53x_data_free(pnd); nfc_device_free(pnd); } #define PN53X_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int pn53x_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) { uint8_t abtFrame[PN53X_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" size_t szFrame = 0; int res = 0; if ((res = pn53x_build_frame(abtFrame, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), abtFrame, szFrame, timeout)) < 0) { pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; if ((res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), timeout)) < 0) { // try to interrupt current device state pn53x_usb_ack(pnd); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, res) == 0) { // The PN53x is running the sent command } else { // For some reasons (eg. send another command while a previous one is // running), the PN533 sometimes directly replies the response packet // instead of ACK frame, so we send a NACK frame to force PN533 to resend // response packet. With this hack, the nextly executed function (ie. // pn53x_usb_receive()) will be able to retreive the correct response // packet. // FIXME Sony reader is also affected by this bug but NACK is not supported if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout)) < 0) { pnd->last_error = res; // try to interrupt current device state pn53x_usb_ack(pnd); return pnd->last_error; } } return NFC_SUCCESS; } #define USB_TIMEOUT_PER_PASS 200 static int pn53x_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) { size_t len; off_t offset = 0; uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; int res; /* * If no timeout is specified but the command is blocking, force a 200ms (USB_TIMEOUT_PER_PASS) * timeout to allow breaking the loop if the user wants to stop it. */ int usb_timeout; int remaining_time = timeout; read: if (timeout == USB_INFINITE_TIMEOUT) { usb_timeout = USB_TIMEOUT_PER_PASS; } else { // A user-provided timeout is set, we have to cut it in multiple chunk to be able to keep an nfc_abort_command() mecanism remaining_time -= USB_TIMEOUT_PER_PASS; if (remaining_time <= 0) { pnd->last_error = NFC_ETIMEOUT; return pnd->last_error; } else { usb_timeout = MIN(remaining_time, USB_TIMEOUT_PER_PASS); } } res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), usb_timeout); if (res == -USB_TIMEDOUT) { if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; pn53x_usb_ack(pnd); pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } else { goto read; } } if (res < 0) { // try to interrupt current device state pn53x_usb_ack(pnd); pnd->last_error = res; return pnd->last_error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 3; if ((0x01 == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { // Error frame log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; return pnd->last_error; } else if ((0xff == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { // Extended frame offset += 2; // (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] (LEN) include TFI + (CC+1) len = (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] - 2; if (((abtRxBuf[offset] + abtRxBuf[offset + 1] + abtRxBuf[offset + 2]) % 256) != 0) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 3; } else { // Normal frame if (256 != (abtRxBuf[offset] + abtRxBuf[offset + 1])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[offset] - 2; offset += 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; return pnd->last_error; } // TFI + PD0 (CC+1) if (abtRxBuf[offset] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; if (abtRxBuf[offset] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; memcpy(pbtData, abtRxBuf + offset, len); offset += len; uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[offset]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; if (0x00 != abtRxBuf[offset]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // The PN53x command is done and we successfully received the reply pnd->last_error = 0; return len; } int pn53x_usb_ack(nfc_device *pnd) { return pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *) pn53x_ack_frame, sizeof(pn53x_ack_frame), 1000); } int pn53x_usb_init(nfc_device *pnd) { int res = 0; // Sometimes PN53x USB doesn't reply ACK one the first frame, so we need to send a dummy one... //pn53x_check_communication (pnd); // Sony RC-S360 doesn't support this command for now so let's use a get_firmware_version instead: const uint8_t abtCmd[] = { GetFirmwareVersion }; pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); // ...and we don't care about error pnd->last_error = 0; if (SONY_RCS360 == DRIVER_DATA(pnd)->model) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "SONY RC-S360 initialization."); const uint8_t abtCmd2[] = { 0x18, 0x01 }; pn53x_transceive(pnd, abtCmd2, sizeof(abtCmd2), NULL, 0, -1); pn53x_usb_ack(pnd); } if ((res = pn53x_init(pnd)) < 0) return res; if (ASK_LOGO == DRIVER_DATA(pnd)->model) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ASK LoGO initialization."); /* Internal registers */ /* Disable 100mA current limit, Power on Secure IC (SVDD) */ pn53x_write_register(pnd, PN53X_REG_Control_switch_rng, 0xFF, SYMBOL_CURLIMOFF | SYMBOL_SIC_SWITCH_EN | SYMBOL_RANDOM_DATAREADY); /* Select the signal to be output on SIGOUT: Modulation signal (envelope) from the internal coder */ pn53x_write_register(pnd, PN53X_REG_CIU_TxSel, 0xFF, 0x14); /* SFR Registers */ /* Setup push-pulls for pins from P30 to P35 */ pn53x_write_register(pnd, PN53X_SFR_P3CFGB, 0xFF, 0x37); /* On ASK LoGO hardware: LEDs port bits definition: * LED 1: bit 2 (P32) * LED 2: bit 1 (P31) * LED 3: bit 0 or 3 (depending of hardware revision) (P30 or P33) * LED 4: bit 5 (P35) Notes: * Set logical 0 to switch LED on; logical 1 to switch LED off. * Bit 4 should be maintained at 1 to keep RF field on. Progressive field activation: The ASK LoGO hardware can progressively power-up the antenna. To use this feature we have to switch on the field by switching on the field on PN533 (RFConfiguration) then set P34 to '1', and cut-off the field by switching off the field on PN533 then set P34 to '0'. */ /* Set P30, P31, P33, P35 to logic 1 and P32, P34 to 0 logic */ /* ie. Switch LED1 on and turn off progressive field */ pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P33) | _BV(P35)); } return NFC_SUCCESS; } static int pn53x_usb_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable) { int res = 0; if ((res = pn53x_set_property_bool(pnd, property, bEnable)) < 0) return res; switch (DRIVER_DATA(pnd)->model) { case ASK_LOGO: if (NP_ACTIVATE_FIELD == property) { /* Switch on/off LED2 and Progressive Field GPIO according to ACTIVATE_FIELD option */ log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Switch progressive field %s", bEnable ? "On" : "Off"); if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P31) | _BV(P34), bEnable ? _BV(P34) : _BV(P31))) < 0) return NFC_ECHIP; } break; case SCM_SCL3711: if (NP_ACTIVATE_FIELD == property) { // Switch on/off LED according to ACTIVATE_FIELD option if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P32), bEnable ? 0 : _BV(P32))) < 0) return res; } break; case NXP_PN531: case NXP_PN533: case SONY_PN531: case SONY_RCS360: case UNKNOWN: // Nothing to do. break; } return NFC_SUCCESS; } static int pn53x_usb_abort_command(nfc_device *pnd) { DRIVER_DATA(pnd)->abort_flag = true; return NFC_SUCCESS; } static int pn53x_usb_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt) { if ((DRIVER_DATA(pnd)->model != ASK_LOGO) || (mode != N_TARGET)) return pn53x_get_supported_modulation(pnd, mode, supported_mt); else // ASK_LOGO has no N_TARGET support *supported_mt = no_target_support; return NFC_SUCCESS; } const struct pn53x_io pn53x_usb_io = { .send = pn53x_usb_send, .receive = pn53x_usb_receive, }; const struct nfc_driver pn53x_usb_driver = { .name = PN53X_USB_DRIVER_NAME, .scan_type = NOT_INTRUSIVE, .scan = pn53x_usb_scan, .open = pn53x_usb_open, .close = pn53x_usb_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_usb_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_usb_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn53x_usb_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
C
/*- * 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 pn532_i2c.c * @brief PN532 driver using I2C bus. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "pn532_i2c.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "buses/i2c.h" #define PN532_I2C_DRIVER_NAME "pn532_i2c" #define LOG_CATEGORY "libnfc.driver.pn532_i2c" #define LOG_GROUP NFC_LOG_GROUP_DRIVER // I2C address of the PN532 chip. #define PN532_I2C_ADDR 0x24 // Internal data structs const struct pn53x_io pn532_i2c_io; struct pn532_i2c_data { i2c_device dev; volatile bool abort_flag; }; /* Delay for the loop waiting for READY frame (in ms) */ #define PN532_RDY_LOOP_DELAY 90 const struct timespec rdyDelay = { .tv_sec = 0, .tv_nsec = PN532_RDY_LOOP_DELAY * 1000 * 1000 }; /* Private Functions Prototypes */ static nfc_device *pn532_i2c_open(const nfc_context *context, const nfc_connstring connstring); static void pn532_i2c_close(nfc_device *pnd); static int pn532_i2c_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); static int pn532_i2c_ack(nfc_device *pnd); static int pn532_i2c_abort_command(nfc_device *pnd); static int pn532_i2c_wakeup(nfc_device *pnd); static int pn532_i2c_wait_rdyframe(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout); static size_t pn532_i2c_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len); #define DRIVER_DATA(pnd) ((struct pn532_i2c_data*)(pnd->driver_data)) /** * @brief Scan all available I2C buses to find PN532 devices. * * @param context NFC context. * @param connstrings array of 'nfc_connstring' buffer (allocated by caller). It is used to store the * connection info strings of all I2C PN532 devices found. * @param connstrings_len length of the connstrings array. * @return number of PN532 devices found on all I2C buses. */ static size_t pn532_i2c_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; i2c_device id; char **i2cPorts = i2c_list_ports(); const char *i2cPort; int iDevice = 0; while ((i2cPort = i2cPorts[iDevice++])) { id = i2c_open(i2cPort, PN532_I2C_ADDR); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find PN532 device on I2C bus %s.", i2cPort); if ((id != INVALID_I2C_ADDRESS) && (id != INVALID_I2C_BUS)) { nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s", PN532_I2C_DRIVER_NAME, i2cPort); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); i2c_close(id); iDevice = 0; while ((i2cPort = i2cPorts[iDevice++])) { free((void *)i2cPort); } free(i2cPorts); return 0; } pnd->driver = &pn532_i2c_driver; pnd->driver_data = malloc(sizeof(struct pn532_i2c_data)); if (!pnd->driver_data) { perror("malloc"); i2c_close(id); nfc_device_free(pnd); iDevice = 0; while ((i2cPort = i2cPorts[iDevice++])) { free((void *)i2cPort); } free(i2cPorts); return 0; } DRIVER_DATA(pnd)->dev = id; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_i2c_io) == NULL) { perror("malloc"); i2c_close(DRIVER_DATA(pnd)->dev); nfc_device_free(pnd); iDevice = 0; while ((i2cPort = i2cPorts[iDevice++])) { free((void *)i2cPort); } free(i2cPorts); return 0; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat power mode CHIP_DATA(pnd)->power_mode = LOWVBAT; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) int res = pn53x_check_communication(pnd); i2c_close(DRIVER_DATA(pnd)->dev); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((i2cPort = i2cPorts[iDevice++])) { free((void *)i2cPort); } free(i2cPorts); return device_found; } /** * @brief Close I2C connection to the PN532 device. * * @param pnd pointer on the device to close. */ static void pn532_i2c_close(nfc_device *pnd) { pn53x_idle(pnd); i2c_close(DRIVER_DATA(pnd)->dev); pn53x_data_free(pnd); nfc_device_free(pnd); } /** * @brief Open an I2C connection to the PN532 device. * * @param context NFC context. * @param connstring connection info to the device ( pn532_i2c:<i2c_devname> ). * @return pointer to the device, or NULL in case of error. */ static nfc_device * pn532_i2c_open(const nfc_context *context, const nfc_connstring connstring) { char *i2c_devname; i2c_device i2c_dev; nfc_device *pnd; int connstring_decode_level = connstring_decode(connstring, PN532_I2C_DRIVER_NAME, NULL, &i2c_devname, NULL); switch (connstring_decode_level) { case 2: break; case 1: break; case 0: return NULL; } i2c_dev = i2c_open(i2c_devname, PN532_I2C_ADDR); if (i2c_dev == INVALID_I2C_BUS || i2c_dev == INVALID_I2C_ADDRESS) { return NULL; } pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); i2c_close(i2c_dev); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", PN532_I2C_DRIVER_NAME, i2c_devname); pnd->driver_data = malloc(sizeof(struct pn532_i2c_data)); if (!pnd->driver_data) { perror("malloc"); i2c_close(i2c_dev); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->dev = i2c_dev; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_i2c_io) == NULL) { perror("malloc"); i2c_close(i2c_dev); nfc_device_free(pnd); return NULL; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat mode CHIP_DATA(pnd)->power_mode = LOWVBAT; // empirical tuning CHIP_DATA(pnd)->timer_correction = 48; pnd->driver = &pn532_i2c_driver; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) if (pn53x_check_communication(pnd) < 0) { nfc_perror(pnd, "pn53x_check_communication"); pn532_i2c_close(pnd); return NULL; } pn53x_init(pnd); return pnd; } static int pn532_i2c_wakeup(nfc_device *pnd) { /* No specific. PN532 holds SCL during wakeup time */ CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 should now be awake return NFC_SUCCESS; } #define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) /** * @brief Send data to the PN532 device. * * @param pnd pointer on the NFC device. * @param pbtData buffer containing frame data. * @param szData size of the buffer. * @param timeout timeout before aborting the operation (in ms). * @return NFC_SUCCESS if operation is successful, or error code. */ static int pn532_i2c_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; // Discard any existing data ? switch (CHIP_DATA(pnd)->power_mode) { case LOWVBAT: { /** PN532C106 wakeup. */ if ((res = pn532_i2c_wakeup(pnd)) < 0) { return res; } // According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000)) < 0) { return res; } } break; case POWERDOWN: { if ((res = pn532_i2c_wakeup(pnd)) < 0) { return res; } } break; case NORMAL: // Nothing to do :) break; }; uint8_t abtFrame[PN532_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" size_t szFrame = 0; if ((res = pn53x_build_frame(abtFrame, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } res = i2c_write(DRIVER_DATA(pnd)->dev, abtFrame, szFrame); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; // Wait for the ACK frame res = pn532_i2c_wait_rdyframe(pnd, abtRxBuf, sizeof(abtRxBuf), timeout); if (res < 0) { if (res == NFC_EOPABORTED) { // Send an ACK frame from host to abort the command. pn532_i2c_ack(pnd); } pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, res) == 0) { // The PN53x is running the sent command } else { return pnd->last_error; } return NFC_SUCCESS; } /** * @brief Read data from the PN532 device until getting a frame with RDY bit set * * @param pnd pointer on the NFC device. * @param pbtData buffer used to store the received frame data. * @param szDataLen allocated size of buffer. * @param timeout timeout delay before aborting the operation (in ms). Use 0 for no timeout. * @return length (in bytes) of the received frame, or NFC_ETIMEOUT if timeout delay has expired, * NFC_EOPABORTED if operation has been aborted, NFC_EIO in case of IO failure */ static int pn532_i2c_wait_rdyframe(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { bool done = false; int res; struct timeval start_tv, cur_tv; long long duration; // Actual I2C response frame includes an additional status byte, // so we use a temporary buffer to read the I2C frame uint8_t i2cRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN + 1]; if (timeout > 0) { // If a timeout is specified, get current timestamp gettimeofday(&start_tv, NULL); } do { // Wait a little bit before reading nanosleep(&rdyDelay, (struct timespec *) NULL); int recCount = i2c_read(DRIVER_DATA(pnd)->dev, i2cRx, szDataLen + 1); if (DRIVER_DATA(pnd)->abort_flag) { // Reset abort flag DRIVER_DATA(pnd)->abort_flag = false; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Wait for a READY frame has been aborted."); return NFC_EOPABORTED; } if (recCount <= 0) { done = true; res = NFC_EIO; } else { const uint8_t rdy = i2cRx[0]; if (rdy & 1) { int copyLength; done = true; res = recCount - 1; copyLength = MIN(res, (int)szDataLen); memcpy(pbtData, &(i2cRx[1]), copyLength); } else { /* Not ready yet. Check for elapsed timeout. */ if (timeout > 0) { gettimeofday(&cur_tv, NULL); duration = (cur_tv.tv_sec - start_tv.tv_sec) * 1000000L + (cur_tv.tv_usec - start_tv.tv_usec); if (duration / 1000 > timeout) { res = NFC_ETIMEOUT; done = true; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "timeout reached with no READY frame."); } } } } } while (!done); return res; } /** * @brief Read a response frame from the PN532 device. * * @param pnd pointer on the NFC device. * @param pbtData buffer used to store the response frame data. * @param szDataLen allocated size of buffer. * @param timeout timeout delay before aborting the operation (in ms). Use 0 for no timeout. * @return length (in bytes) of the response, or NFC_ETIMEOUT if timeout delay has expired, * NFC_EOPABORTED if operation has been aborted, NFC_EIO in case of IO failure */ static int pn532_i2c_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t frameBuf[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; int frameLength; int TFI_idx; size_t len; frameLength = pn532_i2c_wait_rdyframe(pnd, frameBuf, sizeof(frameBuf), timeout); if (NFC_EOPABORTED == pnd->last_error) { return pn532_i2c_ack(pnd); } if (frameLength < 0) { goto error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(frameBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; goto error; } if ((0x01 == frameBuf[3]) && (0xff == frameBuf[4])) { uint8_t errorCode = frameBuf[5]; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Application level error detected (%d)", errorCode); pnd->last_error = NFC_EIO; goto error; } else if ((0xff == frameBuf[3]) && (0xff == frameBuf[4])) { // Extended frame len = (frameBuf[5] << 8) + frameBuf[6]; // Verify length checksum if (((frameBuf[5] + frameBuf[6] + frameBuf[7]) % 256) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } TFI_idx = 8; } else { // Normal frame len = frameBuf[3]; // Verify length checksum if ((uint8_t)(frameBuf[3] + frameBuf[4])) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } TFI_idx = 5; } if ((len - 2) > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; goto error; } uint8_t TFI = frameBuf[TFI_idx]; if (TFI != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; goto error; } if (frameBuf[TFI_idx + 1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Command Code verification failed. (got %d, expected %d)", frameBuf[TFI_idx + 1], CHIP_DATA(pnd)->last_command + 1); pnd->last_error = NFC_EIO; goto error; } uint8_t DCS = frameBuf[TFI_idx + len]; uint8_t btDCS = DCS; // Compute data checksum for (size_t i = 0; i < len; i++) { btDCS += frameBuf[TFI_idx + i]; } if (btDCS != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Data checksum mismatch (DCS = %02x, btDCS = %d)", DCS, btDCS); pnd->last_error = NFC_EIO; goto error; } if (0x00 != frameBuf[TFI_idx + len + 1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Frame postamble mismatch (got %d)", frameBuf[frameLength - 1]); pnd->last_error = NFC_EIO; goto error; } memcpy(pbtData, &frameBuf[TFI_idx + 2], len - 2); /* The PN53x command is done and we successfully received the reply */ return len - 2; error: return pnd->last_error; } /** * @brief Send an ACK frame to the PN532 device. * * @param pnd pointer on the NFC device. * @return NFC_SUCCESS on success, otherwise an error code */ int pn532_i2c_ack(nfc_device *pnd) { return i2c_write(DRIVER_DATA(pnd)->dev, pn53x_ack_frame, sizeof(pn53x_ack_frame)); } /** * @brief Abort any pending operation * * @param pnd pointer on the NFC device. * @return NFC_SUCCESS */ static int pn532_i2c_abort_command(nfc_device *pnd) { if (pnd) { DRIVER_DATA(pnd)->abort_flag = true; } return NFC_SUCCESS; } const struct pn53x_io pn532_i2c_io = { .send = pn532_i2c_send, .receive = pn532_i2c_receive, }; const struct nfc_driver pn532_i2c_driver = { .name = PN532_I2C_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = pn532_i2c_scan, .open = pn532_i2c_open, .close = pn532_i2c_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = pn532_initiator_init_secure_element, .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn532_i2c_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
C
/*- * 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 Anugrah Redja Kusuma * * 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 acr122s.c * @brief Driver for ACS ACR122S devices */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "acr122s.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <string.h> #include <unistd.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "uart.h" #define ACR122S_DEFAULT_SPEED 9600 #define ACR122S_DRIVER_NAME "ACR122S" #define LOG_CATEGORY "libnfc.driver.acr122s" #define LOG_GROUP NFC_LOG_GROUP_DRIVER // Internal data structs struct acr122s_data { serial_port port; uint8_t seq; #ifndef WIN32 int abort_fds[2]; #else volatile bool abort_flag; #endif }; const struct pn53x_io acr122s_io; #define STX 2 #define ETX 3 #define APDU_SIZE(p) ((uint32_t) (p[2] | p[3] << 8 | p[4] << 16 | p[5] << 24)) #define FRAME_OVERHEAD 13 #define FRAME_SIZE(p) (APDU_SIZE(p) + FRAME_OVERHEAD) #define MAX_FRAME_SIZE (FRAME_OVERHEAD + 5 + 255) enum { ICC_POWER_ON_REQ_MSG = 0x62, ICC_POWER_OFF_REQ_MSG = 0x63, XFR_BLOCK_REQ_MSG = 0x6F, ICC_POWER_ON_RES_MSG = 0x80, ICC_POWER_OFF_RES_MSG = 0x81, XFR_BLOCK_RES_MSG = 0x80, }; enum { POWER_AUTO = 0, POWER_5_0_V = 1, POWER_3_0_V = 2, POWER_1_8_V = 3, }; #pragma pack(push, 1) struct icc_power_on_req { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t power_select; uint8_t rfu[2]; }; struct icc_power_on_res { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t status; uint8_t error; uint8_t chain_parameter; }; struct icc_power_off_req { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t rfu[3]; }; struct icc_power_off_res { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t status; uint8_t error; uint8_t clock_status; }; struct xfr_block_req { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t bwi; uint8_t rfu[2]; }; struct xfr_block_res { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t status; uint8_t error; uint8_t chain_parameter; }; struct apdu_header { uint8_t class; uint8_t ins; uint8_t p1; uint8_t p2; uint8_t length; }; #pragma pack(pop) #define DRIVER_DATA(pnd) ((struct acr122s_data *) (pnd->driver_data)) /** * Fix a command frame with a valid prefix, checksum, and suffix. * * @param frame is command frame to fix * @note command frame length (uint32_t at offset 2) should be valid */ static void acr122s_fix_frame(uint8_t *frame) { size_t frame_size = FRAME_SIZE(frame); frame[0] = STX; frame[frame_size - 1] = ETX; uint8_t *csum = frame + frame_size - 2; *csum = 0; for (uint8_t *p = frame + 1; p < csum; p++) *csum ^= *p; } /** * Send a command frame to ACR122S and check its ACK status. * * @param: pnd is target nfc device * @param: cmd is command frame to send * @param: timeout * @return 0 if success */ static int acr122s_send_frame(nfc_device *pnd, uint8_t *frame, int timeout) { size_t frame_size = FRAME_SIZE(frame); uint8_t ack[4]; uint8_t positive_ack[4] = { STX, 0, 0, ETX }; serial_port port = DRIVER_DATA(pnd)->port; int ret; void *abort_p; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->abort_fds[1]); #else abort_p = &(DRIVER_DATA(pnd)->abort_flag); #endif if ((ret = uart_send(port, frame, frame_size, timeout)) < 0) return ret; if ((ret = uart_receive(port, ack, 4, abort_p, timeout)) < 0) return ret; if (memcmp(ack, positive_ack, 4) != 0) { pnd->last_error = NFC_EIO; return pnd->last_error; } struct xfr_block_req *req = (struct xfr_block_req *) &frame[1]; DRIVER_DATA(pnd)->seq = req->seq + 1; return 0; } /** * Receive response frame after a successfull acr122s_send_command(). * * @param: pnd is target nfc device * @param: frame is buffer where received response frame will be stored * @param: frame_size is frame size * @param: abort_p * @param: timeout * @note returned frame size can be fetched using FRAME_SIZE macro * * @return 0 if success */ static int acr122s_recv_frame(nfc_device *pnd, uint8_t *frame, size_t frame_size, void *abort_p, int timeout) { if (frame_size < 13) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } int ret; serial_port port = DRIVER_DATA(pnd)->port; if ((ret = uart_receive(port, frame, 11, abort_p, timeout)) != 0) return ret; // Is buffer sufficient to store response? if (frame_size < FRAME_SIZE(frame)) { pnd->last_error = NFC_EIO; return pnd->last_error; } size_t remaining = FRAME_SIZE(frame) - 11; if ((ret = uart_receive(port, frame + 11, remaining, abort_p, timeout)) != 0) return ret; struct xfr_block_res *res = (struct xfr_block_res *) &frame[1]; if ((uint8_t)(res->seq + 1) != DRIVER_DATA(pnd)->seq) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Invalid response sequence number."); pnd->last_error = NFC_EIO; return pnd->last_error; } return 0; } #define APDU_OVERHEAD (FRAME_OVERHEAD + 5) /** * Convert host uint32 to litle endian uint32 */ static uint32_t le32(uint32_t val) { uint32_t res; uint8_t *p = (uint8_t *) &res; p[0] = val; p[1] = val >> 8; p[2] = val >> 16; p[3] = val >> 24; return res; } /** * Build an ACR122S command frame from a PN532 command. * * @param pnd is device for which the command frame will be generated * @param frame is where the resulting command frame will be generated * @param frame_size is the passed command frame size * @param p1 * @param p2 * @param data is PN532 APDU data without the direction prefix (0xD4) * @param data_size is APDU data size * @param should_prefix 1 if prefix 0xD4 should be inserted before APDU data, 0 if not * * @return true if frame built successfully */ static bool acr122s_build_frame(nfc_device *pnd, uint8_t *frame, size_t frame_size, uint8_t p1, uint8_t p2, const uint8_t *data, size_t data_size, int should_prefix) { if (frame_size < data_size + APDU_OVERHEAD + should_prefix) return false; if (data_size + should_prefix > 255) return false; if (data == NULL) return false; struct xfr_block_req *req = (struct xfr_block_req *) &frame[1]; req->message_type = XFR_BLOCK_REQ_MSG; req->length = le32(5 + data_size + should_prefix); req->slot = 0; req->seq = DRIVER_DATA(pnd)->seq; req->bwi = 0; req->rfu[0] = 0; req->rfu[1] = 0; struct apdu_header *header = (struct apdu_header *) &frame[11]; header->class = 0xff; header->ins = 0; header->p1 = p1; header->p2 = p2; header->length = data_size + should_prefix; uint8_t *buf = (uint8_t *) &frame[16]; if (should_prefix) *buf++ = 0xD4; memcpy(buf, data, data_size); acr122s_fix_frame(frame); return true; } static int acr122s_activate_sam(nfc_device *pnd) { uint8_t cmd[13]; memset(cmd, 0, sizeof(cmd)); cmd[1] = ICC_POWER_ON_REQ_MSG; acr122s_fix_frame(cmd); uint8_t resp[MAX_FRAME_SIZE]; int ret; if ((ret = acr122s_send_frame(pnd, cmd, 0)) != 0) return ret; if ((ret = acr122s_recv_frame(pnd, resp, MAX_FRAME_SIZE, 0, 0)) != 0) return ret; CHIP_DATA(pnd)->power_mode = NORMAL; return 0; } static int acr122s_deactivate_sam(nfc_device *pnd) { uint8_t cmd[13]; memset(cmd, 0, sizeof(cmd)); cmd[1] = ICC_POWER_OFF_REQ_MSG; acr122s_fix_frame(cmd); uint8_t resp[MAX_FRAME_SIZE]; int ret; if ((ret = acr122s_send_frame(pnd, cmd, 0)) != 0) return ret; if ((ret = acr122s_recv_frame(pnd, resp, MAX_FRAME_SIZE, 0, 0)) != 0) return ret; CHIP_DATA(pnd)->power_mode = LOWVBAT; return 0; } static int acr122s_get_firmware_version(nfc_device *pnd, char *version, size_t length) { int ret; uint8_t cmd[MAX_FRAME_SIZE]; if (! acr122s_build_frame(pnd, cmd, sizeof(cmd), 0x48, 0, NULL, 0, 0)) { return NFC_EINVARG; } if ((ret = acr122s_send_frame(pnd, cmd, 1000)) != 0) return ret; if ((ret = acr122s_recv_frame(pnd, cmd, sizeof(cmd), 0, 0)) != 0) return ret; size_t len = APDU_SIZE(cmd); if (len + 1 > length) len = length - 1; memcpy(version, cmd + 11, len); version[len] = 0; return 0; } struct acr122s_descriptor { char *port; uint32_t speed; }; static size_t acr122s_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; serial_port sp; char **acPorts = uart_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = uart_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find ACR122S device on serial port: %s at %d baud.", acPort, ACR122S_DEFAULT_SPEED); if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp, true); uart_set_speed(sp, ACR122S_DEFAULT_SPEED); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ACR122S_DRIVER_NAME, acPort, ACR122S_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); uart_close(sp); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } pnd->driver = &acr122s_driver; pnd->driver_data = malloc(sizeof(struct acr122s_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } DRIVER_DATA(pnd)->port = sp; DRIVER_DATA(pnd)->seq = 0; #ifndef WIN32 if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0) { uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif if (pn53x_data_new(pnd, &acr122s_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } CHIP_DATA(pnd)->type = PN532; CHIP_DATA(pnd)->power_mode = NORMAL; char version[32]; int ret = acr122s_get_firmware_version(pnd, version, sizeof(version)); if (ret == 0 && strncmp("ACR122S", version, 7) != 0) { ret = -1; } uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (ret != 0) continue; // ACR122S reader is found memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } static void acr122s_close(nfc_device *pnd) { acr122s_deactivate_sam(pnd); pn53x_idle(pnd); uart_close(DRIVER_DATA(pnd)->port); #ifndef WIN32 // Release file descriptors used for abort mecanism close(DRIVER_DATA(pnd)->abort_fds[0]); close(DRIVER_DATA(pnd)->abort_fds[1]); #endif pn53x_data_free(pnd); nfc_device_free(pnd); } static nfc_device * acr122s_open(const nfc_context *context, const nfc_connstring connstring) { serial_port sp; nfc_device *pnd; struct acr122s_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, ACR122S_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = ACR122S_DEFAULT_SPEED; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to connect to: %s at %d baud.", ndd.port, ndd.speed); sp = uart_open(ndd.port); if (sp == INVALID_SERIAL_PORT) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); free(ndd.port); return NULL; } if (sp == CLAIMED_SERIAL_PORT) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); free(ndd.port); return NULL; } uart_flush_input(sp, true); uart_set_speed(sp, ndd.speed); pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); uart_close(sp); return NULL; } pnd->driver = &acr122s_driver; strcpy(pnd->name, ACR122S_DRIVER_NAME); free(ndd.port); pnd->driver_data = malloc(sizeof(struct acr122s_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; DRIVER_DATA(pnd)->seq = 0; #ifndef WIN32 if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0) { uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif if (pn53x_data_new(pnd, &acr122s_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } CHIP_DATA(pnd)->type = PN532; #if 1 // Retrieve firmware version char version[DEVICE_NAME_LENGTH]; if (acr122s_get_firmware_version(pnd, version, sizeof(version)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Cannot get reader firmware."); acr122s_close(pnd); return NULL; } if (strncmp(version, "ACR122S", 7) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid firmware version: %s", version); acr122s_close(pnd); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s", version); // Activate SAM before operating if (acr122s_activate_sam(pnd) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Cannot activate SAM."); acr122s_close(pnd); return NULL; } #endif if (pn53x_init(pnd) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Failed initializing PN532 chip."); acr122s_close(pnd); return NULL; } return pnd; } static int acr122s_send(nfc_device *pnd, const uint8_t *buf, const size_t buf_len, int timeout) { uart_flush_input(DRIVER_DATA(pnd)->port, false); uint8_t cmd[MAX_FRAME_SIZE]; if (! acr122s_build_frame(pnd, cmd, sizeof(cmd), 0, 0, buf, buf_len, 1)) { return NFC_EINVARG; } int ret; if ((ret = acr122s_send_frame(pnd, cmd, timeout)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = ret; return pnd->last_error; } return NFC_SUCCESS; } static int acr122s_receive(nfc_device *pnd, uint8_t *buf, size_t buf_len, int timeout) { void *abort_p; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->abort_fds[1]); #else abort_p = &(DRIVER_DATA(pnd)->abort_flag); #endif uint8_t tmp[MAX_FRAME_SIZE]; pnd->last_error = acr122s_recv_frame(pnd, tmp, sizeof(tmp), abort_p, timeout); if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } if (pnd->last_error < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return -1; } size_t data_len = FRAME_SIZE(tmp) - 17; if (data_len > buf_len) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Receive buffer too small. (buf_len: %" PRIuPTR ", data_len: %" PRIuPTR ")", buf_len, data_len); pnd->last_error = NFC_EIO; return pnd->last_error; } memcpy(buf, tmp + 13, data_len); return data_len; } static int acr122s_abort_command(nfc_device *pnd) { if (pnd) { #ifndef WIN32 close(DRIVER_DATA(pnd)->abort_fds[0]); close(DRIVER_DATA(pnd)->abort_fds[1]); if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0) { return NFC_ESOFT; } #else DRIVER_DATA(pnd)->abort_flag = true; #endif } return NFC_SUCCESS; } const struct pn53x_io acr122s_io = { .send = acr122s_send, .receive = acr122s_receive, }; const struct nfc_driver acr122s_driver = { .name = ACR122S_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = acr122s_scan, .open = acr122s_open, .close = acr122s_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = acr122s_abort_command, .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
C
/*- * 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 acr122s.h * @brief Driver for ACS ACR122S devices */ #ifndef __NFC_DRIVER_ACR122S_H__ #define __NFC_DRIVER_ACR122S_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver acr122s_driver; #endif
C
/*- * 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 pn532_uart.c * @brief PN532 driver using UART bus (UART, RS232, etc.) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "pn532_uart.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <unistd.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "uart.h" #define PN532_UART_DEFAULT_SPEED 115200 #define PN532_UART_DRIVER_NAME "pn532_uart" #define LOG_CATEGORY "libnfc.driver.pn532_uart" #define LOG_GROUP NFC_LOG_GROUP_DRIVER // Internal data structs const struct pn53x_io pn532_uart_io; struct pn532_uart_data { serial_port port; #ifndef WIN32 int iAbortFds[2]; #else volatile bool abort_flag; #endif }; // Prototypes int pn532_uart_ack(nfc_device *pnd); int pn532_uart_wakeup(nfc_device *pnd); #define DRIVER_DATA(pnd) ((struct pn532_uart_data*)(pnd->driver_data)) static size_t pn532_uart_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; serial_port sp; char **acPorts = uart_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = uart_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find PN532 device on serial port: %s at %d baud.", acPort, PN532_UART_DEFAULT_SPEED); if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp, true); // Serial port claimed but we need to check if a PN532_UART is opened. uart_set_speed(sp, PN532_UART_DEFAULT_SPEED); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, PN532_UART_DRIVER_NAME, acPort, PN532_UART_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); uart_close(sp); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } pnd->driver = &pn532_uart_driver; pnd->driver_data = malloc(sizeof(struct pn532_uart_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_uart_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat power mode CHIP_DATA(pnd)->power_mode = LOWVBAT; #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return 0; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif // Check communication using "Diagnose" command, with "Communication test" (0x00) int res = pn53x_check_communication(pnd); uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } struct pn532_uart_descriptor { char *port; uint32_t speed; }; static void pn532_uart_close(nfc_device *pnd) { pn53x_idle(pnd); // Release UART port uart_close(DRIVER_DATA(pnd)->port); #ifndef WIN32 // Release file descriptors used for abort mecanism close(DRIVER_DATA(pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[1]); #endif pn53x_data_free(pnd); nfc_device_free(pnd); } static nfc_device * pn532_uart_open(const nfc_context *context, const nfc_connstring connstring) { struct pn532_uart_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, PN532_UART_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = PN532_UART_DEFAULT_SPEED; } serial_port sp; nfc_device *pnd = NULL; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open: %s at %d baud.", ndd.port, ndd.speed); sp = uart_open(ndd.port); if (sp == INVALID_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); if (sp == CLAIMED_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT)) { free(ndd.port); return NULL; } // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp, true); uart_set_speed(sp, ndd.speed); // We have a connection pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); uart_close(sp); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", PN532_UART_DRIVER_NAME, ndd.port); free(ndd.port); pnd->driver_data = malloc(sizeof(struct pn532_uart_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_uart_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat mode CHIP_DATA(pnd)->power_mode = LOWVBAT; // empirical tuning CHIP_DATA(pnd)->timer_correction = 48; pnd->driver = &pn532_uart_driver; #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); return NULL; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif // Check communication using "Diagnose" command, with "Communication test" (0x00) if (pn53x_check_communication(pnd) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "pn53x_check_communication error"); pn532_uart_close(pnd); return NULL; } pn53x_init(pnd); return pnd; } int pn532_uart_wakeup(nfc_device *pnd) { /* High Speed Unit (HSU) wake up consist to send 0x55 and wait a "long" delay for PN532 being wakeup. */ const uint8_t pn532_wakeup_preamble[] = { 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; int res = uart_send(DRIVER_DATA(pnd)->port, pn532_wakeup_preamble, sizeof(pn532_wakeup_preamble), 0); CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 should now be awake return res; } #define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int pn532_uart_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; // Before sending anything, we need to discard from any junk bytes uart_flush_input(DRIVER_DATA(pnd)->port, false); switch (CHIP_DATA(pnd)->power_mode) { case LOWVBAT: { /** PN532C106 wakeup. */ if ((res = pn532_uart_wakeup(pnd)) < 0) { return res; } // According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000)) < 0) { return res; } } break; case POWERDOWN: { if ((res = pn532_uart_wakeup(pnd)) < 0) { return res; } } break; case NORMAL: // Nothing to do :) break; }; uint8_t abtFrame[PN532_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" size_t szFrame = 0; if ((res = pn53x_build_frame(abtFrame, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } res = uart_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame, timeout); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; res = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, sizeof(abtRxBuf), 0, timeout); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to read ACK"); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { // The PN53x is running the sent command } else { return pnd->last_error; } return NFC_SUCCESS; } static int pn532_uart_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t abtRxBuf[5]; size_t len; void *abort_p = NULL; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->iAbortFds[1]); #else abort_p = (void *) & (DRIVER_DATA(pnd)->abort_flag); #endif pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 5, abort_p, timeout); if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { pn532_uart_ack(pnd); return NFC_EOPABORTED; } if (pnd->last_error < 0) { goto error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; goto error; } if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Error frame uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; goto error; } else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Extended frame pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } // (abtRxBuf[0] << 8) + abtRxBuf[1] (LEN) include TFI + (CC+1) len = (abtRxBuf[0] << 8) + abtRxBuf[1] - 2; if (((abtRxBuf[0] + abtRxBuf[1] + abtRxBuf[2]) % 256) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } } else { // Normal frame if (256 != (abtRxBuf[3] + abtRxBuf[4])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[3] - 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; goto error; } // TFI + PD0 (CC+1) pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } if (abtRxBuf[0] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; goto error; } if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; goto error; } if (len) { pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, pbtData, len, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } } pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[0]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } if (0x00 != abtRxBuf[1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; goto error; } // The PN53x command is done and we successfully received the reply return len; error: uart_flush_input(DRIVER_DATA(pnd)->port, true); return pnd->last_error; } int pn532_uart_ack(nfc_device *pnd) { if (POWERDOWN == CHIP_DATA(pnd)->power_mode) { int res = 0; if ((res = pn532_uart_wakeup(pnd)) < 0) { return res; } } return (uart_send(DRIVER_DATA(pnd)->port, pn53x_ack_frame, sizeof(pn53x_ack_frame), 0)); } static int pn532_uart_abort_command(nfc_device *pnd) { if (pnd) { #ifndef WIN32 close(DRIVER_DATA(pnd)->iAbortFds[0]); if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { return NFC_ESOFT; } #else DRIVER_DATA(pnd)->abort_flag = true; #endif } return NFC_SUCCESS; } const struct pn53x_io pn532_uart_io = { .send = pn532_uart_send, .receive = pn532_uart_receive, }; const struct nfc_driver pn532_uart_driver = { .name = PN532_UART_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = pn532_uart_scan, .open = pn532_uart_open, .close = pn532_uart_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = pn532_initiator_init_secure_element, .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn532_uart_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
C
/*- * 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 pn53x_usb.h * @brief Drive for PN53x USB devices */ #ifndef __NFC_DRIVER_PN53X_USB_H__ #define __NFC_DRIVER_PN53X_USB_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver pn53x_usb_driver; #endif // ! __NFC_DRIVER_PN53X_USB_H__
C
/*- * 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 acr122_usb.h * @brief Driver for ACR122 devices using direct USB connection (without PCSC) */ #ifndef __NFC_DRIVER_ACR122_USB_H__ #define __NFC_DRIVER_ACR122_USB_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver acr122_usb_driver; #endif // ! __NFC_DRIVER_ACR122_USB_H__
C
/*- * 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 acr122_pcsc.h * @brief Driver for ACR122 devices (behind PC/SC daemon) */ #ifndef __NFC_DRIVER_ACR122_PCSC_H__ #define __NFC_DRIVER_ACR122_PCSC_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver acr122_pcsc_driver; #endif // ! __NFC_DRIVER_ACR122_PCSC_H__
C
/*- * 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 iso14443-subr.c * @brief Defines some function extracted for ISO/IEC 14443 */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" /** * @brief CRC_A * */ void iso14443a_crc(uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc) { uint8_t bt; uint32_t wCrc = 0x6363; do { bt = *pbtData++; bt = (bt ^ (uint8_t)(wCrc & 0x00FF)); bt = (bt ^ (bt << 4)); wCrc = (wCrc >> 8) ^ ((uint32_t) bt << 8) ^ ((uint32_t) bt << 3) ^ ((uint32_t) bt >> 4); } while (--szLen); *pbtCrc++ = (uint8_t)(wCrc & 0xFF); *pbtCrc = (uint8_t)((wCrc >> 8) & 0xFF); } /** * @brief Append CRC_A * */ void iso14443a_crc_append(uint8_t *pbtData, size_t szLen) { iso14443a_crc(pbtData, szLen, pbtData + szLen); } /** * @brief CRC_B * */ void iso14443b_crc(uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc) { uint8_t bt; uint32_t wCrc = 0xFFFF; do { bt = *pbtData++; bt = (bt ^ (uint8_t)(wCrc & 0x00FF)); bt = (bt ^ (bt << 4)); wCrc = (wCrc >> 8) ^ ((uint32_t) bt << 8) ^ ((uint32_t) bt << 3) ^ ((uint32_t) bt >> 4); } while (--szLen); wCrc = ~wCrc; *pbtCrc++ = (uint8_t)(wCrc & 0xFF); *pbtCrc = (uint8_t)((wCrc >> 8) & 0xFF); } /** * @brief Append CRC_B * */ void iso14443b_crc_append(uint8_t *pbtData, size_t szLen) { iso14443b_crc(pbtData, szLen, pbtData + szLen); } /** * @brief Locate historical bytes * @see ISO/IEC 14443-4 (5.2.7 Historical bytes) */ uint8_t * iso14443a_locate_historical_bytes(uint8_t *pbtAts, size_t szAts, size_t *pszTk) { if (szAts) { size_t offset = 1; if (pbtAts[0] & 0x10) { // TA offset++; } if (pbtAts[0] & 0x20) { // TB offset++; } if (pbtAts[0] & 0x40) { // TC offset++; } if (szAts > offset) { *pszTk = (szAts - offset); return (pbtAts + offset); } } *pszTk = 0; return NULL; } /** * @brief Add cascade tags (0x88) in UID * @see ISO/IEC 14443-3 (6.4.4 UID contents and cascade levels) */ void iso14443_cascade_uid(const uint8_t abtUID[], const size_t szUID, uint8_t *pbtCascadedUID, size_t *pszCascadedUID) { switch (szUID) { case 7: pbtCascadedUID[0] = 0x88; memcpy(pbtCascadedUID + 1, abtUID, 7); *pszCascadedUID = 8; break; case 10: pbtCascadedUID[0] = 0x88; memcpy(pbtCascadedUID + 1, abtUID, 3); pbtCascadedUID[4] = 0x88; memcpy(pbtCascadedUID + 5, abtUID + 3, 7); *pszCascadedUID = 12; break; case 4: default: memcpy(pbtCascadedUID, abtUID, szUID); *pszCascadedUID = szUID; break; } }
C
/*- * 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 pn53x.c * @brief PN531, PN532 and PN533 common functions */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdlib.h> #include "nfc/nfc.h" #include "nfc-internal.h" #include "pn53x.h" #include "pn53x-internal.h" #include "mirror-subr.h" #define LOG_CATEGORY "libnfc.chip.pn53x" #define LOG_GROUP NFC_LOG_GROUP_CHIP const uint8_t pn53x_ack_frame[] = { 0x00, 0x00, 0xff, 0x00, 0xff, 0x00 }; const uint8_t pn53x_nack_frame[] = { 0x00, 0x00, 0xff, 0xff, 0x00, 0x00 }; static const uint8_t pn53x_error_frame[] = { 0x00, 0x00, 0xff, 0x01, 0xff, 0x7f, 0x81, 0x00 }; const nfc_baud_rate pn532_iso14443a_supported_baud_rates[] = { NBR_424, NBR_212, NBR_106, 0 }; const nfc_baud_rate pn533_iso14443a_supported_baud_rates[] = { NBR_847, NBR_424, NBR_212, NBR_106, 0 }; const nfc_baud_rate pn53x_felica_supported_baud_rates[] = { NBR_424, NBR_212, 0 }; const nfc_baud_rate pn53x_dep_supported_baud_rates[] = { NBR_424, NBR_212, NBR_106, 0 }; const nfc_baud_rate pn53x_jewel_supported_baud_rates[] = { NBR_106, 0 }; const nfc_baud_rate pn532_iso14443b_supported_baud_rates[] = { NBR_106, 0 }; const nfc_baud_rate pn533_iso14443b_supported_baud_rates[] = { NBR_847, NBR_424, NBR_212, NBR_106, 0 }; const nfc_modulation_type pn53x_supported_modulation_as_target[] = {NMT_ISO14443A, NMT_FELICA, NMT_DEP, 0}; /* prototypes */ int pn53x_reset_settings(struct nfc_device *pnd); int pn53x_writeback_register(struct nfc_device *pnd); nfc_modulation pn53x_ptt_to_nm(const pn53x_target_type ptt); pn53x_modulation pn53x_nm_to_pm(const nfc_modulation nm); pn53x_target_type pn53x_nm_to_ptt(const nfc_modulation nm); void *pn53x_current_target_new(const struct nfc_device *pnd, const nfc_target *pnt); void pn53x_current_target_free(const struct nfc_device *pnd); bool pn53x_current_target_is(const struct nfc_device *pnd, const nfc_target *pnt); /* implementations */ int pn53x_init(struct nfc_device *pnd) { int res = 0; // GetFirmwareVersion command is used to set PN53x chips type (PN531, PN532 or PN533) if ((res = pn53x_decode_firmware_version(pnd)) < 0) { return res; } if (!CHIP_DATA(pnd)->supported_modulation_as_initiator) { CHIP_DATA(pnd)->supported_modulation_as_initiator = malloc(sizeof(nfc_modulation_type) * 9); if (! CHIP_DATA(pnd)->supported_modulation_as_initiator) return NFC_ESOFT; int nbSupportedModulation = 0; if ((pnd->btSupportByte & SUPPORT_ISO14443A)) { CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443A; nbSupportedModulation++; CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_FELICA; nbSupportedModulation++; } if (pnd->btSupportByte & SUPPORT_ISO14443B) { CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443B; nbSupportedModulation++; CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443BI; nbSupportedModulation++; CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443B2SR; nbSupportedModulation++; CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443B2CT; nbSupportedModulation++; } if (CHIP_DATA(pnd)->type != PN531) { CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_JEWEL; nbSupportedModulation++; } CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_DEP; nbSupportedModulation++; CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = 0; } if (!CHIP_DATA(pnd)->supported_modulation_as_target) { CHIP_DATA(pnd)->supported_modulation_as_target = (nfc_modulation_type *) pn53x_supported_modulation_as_target; } // CRC handling should be enabled by default as declared in nfc_device_new // which is the case by default for pn53x, so nothing to do here // Parity handling should be enabled by default as declared in nfc_device_new // which is the case by default for pn53x, so nothing to do here // We can't read these parameters, so we set a default config by using the SetParameters wrapper // Note: pn53x_SetParameters() will save the sent value in pnd->ui8Parameters cache if ((res = pn53x_SetParameters(pnd, PARAM_AUTO_ATR_RES | PARAM_AUTO_RATS)) < 0) { return res; } if ((res = pn53x_reset_settings(pnd)) < 0) { return res; } return NFC_SUCCESS; } int pn53x_reset_settings(struct nfc_device *pnd) { int res = 0; // Reset the ending transmission bits register, it is unknown what the last tranmission used there CHIP_DATA(pnd)->ui8TxBits = 0; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_BitFraming, SYMBOL_TX_LAST_BITS, 0x00)) < 0) { return res; } // Make sure we reset the CRC and parity to chip handling. if ((res = pn53x_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0) return res; if ((res = pn53x_set_property_bool(pnd, NP_HANDLE_PARITY, true)) < 0) return res; // Activate "easy framing" feature by default if ((res = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0) return res; // Deactivate the CRYPTO1 cipher, it may could cause problems when still active if ((res = pn53x_set_property_bool(pnd, NP_ACTIVATE_CRYPTO1, false)) < 0) return res; return NFC_SUCCESS; } int pn53x_transceive(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRxLen, int timeout) { bool mi = false; int res = 0; if (CHIP_DATA(pnd)->wb_trigged) { if ((res = pn53x_writeback_register(pnd)) < 0) { return res; } } PNCMD_TRACE(pbtTx[0]); if (timeout > 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Timeout value: %d", timeout); } else if (timeout == 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "No timeout"); } else if (timeout == -1) { timeout = CHIP_DATA(pnd)->timeout_command; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid timeout value: %d", timeout); } uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); // Check if receiving buffers are available, if not, replace them if (szRxLen == 0 || !pbtRx) { pbtRx = abtRx; } else { szRx = szRxLen; } // Call the send/receice callback functions of the current driver if ((res = CHIP_DATA(pnd)->io->send(pnd, pbtTx, szTx, timeout)) < 0) { return res; } // Command is sent, we store the command CHIP_DATA(pnd)->last_command = pbtTx[0]; // Handle power mode for PN532 if ((CHIP_DATA(pnd)->type == PN532) && (TgInitAsTarget == pbtTx[0])) { // PN532 automatically goes into PowerDown mode when TgInitAsTarget command will be sent CHIP_DATA(pnd)->power_mode = POWERDOWN; } if ((res = CHIP_DATA(pnd)->io->receive(pnd, pbtRx, szRx, timeout)) < 0) { return res; } if ((CHIP_DATA(pnd)->type == PN532) && (TgInitAsTarget == pbtTx[0])) { // PN532 automatically wakeup on external RF field CHIP_DATA(pnd)->power_mode = NORMAL; // When TgInitAsTarget reply that means an external RF have waken up the chip } switch (pbtTx[0]) { case PowerDown: case InDataExchange: case InCommunicateThru: case InJumpForPSL: case InPSL: case InATR: case InSelect: case InJumpForDEP: case TgGetData: case TgGetInitiatorCommand: case TgSetData: case TgResponseToInitiator: case TgSetGeneralBytes: case TgSetMetaData: if (pbtRx[0] & 0x80) { abort(); } // NAD detected // if (pbtRx[0] & 0x40) { abort(); } // MI detected mi = pbtRx[0] & 0x40; CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; break; case Diagnose: if (pbtTx[1] == 0x06) { // Diagnose: Card presence detection CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; } else { CHIP_DATA(pnd)->last_status_byte = 0; }; break; case InDeselect: case InRelease: if (CHIP_DATA(pnd)->type == RCS360) { // Error code is in pbtRx[1] but we ignore error code anyway // because other PN53x chips always return 0 on those commands CHIP_DATA(pnd)->last_status_byte = 0; break; } CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; break; case ReadRegister: case WriteRegister: if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by the status byte CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; } else { CHIP_DATA(pnd)->last_status_byte = 0; } break; default: CHIP_DATA(pnd)->last_status_byte = 0; } while (mi) { int res2; uint8_t abtRx2[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; // Send empty command to card if ((res2 = CHIP_DATA(pnd)->io->send(pnd, pbtTx, 2, timeout)) < 0) { return res2; } if ((res2 = CHIP_DATA(pnd)->io->receive(pnd, abtRx2, sizeof(abtRx2), timeout)) < 0) { return res2; } mi = abtRx2[0] & 0x40; if ((size_t)(res + res2 - 1) > szRx) { CHIP_DATA(pnd)->last_status_byte = ESMALLBUF; break; } memcpy(pbtRx + res, abtRx2 + 1, res2 - 1); // Copy last status byte pbtRx[0] = abtRx2[0]; res += res2 - 1; } szRx = (size_t) res; switch (CHIP_DATA(pnd)->last_status_byte) { case 0: res = (int)szRx; break; case ETIMEOUT: case ECRC: case EPARITY: case EBITCOUNT: case EFRAMING: case EBITCOLL: case ERFPROTO: case ERFTIMEOUT: case EDEPUNKCMD: case EDEPINVSTATE: case ENAD: case ENFCID3: case EINVRXFRAM: case EBCC: case ECID: res = NFC_ERFTRANS; break; case ESMALLBUF: case EOVCURRENT: case EBUFOVF: case EOVHEAT: case EINBUFOVF: res = NFC_ECHIP; break; case EINVPARAM: case EOPNOTALL: case ECMD: case ENSECNOTSUPP: res = NFC_EINVARG; break; case ETGREL: case ECDISCARDED: res = NFC_ETGRELEASED; pn53x_current_target_free(pnd); break; case EMFAUTH: // When a MIFARE Classic AUTH fails, the tag is automatically in HALT state res = NFC_EMFCAUTHFAIL; break; default: res = NFC_ECHIP; break; }; if (res < 0) { pnd->last_error = res; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Chip error: \"%s\" (%02x), returned error: \"%s\" (%d))", pn53x_strerror(pnd), CHIP_DATA(pnd)->last_status_byte, nfc_strerror(pnd), res); } else { pnd->last_error = 0; } return res; } int pn53x_set_parameters(struct nfc_device *pnd, const uint8_t ui8Parameter, const bool bEnable) { uint8_t ui8Value = (bEnable) ? (CHIP_DATA(pnd)->ui8Parameters | ui8Parameter) : (CHIP_DATA(pnd)->ui8Parameters & ~(ui8Parameter)); if (ui8Value != CHIP_DATA(pnd)->ui8Parameters) { return pn53x_SetParameters(pnd, ui8Value); } return NFC_SUCCESS; } int pn53x_set_tx_bits(struct nfc_device *pnd, const uint8_t ui8Bits) { // Test if we need to update the transmission bits register setting if (CHIP_DATA(pnd)->ui8TxBits != ui8Bits) { int res = 0; // Set the amount of transmission bits in the PN53X chip register if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_BitFraming, SYMBOL_TX_LAST_BITS, ui8Bits)) < 0) return res; // Store the new setting CHIP_DATA(pnd)->ui8TxBits = ui8Bits; } return NFC_SUCCESS; } int pn53x_wrap_frame(const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtFrame) { uint8_t btFrame; uint8_t btData; uint32_t uiBitPos; uint32_t uiDataPos = 0; size_t szBitsLeft = szTxBits; size_t szFrameBits = 0; // Make sure we should frame at least something if (szBitsLeft == 0) return NFC_ECHIP; // Handle a short response (1byte) as a special case if (szBitsLeft < 9) { *pbtFrame = *pbtTx; szFrameBits = szTxBits; return szFrameBits; } // We start by calculating the frame length in bits szFrameBits = szTxBits + (szTxBits / 8); // Parse the data bytes and add the parity bits // This is really a sensitive process, mirror the frame bytes and append parity bits // buffer = mirror(frame-byte) + parity + mirror(frame-byte) + parity + ... // split "buffer" up in segments of 8 bits again and mirror them // air-bytes = mirror(buffer-byte) + mirror(buffer-byte) + mirror(buffer-byte) + .. while (true) { // Reset the temporary frame byte; btFrame = 0; for (uiBitPos = 0; uiBitPos < 8; uiBitPos++) { // Copy as much data that fits in the frame byte btData = mirror(pbtTx[uiDataPos]); btFrame |= (btData >> uiBitPos); // Save this frame byte *pbtFrame = mirror(btFrame); // Set the remaining bits of the date in the new frame byte and append the parity bit btFrame = (btData << (8 - uiBitPos)); btFrame |= ((pbtTxPar[uiDataPos] & 0x01) << (7 - uiBitPos)); // Backup the frame bits we have so far pbtFrame++; *pbtFrame = mirror(btFrame); // Increase the data (without parity bit) position uiDataPos++; // Test if we are done if (szBitsLeft < 9) return szFrameBits; szBitsLeft -= 8; } // Every 8 data bytes we lose one frame byte to the parities pbtFrame++; } } int pn53x_unwrap_frame(const uint8_t *pbtFrame, const size_t szFrameBits, uint8_t *pbtRx, uint8_t *pbtRxPar) { uint8_t btFrame; uint8_t btData; uint8_t uiBitPos; uint32_t uiDataPos = 0; uint8_t *pbtFramePos = (uint8_t *) pbtFrame; size_t szBitsLeft = szFrameBits; size_t szRxBits = 0; // Make sure we should frame at least something if (szBitsLeft == 0) return NFC_ECHIP; // Handle a short response (1byte) as a special case if (szBitsLeft < 9) { *pbtRx = *pbtFrame; szRxBits = szFrameBits; return szRxBits; } // Calculate the data length in bits szRxBits = szFrameBits - (szFrameBits / 9); // Parse the frame bytes, remove the parity bits and store them in the parity array // This process is the reverse of WrapFrame(), look there for more info while (true) { for (uiBitPos = 0; uiBitPos < 8; uiBitPos++) { btFrame = mirror(pbtFramePos[uiDataPos]); btData = (btFrame << uiBitPos); btFrame = mirror(pbtFramePos[uiDataPos + 1]); btData |= (btFrame >> (8 - uiBitPos)); pbtRx[uiDataPos] = mirror(btData); if (pbtRxPar != NULL) pbtRxPar[uiDataPos] = ((btFrame >> (7 - uiBitPos)) & 0x01); // Increase the data (without parity bit) position uiDataPos++; // Test if we are done if (szBitsLeft < 9) return szRxBits; szBitsLeft -= 9; } // Every 8 data bytes we lose one frame byte to the parities pbtFramePos++; } } int pn53x_decode_target_data(const uint8_t *pbtRawData, size_t szRawData, pn53x_type type, nfc_modulation_type nmt, nfc_target_info *pnti) { uint8_t szAttribRes; const uint8_t *pbtUid; switch (nmt) { case NMT_ISO14443A: // We skip the first byte: its the target number (Tg) pbtRawData++; // Somehow they switched the lower and upper ATQA bytes around for the PN531 chipset if (type == PN531) { pnti->nai.abtAtqa[1] = *(pbtRawData++); pnti->nai.abtAtqa[0] = *(pbtRawData++); } else { pnti->nai.abtAtqa[0] = *(pbtRawData++); pnti->nai.abtAtqa[1] = *(pbtRawData++); } pnti->nai.btSak = *(pbtRawData++); // Copy the NFCID1 pnti->nai.szUidLen = *(pbtRawData++); pbtUid = pbtRawData; pbtRawData += pnti->nai.szUidLen; // Did we received an optional ATS (Smardcard ATR) if (szRawData > (pnti->nai.szUidLen + 5)) { pnti->nai.szAtsLen = ((*(pbtRawData++)) - 1); // In pbtRawData, ATS Length byte is counted in ATS Frame. memcpy(pnti->nai.abtAts, pbtRawData, pnti->nai.szAtsLen); } else { pnti->nai.szAtsLen = 0; } // For PN531, strip CT (Cascade Tag) to retrieve and store the _real_ UID // (e.g. 0x8801020304050607 is in fact 0x01020304050607) if ((pnti->nai.szUidLen == 8) && (pbtUid[0] == 0x88)) { pnti->nai.szUidLen = 7; memcpy(pnti->nai.abtUid, pbtUid + 1, 7); // } else if ((pnti->nai.szUidLen == 12) && (pbtUid[0] == 0x88) && (pbtUid[4] == 0x88)) { } else if (pnti->nai.szUidLen > 10) { pnti->nai.szUidLen = 10; memcpy(pnti->nai.abtUid, pbtUid + 1, 3); memcpy(pnti->nai.abtUid + 3, pbtUid + 5, 3); memcpy(pnti->nai.abtUid + 6, pbtUid + 8, 4); } else { // For PN532, PN533 memcpy(pnti->nai.abtUid, pbtUid, pnti->nai.szUidLen); } break; case NMT_ISO14443B: // We skip the first byte: its the target number (Tg) pbtRawData++; // Now we are in ATQB, we skip the first ATQB byte always equal to 0x50 pbtRawData++; // Store the PUPI (Pseudo-Unique PICC Identifier) memcpy(pnti->nbi.abtPupi, pbtRawData, 4); pbtRawData += 4; // Store the Application Data memcpy(pnti->nbi.abtApplicationData, pbtRawData, 4); pbtRawData += 4; // Store the Protocol Info memcpy(pnti->nbi.abtProtocolInfo, pbtRawData, 3); pbtRawData += 3; // We leave the ATQB field, we now enter in Card IDentifier szAttribRes = *(pbtRawData++); if (szAttribRes) { pnti->nbi.ui8CardIdentifier = *(pbtRawData++); } break; case NMT_ISO14443BI: // Skip V & T Addresses pbtRawData++; if (*pbtRawData != 0x07) { // 0x07 = REPGEN return NFC_ECHIP; } pbtRawData++; // Store the UID memcpy(pnti->nii.abtDIV, pbtRawData, 4); pbtRawData += 4; pnti->nii.btVerLog = *(pbtRawData++); if (pnti->nii.btVerLog & 0x80) { // Type = long? pnti->nii.btConfig = *(pbtRawData++); if (pnti->nii.btConfig & 0x40) { memcpy(pnti->nii.abtAtr, pbtRawData, szRawData - 8); pnti->nii.szAtrLen = szRawData - 8; } } break; case NMT_ISO14443B2SR: // Store the UID memcpy(pnti->nsi.abtUID, pbtRawData, 8); break; case NMT_ISO14443B2CT: // Store UID LSB memcpy(pnti->nci.abtUID, pbtRawData, 2); pbtRawData += 2; // Store Prod Code & Fab Code pnti->nci.btProdCode = *(pbtRawData++); pnti->nci.btFabCode = *(pbtRawData++); // Store UID MSB memcpy(pnti->nci.abtUID + 2, pbtRawData, 2); break; case NMT_FELICA: // We skip the first byte: its the target number (Tg) pbtRawData++; // Store the mandatory info pnti->nfi.szLen = *(pbtRawData++); pnti->nfi.btResCode = *(pbtRawData++); // Copy the NFCID2t memcpy(pnti->nfi.abtId, pbtRawData, 8); pbtRawData += 8; // Copy the felica padding memcpy(pnti->nfi.abtPad, pbtRawData, 8); pbtRawData += 8; // Test if the System code (SYST_CODE) is available if (pnti->nfi.szLen > 18) { memcpy(pnti->nfi.abtSysCode, pbtRawData, 2); } break; case NMT_JEWEL: // We skip the first byte: its the target number (Tg) pbtRawData++; // Store the mandatory info memcpy(pnti->nji.btSensRes, pbtRawData, 2); pbtRawData += 2; memcpy(pnti->nji.btId, pbtRawData, 4); break; // Should not happend... case NMT_DEP: return NFC_ECHIP; } return NFC_SUCCESS; } static int pn53x_ReadRegister(struct nfc_device *pnd, uint16_t ui16RegisterAddress, uint8_t *ui8Value) { uint8_t abtCmd[] = { ReadRegister, ui16RegisterAddress >> 8, ui16RegisterAddress & 0xff }; uint8_t abtRegValue[2]; size_t szRegValue = sizeof(abtRegValue); int res = 0; PNREG_TRACE(ui16RegisterAddress); if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRegValue, szRegValue, -1)) < 0) { return res; } if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte *ui8Value = abtRegValue[1]; } else { *ui8Value = abtRegValue[0]; } return NFC_SUCCESS; } int pn53x_read_register(struct nfc_device *pnd, uint16_t ui16RegisterAddress, uint8_t *ui8Value) { return pn53x_ReadRegister(pnd, ui16RegisterAddress, ui8Value); } static int pn53x_WriteRegister(struct nfc_device *pnd, const uint16_t ui16RegisterAddress, const uint8_t ui8Value) { uint8_t abtCmd[] = { WriteRegister, ui16RegisterAddress >> 8, ui16RegisterAddress & 0xff, ui8Value }; PNREG_TRACE(ui16RegisterAddress); return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_write_register(struct nfc_device *pnd, const uint16_t ui16RegisterAddress, const uint8_t ui8SymbolMask, const uint8_t ui8Value) { if ((ui16RegisterAddress < PN53X_CACHE_REGISTER_MIN_ADDRESS) || (ui16RegisterAddress > PN53X_CACHE_REGISTER_MAX_ADDRESS)) { // Direct write if (ui8SymbolMask != 0xff) { int res = 0; uint8_t ui8CurrentValue; if ((res = pn53x_read_register(pnd, ui16RegisterAddress, &ui8CurrentValue)) < 0) return res; uint8_t ui8NewValue = ((ui8Value & ui8SymbolMask) | (ui8CurrentValue & (~ui8SymbolMask))); if (ui8NewValue != ui8CurrentValue) { return pn53x_WriteRegister(pnd, ui16RegisterAddress, ui8NewValue); } } else { return pn53x_WriteRegister(pnd, ui16RegisterAddress, ui8Value); } } else { // Write-back cache area const int internal_address = ui16RegisterAddress - PN53X_CACHE_REGISTER_MIN_ADDRESS; CHIP_DATA(pnd)->wb_data[internal_address] = (CHIP_DATA(pnd)->wb_data[internal_address] & CHIP_DATA(pnd)->wb_mask[internal_address] & (~ui8SymbolMask)) | (ui8Value & ui8SymbolMask); CHIP_DATA(pnd)->wb_mask[internal_address] = CHIP_DATA(pnd)->wb_mask[internal_address] | ui8SymbolMask; CHIP_DATA(pnd)->wb_trigged = true; } return NFC_SUCCESS; } int pn53x_writeback_register(struct nfc_device *pnd) { int res = 0; // TODO Check at each step (ReadRegister, WriteRegister) if we didn't exceed max supported frame length BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); // First step, it looks for registers to be read before applying the requested mask CHIP_DATA(pnd)->wb_trigged = false; for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) { if ((CHIP_DATA(pnd)->wb_mask[n]) && (CHIP_DATA(pnd)->wb_mask[n] != 0xff)) { // This register needs to be read: mask is present but does not cover full data width (ie. mask != 0xff) const uint16_t pn53x_register_address = PN53X_CACHE_REGISTER_MIN_ADDRESS + n; BUFFER_APPEND(abtReadRegisterCmd, pn53x_register_address >> 8); BUFFER_APPEND(abtReadRegisterCmd, pn53x_register_address & 0xff); } } if (BUFFER_SIZE(abtReadRegisterCmd) > 1) { // It needs to read some registers uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // It transceives the previously constructed ReadRegister command if ((res = pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1)) < 0) { return res; } size_t i = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte i = 1; } for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) { if ((CHIP_DATA(pnd)->wb_mask[n]) && (CHIP_DATA(pnd)->wb_mask[n] != 0xff)) { CHIP_DATA(pnd)->wb_data[n] = ((CHIP_DATA(pnd)->wb_data[n] & CHIP_DATA(pnd)->wb_mask[n]) | (abtRes[i] & (~CHIP_DATA(pnd)->wb_mask[n]))); if (CHIP_DATA(pnd)->wb_data[n] != abtRes[i]) { // Requested value is different from read one CHIP_DATA(pnd)->wb_mask[n] = 0xff; // We can now apply whole data bits } else { CHIP_DATA(pnd)->wb_mask[n] = 0x00; // We already have the right value } i++; } } } // Now, the writeback-cache only has masks with 0xff, we can start to WriteRegister BUFFER_INIT(abtWriteRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtWriteRegisterCmd, WriteRegister); for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) { if (CHIP_DATA(pnd)->wb_mask[n] == 0xff) { const uint16_t pn53x_register_address = PN53X_CACHE_REGISTER_MIN_ADDRESS + n; PNREG_TRACE(pn53x_register_address); BUFFER_APPEND(abtWriteRegisterCmd, pn53x_register_address >> 8); BUFFER_APPEND(abtWriteRegisterCmd, pn53x_register_address & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, CHIP_DATA(pnd)->wb_data[n]); // This register is handled, we reset the mask to prevent CHIP_DATA(pnd)->wb_mask[n] = 0x00; } } if (BUFFER_SIZE(abtWriteRegisterCmd) > 1) { // We need to write some registers if ((res = pn53x_transceive(pnd, abtWriteRegisterCmd, BUFFER_SIZE(abtWriteRegisterCmd), NULL, 0, -1)) < 0) { return res; } } return NFC_SUCCESS; } int pn53x_decode_firmware_version(struct nfc_device *pnd) { const uint8_t abtCmd[] = { GetFirmwareVersion }; uint8_t abtFw[4]; size_t szFwLen = sizeof(abtFw); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtFw, szFwLen, -1)) < 0) { return res; } szFwLen = (size_t) res; // Determine which version of chip it is: PN531 will return only 2 bytes, while others return 4 bytes and have the first to tell the version IC if (szFwLen == 2) { CHIP_DATA(pnd)->type = PN531; } else if (szFwLen == 4) { if (abtFw[0] == 0x32) { // PN532 version IC CHIP_DATA(pnd)->type = PN532; } else if (abtFw[0] == 0x33) { // PN533 version IC if (abtFw[1] == 0x01) { // Sony ROM code CHIP_DATA(pnd)->type = RCS360; } else { CHIP_DATA(pnd)->type = PN533; } } else { // Unknown version IC return NFC_ENOTIMPL; } } else { // Unknown chip return NFC_ENOTIMPL; } // Convert firmware info in text, PN531 gives 2 bytes info, but PN532 and PN533 gives 4 switch (CHIP_DATA(pnd)->type) { case PN531: snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN531 v%d.%d", abtFw[0], abtFw[1]); pnd->btSupportByte = SUPPORT_ISO14443A | SUPPORT_ISO18092; break; case PN532: snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN532 v%d.%d", abtFw[1], abtFw[2]); pnd->btSupportByte = abtFw[3]; break; case PN533: case RCS360: snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN533 v%d.%d", abtFw[1], abtFw[2]); pnd->btSupportByte = abtFw[3]; break; case PN53X: // Could not happend break; } return NFC_SUCCESS; } static uint8_t pn53x_int_to_timeout(const int ms) { uint8_t res = 0; if (ms) { res = 0x10; for (int i = 3280; i > 1; i /= 2) { if (ms > i) break; res--; } } return res; } int pn53x_set_property_int(struct nfc_device *pnd, const nfc_property property, const int value) { switch (property) { case NP_TIMEOUT_COMMAND: CHIP_DATA(pnd)->timeout_command = value; break; case NP_TIMEOUT_ATR: CHIP_DATA(pnd)->timeout_atr = value; return pn53x_RFConfiguration__Various_timings(pnd, pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_atr), pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_communication)); case NP_TIMEOUT_COM: CHIP_DATA(pnd)->timeout_communication = value; return pn53x_RFConfiguration__Various_timings(pnd, pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_atr), pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_communication)); // Following properties are invalid (not integer) case NP_HANDLE_CRC: case NP_HANDLE_PARITY: case NP_ACTIVATE_FIELD: case NP_ACTIVATE_CRYPTO1: case NP_INFINITE_SELECT: case NP_ACCEPT_INVALID_FRAMES: case NP_ACCEPT_MULTIPLE_FRAMES: case NP_AUTO_ISO14443_4: case NP_EASY_FRAMING: case NP_FORCE_ISO14443_A: case NP_FORCE_ISO14443_B: case NP_FORCE_SPEED_106: return NFC_EINVARG; } return NFC_SUCCESS; } int pn53x_set_property_bool(struct nfc_device *pnd, const nfc_property property, const bool bEnable) { uint8_t btValue; int res = 0; switch (property) { case NP_HANDLE_CRC: // Enable or disable automatic receiving/sending of CRC bytes if (bEnable == pnd->bCrc) { // Nothing to do return NFC_SUCCESS; } // TX and RX are both represented by the symbol 0x80 btValue = (bEnable) ? 0x80 : 0x00; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_CRC_ENABLE, btValue)) < 0) return res; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_CRC_ENABLE, btValue)) < 0) return res; pnd->bCrc = bEnable; return NFC_SUCCESS; case NP_HANDLE_PARITY: // Handle parity bit by PN53X chip or parse it as data bit if (bEnable == pnd->bPar) // Nothing to do return NFC_SUCCESS; btValue = (bEnable) ? 0x00 : SYMBOL_PARITY_DISABLE; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_ManualRCV, SYMBOL_PARITY_DISABLE, btValue)) < 0) return res; pnd->bPar = bEnable; return NFC_SUCCESS; case NP_EASY_FRAMING: pnd->bEasyFraming = bEnable; return NFC_SUCCESS; case NP_ACTIVATE_FIELD: return pn53x_RFConfiguration__RF_field(pnd, bEnable); case NP_ACTIVATE_CRYPTO1: btValue = (bEnable) ? SYMBOL_MF_CRYPTO1_ON : 0x00; return pn53x_write_register(pnd, PN53X_REG_CIU_Status2, SYMBOL_MF_CRYPTO1_ON, btValue); case NP_INFINITE_SELECT: // TODO Made some research around this point: // timings could be tweak better than this, and maybe we can tweak timings // to "gain" a sort-of hardware polling (ie. like PN532 does) pnd->bInfiniteSelect = bEnable; return pn53x_RFConfiguration__MaxRetries(pnd, (bEnable) ? 0xff : 0x00, // MxRtyATR, default: active = 0xff, passive = 0x02 (bEnable) ? 0xff : 0x01, // MxRtyPSL, default: 0x01 (bEnable) ? 0xff : 0x02 // MxRtyPassiveActivation, default: 0xff (0x00 leads to problems with PN531) ); case NP_ACCEPT_INVALID_FRAMES: btValue = (bEnable) ? SYMBOL_RX_NO_ERROR : 0x00; return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_NO_ERROR, btValue); case NP_ACCEPT_MULTIPLE_FRAMES: btValue = (bEnable) ? SYMBOL_RX_MULTIPLE : 0x00; return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_MULTIPLE, btValue); case NP_AUTO_ISO14443_4: if (bEnable == pnd->bAutoIso14443_4) // Nothing to do return NFC_SUCCESS; pnd->bAutoIso14443_4 = bEnable; return pn53x_set_parameters(pnd, PARAM_AUTO_RATS, bEnable); case NP_FORCE_ISO14443_A: if (!bEnable) { // Nothing to do return NFC_SUCCESS; } // Force pn53x to be in ISO14443-A mode if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_FRAMING, 0x00)) < 0) { return res; } if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_FRAMING, 0x00)) < 0) { return res; } // Set the PN53X to force 100% ASK Modified miller decoding (default for 14443A cards) return pn53x_write_register(pnd, PN53X_REG_CIU_TxAuto, SYMBOL_FORCE_100_ASK, 0x40); case NP_FORCE_ISO14443_B: if (!bEnable) { // Nothing to do return NFC_SUCCESS; } // Force pn53x to be in ISO14443-B mode if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_FRAMING, 0x03)) < 0) { return res; } return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_FRAMING, 0x03); case NP_FORCE_SPEED_106: if (!bEnable) { // Nothing to do return NFC_SUCCESS; } // Force pn53x to be at 106 kbps if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_SPEED, 0x00)) < 0) { return res; } return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_SPEED, 0x00); // Following properties are invalid (not boolean) case NP_TIMEOUT_COMMAND: case NP_TIMEOUT_ATR: case NP_TIMEOUT_COM: return NFC_EINVARG; } return NFC_EINVARG; } int pn53x_idle(struct nfc_device *pnd) { int res = 0; switch (CHIP_DATA(pnd)->operating_mode) { case TARGET: // InRelease used in target mode stops the target emulation and no more // tag are seen from external initiator if ((res = pn53x_InRelease(pnd, 0)) < 0) { return res; } if ((CHIP_DATA(pnd)->type == PN532) && (pnd->driver->powerdown)) { // Use PowerDown to go in "Low VBat" power mode if ((res = pnd->driver->powerdown(pnd)) < 0) { return res; } } break; case INITIATOR: // Use InRelease to go in "Standby mode" if ((res = pn53x_InRelease(pnd, 0)) < 0) { return res; } // Disable RF field to avoid heating if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0) { return res; } if ((CHIP_DATA(pnd)->type == PN532) && (pnd->driver->powerdown)) { // Use PowerDown to go in "Low VBat" power mode if ((res = pnd->driver->powerdown(pnd)) < 0) { return res; } } break; case IDLE: // Nothing to do. break; }; // Clear the current nfc_target pn53x_current_target_free(pnd); CHIP_DATA(pnd)->operating_mode = IDLE; return NFC_SUCCESS; } int pn53x_check_communication(struct nfc_device *pnd) { const uint8_t abtCmd[] = { Diagnose, 0x00, 'l', 'i', 'b', 'n', 'f', 'c' }; const uint8_t abtExpectedRx[] = { 0x00, 'l', 'i', 'b', 'n', 'f', 'c' }; uint8_t abtRx[sizeof(abtExpectedRx)]; size_t szRx = sizeof(abtRx); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, szRx, 500)) < 0) return res; szRx = (size_t) res; if ((sizeof(abtExpectedRx) == szRx) && (0 == memcmp(abtRx, abtExpectedRx, sizeof(abtExpectedRx)))) return NFC_SUCCESS; return NFC_EIO; } int pn53x_initiator_init(struct nfc_device *pnd) { pn53x_reset_settings(pnd); int res; if (CHIP_DATA(pnd)->sam_mode != PSM_NORMAL) { if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, -1)) < 0) { return res; } } // Configure the PN53X to be an Initiator or Reader/Writer if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_Control, SYMBOL_INITIATOR, 0x10)) < 0) return res; CHIP_DATA(pnd)->operating_mode = INITIATOR; return NFC_SUCCESS; } int pn532_initiator_init_secure_element(struct nfc_device *pnd) { return pn532_SAMConfiguration(pnd, PSM_WIRED_CARD, -1); } static int pn53x_initiator_select_passive_target_ext(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt, int timeout) { uint8_t abtTargetsData[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szTargetsData = sizeof(abtTargetsData); int res = 0; nfc_target nttmp; if (nm.nmt == NMT_ISO14443BI || nm.nmt == NMT_ISO14443B2SR || nm.nmt == NMT_ISO14443B2CT) { if (CHIP_DATA(pnd)->type == RCS360) { // TODO add support for RC-S360, at the moment it refuses to send raw frames without a first select pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } // No native support in InListPassiveTarget so we do discovery by hand if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_ISO14443_B, true)) < 0) { return res; } if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_SPEED_106, true)) < 0) { return res; } if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0) { return res; } if ((res = nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false)) < 0) { return res; } bool found = false; do { if (nm.nmt == NMT_ISO14443B2SR) { // Some work to do before getting the UID... uint8_t abtInitiate[] = "\x06\x00"; size_t szInitiateLen = 2; uint8_t abtSelect[] = { 0x0e, 0x00 }; uint8_t abtRx[1]; // Getting random Chip_ID if ((res = pn53x_initiator_transceive_bytes(pnd, abtInitiate, szInitiateLen, abtRx, sizeof(abtRx), timeout)) < 0) { if ((res == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Chip timeout continue; } else return res; } abtSelect[1] = abtRx[0]; if ((res = pn53x_initiator_transceive_bytes(pnd, abtSelect, sizeof(abtSelect), abtRx, sizeof(abtRx), timeout)) < 0) { return res; } szTargetsData = (size_t)res; } else if (nm.nmt == NMT_ISO14443B2CT) { // Some work to do before getting the UID... const uint8_t abtReqt[] = { 0x10 }; // Getting product code / fab code & store it in output buffer after the serial nr we'll obtain later if ((res = pn53x_initiator_transceive_bytes(pnd, abtReqt, sizeof(abtReqt), abtTargetsData + 2, sizeof(abtTargetsData) - 2, timeout)) < 0) { if ((res == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Chip timeout continue; } else return res; } szTargetsData = (size_t)res; } if ((res = pn53x_initiator_transceive_bytes(pnd, pbtInitData, szInitData, abtTargetsData, sizeof(abtTargetsData), timeout)) < 0) { if ((res == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Chip timeout continue; } else return res; } szTargetsData = (size_t)res; if (nm.nmt == NMT_ISO14443B2CT) { if (szTargetsData != 2) return 0; // Target is not ISO14443B2CT uint8_t abtRead[] = { 0xC4 }; // Reading UID_MSB (Read address 4) if ((res = pn53x_initiator_transceive_bytes(pnd, abtRead, sizeof(abtRead), abtTargetsData + 4, sizeof(abtTargetsData) - 4, timeout)) < 0) { return res; } szTargetsData = 6; // u16 UID_LSB, u8 prod code, u8 fab code, u16 UID_MSB } nttmp.nm = nm; if ((res = pn53x_decode_target_data(abtTargetsData, szTargetsData, CHIP_DATA(pnd)->type, nm.nmt, &(nttmp.nti))) < 0) { return res; } if (nm.nmt == NMT_ISO14443BI) { // Select tag uint8_t abtAttrib[6]; memcpy(abtAttrib, abtTargetsData, sizeof(abtAttrib)); abtAttrib[1] = 0x0f; // ATTRIB if ((res = pn53x_initiator_transceive_bytes(pnd, abtAttrib, sizeof(abtAttrib), NULL, 0, timeout)) < 0) { return res; } szTargetsData = (size_t)res; } found = true; break; } while (pnd->bInfiniteSelect); if (! found) return 0; } else { const pn53x_modulation pm = pn53x_nm_to_pm(nm); if ((PM_UNDEFINED == pm) || (NBR_UNDEFINED == nm.nbr)) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } if ((res = pn53x_InListPassiveTarget(pnd, pm, 1, pbtInitData, szInitData, abtTargetsData, &szTargetsData, timeout)) <= 0) return res; if (szTargetsData <= 1) // For Coverity to know szTargetsData is always > 1 if res > 0 return 0; nttmp.nm = nm; if ((res = pn53x_decode_target_data(abtTargetsData + 1, szTargetsData - 1, CHIP_DATA(pnd)->type, nm.nmt, &(nttmp.nti))) < 0) { return res; } if ((nm.nmt == NMT_ISO14443A) && (nm.nbr != NBR_106)) { uint8_t pncmd_inpsl[4] = { InPSL, 0x01 }; pncmd_inpsl[2] = nm.nbr - 1; pncmd_inpsl[3] = nm.nbr - 1; if ((res = pn53x_transceive(pnd, pncmd_inpsl, sizeof(pncmd_inpsl), NULL, 0, 0)) < 0) { return res; } } } if (pn53x_current_target_new(pnd, &nttmp) == NULL) { pnd->last_error = NFC_ESOFT; return pnd->last_error; } // Is a tag info struct available if (pnt) { memcpy(pnt, &nttmp, sizeof(nfc_target)); } return abtTargetsData[0]; } int pn53x_initiator_select_passive_target(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt) { return pn53x_initiator_select_passive_target_ext(pnd, nm, pbtInitData, szInitData, pnt, 0); } int pn53x_initiator_poll_target(struct nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt) { int res = 0; if (CHIP_DATA(pnd)->type == PN532) { size_t szTargetTypes = 0; pn53x_target_type apttTargetTypes[32]; memset(apttTargetTypes, PTT_UNDEFINED, 32 * sizeof(pn53x_target_type)); for (size_t n = 0; n < szModulations; n++) { const pn53x_target_type ptt = pn53x_nm_to_ptt(pnmModulations[n]); if (PTT_UNDEFINED == ptt) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } apttTargetTypes[szTargetTypes] = ptt; if ((pnd->bAutoIso14443_4) && (ptt == PTT_MIFARE)) { // Hack to have ATS apttTargetTypes[szTargetTypes] = PTT_ISO14443_4A_106; szTargetTypes++; apttTargetTypes[szTargetTypes] = PTT_MIFARE; } szTargetTypes++; } nfc_target ntTargets[2]; if ((res = pn53x_InAutoPoll(pnd, apttTargetTypes, szTargetTypes, uiPollNr, uiPeriod, ntTargets, 0)) < 0) return res; switch (res) { case 1: *pnt = ntTargets[0]; if (pn53x_current_target_new(pnd, pnt) == NULL) { return pnd->last_error = NFC_ESOFT; } return res; case 2: *pnt = ntTargets[1]; // We keep the selected one if (pn53x_current_target_new(pnd, pnt) == NULL) { return pnd->last_error = NFC_ESOFT; } return res; default: return NFC_ECHIP; } } else { bool bInfiniteSelect = pnd->bInfiniteSelect; int result = 0; if ((res = pn53x_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0) return res; // FIXME It does not support DEP targets do { for (size_t p = 0; p < uiPollNr; p++) { for (size_t n = 0; n < szModulations; n++) { uint8_t *pbtInitiatorData; size_t szInitiatorData; prepare_initiator_data(pnmModulations[n], &pbtInitiatorData, &szInitiatorData); const int timeout_ms = uiPeriod * 150; if ((res = pn53x_initiator_select_passive_target_ext(pnd, pnmModulations[n], pbtInitiatorData, szInitiatorData, pnt, timeout_ms)) < 0) { if (pnd->last_error != NFC_ETIMEOUT) { result = pnd->last_error; goto end; } } else { result = res; goto end; } } } } while (uiPollNr == 0xff); // uiPollNr==0xff means infinite polling // We reach this point when each listing give no result, we simply have to return 0 end: if (! bInfiniteSelect) { if ((res = pn53x_set_property_bool(pnd, NP_INFINITE_SELECT, false)) < 0) return res; } return result; } return NFC_ECHIP; } int pn53x_initiator_select_dep_target(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout) { const uint8_t abtPassiveInitiatorData[] = { 0x00, 0xff, 0xff, 0x00, 0x0f }; // Only for 212/424 kpbs: First 4 bytes shall be set like this according to NFCIP-1, last byte is TSN (Time Slot Number) const uint8_t *pbtPassiveInitiatorData = NULL; switch (nbr) { case NBR_212: case NBR_424: // Only use this predefined bytes array when we are at 212/424kbps pbtPassiveInitiatorData = abtPassiveInitiatorData; break; case NBR_106: // Nothing to do break; case NBR_847: case NBR_UNDEFINED: return NFC_EINVARG; } pn53x_current_target_free(pnd); int res; if (pndiInitiator) { res = pn53x_InJumpForDEP(pnd, ndm, nbr, pbtPassiveInitiatorData, pndiInitiator->abtNFCID3, pndiInitiator->abtGB, pndiInitiator->szGB, pnt, timeout); } else { res = pn53x_InJumpForDEP(pnd, ndm, nbr, pbtPassiveInitiatorData, NULL, NULL, 0, pnt, timeout); } if (res > 0) { if (pn53x_current_target_new(pnd, pnt) == NULL) { return NFC_ESOFT; } } return res; } int pn53x_initiator_transceive_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar) { int res = 0; size_t szFrameBits = 0; size_t szFrameBytes = 0; size_t szRxBits = 0; uint8_t ui8rcc; uint8_t ui8Bits = 0; uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN] = { InCommunicateThru }; // Check if we should prepare the parity bits ourself if (!pnd->bPar) { // Convert data with parity to a frame if ((res = pn53x_wrap_frame(pbtTx, szTxBits, pbtTxPar, abtCmd + 1)) < 0) return res; szFrameBits = res; } else { szFrameBits = szTxBits; } // Retrieve the leading bits ui8Bits = szFrameBits % 8; // Get the amount of frame bytes + optional (1 byte if there are leading bits) szFrameBytes = (szFrameBits / 8) + ((ui8Bits == 0) ? 0 : 1); // When the parity is handled before us, we just copy the data if (pnd->bPar) memcpy(abtCmd + 1, pbtTx, szFrameBytes); // Set the amount of transmission bits in the PN53X chip register if ((res = pn53x_set_tx_bits(pnd, ui8Bits)) < 0) return res; // Send the frame to the PN53X chip and get the answer // We have to give the amount of bytes + (the command byte 0x42) uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); if ((res = pn53x_transceive(pnd, abtCmd, szFrameBytes + 1, abtRx, szRx, -1)) < 0) return res; szRx = (size_t) res; // Get the last bit-count that is stored in the received byte if ((res = pn53x_read_register(pnd, PN53X_REG_CIU_Control, &ui8rcc)) < 0) return res; ui8Bits = ui8rcc & SYMBOL_RX_LAST_BITS; // Recover the real frame length in bits szFrameBits = ((szRx - 1 - ((ui8Bits == 0) ? 0 : 1)) * 8) + ui8Bits; if (pbtRx != NULL) { // Ignore the status byte from the PN53X here, it was checked earlier in pn53x_transceive() // Check if we should recover the parity bits ourself if (!pnd->bPar) { // Unwrap the response frame if ((res = pn53x_unwrap_frame(abtRx + 1, szFrameBits, pbtRx, pbtRxPar)) < 0) return res; szRxBits = res; } else { // Save the received bits szRxBits = szFrameBits; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx - 1); } } // Everything went successful return szRxBits; } int pn53x_initiator_transceive_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout) { size_t szExtraTxLen; uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; int res = 0; // We can not just send bytes without parity if while the PN53X expects we handled them if (!pnd->bPar) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } // Copy the data into the command frame if (pnd->bEasyFraming) { abtCmd[0] = InDataExchange; abtCmd[1] = 1; /* target number */ memcpy(abtCmd + 2, pbtTx, szTx); szExtraTxLen = 2; } else { abtCmd[0] = InCommunicateThru; memcpy(abtCmd + 1, pbtTx, szTx); szExtraTxLen = 1; } // To transfer command frames bytes we can not have any leading bits, reset this to zero if ((res = pn53x_set_tx_bits(pnd, 0)) < 0) { pnd->last_error = res; return pnd->last_error; } // Send the frame to the PN53X chip and get the answer // We have to give the amount of bytes + (the two command bytes 0xD4, 0x42) uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; if ((res = pn53x_transceive(pnd, abtCmd, szTx + szExtraTxLen, abtRx, sizeof(abtRx), timeout)) < 0) { pnd->last_error = res; return pnd->last_error; } const size_t szRxLen = (size_t)res - 1; if (pbtRx != NULL) { if (szRxLen > szRx) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Buffer size is too short: %" PRIuPTR " available(s), %" PRIuPTR " needed", szRx, szRxLen); return NFC_EOVFLOW; } // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRxLen); } // Everything went successful, we return received bytes count return szRxLen; } static void __pn53x_init_timer(struct nfc_device *pnd, const uint32_t max_cycles) { // The prescaler will dictate what will be the precision and // the largest delay to measure before saturation. Some examples: // prescaler = 0 => precision: ~73ns timer saturates at ~5ms // prescaler = 1 => precision: ~221ns timer saturates at ~15ms // prescaler = 2 => precision: ~369ns timer saturates at ~25ms // prescaler = 10 => precision: ~1.5us timer saturates at ~100ms if (max_cycles > 0xFFFF) { CHIP_DATA(pnd)->timer_prescaler = ((max_cycles / 0xFFFF) - 1) / 2; } else { CHIP_DATA(pnd)->timer_prescaler = 0; } uint16_t reloadval = 0xFFFF; // Initialize timer pn53x_write_register(pnd, PN53X_REG_CIU_TMode, 0xFF, SYMBOL_TAUTO | ((CHIP_DATA(pnd)->timer_prescaler >> 8) & SYMBOL_TPRESCALERHI)); pn53x_write_register(pnd, PN53X_REG_CIU_TPrescaler, 0xFF, (CHIP_DATA(pnd)->timer_prescaler & SYMBOL_TPRESCALERLO)); pn53x_write_register(pnd, PN53X_REG_CIU_TReloadVal_hi, 0xFF, (reloadval >> 8) & 0xFF); pn53x_write_register(pnd, PN53X_REG_CIU_TReloadVal_lo, 0xFF, reloadval & 0xFF); } static uint32_t __pn53x_get_timer(struct nfc_device *pnd, const uint8_t last_cmd_byte) { uint8_t parity; uint8_t counter_hi, counter_lo; uint16_t counter, u16cycles; uint32_t u32cycles; size_t off = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte off = 1; } // Read timer BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_hi >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_hi & 0xff); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_lo >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_lo & 0xff); uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // Let's send the previously constructed ReadRegister command if (pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1) < 0) { return false; } counter_hi = abtRes[off]; counter_lo = abtRes[off + 1]; counter = counter_hi; counter = (counter << 8) + counter_lo; if (counter == 0) { // counter saturated u32cycles = 0xFFFFFFFF; } else { u16cycles = 0xFFFF - counter; u32cycles = u16cycles; u32cycles *= (CHIP_DATA(pnd)->timer_prescaler * 2 + 1); u32cycles++; // Correction depending on PN53x Rx detection handling: // timer stops after 5 (or 2 for PN531) bits are received if (CHIP_DATA(pnd)->type == PN531) { u32cycles -= (2 * 128); } else { u32cycles -= (5 * 128); } // Correction depending on last parity bit sent parity = (last_cmd_byte >> 7) ^ ((last_cmd_byte >> 6) & 1) ^ ((last_cmd_byte >> 5) & 1) ^ ((last_cmd_byte >> 4) & 1) ^ ((last_cmd_byte >> 3) & 1) ^ ((last_cmd_byte >> 2) & 1) ^ ((last_cmd_byte >> 1) & 1) ^ (last_cmd_byte & 1); parity = parity ? 0 : 1; // When sent ...YY (cmd ends with logical 1, so when last parity bit is 1): if (parity) { // it finishes 64us sooner than a ...ZY signal u32cycles += 64; } // Correction depending on device design u32cycles += CHIP_DATA(pnd)->timer_correction; } return u32cycles; } int pn53x_initiator_transceive_bits_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles) { // TODO Do something with these bytes... (void) pbtTxPar; (void) pbtRxPar; uint16_t i; uint8_t sz = 0; int res = 0; size_t szRxBits = 0; // Sorry, no arbitrary parity bits support for now if (!pnd->bPar) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } // Sorry, no easy framing support if (pnd->bEasyFraming) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } // TODO CRC support but it probably doesn't make sense for (szTxBits % 8 != 0) ... if (pnd->bCrc) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } __pn53x_init_timer(pnd, *cycles); // Once timer is started, we cannot use Tama commands anymore. // E.g. on SCL3711 timer settings are reset by 0x42 InCommunicateThru command to: // 631a=82 631b=a5 631c=02 631d=00 // Prepare FIFO BUFFER_INIT(abtWriteRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtWriteRegisterCmd, WriteRegister); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_COMMAND & SYMBOL_COMMAND_TRANSCEIVE); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_FLUSH_BUFFER); for (i = 0; i < ((szTxBits / 8) + 1); i++) { BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, pbtTx[i]); } // Send data BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_START_SEND | ((szTxBits % 8) & SYMBOL_TX_LAST_BITS)); // Let's send the previously constructed WriteRegister command if ((res = pn53x_transceive(pnd, abtWriteRegisterCmd, BUFFER_SIZE(abtWriteRegisterCmd), NULL, 0, -1)) < 0) { return res; } // Recv data // we've to watch for coming data until we decide to timeout. // our PN53x timer saturates after 4.8ms so this function shouldn't be used for // responses coming very late anyway. // Ideally we should implement a real timer here too but looping a few times is good enough. for (i = 0; i < (3 * (CHIP_DATA(pnd)->timer_prescaler * 2 + 1)); i++) { pn53x_read_register(pnd, PN53X_REG_CIU_FIFOLevel, &sz); if (sz > 0) break; } size_t off = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte off = 1; } while (1) { BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); for (i = 0; i < sz; i++) { BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); } BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // Let's send the previously constructed ReadRegister command if ((res = pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1)) < 0) { return res; } for (i = 0; i < sz; i++) { pbtRx[i + szRxBits] = abtRes[i + off]; } szRxBits += (size_t)(sz & SYMBOL_FIFO_LEVEL); sz = abtRes[sz + off]; if (sz == 0) break; } szRxBits *= 8; // in bits, not bytes // Recv corrected timer value *cycles = __pn53x_get_timer(pnd, pbtTx[szTxBits / 8]); return szRxBits; } int pn53x_initiator_transceive_bytes_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, uint32_t *cycles) { uint16_t i; uint8_t sz = 0; int res = 0; // We can not just send bytes without parity while the PN53X expects we handled them if (!pnd->bPar) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } // Sorry, no easy framing support // TODO to be changed once we'll provide easy framing support from libnfc itself... if (pnd->bEasyFraming) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } uint8_t txmode = 0; if (pnd->bCrc) { // check if we're in TypeA or TypeB mode to compute right CRC later if ((res = pn53x_read_register(pnd, PN53X_REG_CIU_TxMode, &txmode)) < 0) { return res; } } __pn53x_init_timer(pnd, *cycles); // Once timer is started, we cannot use Tama commands anymore. // E.g. on SCL3711 timer settings are reset by 0x42 InCommunicateThru command to: // 631a=82 631b=a5 631c=02 631d=00 // Prepare FIFO BUFFER_INIT(abtWriteRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtWriteRegisterCmd, WriteRegister); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_COMMAND & SYMBOL_COMMAND_TRANSCEIVE); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_FLUSH_BUFFER); for (i = 0; i < szTx; i++) { BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, pbtTx[i]); } // Send data BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_START_SEND); // Let's send the previously constructed WriteRegister command if ((res = pn53x_transceive(pnd, abtWriteRegisterCmd, BUFFER_SIZE(abtWriteRegisterCmd), NULL, 0, -1)) < 0) { return res; } // Recv data size_t szRxLen = 0; // we've to watch for coming data until we decide to timeout. // our PN53x timer saturates after 4.8ms so this function shouldn't be used for // responses coming very late anyway. // Ideally we should implement a real timer here too but looping a few times is good enough. for (i = 0; i < (3 * (CHIP_DATA(pnd)->timer_prescaler * 2 + 1)); i++) { pn53x_read_register(pnd, PN53X_REG_CIU_FIFOLevel, &sz); if (sz > 0) break; } size_t off = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte off = 1; } while (1) { BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); for (i = 0; i < sz; i++) { BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); } BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // Let's send the previously constructed ReadRegister command if ((res = pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1)) < 0) { return res; } if (pbtRx != NULL) { if ((szRxLen + sz) > szRx) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Buffer size is too short: %" PRIuPTR " available(s), %" PRIuPTR " needed", szRx, szRxLen + sz); return NFC_EOVFLOW; } // Copy the received bytes for (i = 0; i < sz; i++) { pbtRx[i + szRxLen] = abtRes[i + off]; } } szRxLen += (size_t)(sz & SYMBOL_FIFO_LEVEL); sz = abtRes[sz + off]; if (sz == 0) break; } // Recv corrected timer value if (pnd->bCrc) { // We've to compute CRC ourselves to know last byte actually sent uint8_t *pbtTxRaw; pbtTxRaw = (uint8_t *) malloc(szTx + 2); if (!pbtTxRaw) return NFC_ESOFT; memcpy(pbtTxRaw, pbtTx, szTx); if ((txmode & SYMBOL_TX_FRAMING) == 0x00) iso14443a_crc_append(pbtTxRaw, szTx); else if ((txmode & SYMBOL_TX_FRAMING) == 0x03) iso14443b_crc_append(pbtTxRaw, szTx); else log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unsupported framing type %02X, cannot adjust CRC cycles", txmode & SYMBOL_TX_FRAMING); *cycles = __pn53x_get_timer(pnd, pbtTxRaw[szTx + 1]); free(pbtTxRaw); } else { *cycles = __pn53x_get_timer(pnd, pbtTx[szTx - 1]); } return szRxLen; } int pn53x_initiator_deselect_target(struct nfc_device *pnd) { pn53x_current_target_free(pnd); return pn53x_InDeselect(pnd, 0); // 0 mean deselect all selected targets } static int pn53x_Diagnose06(struct nfc_device *pnd) { // Send Card Presence command const uint8_t abtCmd[] = { Diagnose, 0x06 }; uint8_t abtRx[1]; int ret = 0; int failures = 0; // Card Presence command can take more time than default one: when a card is // removed from the field, the PN53x took few hundred ms more to reply // correctly. Longest delay observed was with a JCOP31 on a PN532. // 1000 ms should be enough to detect all tested cases while (failures < 2) { if ((ret = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, sizeof(abtRx), 1000)) != 1) { // When it fails with a timeout (0x01) chip error, it means the target is not reacheable anymore if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { return NFC_ETGRELEASED; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { return NFC_SUCCESS; } } return ret; } static int pn53x_ISO14443A_4_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping -4A"); if (CHIP_DATA(pnd)->type == PN533) { ret = pn53x_Diagnose06(pnd); if ((ret == NFC_ETIMEOUT) || (ret == NFC_ETGRELEASED)) { // This happens e.g. when a JCOP31 is removed from PN533 // InRelease takes an abnormal time to reply so let's take care of it now with large timeout: const uint8_t abtCmd[] = { InRelease, 0x00 }; pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 2000); ret = NFC_ETGRELEASED; } } else if (CHIP_DATA(pnd)->type == PN532) { // Diagnose06 failed completely with a JCOP31 on a PN532 so let's do it manually if ((ret = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, false)) < 0) return ret; uint8_t abtCmd[1] = {0xb2}; // CID=0 int failures = 0; while (failures < 2) { if ((ret = nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 300)) < 1) { if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Timeout ret = NFC_ETGRELEASED; break; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { ret = NFC_SUCCESS; break; } } int ret2; if ((ret2 = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0) ret = ret2; } else { ret = NFC_EDEVNOTSUPP; } return ret; } static int pn53x_ISO14443A_Jewel_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping Jewel"); uint8_t abtCmd[1] = {0x78}; int failures = 0; while (failures < 2) { if ((ret = nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)) < 1) { if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Timeout return NFC_ETGRELEASED; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { return NFC_SUCCESS; } } return ret; } static int pn53x_ISO14443A_MFUL_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping MFUL"); // Limitation: test on MFULC non-authenticated with read of first sector forbidden will fail if (CHIP_DATA(pnd)->type == PN533) { ret = pn53x_Diagnose06(pnd); } else { uint8_t abtCmd[2] = {0x30, 0x00}; int failures = 0; while (failures < 2) { if ((ret = nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)) < 1) { if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Timeout return NFC_ETGRELEASED; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { return NFC_SUCCESS; } } } return ret; } static int pn53x_ISO14443A_MFC_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping MFC"); if ((CHIP_DATA(pnd)->type == PN533) && (CHIP_DATA(pnd)->current_target->nti.nai.btSak != 0x09)) { // MFC Mini (atqa0004/sak09) fails on PN533, so we exclude it ret = pn53x_Diagnose06(pnd); } else { // Limitation: re-select will lose authentication of already authenticated sector bool bInfiniteSelect = pnd->bInfiniteSelect; uint8_t pbtInitiatorData[12]; size_t szInitiatorData = 0; iso14443_cascade_uid(CHIP_DATA(pnd)->current_target->nti.nai.abtUid, CHIP_DATA(pnd)->current_target->nti.nai.szUidLen, pbtInitiatorData, &szInitiatorData); if ((ret = pn53x_set_property_bool(pnd, NP_INFINITE_SELECT, false)) < 0) return ret; if ((ret = pn53x_initiator_select_passive_target_ext(pnd, CHIP_DATA(pnd)->current_target->nm, pbtInitiatorData, szInitiatorData, NULL, 300)) == 1) { ret = NFC_SUCCESS; } else if ((ret == 0) || (ret == NFC_ETIMEOUT)) { ret = NFC_ETGRELEASED; } if (bInfiniteSelect) { int ret2; if ((ret2 = pn53x_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0) return ret2; } } return ret; } static int pn53x_DEP_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping DEP"); if ((CHIP_DATA(pnd)->type == PN531) || (CHIP_DATA(pnd)->type == PN532) || (CHIP_DATA(pnd)->type == PN533)) ret = pn53x_Diagnose06(pnd); else ret = NFC_EDEVNOTSUPP; return ret; } static int pn53x_Felica_is_present(struct nfc_device *pnd) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping Felica"); // if (CHIP_DATA(pnd)->type == PN533) { ret = pn53x_Diagnose06(pnd); } else... // Because ping fails now & then, better not to use Diagnose at all // Limitation: does not work on Felica Lite cards (neither Diagnose nor our method) uint8_t abtCmd[10] = {0x0A, 0x04}; memcpy(abtCmd + 2, CHIP_DATA(pnd)->current_target->nti.nfi.abtId, 8); int failures = 0; // Sometimes ping fails so we want to give the card some more chances... while (failures < 3) { if (nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 300) == 11) { return NFC_SUCCESS; } else { failures++; } } return NFC_ETGRELEASED; } static int pn53x_ISO14443B_4_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping -4B"); if (CHIP_DATA(pnd)->type == PN533) { // Not supported on PN532 even if the doc is same as for PN533 ret = pn53x_Diagnose06(pnd); } else { // Sending R(NACK) in raw: if ((ret = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, false)) < 0) return ret; // uint8_t abtCmd[1] = {0xb2}; // if on PN533, CID=0 uint8_t abtCmd[2] = {0xba, 0x01}; // if on PN532, CID=1 int failures = 0; while (failures < 2) { if ((ret = nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 300)) < 1) { if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Timeout ret = NFC_ETGRELEASED; break; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { ret = NFC_SUCCESS; break; } } int ret2; if ((ret2 = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0) ret = ret2; } return ret; } static int pn53x_ISO14443B_I_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping B'"); // Sending ATTRIB in raw: if ((ret = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, false)) < 0) return ret; uint8_t abtCmd[6] = {0x01, 0x0f}; memcpy(abtCmd + 2, CHIP_DATA(pnd)->current_target->nti.nii.abtDIV, 4); int failures = 0; while (failures < 2) { if ((ret = nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 300)) < 1) { if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Timeout ret = NFC_ETGRELEASED; break; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { ret = NFC_SUCCESS; break; } } int ret2; if ((ret2 = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0) ret = ret2; return ret; } static int pn53x_ISO14443B_SR_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping B2 ST SRx"); // Sending Get_UID in raw: (EASY_FRAMING is already supposed to be false) uint8_t abtCmd[1] = {0x0b}; int failures = 0; while (failures < 2) { if ((ret = nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 300)) < 1) { if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Timeout ret = NFC_ETGRELEASED; break; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { ret = NFC_SUCCESS; break; } } return ret; } static int pn53x_ISO14443B_CT_is_present(struct nfc_device *pnd) { int ret; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): Ping B2 ASK CTx"); // Sending SELECT in raw: (EASY_FRAMING is already supposed to be false) uint8_t abtCmd[3] = {0x9f}; memcpy(abtCmd + 1, CHIP_DATA(pnd)->current_target->nti.nci.abtUID, 2); int failures = 0; while (failures < 2) { if ((ret = nfc_initiator_transceive_bytes(pnd, abtCmd, sizeof(abtCmd), NULL, 0, 300)) < 1) { if ((ret == NFC_ERFTRANS) && (CHIP_DATA(pnd)->last_status_byte == 0x01)) { // Timeout ret = NFC_ETGRELEASED; break; } else { // Other errors can appear when card is tired-off, let's try again failures++; } } else { ret = NFC_SUCCESS; break; } } return ret; } int pn53x_initiator_target_is_present(struct nfc_device *pnd, const nfc_target *pnt) { // Check if there is a saved target if (CHIP_DATA(pnd)->current_target == NULL) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): no saved target"); return pnd->last_error = NFC_EINVARG; } // Check if the argument target nt is equals to current saved target if ((pnt != NULL) && (!pn53x_current_target_is(pnd, pnt))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): another target"); return pnd->last_error = NFC_ETGRELEASED; } // Ping target int ret = NFC_EDEVNOTSUPP; switch (CHIP_DATA(pnd)->current_target->nm.nmt) { case NMT_ISO14443A: if (CHIP_DATA(pnd)->current_target->nti.nai.btSak & 0x20) { ret = pn53x_ISO14443A_4_is_present(pnd); } else if ((CHIP_DATA(pnd)->current_target->nti.nai.abtAtqa[0] == 0x00) && (CHIP_DATA(pnd)->current_target->nti.nai.abtAtqa[1] == 0x44) && (CHIP_DATA(pnd)->current_target->nti.nai.btSak == 0x00)) { ret = pn53x_ISO14443A_MFUL_is_present(pnd); } else if (CHIP_DATA(pnd)->current_target->nti.nai.btSak & 0x08) { ret = pn53x_ISO14443A_MFC_is_present(pnd); } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "target_is_present(): card type A not supported"); ret = NFC_EDEVNOTSUPP; } break; case NMT_DEP: ret = pn53x_DEP_is_present(pnd); break; case NMT_FELICA: ret = pn53x_Felica_is_present(pnd); break; case NMT_JEWEL: ret = pn53x_ISO14443A_Jewel_is_present(pnd); break; case NMT_ISO14443B: ret = pn53x_ISO14443B_4_is_present(pnd); break; case NMT_ISO14443BI: ret = pn53x_ISO14443B_I_is_present(pnd); break; case NMT_ISO14443B2SR: ret = pn53x_ISO14443B_SR_is_present(pnd); break; case NMT_ISO14443B2CT: ret = pn53x_ISO14443B_CT_is_present(pnd); break; } if (ret == NFC_ETGRELEASED) pn53x_current_target_free(pnd); return pnd->last_error = ret; } #define SAK_ISO14443_4_COMPLIANT 0x20 #define SAK_ISO18092_COMPLIANT 0x40 int pn53x_target_init(struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRxLen, int timeout) { pn53x_reset_settings(pnd); CHIP_DATA(pnd)->operating_mode = TARGET; pn53x_target_mode ptm = PTM_NORMAL; int res = 0; switch (pnt->nm.nmt) { case NMT_ISO14443A: ptm = PTM_PASSIVE_ONLY; if ((pnt->nti.nai.abtUid[0] != 0x08) || (pnt->nti.nai.szUidLen != 4)) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } pn53x_set_parameters(pnd, PARAM_AUTO_ATR_RES, false); if (CHIP_DATA(pnd)->type == PN532) { // We have a PN532 if ((pnt->nti.nai.btSak & SAK_ISO14443_4_COMPLIANT) && (pnd->bAutoIso14443_4)) { // We have a ISO14443-4 tag to emulate and NP_AUTO_14443_4A option is enabled ptm |= PTM_ISO14443_4_PICC_ONLY; // We add ISO14443-4 restriction pn53x_set_parameters(pnd, PARAM_14443_4_PICC, true); } else { pn53x_set_parameters(pnd, PARAM_14443_4_PICC, false); } } break; case NMT_FELICA: ptm = PTM_PASSIVE_ONLY; break; case NMT_DEP: pn53x_set_parameters(pnd, PARAM_AUTO_ATR_RES, true); ptm = PTM_DEP_ONLY; if (pnt->nti.ndi.ndm == NDM_PASSIVE) { ptm |= PTM_PASSIVE_ONLY; // We add passive mode restriction } break; case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_JEWEL: pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } // Let the PN53X be activated by the RF level detector from power down mode if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxAuto, SYMBOL_INITIAL_RF_ON, 0x04)) < 0) return res; uint8_t abtMifareParams[6]; uint8_t *pbtMifareParams = NULL; uint8_t *pbtTkt = NULL; size_t szTkt = 0; uint8_t abtFeliCaParams[18]; uint8_t *pbtFeliCaParams = NULL; const uint8_t *pbtNFCID3t = NULL; const uint8_t *pbtGBt = NULL; size_t szGBt = 0; switch (pnt->nm.nmt) { case NMT_ISO14443A: { // Set ATQA (SENS_RES) abtMifareParams[0] = pnt->nti.nai.abtAtqa[1]; abtMifareParams[1] = pnt->nti.nai.abtAtqa[0]; // Set UID // Note: in this mode we can only emulate a single size (4 bytes) UID where the first is hard-wired by PN53x as 0x08 abtMifareParams[2] = pnt->nti.nai.abtUid[1]; abtMifareParams[3] = pnt->nti.nai.abtUid[2]; abtMifareParams[4] = pnt->nti.nai.abtUid[3]; // Set SAK (SEL_RES) abtMifareParams[5] = pnt->nti.nai.btSak; pbtMifareParams = abtMifareParams; // Historical Bytes pbtTkt = iso14443a_locate_historical_bytes(pnt->nti.nai.abtAts, pnt->nti.nai.szAtsLen, &szTkt); } break; case NMT_FELICA: // Set NFCID2t memcpy(abtFeliCaParams, pnt->nti.nfi.abtId, 8); // Set PAD memcpy(abtFeliCaParams + 8, pnt->nti.nfi.abtPad, 8); // Set SystemCode memcpy(abtFeliCaParams + 16, pnt->nti.nfi.abtSysCode, 2); pbtFeliCaParams = abtFeliCaParams; break; case NMT_DEP: // Set NFCID3 pbtNFCID3t = pnt->nti.ndi.abtNFCID3; // Set General Bytes, if relevant szGBt = pnt->nti.ndi.szGB; if (szGBt) pbtGBt = pnt->nti.ndi.abtGB; // Set ISO/IEC 14443 part // Set ATQA (SENS_RES) abtMifareParams[0] = 0x08; abtMifareParams[1] = 0x00; // Set UID // Note: in this mode we can only emulate a single size (4 bytes) UID where the first is hard-wired by PN53x as 0x08 abtMifareParams[2] = 0x12; abtMifareParams[3] = 0x34; abtMifareParams[4] = 0x56; // Set SAK (SEL_RES) abtMifareParams[5] = SAK_ISO18092_COMPLIANT; // Allow ISO/IEC 18092 in DEP mode pbtMifareParams = abtMifareParams; // Set FeliCa part // Set NFCID2t abtFeliCaParams[0] = 0x01; abtFeliCaParams[1] = 0xfe; abtFeliCaParams[2] = 0x12; abtFeliCaParams[3] = 0x34; abtFeliCaParams[4] = 0x56; abtFeliCaParams[5] = 0x78; abtFeliCaParams[6] = 0x90; abtFeliCaParams[7] = 0x12; // Set PAD abtFeliCaParams[8] = 0xc0; abtFeliCaParams[9] = 0xc1; abtFeliCaParams[10] = 0xc2; abtFeliCaParams[11] = 0xc3; abtFeliCaParams[12] = 0xc4; abtFeliCaParams[13] = 0xc5; abtFeliCaParams[14] = 0xc6; abtFeliCaParams[15] = 0xc7; // Set System Code abtFeliCaParams[16] = 0x0f; abtFeliCaParams[17] = 0xab; pbtFeliCaParams = abtFeliCaParams; break; case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_JEWEL: pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } bool targetActivated = false; size_t szRx; while (!targetActivated) { uint8_t btActivatedMode; if ((res = pn53x_TgInitAsTarget(pnd, ptm, pbtMifareParams, pbtTkt, szTkt, pbtFeliCaParams, pbtNFCID3t, pbtGBt, szGBt, pbtRx, szRxLen, &btActivatedMode, timeout)) < 0) { if (res == NFC_ETIMEOUT) { pn53x_idle(pnd); } return res; } szRx = (size_t) res; nfc_modulation nm = { .nmt = NMT_DEP, // Silent compilation warnings .nbr = NBR_UNDEFINED }; nfc_dep_mode ndm = NDM_UNDEFINED; // Decode activated "mode" switch (btActivatedMode & 0x70) { // Baud rate case 0x00: // 106kbps nm.nbr = NBR_106; break; case 0x10: // 212kbps nm.nbr = NBR_212; break; case 0x20: // 424kbps nm.nbr = NBR_424; break; }; if (btActivatedMode & 0x04) { // D.E.P. nm.nmt = NMT_DEP; if ((btActivatedMode & 0x03) == 0x01) { // Active mode ndm = NDM_ACTIVE; } else { // Passive mode ndm = NDM_PASSIVE; } } else { // Not D.E.P. if ((btActivatedMode & 0x03) == 0x00) { // MIFARE nm.nmt = NMT_ISO14443A; } else if ((btActivatedMode & 0x03) == 0x02) { // FeliCa nm.nmt = NMT_FELICA; } } if (pnt->nm.nmt == nm.nmt) { // Actual activation have the right modulation type if ((pnt->nm.nbr == NBR_UNDEFINED) || (pnt->nm.nbr == nm.nbr)) { // Have the right baud rate (or undefined) if ((pnt->nm.nmt != NMT_DEP) || (pnt->nti.ndi.ndm == NDM_UNDEFINED) || (pnt->nti.ndi.ndm == ndm)) { // Have the right DEP mode (or is not a DEP) targetActivated = true; } } } if (targetActivated) { pnt->nm.nbr = nm.nbr; // Update baud rate if (pnt->nm.nmt == NMT_DEP) { pnt->nti.ndi.ndm = ndm; // Update DEP mode } if (pn53x_current_target_new(pnd, pnt) == NULL) { pnd->last_error = NFC_ESOFT; return pnd->last_error; } if (ptm & PTM_ISO14443_4_PICC_ONLY) { // When PN532 is in PICC target mode, it automatically reply to RATS so // we don't need to forward this command szRx = 0; } } } return szRx; } int pn53x_target_receive_bits(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar) { size_t szRxBits = 0; uint8_t abtCmd[] = { TgGetInitiatorCommand }; uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = 0; // Try to gather a received frame from the reader if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, szRx, -1)) < 0) return res; szRx = (size_t) res; // Get the last bit-count that is stored in the received byte uint8_t ui8rcc; if ((res = pn53x_read_register(pnd, PN53X_REG_CIU_Control, &ui8rcc)) < 0) return res; uint8_t ui8Bits = ui8rcc & SYMBOL_RX_LAST_BITS; // Recover the real frame length in bits size_t szFrameBits = ((szRx - 1 - ((ui8Bits == 0) ? 0 : 1)) * 8) + ui8Bits; // Ignore the status byte from the PN53X here, it was checked earlier in pn53x_transceive() // Check if we should recover the parity bits ourself if (!pnd->bPar) { // Unwrap the response frame if ((res = pn53x_unwrap_frame(abtRx + 1, szFrameBits, pbtRx, pbtRxPar)) < 0) return res; szRxBits = res; } else { // Save the received bits szRxBits = szFrameBits; if ((szRx - 1) > szRxLen) return NFC_EOVFLOW; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx - 1); } // Everyting seems ok, return received bits count return szRxBits; } int pn53x_target_receive_bytes(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout) { uint8_t abtCmd[1]; // XXX I think this is not a clean way to provide some kind of "EasyFraming" // but at the moment I have no more better than this if (pnd->bEasyFraming) { switch (CHIP_DATA(pnd)->current_target->nm.nmt) { case NMT_DEP: abtCmd[0] = TgGetData; break; case NMT_ISO14443A: if (CHIP_DATA(pnd)->current_target->nti.nai.btSak & SAK_ISO14443_4_COMPLIANT) { // We are dealing with a ISO/IEC 14443-4 compliant target if ((CHIP_DATA(pnd)->type == PN532) && (pnd->bAutoIso14443_4)) { // We are using ISO/IEC 14443-4 PICC emulation capability from the PN532 abtCmd[0] = TgGetData; break; } else { // TODO Support EasyFraming for other cases by software pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } } // NO BREAK case NMT_JEWEL: case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_FELICA: abtCmd[0] = TgGetInitiatorCommand; break; } } else { abtCmd[0] = TgGetInitiatorCommand; } // Try to gather a received frame from the reader uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, szRx, timeout)) < 0) return pnd->last_error; szRx = (size_t) res; // Save the received bytes count szRx -= 1; if (szRx > szRxLen) return NFC_EOVFLOW; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx); // Everyting seems ok, return received bytes count return szRx; } int pn53x_target_send_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar) { size_t szFrameBits = 0; size_t szFrameBytes = 0; uint8_t ui8Bits = 0; uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN] = { TgResponseToInitiator }; int res = 0; // Check if we should prepare the parity bits ourself if (!pnd->bPar) { // Convert data with parity to a frame if ((res = pn53x_wrap_frame(pbtTx, szTxBits, pbtTxPar, abtCmd + 1)) < 0) return res; szFrameBits = res; } else { szFrameBits = szTxBits; } // Retrieve the leading bits ui8Bits = szFrameBits % 8; // Get the amount of frame bytes + optional (1 byte if there are leading bits) szFrameBytes = (szFrameBits / 8) + ((ui8Bits == 0) ? 0 : 1); // When the parity is handled before us, we just copy the data if (pnd->bPar) memcpy(abtCmd + 1, pbtTx, szFrameBytes); // Set the amount of transmission bits in the PN53X chip register if ((res = pn53x_set_tx_bits(pnd, ui8Bits)) < 0) return res; // Try to send the bits to the reader if ((res = pn53x_transceive(pnd, abtCmd, szFrameBytes + 1, NULL, 0, -1)) < 0) return res; // Everyting seems ok, return return sent bits count return szTxBits; } int pn53x_target_send_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout) { uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; int res = 0; // We can not just send bytes without parity if while the PN53X expects we handled them if (!pnd->bPar) return NFC_ECHIP; // XXX I think this is not a clean way to provide some kind of "EasyFraming" // but at the moment I have no more better than this if (pnd->bEasyFraming) { switch (CHIP_DATA(pnd)->current_target->nm.nmt) { case NMT_DEP: abtCmd[0] = TgSetData; break; case NMT_ISO14443A: if (CHIP_DATA(pnd)->current_target->nti.nai.btSak & SAK_ISO14443_4_COMPLIANT) { // We are dealing with a ISO/IEC 14443-4 compliant target if ((CHIP_DATA(pnd)->type == PN532) && (pnd->bAutoIso14443_4)) { // We are using ISO/IEC 14443-4 PICC emulation capability from the PN532 abtCmd[0] = TgSetData; break; } else { // TODO Support EasyFraming for other cases by software pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } } // NO BREAK case NMT_JEWEL: case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_FELICA: abtCmd[0] = TgResponseToInitiator; break; } } else { abtCmd[0] = TgResponseToInitiator; } // Copy the data into the command frame memcpy(abtCmd + 1, pbtTx, szTx); // Try to send the bits to the reader if ((res = pn53x_transceive(pnd, abtCmd, szTx + 1, NULL, 0, timeout)) < 0) return res; // Everyting seems ok, return sent byte count return szTx; } static struct sErrorMessage { int iErrorCode; const char *pcErrorMsg; } sErrorMessages[] = { /* Chip-level errors (internal errors, RF errors, etc.) */ { 0x00, "Success" }, { ETIMEOUT, "Timeout" }, // Time Out, the target has not answered { ECRC, "CRC Error" }, // A CRC error has been detected by the CIU { EPARITY, "Parity Error" }, // A Parity error has been detected by the CIU { EBITCOUNT, "Erroneous Bit Count" }, // During an anti-collision/select operation (ISO/IEC14443-3 Type A and ISO/IEC18092 106 kbps passive mode), an erroneous Bit Count has been detected { EFRAMING, "Framing Error" }, // Framing error during MIFARE operation { EBITCOLL, "Bit-collision" }, // An abnormal bit-collision has been detected during bit wise anti-collision at 106 kbps { ESMALLBUF, "Communication Buffer Too Small" }, // Communication buffer size insufficient { EBUFOVF, "Buffer Overflow" }, // RF Buffer overflow has been detected by the CIU (bit BufferOvfl of the register CIU_Error) { ERFPROTO, "RF Protocol Error" }, // RF Protocol error (see PN53x manual) { EOVHEAT, "Chip Overheating" }, // Temperature error: the internal temperature sensor has detected overheating, and therefore has automatically switched off the antenna drivers { EINBUFOVF, "Internal Buffer overflow."}, // Internal buffer overflow { EINVPARAM, "Invalid Parameter"}, // Invalid parameter (range, format, …) { EOPNOTALL, "Operation Not Allowed" }, // Operation not allowed in this configuration (host controller interface) { ECMD, "Command Not Acceptable" }, // Command is not acceptable due to the current context { EOVCURRENT, "Over Current" }, /* DEP errors */ { ERFTIMEOUT, "RF Timeout" }, // In active communication mode, the RF field has not been switched on in time by the counterpart (as defined in NFCIP-1 standard) { EDEPUNKCMD, "Unknown DEP Command" }, { EDEPINVSTATE, "Invalid DEP State" }, // DEP Protocol: Invalid device state, the system is in a state which does not allow the operation { ENAD, "NAD Missing in DEP Frame" }, /* MIFARE */ { EMFAUTH, "Mifare Authentication Error" }, /* Misc */ { EINVRXFRAM, "Invalid Received Frame" }, // DEP Protocol, Mifare or ISO/IEC14443-4: The data format does not match to the specification. { ENSECNOTSUPP, "NFC Secure not supported" }, // Target or Initiator does not support NFC Secure { EBCC, "Wrong UID Check Byte (BCC)" }, // ISO/IEC14443-3: UID Check byte is wrong { ETGREL, "Target Released" }, // Target have been released by initiator { ECID, "Card ID Mismatch" }, // ISO14443 type B: Card ID mismatch, meaning that the expected card has been exchanged with another one. { ECDISCARDED, "Card Discarded" }, // ISO/IEC14443 type B: the card previously activated has disappeared. { ENFCID3, "NFCID3 Mismatch" }, }; const char * pn53x_strerror(const struct nfc_device *pnd) { const char *pcRes = "Unknown error"; size_t i; for (i = 0; i < (sizeof(sErrorMessages) / sizeof(struct sErrorMessage)); i++) { if (sErrorMessages[i].iErrorCode == CHIP_DATA(pnd)->last_status_byte) { pcRes = sErrorMessages[i].pcErrorMsg; break; } } return pcRes; } int pn53x_RFConfiguration__RF_field(struct nfc_device *pnd, bool bEnable) { uint8_t abtCmd[] = { RFConfiguration, RFCI_FIELD, (bEnable) ? 0x01 : 0x00 }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_RFConfiguration__Various_timings(struct nfc_device *pnd, const uint8_t fATR_RES_Timeout, const uint8_t fRetryTimeout) { uint8_t abtCmd[] = { RFConfiguration, RFCI_TIMING, 0x00, // RFU fATR_RES_Timeout, // ATR_RES timeout (default: 0x0B 102.4 ms) fRetryTimeout // TimeOut during non-DEP communications (default: 0x0A 51.2 ms) }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_RFConfiguration__MaxRtyCOM(struct nfc_device *pnd, const uint8_t MaxRtyCOM) { uint8_t abtCmd[] = { RFConfiguration, RFCI_RETRY_DATA, MaxRtyCOM // MaxRtyCOM, default: 0x00 (no retry, only one try), inifite: 0xff }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_RFConfiguration__MaxRetries(struct nfc_device *pnd, const uint8_t MxRtyATR, const uint8_t MxRtyPSL, const uint8_t MxRtyPassiveActivation) { // Retry format: 0x00 means only 1 try, 0xff means infinite uint8_t abtCmd[] = { RFConfiguration, RFCI_RETRY_SELECT, MxRtyATR, // MxRtyATR, default: active = 0xff, passive = 0x02 MxRtyPSL, // MxRtyPSL, default: 0x01 MxRtyPassiveActivation // MxRtyPassiveActivation, default: 0xff (0x00 leads to problems with PN531) }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_SetParameters(struct nfc_device *pnd, const uint8_t ui8Value) { uint8_t abtCmd[] = { SetParameters, ui8Value }; int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)) < 0) { return res; } // We save last parameters in register cache CHIP_DATA(pnd)->ui8Parameters = ui8Value; return NFC_SUCCESS; } int pn532_SAMConfiguration(struct nfc_device *pnd, const pn532_sam_mode sam_mode, int timeout) { uint8_t abtCmd[] = { SAMConfiguration, sam_mode, 0x00, 0x00 }; size_t szCmd = sizeof(abtCmd); if (CHIP_DATA(pnd)->type != PN532) { // This function is not supported by pn531 neither pn533 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } switch (sam_mode) { case PSM_NORMAL: // Normal mode case PSM_WIRED_CARD: // Wired card mode szCmd = 2; break; case PSM_VIRTUAL_CARD: // Virtual card mode case PSM_DUAL_CARD: // Dual card mode // TODO Implement timeout handling szCmd = 3; break; default: pnd->last_error = NFC_EINVARG; return pnd->last_error; } CHIP_DATA(pnd)->sam_mode = sam_mode; return (pn53x_transceive(pnd, abtCmd, szCmd, NULL, 0, timeout)); } int pn53x_PowerDown(struct nfc_device *pnd) { uint8_t abtCmd[] = { PowerDown, 0xf0 }; int res; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)) < 0) return res; CHIP_DATA(pnd)->power_mode = LOWVBAT; return res; } /** * @brief C wrapper to InListPassiveTarget command * @return Returns selected targets count on success, otherwise returns libnfc's error code (negative value) * * @param pnd struct nfc_device struct pointer that represent currently used device * @param pmInitModulation Desired modulation * @param pbtInitiatorData Optional initiator data used for Felica, ISO14443B, Topaz Polling or for ISO14443A selecting a specific UID * @param szInitiatorData Length of initiator data \a pbtInitiatorData * @param pbtTargetsData pointer on a pre-allocated byte array to receive TargetData[n] as described in pn53x user manual * @param pszTargetsData size_t pointer where size of \a pbtTargetsData will be written * * @note Selected targets count can be found in \a pbtTargetsData[0] if available (i.e. \a pszTargetsData content is more than 0) * @note To decode theses TargetData[n], there is @fn pn53x_decode_target_data */ int pn53x_InListPassiveTarget(struct nfc_device *pnd, const pn53x_modulation pmInitModulation, const uint8_t szMaxTargets, const uint8_t *pbtInitiatorData, const size_t szInitiatorData, uint8_t *pbtTargetsData, size_t *pszTargetsData, int timeout) { uint8_t abtCmd[15] = { InListPassiveTarget }; abtCmd[1] = szMaxTargets; // MaxTg switch (pmInitModulation) { case PM_ISO14443A_106: case PM_FELICA_212: case PM_FELICA_424: // all gone fine. break; case PM_ISO14443B_106: if (!(pnd->btSupportByte & SUPPORT_ISO14443B)) { // Eg. Some PN532 doesn't support type B! pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } break; case PM_JEWEL_106: if (CHIP_DATA(pnd)->type == PN531) { // These modulations are not supported by pn531 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } break; case PM_ISO14443B_212: case PM_ISO14443B_424: case PM_ISO14443B_847: if ((CHIP_DATA(pnd)->type != PN533) || (!(pnd->btSupportByte & SUPPORT_ISO14443B))) { // These modulations are not supported by pn531 neither pn532 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } break; case PM_UNDEFINED: pnd->last_error = NFC_EINVARG; return pnd->last_error; } abtCmd[2] = pmInitModulation; // BrTy, the type of init modulation used for polling a passive tag // Set the optional initiator data (used for Felica, ISO14443B, Topaz Polling or for ISO14443A selecting a specific UID). if (pbtInitiatorData) memcpy(abtCmd + 3, pbtInitiatorData, szInitiatorData); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, 3 + szInitiatorData, pbtTargetsData, *pszTargetsData, timeout)) < 0) { return res; } *pszTargetsData = (size_t) res; return pbtTargetsData[0]; } int pn53x_InDeselect(struct nfc_device *pnd, const uint8_t ui8Target) { if (CHIP_DATA(pnd)->type == RCS360) { // We should do act here *only* if a target was previously selected uint8_t abtStatus[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szStatus = sizeof(abtStatus); uint8_t abtCmdGetStatus[] = { GetGeneralStatus }; int res = 0; if ((res = pn53x_transceive(pnd, abtCmdGetStatus, sizeof(abtCmdGetStatus), abtStatus, szStatus, -1)) < 0) { return res; } szStatus = (size_t) res; if ((szStatus < 3) || (abtStatus[2] == 0)) { return NFC_SUCCESS; } // No much choice what to deselect actually... uint8_t abtCmdRcs360[] = { InDeselect, 0x01, 0x01 }; return (pn53x_transceive(pnd, abtCmdRcs360, sizeof(abtCmdRcs360), NULL, 0, -1)); } uint8_t abtCmd[] = { InDeselect, ui8Target }; return (pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)); } int pn53x_InRelease(struct nfc_device *pnd, const uint8_t ui8Target) { int res = 0; if (CHIP_DATA(pnd)->type == RCS360) { // We should do act here *only* if a target was previously selected uint8_t abtStatus[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szStatus = sizeof(abtStatus); uint8_t abtCmdGetStatus[] = { GetGeneralStatus }; if ((res = pn53x_transceive(pnd, abtCmdGetStatus, sizeof(abtCmdGetStatus), abtStatus, szStatus, -1)) < 0) { return res; } szStatus = (size_t) res; if ((szStatus < 3) || (abtStatus[2] == 0)) { return NFC_SUCCESS; } // No much choice what to release actually... uint8_t abtCmdRcs360[] = { InRelease, 0x01, 0x01 }; res = pn53x_transceive(pnd, abtCmdRcs360, sizeof(abtCmdRcs360), NULL, 0, -1); return (res >= 0) ? NFC_SUCCESS : res; } uint8_t abtCmd[] = { InRelease, ui8Target }; res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); return (res >= 0) ? NFC_SUCCESS : res; } int pn53x_InAutoPoll(struct nfc_device *pnd, const pn53x_target_type *ppttTargetTypes, const size_t szTargetTypes, const uint8_t btPollNr, const uint8_t btPeriod, nfc_target *pntTargets, const int timeout) { size_t szTargetFound = 0; if (CHIP_DATA(pnd)->type != PN532) { // This function is not supported by pn531 neither pn533 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } // InAutoPoll frame looks like this { 0xd4, 0x60, 0x0f, 0x01, 0x00 } => { direction, command, pollnr, period, types... } size_t szTxInAutoPoll = 3 + szTargetTypes; uint8_t abtCmd[3 + 15] = { InAutoPoll, btPollNr, btPeriod }; for (size_t n = 0; n < szTargetTypes; n++) { abtCmd[3 + n] = ppttTargetTypes[n]; } uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = pn53x_transceive(pnd, abtCmd, szTxInAutoPoll, abtRx, szRx, timeout); szRx = (size_t) res; if (res < 0) { return res; } else if (szRx > 0) { szTargetFound = abtRx[0]; if (szTargetFound > 0) { uint8_t ln; uint8_t *pbt = abtRx + 1; /* 1st target */ // Target type pn53x_target_type ptt = *(pbt++); pntTargets[0].nm = pn53x_ptt_to_nm(ptt); // AutoPollTargetData length ln = *(pbt++); if ((res = pn53x_decode_target_data(pbt, ln, CHIP_DATA(pnd)->type, pntTargets[0].nm.nmt, &(pntTargets[0].nti))) < 0) { return res; } pbt += ln; if (abtRx[0] > 1) { /* 2nd target */ // Target type ptt = *(pbt++); pntTargets[1].nm = pn53x_ptt_to_nm(ptt); // AutoPollTargetData length ln = *(pbt++); pn53x_decode_target_data(pbt, ln, CHIP_DATA(pnd)->type, pntTargets[1].nm.nmt, &(pntTargets[1].nti)); } } } return szTargetFound; } /** * @brief Wrapper for InJumpForDEP command * @param pmInitModulation desired initial modulation * @param pbtPassiveInitiatorData NFCID1 (4 bytes) at 106kbps (optionnal, see NFCIP-1: 11.2.1.26) or Polling Request Frame's payload (5 bytes) at 212/424kbps (mandatory, see NFCIP-1: 11.2.2.5) * @param szPassiveInitiatorData size of pbtPassiveInitiatorData content * @param pbtNFCID3i NFCID3 of the initiator * @param pbtGBi General Bytes of the initiator * @param szGBi count of General Bytes * @param[out] pnt \a nfc_target which will be filled by this function */ int pn53x_InJumpForDEP(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const uint8_t *pbtPassiveInitiatorData, const uint8_t *pbtNFCID3i, const uint8_t *pbtGBi, const size_t szGBi, nfc_target *pnt, const int timeout) { // Max frame size = 1 (Command) + 1 (ActPass) + 1 (Baud rate) + 1 (Next) + 5 (PassiveInitiatorData) + 10 (NFCID3) + 48 (General bytes) = 67 bytes uint8_t abtCmd[67] = { InJumpForDEP, (ndm == NDM_ACTIVE) ? 0x01 : 0x00 }; size_t offset = 4; // 1 byte for command, 1 byte for DEP mode (Active/Passive), 1 byte for baud rate, 1 byte for following parameters flag switch (nbr) { case NBR_106: abtCmd[2] = 0x00; // baud rate is 106 kbps if (pbtPassiveInitiatorData && (ndm == NDM_PASSIVE)) { /* can't have passive initiator data when using active mode */ abtCmd[3] |= 0x01; memcpy(abtCmd + offset, pbtPassiveInitiatorData, 4); offset += 4; } break; case NBR_212: abtCmd[2] = 0x01; // baud rate is 212 kbps if (pbtPassiveInitiatorData && (ndm == NDM_PASSIVE)) { abtCmd[3] |= 0x01; memcpy(abtCmd + offset, pbtPassiveInitiatorData, 5); offset += 5; } break; case NBR_424: abtCmd[2] = 0x02; // baud rate is 424 kbps if (pbtPassiveInitiatorData && (ndm == NDM_PASSIVE)) { abtCmd[3] |= 0x01; memcpy(abtCmd + offset, pbtPassiveInitiatorData, 5); offset += 5; } break; case NBR_847: case NBR_UNDEFINED: pnd->last_error = NFC_EINVARG; return pnd->last_error; } if (pbtNFCID3i) { abtCmd[3] |= 0x02; memcpy(abtCmd + offset, pbtNFCID3i, 10); offset += 10; } if (szGBi && pbtGBi) { abtCmd[3] |= 0x04; memcpy(abtCmd + offset, pbtGBi, szGBi); offset += szGBi; } uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = 0; // Try to find a target, call the transceive callback function of the current device if ((res = pn53x_transceive(pnd, abtCmd, offset, abtRx, szRx, timeout)) < 0) return res; szRx = (size_t) res; // Make sure one target has been found, the PN53X returns 0x00 if none was available if (abtRx[1] >= 1) { // Is a target struct available if (pnt) { pnt->nm.nmt = NMT_DEP; pnt->nm.nbr = nbr; pnt->nti.ndi.ndm = ndm; memcpy(pnt->nti.ndi.abtNFCID3, abtRx + 2, 10); pnt->nti.ndi.btDID = abtRx[12]; pnt->nti.ndi.btBS = abtRx[13]; pnt->nti.ndi.btBR = abtRx[14]; pnt->nti.ndi.btTO = abtRx[15]; pnt->nti.ndi.btPP = abtRx[16]; if (szRx > 17) { pnt->nti.ndi.szGB = szRx - 17; memcpy(pnt->nti.ndi.abtGB, abtRx + 17, pnt->nti.ndi.szGB); } else { pnt->nti.ndi.szGB = 0; } } } return abtRx[1]; } int pn53x_TgInitAsTarget(struct nfc_device *pnd, pn53x_target_mode ptm, const uint8_t *pbtMifareParams, const uint8_t *pbtTkt, size_t szTkt, const uint8_t *pbtFeliCaParams, const uint8_t *pbtNFCID3t, const uint8_t *pbtGBt, const size_t szGBt, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtModeByte, int timeout) { uint8_t abtCmd[39 + 47 + 48] = { TgInitAsTarget }; // Worst case: 39-byte base, 47 bytes max. for General Bytes, 48 bytes max. for Historical Bytes size_t szOptionalBytes = 0; int res = 0; // Clear the target init struct, reset to all zeros memset(abtCmd + 1, 0x00, sizeof(abtCmd) - 1); // Store the target mode in the initialization params abtCmd[1] = ptm; // MIFARE part if (pbtMifareParams) { memcpy(abtCmd + 2, pbtMifareParams, 6); } // FeliCa part if (pbtFeliCaParams) { memcpy(abtCmd + 8, pbtFeliCaParams, 18); } // DEP part if (pbtNFCID3t) { memcpy(abtCmd + 26, pbtNFCID3t, 10); } // General Bytes (ISO/IEC 18092) if ((CHIP_DATA(pnd)->type == PN531) || (CHIP_DATA(pnd)->type == RCS360)) { if (szGBt) { memcpy(abtCmd + 36, pbtGBt, szGBt); szOptionalBytes = szGBt; } } else { abtCmd[36] = (uint8_t)(szGBt); if (szGBt) { memcpy(abtCmd + 37, pbtGBt, szGBt); } szOptionalBytes = szGBt + 1; } // Historical bytes (ISO/IEC 14443-4) if ((CHIP_DATA(pnd)->type != PN531) && (CHIP_DATA(pnd)->type != RCS360)) { // PN531 does not handle Historical Bytes abtCmd[36 + szOptionalBytes] = (uint8_t)(szTkt); if (szTkt) { memcpy(abtCmd + 37 + szOptionalBytes, pbtTkt, szTkt); } szOptionalBytes += szTkt + 1; } // Request the initialization as a target uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); if ((res = pn53x_transceive(pnd, abtCmd, 36 + szOptionalBytes, abtRx, szRx, timeout)) < 0) return res; szRx = (size_t) res; // Note: the first byte is skip: // its the "mode" byte which contains baudrate, DEP and Framing type (Mifare, active or FeliCa) datas. if (pbtModeByte) { *pbtModeByte = abtRx[0]; } // Save the received byte count szRx -= 1; if ((szRx - 1) > szRxLen) return NFC_EOVFLOW; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx); return szRx; } int pn53x_check_ack_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen) { if (szRxFrameLen >= sizeof(pn53x_ack_frame)) { if (0 == memcmp(pbtRxFrame, pn53x_ack_frame, sizeof(pn53x_ack_frame))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "PN53x ACKed"); return NFC_SUCCESS; } } pnd->last_error = NFC_EIO; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unexpected PN53x reply!"); return pnd->last_error; } int pn53x_check_error_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen) { if (szRxFrameLen >= sizeof(pn53x_error_frame)) { if (0 == memcmp(pbtRxFrame, pn53x_error_frame, sizeof(pn53x_error_frame))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "PN53x sent an error frame"); pnd->last_error = NFC_EIO; return pnd->last_error; } } return NFC_SUCCESS; } /** * @brief Build a PN53x frame * * @param pbtData payload (bytes array) of the frame, will become PD0, ..., PDn in PN53x frame * @note The first byte of pbtData is the Command Code (CC) */ int pn53x_build_frame(uint8_t *pbtFrame, size_t *pszFrame, const uint8_t *pbtData, const size_t szData) { if (szData <= PN53x_NORMAL_FRAME__DATA_MAX_LEN) { // LEN - Packet length = data length (len) + checksum (1) + end of stream marker (1) pbtFrame[3] = szData + 1; // LCS - Packet length checksum pbtFrame[4] = 256 - (szData + 1); // TFI pbtFrame[5] = 0xD4; // DATA - Copy the PN53X command into the packet buffer memcpy(pbtFrame + 6, pbtData, szData); // DCS - Calculate data payload checksum uint8_t btDCS = (256 - 0xD4); for (size_t szPos = 0; szPos < szData; szPos++) { btDCS -= pbtData[szPos]; } pbtFrame[6 + szData] = btDCS; // 0x00 - End of stream marker pbtFrame[szData + 7] = 0x00; (*pszFrame) = szData + PN53x_NORMAL_FRAME__OVERHEAD; } else if (szData <= PN53x_EXTENDED_FRAME__DATA_MAX_LEN) { // Extended frame marker pbtFrame[3] = 0xff; pbtFrame[4] = 0xff; // LENm pbtFrame[5] = (szData + 1) >> 8; // LENl pbtFrame[6] = (szData + 1) & 0xff; // LCS pbtFrame[7] = 256 - ((pbtFrame[5] + pbtFrame[6]) & 0xff); // TFI pbtFrame[8] = 0xD4; // DATA - Copy the PN53X command into the packet buffer memcpy(pbtFrame + 9, pbtData, szData); // DCS - Calculate data payload checksum uint8_t btDCS = (256 - 0xD4); for (size_t szPos = 0; szPos < szData; szPos++) { btDCS -= pbtData[szPos]; } pbtFrame[9 + szData] = btDCS; // 0x00 - End of stream marker pbtFrame[szData + 10] = 0x00; (*pszFrame) = szData + PN53x_EXTENDED_FRAME__OVERHEAD; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "We can't send more than %d bytes in a raw (requested: %" PRIdPTR ")", PN53x_EXTENDED_FRAME__DATA_MAX_LEN, szData); return NFC_ECHIP; } return NFC_SUCCESS; } pn53x_modulation pn53x_nm_to_pm(const nfc_modulation nm) { switch (nm.nmt) { case NMT_ISO14443A: return PM_ISO14443A_106; case NMT_ISO14443B: switch (nm.nbr) { case NBR_106: return PM_ISO14443B_106; case NBR_212: return PM_ISO14443B_212; case NBR_424: return PM_ISO14443B_424; case NBR_847: return PM_ISO14443B_847; case NBR_UNDEFINED: // Nothing to do... break; } break; case NMT_JEWEL: return PM_JEWEL_106; case NMT_FELICA: switch (nm.nbr) { case NBR_212: return PM_FELICA_212; case NBR_424: return PM_FELICA_424; case NBR_106: case NBR_847: case NBR_UNDEFINED: // Nothing to do... break; } break; case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_DEP: // Nothing to do... break; } return PM_UNDEFINED; } nfc_modulation pn53x_ptt_to_nm(const pn53x_target_type ptt) { switch (ptt) { case PTT_GENERIC_PASSIVE_106: case PTT_GENERIC_PASSIVE_212: case PTT_GENERIC_PASSIVE_424: case PTT_UNDEFINED: // XXX This should not happend, how handle it cleanly ? break; case PTT_MIFARE: case PTT_ISO14443_4A_106: return (const nfc_modulation) { .nmt = NMT_ISO14443A, .nbr = NBR_106 }; case PTT_ISO14443_4B_106: case PTT_ISO14443_4B_TCL_106: return (const nfc_modulation) { .nmt = NMT_ISO14443B, .nbr = NBR_106 }; case PTT_JEWEL_106: return (const nfc_modulation) { .nmt = NMT_JEWEL, .nbr = NBR_106 }; case PTT_FELICA_212: return (const nfc_modulation) { .nmt = NMT_FELICA, .nbr = NBR_212 }; case PTT_FELICA_424: return (const nfc_modulation) { .nmt = NMT_FELICA, .nbr = NBR_424 }; case PTT_DEP_PASSIVE_106: case PTT_DEP_ACTIVE_106: return (const nfc_modulation) { .nmt = NMT_DEP, .nbr = NBR_106 }; case PTT_DEP_PASSIVE_212: case PTT_DEP_ACTIVE_212: return (const nfc_modulation) { .nmt = NMT_DEP, .nbr = NBR_212 }; case PTT_DEP_PASSIVE_424: case PTT_DEP_ACTIVE_424: return (const nfc_modulation) { .nmt = NMT_DEP, .nbr = NBR_424 }; } // We should never be here, this line silent compilation warning return (const nfc_modulation) { .nmt = NMT_ISO14443A, .nbr = NBR_106 }; } pn53x_target_type pn53x_nm_to_ptt(const nfc_modulation nm) { switch (nm.nmt) { case NMT_ISO14443A: return PTT_MIFARE; // return PTT_ISO14443_4A_106; case NMT_ISO14443B: switch (nm.nbr) { case NBR_106: return PTT_ISO14443_4B_106; case NBR_UNDEFINED: case NBR_212: case NBR_424: case NBR_847: // Nothing to do... break; } break; case NMT_JEWEL: return PTT_JEWEL_106; case NMT_FELICA: switch (nm.nbr) { case NBR_212: return PTT_FELICA_212; case NBR_424: return PTT_FELICA_424; case NBR_UNDEFINED: case NBR_106: case NBR_847: // Nothing to do... break; } break; case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_DEP: // Nothing to do... break; } return PTT_UNDEFINED; } int pn53x_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt) { switch (mode) { case N_TARGET: *supported_mt = CHIP_DATA(pnd)->supported_modulation_as_target; break; case N_INITIATOR: *supported_mt = CHIP_DATA(pnd)->supported_modulation_as_initiator; break; default: return NFC_EINVARG; } return NFC_SUCCESS; } int pn53x_get_supported_baud_rate(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br) { switch (nmt) { case NMT_FELICA: *supported_br = (nfc_baud_rate *)pn53x_felica_supported_baud_rates; break; case NMT_ISO14443A: { if ((CHIP_DATA(pnd)->type != PN533) || (mode == N_TARGET)) { *supported_br = (nfc_baud_rate *)pn532_iso14443a_supported_baud_rates; } else { *supported_br = (nfc_baud_rate *)pn533_iso14443a_supported_baud_rates; } } break; case NMT_ISO14443B: { if ((CHIP_DATA(pnd)->type != PN533)) { *supported_br = (nfc_baud_rate *)pn532_iso14443b_supported_baud_rates; } else { *supported_br = (nfc_baud_rate *)pn533_iso14443b_supported_baud_rates; } } break; case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: *supported_br = (nfc_baud_rate *)pn532_iso14443b_supported_baud_rates; break; case NMT_JEWEL: *supported_br = (nfc_baud_rate *)pn53x_jewel_supported_baud_rates; break; case NMT_DEP: *supported_br = (nfc_baud_rate *)pn53x_dep_supported_baud_rates; break; default: return NFC_EINVARG; } return NFC_SUCCESS; } int pn53x_get_information_about(nfc_device *pnd, char **pbuf) { size_t buflen = 2048; *pbuf = malloc(buflen); if (! *pbuf) { return NFC_ESOFT; } char *buf = *pbuf; int res; if ((res = snprintf(buf, buflen, "chip: %s\n", CHIP_DATA(pnd)->firmware_text)) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; if ((res = snprintf(buf, buflen, "initator mode modulations: ")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; const nfc_modulation_type *nmt; if ((res = nfc_device_get_supported_modulation(pnd, N_INITIATOR, &nmt)) < 0) { free(*pbuf); return res; } for (int i = 0; nmt[i]; i++) { if ((res = snprintf(buf, buflen, "%s%s (", (i == 0) ? "" : ", ", str_nfc_modulation_type(nmt[i]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; const nfc_baud_rate *nbr; if ((res = nfc_device_get_supported_baud_rate(pnd, N_INITIATOR, nmt[i], &nbr)) < 0) { free(*pbuf); return res; } for (int j = 0; nbr[j]; j++) { if ((res = snprintf(buf, buflen, "%s%s", (j == 0) ? "" : ", ", str_nfc_baud_rate(nbr[j]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, ")")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, "\n")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; if ((res = snprintf(buf, buflen, "target mode modulations: ")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; if ((res = nfc_device_get_supported_modulation(pnd, N_TARGET, &nmt)) < 0) { free(*pbuf); return res; } for (int i = 0; nmt[i]; i++) { if ((res = snprintf(buf, buflen, "%s%s (", (i == 0) ? "" : ", ", str_nfc_modulation_type(nmt[i]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; const nfc_baud_rate *nbr; if ((res = nfc_device_get_supported_baud_rate(pnd, N_TARGET, nmt[i], &nbr)) < 0) { free(*pbuf); return res; } for (int j = 0; nbr[j]; j++) { if ((res = snprintf(buf, buflen, "%s%s", (j == 0) ? "" : ", ", str_nfc_baud_rate(nbr[j]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, ")")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, "\n")) < 0) { free(*pbuf); return NFC_ESOFT; } //buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } //buflen -= res; return NFC_SUCCESS; } void * pn53x_current_target_new(const struct nfc_device *pnd, const nfc_target *pnt) { if (pnt == NULL) { return NULL; } // Keep the current nfc_target for further commands if (CHIP_DATA(pnd)->current_target) { free(CHIP_DATA(pnd)->current_target); } CHIP_DATA(pnd)->current_target = malloc(sizeof(nfc_target)); if (!CHIP_DATA(pnd)->current_target) { return NULL; } memcpy(CHIP_DATA(pnd)->current_target, pnt, sizeof(nfc_target)); return CHIP_DATA(pnd)->current_target; } void pn53x_current_target_free(const struct nfc_device *pnd) { if (CHIP_DATA(pnd)->current_target) { free(CHIP_DATA(pnd)->current_target); CHIP_DATA(pnd)->current_target = NULL; } } bool pn53x_current_target_is(const struct nfc_device *pnd, const nfc_target *pnt) { if ((CHIP_DATA(pnd)->current_target == NULL) || (pnt == NULL)) { return false; } // XXX It will not work if it is not binary-equal to current target if (0 != memcmp(pnt, CHIP_DATA(pnd)->current_target, sizeof(nfc_target))) { return false; } return true; } void * pn53x_data_new(struct nfc_device *pnd, const struct pn53x_io *io) { pnd->chip_data = malloc(sizeof(struct pn53x_data)); if (!pnd->chip_data) { return NULL; } // Keep I/O functions CHIP_DATA(pnd)->io = io; // Set type to generic (means unknown) CHIP_DATA(pnd)->type = PN53X; // Set power mode to normal, if your device starts in LowVBat (ie. PN532 // UART) the driver layer have to correctly set it. CHIP_DATA(pnd)->power_mode = NORMAL; // PN53x starts in initiator mode CHIP_DATA(pnd)->operating_mode = INITIATOR; // Clear last status byte CHIP_DATA(pnd)->last_status_byte = 0x00; // Set current target to NULL CHIP_DATA(pnd)->current_target = NULL; // Set current sam_mode to normal mode CHIP_DATA(pnd)->sam_mode = PSM_NORMAL; // WriteBack cache is clean CHIP_DATA(pnd)->wb_trigged = false; memset(CHIP_DATA(pnd)->wb_mask, 0x00, PN53X_CACHE_REGISTER_SIZE); // Set default command timeout (350 ms) CHIP_DATA(pnd)->timeout_command = 350; // Set default ATR timeout (103 ms) CHIP_DATA(pnd)->timeout_atr = 103; // Set default communication timeout (52 ms) CHIP_DATA(pnd)->timeout_communication = 52; CHIP_DATA(pnd)->supported_modulation_as_initiator = NULL; CHIP_DATA(pnd)->supported_modulation_as_target = NULL; return pnd->chip_data; } void pn53x_data_free(struct nfc_device *pnd) { // Free current target pn53x_current_target_free(pnd); // Free supported modulation(s) if (CHIP_DATA(pnd)->supported_modulation_as_initiator) { free(CHIP_DATA(pnd)->supported_modulation_as_initiator); } free(pnd->chip_data); }
C
/*- * 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 pn53x.h * @brief PN531, PN532 and PN533 common functions */ #ifndef __NFC_CHIPS_PN53X_H__ # define __NFC_CHIPS_PN53X_H__ # include <nfc/nfc-types.h> # include "pn53x-internal.h" // Registers and symbols masks used to covers parts within a register // PN53X_REG_CIU_TxMode # define SYMBOL_TX_CRC_ENABLE 0x80 # define SYMBOL_TX_SPEED 0x70 // TX_FRAMING bits explanation: // 00 : ISO/IEC 14443A/MIFARE and Passive Communication mode 106 kbit/s // 01 : Active Communication mode // 10 : FeliCa and Passive Communication mode at 212 kbit/s and 424 kbit/s // 11 : ISO/IEC 14443B # define SYMBOL_TX_FRAMING 0x03 // PN53X_REG_Control_switch_rng # define SYMBOL_CURLIMOFF 0x08 /* When set to 1, the 100 mA current limitations is desactivated. */ # define SYMBOL_SIC_SWITCH_EN 0x10 /* When set to logic 1, the SVDD switch is enabled and the SVDD output delivers power to secure IC and internal pads (SIGIN, SIGOUT and P34). */ # define SYMBOL_RANDOM_DATAREADY 0x02 /* When set to logic 1, a new random number is available. */ // PN53X_REG_CIU_RxMode # define SYMBOL_RX_CRC_ENABLE 0x80 # define SYMBOL_RX_SPEED 0x70 # define SYMBOL_RX_NO_ERROR 0x08 # define SYMBOL_RX_MULTIPLE 0x04 // RX_FRAMING follow same scheme than TX_FRAMING # define SYMBOL_RX_FRAMING 0x03 // PN53X_REG_CIU_TxAuto # define SYMBOL_FORCE_100_ASK 0x40 # define SYMBOL_AUTO_WAKE_UP 0x20 # define SYMBOL_INITIAL_RF_ON 0x04 // PN53X_REG_CIU_ManualRCV # define SYMBOL_PARITY_DISABLE 0x10 // PN53X_REG_CIU_TMode # define SYMBOL_TAUTO 0x80 # define SYMBOL_TPRESCALERHI 0x0F // PN53X_REG_CIU_TPrescaler # define SYMBOL_TPRESCALERLO 0xFF // PN53X_REG_CIU_Command # define SYMBOL_COMMAND 0x0F # define SYMBOL_COMMAND_TRANSCEIVE 0xC // PN53X_REG_CIU_Status2 # define SYMBOL_MF_CRYPTO1_ON 0x08 // PN53X_REG_CIU_FIFOLevel # define SYMBOL_FLUSH_BUFFER 0x80 # define SYMBOL_FIFO_LEVEL 0x7F // PN53X_REG_CIU_Control # define SYMBOL_INITIATOR 0x10 # define SYMBOL_RX_LAST_BITS 0x07 // PN53X_REG_CIU_BitFraming # define SYMBOL_START_SEND 0x80 # define SYMBOL_RX_ALIGN 0x70 # define SYMBOL_TX_LAST_BITS 0x07 // PN53X Support Byte flags #define SUPPORT_ISO14443A 0x01 #define SUPPORT_ISO14443B 0x02 #define SUPPORT_ISO18092 0x04 // Internal parameters flags # define PARAM_NONE 0x00 # define PARAM_NAD_USED 0x01 # define PARAM_DID_USED 0x02 # define PARAM_AUTO_ATR_RES 0x04 # define PARAM_AUTO_RATS 0x10 # define PARAM_14443_4_PICC 0x20 /* Only for PN532 */ # define PARAM_NFC_SECURE 0x20 /* Only for PN533 */ # define PARAM_NO_AMBLE 0x40 /* Only for PN532 */ // Radio Field Configure Items // Configuration Data length # define RFCI_FIELD 0x01 // 1 # define RFCI_TIMING 0x02 // 3 # define RFCI_RETRY_DATA 0x04 // 1 # define RFCI_RETRY_SELECT 0x05 // 3 # define RFCI_ANALOG_TYPE_A_106 0x0A // 11 # define RFCI_ANALOG_TYPE_A_212_424 0x0B // 8 # define RFCI_ANALOG_TYPE_B 0x0C // 3 # define RFCI_ANALOG_TYPE_14443_4 0x0D // 9 /** * @enum pn53x_power_mode * @brief PN53x power mode enumeration */ typedef enum { NORMAL, // In that case, there is no power saved but the PN53x reacts as fast as possible on the host controller interface. POWERDOWN, // Only on PN532, need to be wake up to process commands with a long preamble LOWVBAT // Only on PN532, need to be wake up to process commands with a long preamble and SAMConfiguration command } pn53x_power_mode; /** * @enum pn53x_operating_mode * @brief PN53x operatin mode enumeration */ typedef enum { IDLE, INITIATOR, TARGET, } pn53x_operating_mode; /** * @enum pn532_sam_mode * @brief PN532 SAM mode enumeration */ typedef enum { PSM_NORMAL = 0x01, PSM_VIRTUAL_CARD = 0x02, PSM_WIRED_CARD = 0x03, PSM_DUAL_CARD = 0x04 } pn532_sam_mode; /** * @internal * @struct pn53x_io * @brief PN53x I/O structure */ struct pn53x_io { int (*send)(struct nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); int (*receive)(struct nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout); }; /* defines */ #define PN53X_CACHE_REGISTER_MIN_ADDRESS PN53X_REG_CIU_Mode #define PN53X_CACHE_REGISTER_MAX_ADDRESS PN53X_REG_CIU_Coll #define PN53X_CACHE_REGISTER_SIZE ((PN53X_CACHE_REGISTER_MAX_ADDRESS - PN53X_CACHE_REGISTER_MIN_ADDRESS) + 1) /** * @internal * @struct pn53x_data * @brief PN53x data structure */ struct pn53x_data { /** Chip type (PN531, PN532 or PN533) */ pn53x_type type; /** Chip firmware text */ char firmware_text[22]; /** Current power mode */ pn53x_power_mode power_mode; /** Current operating mode */ pn53x_operating_mode operating_mode; /** Current emulated target */ nfc_target *current_target; /** Current sam mode (only applicable for PN532) */ pn532_sam_mode sam_mode; /** PN53x I/O functions stored in struct */ const struct pn53x_io *io; /** Last status byte returned by PN53x */ uint8_t last_status_byte; /** Register cache for REG_CIU_BIT_FRAMING, SYMBOL_TX_LAST_BITS: The last TX bits setting, we need to reset this if it does not apply anymore */ uint8_t ui8TxBits; /** Register cache for SetParameters function. */ uint8_t ui8Parameters; /** Last sent command */ uint8_t last_command; /** Interframe timer correction */ int16_t timer_correction; /** Timer prescaler */ uint16_t timer_prescaler; /** WriteBack cache */ uint8_t wb_data[PN53X_CACHE_REGISTER_SIZE]; uint8_t wb_mask[PN53X_CACHE_REGISTER_SIZE]; bool wb_trigged; /** Command timeout */ int timeout_command; /** ATR timeout */ int timeout_atr; /** Communication timeout */ int timeout_communication; /** Supported modulation type */ nfc_modulation_type *supported_modulation_as_initiator; nfc_modulation_type *supported_modulation_as_target; }; #define CHIP_DATA(pnd) ((struct pn53x_data*)(pnd->chip_data)) /** * @enum pn53x_modulation * @brief NFC modulation enumeration */ typedef enum { /** Undefined modulation */ PM_UNDEFINED = -1, /** ISO14443-A (NXP MIFARE) http://en.wikipedia.org/wiki/MIFARE */ PM_ISO14443A_106 = 0x00, /** JIS X 6319-4 (Sony Felica) http://en.wikipedia.org/wiki/FeliCa */ PM_FELICA_212 = 0x01, /** JIS X 6319-4 (Sony Felica) http://en.wikipedia.org/wiki/FeliCa */ PM_FELICA_424 = 0x02, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531) */ PM_ISO14443B_106 = 0x03, /** Jewel Topaz (Innovision Research & Development) (Not supported by PN531) */ PM_JEWEL_106 = 0x04, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531 nor PN532) */ PM_ISO14443B_212 = 0x06, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531 nor PN532) */ PM_ISO14443B_424 = 0x07, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531 nor PN532) */ PM_ISO14443B_847 = 0x08, } pn53x_modulation; /** * @enum pn53x_target_type * @brief NFC target type enumeration */ typedef enum { /** Undefined target type */ PTT_UNDEFINED = -1, /** Generic passive 106 kbps (ISO/IEC14443-4A, mifare, DEP) */ PTT_GENERIC_PASSIVE_106 = 0x00, /** Generic passive 212 kbps (FeliCa, DEP) */ PTT_GENERIC_PASSIVE_212 = 0x01, /** Generic passive 424 kbps (FeliCa, DEP) */ PTT_GENERIC_PASSIVE_424 = 0x02, /** Passive 106 kbps ISO/IEC14443-4B */ PTT_ISO14443_4B_106 = 0x03, /** Innovision Jewel tag */ PTT_JEWEL_106 = 0x04, /** Mifare card */ PTT_MIFARE = 0x10, /** FeliCa 212 kbps card */ PTT_FELICA_212 = 0x11, /** FeliCa 424 kbps card */ PTT_FELICA_424 = 0x12, /** Passive 106 kbps ISO/IEC 14443-4A */ PTT_ISO14443_4A_106 = 0x20, /** Passive 106 kbps ISO/IEC 14443-4B with TCL flag */ PTT_ISO14443_4B_TCL_106 = 0x23, /** DEP passive 106 kbps */ PTT_DEP_PASSIVE_106 = 0x40, /** DEP passive 212 kbps */ PTT_DEP_PASSIVE_212 = 0x41, /** DEP passive 424 kbps */ PTT_DEP_PASSIVE_424 = 0x42, /** DEP active 106 kbps */ PTT_DEP_ACTIVE_106 = 0x80, /** DEP active 212 kbps */ PTT_DEP_ACTIVE_212 = 0x81, /** DEP active 424 kbps */ PTT_DEP_ACTIVE_424 = 0x82, } pn53x_target_type; /** * @enum pn53x_target_mode * @brief PN53x target mode enumeration */ typedef enum { /** Configure the PN53x to accept all initiator mode */ PTM_NORMAL = 0x00, /** Configure the PN53x to accept to be initialized only in passive mode */ PTM_PASSIVE_ONLY = 0x01, /** Configure the PN53x to accept to be initialized only as DEP target */ PTM_DEP_ONLY = 0x02, /** Configure the PN532 to accept to be initialized only as ISO/IEC14443-4 PICC */ PTM_ISO14443_4_PICC_ONLY = 0x04 } pn53x_target_mode; extern const uint8_t pn53x_ack_frame[PN53x_ACK_FRAME__LEN]; extern const uint8_t pn53x_nack_frame[PN53x_ACK_FRAME__LEN]; int pn53x_init(struct nfc_device *pnd); int pn53x_transceive(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_set_parameters(struct nfc_device *pnd, const uint8_t ui8Value, const bool bEnable); int pn53x_set_tx_bits(struct nfc_device *pnd, const uint8_t ui8Bits); int pn53x_wrap_frame(const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtFrame); int pn53x_unwrap_frame(const uint8_t *pbtFrame, const size_t szFrameBits, uint8_t *pbtRx, uint8_t *pbtRxPar); int pn53x_decode_target_data(const uint8_t *pbtRawData, size_t szRawData, pn53x_type chip_type, nfc_modulation_type nmt, nfc_target_info *pnti); int pn53x_read_register(struct nfc_device *pnd, uint16_t ui16Reg, uint8_t *ui8Value); int pn53x_write_register(struct nfc_device *pnd, uint16_t ui16Reg, uint8_t ui8SymbolMask, uint8_t ui8Value); int pn53x_decode_firmware_version(struct nfc_device *pnd); int pn53x_set_property_int(struct nfc_device *pnd, const nfc_property property, const int value); int pn53x_set_property_bool(struct nfc_device *pnd, const nfc_property property, const bool bEnable); int pn53x_check_communication(struct nfc_device *pnd); int pn53x_idle(struct nfc_device *pnd); // NFC device as Initiator functions int pn53x_initiator_init(struct nfc_device *pnd); int pn532_initiator_init_secure_element(struct nfc_device *pnd); int pn53x_initiator_select_passive_target(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt); int pn53x_initiator_poll_target(struct nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt); int pn53x_initiator_select_dep_target(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout); int pn53x_initiator_transceive_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar); int pn53x_initiator_transceive_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout); int pn53x_initiator_transceive_bits_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles); int pn53x_initiator_transceive_bytes_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, uint32_t *cycles); int pn53x_initiator_deselect_target(struct nfc_device *pnd); int pn53x_initiator_target_is_present(struct nfc_device *pnd, const nfc_target *pnt); // NFC device as Target functions int pn53x_target_init(struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_target_receive_bits(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar); int pn53x_target_receive_bytes(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_target_send_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar); int pn53x_target_send_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout); // Error handling functions const char *pn53x_strerror(const struct nfc_device *pnd); // C wrappers for PN53x commands int pn53x_SetParameters(struct nfc_device *pnd, const uint8_t ui8Value); int pn532_SAMConfiguration(struct nfc_device *pnd, const pn532_sam_mode mode, int timeout); int pn53x_PowerDown(struct nfc_device *pnd); int pn53x_InListPassiveTarget(struct nfc_device *pnd, const pn53x_modulation pmInitModulation, const uint8_t szMaxTargets, const uint8_t *pbtInitiatorData, const size_t szInitiatorDataLen, uint8_t *pbtTargetsData, size_t *pszTargetsData, int timeout); int pn53x_InDeselect(struct nfc_device *pnd, const uint8_t ui8Target); int pn53x_InRelease(struct nfc_device *pnd, const uint8_t ui8Target); int pn53x_InAutoPoll(struct nfc_device *pnd, const pn53x_target_type *ppttTargetTypes, const size_t szTargetTypes, const uint8_t btPollNr, const uint8_t btPeriod, nfc_target *pntTargets, const int timeout); int pn53x_InJumpForDEP(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const uint8_t *pbtPassiveInitiatorData, const uint8_t *pbtNFCID3i, const uint8_t *pbtGB, const size_t szGB, nfc_target *pnt, const int timeout); int pn53x_TgInitAsTarget(struct nfc_device *pnd, pn53x_target_mode ptm, const uint8_t *pbtMifareParams, const uint8_t *pbtTkt, size_t szTkt, const uint8_t *pbtFeliCaParams, const uint8_t *pbtNFCID3t, const uint8_t *pbtGB, const size_t szGB, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtModeByte, int timeout); // RFConfiguration int pn53x_RFConfiguration__RF_field(struct nfc_device *pnd, bool bEnable); int pn53x_RFConfiguration__Various_timings(struct nfc_device *pnd, const uint8_t fATR_RES_Timeout, const uint8_t fRetryTimeout); int pn53x_RFConfiguration__MaxRtyCOM(struct nfc_device *pnd, const uint8_t MaxRtyCOM); int pn53x_RFConfiguration__MaxRetries(struct nfc_device *pnd, const uint8_t MxRtyATR, const uint8_t MxRtyPSL, const uint8_t MxRtyPassiveActivation); // Misc int pn53x_check_ack_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen); int pn53x_check_error_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen); int pn53x_build_frame(uint8_t *pbtFrame, size_t *pszFrame, const uint8_t *pbtData, const size_t szData); int pn53x_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt); int pn53x_get_supported_baud_rate(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); int pn53x_get_information_about(nfc_device *pnd, char **pbuf); void *pn53x_data_new(struct nfc_device *pnd, const struct pn53x_io *io); void pn53x_data_free(struct nfc_device *pnd); #endif // __NFC_CHIPS_PN53X_H__
C
/*- * 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 pn53x-internal.h * @brief PN531, PN532 and PN533 defines and compatibility */ #ifndef __PN53X_INTERNAL_H__ #define __PN53X_INTERNAL_H__ #include "log.h" // Miscellaneous #define Diagnose 0x00 #define GetFirmwareVersion 0x02 #define GetGeneralStatus 0x04 #define ReadRegister 0x06 #define WriteRegister 0x08 #define ReadGPIO 0x0C #define WriteGPIO 0x0E #define SetSerialBaudRate 0x10 #define SetParameters 0x12 #define SAMConfiguration 0x14 #define PowerDown 0x16 #define AlparCommandForTDA 0x18 // RC-S360 has another command 0x18 for reset &..? // RF communication #define RFConfiguration 0x32 #define RFRegulationTest 0x58 // Initiator #define InJumpForDEP 0x56 #define InJumpForPSL 0x46 #define InListPassiveTarget 0x4A #define InATR 0x50 #define InPSL 0x4E #define InDataExchange 0x40 #define InCommunicateThru 0x42 #define InQuartetByteExchange 0x38 #define InDeselect 0x44 #define InRelease 0x52 #define InSelect 0x54 #define InActivateDeactivatePaypass 0x48 #define InAutoPoll 0x60 // Target #define TgInitAsTarget 0x8C #define TgSetGeneralBytes 0x92 #define TgGetData 0x86 #define TgSetData 0x8E #define TgSetDataSecure 0x96 #define TgSetMetaData 0x94 #define TgSetMetaDataSecure 0x98 #define TgGetInitiatorCommand 0x88 #define TgResponseToInitiator 0x90 #define TgGetTargetStatus 0x8A /** @note PN53x's normal frame: * * .-- Start * | .-- Packet length * | | .-- Length checksum * | | | .-- Direction (D4 Host to PN, D5 PN to Host) * | | | | .-- Code * | | | | | .-- Packet checksum * | | | | | | .-- Postamble * V | | | | | | * ----- V V V V V V * 00 FF 02 FE D4 02 2A 00 */ /** @note PN53x's extended frame: * * .-- Start * | .-- Fixed to FF to enable extended frame * | | .-- Packet length * | | | .-- Length checksum * | | | | .-- Direction (D4 Host to PN, D5 PN to Host) * | | | | | .-- Code * | | | | | | .-- Packet checksum * | | | | | | | .-- Postamble * V V V | | | | | * ----- ----- ----- V V V V V * 00 FF FF FF 00 02 FE D4 02 2A 00 */ /** * Start bytes, packet length, length checksum, direction, packet checksum and postamble are overhead */ // The TFI is considered part of the overhead # define PN53x_NORMAL_FRAME__DATA_MAX_LEN 254 # define PN53x_NORMAL_FRAME__OVERHEAD 8 # define PN53x_EXTENDED_FRAME__DATA_MAX_LEN 264 # define PN53x_EXTENDED_FRAME__OVERHEAD 11 # define PN53x_ACK_FRAME__LEN 6 typedef struct { uint8_t ui8Code; uint8_t ui8CompatFlags; #ifdef LOG const char *abtCommandText; #endif } pn53x_command; typedef enum { PN53X = 0x00, // Unknown PN53x chip type PN531 = 0x01, PN532 = 0x02, PN533 = 0x04, RCS360 = 0x08 } pn53x_type; #ifndef LOG # define PNCMD( X, Y ) { X , Y } # define PNCMD_TRACE( X ) do {} while(0) #else # define PNCMD( X, Y ) { X , Y, #X } # define PNCMD_TRACE( X ) do { \ for (size_t i=0; i<(sizeof(pn53x_commands)/sizeof(pn53x_command)); i++) { \ if ( X == pn53x_commands[i].ui8Code ) { \ log_put( LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", pn53x_commands[i].abtCommandText ); \ break; \ } \ } \ } while(0) #endif static const pn53x_command pn53x_commands[] = { // Miscellaneous PNCMD(Diagnose, PN531 | PN532 | PN533 | RCS360), PNCMD(GetFirmwareVersion, PN531 | PN532 | PN533 | RCS360), PNCMD(GetGeneralStatus, PN531 | PN532 | PN533 | RCS360), PNCMD(ReadRegister, PN531 | PN532 | PN533 | RCS360), PNCMD(WriteRegister, PN531 | PN532 | PN533 | RCS360), PNCMD(ReadGPIO, PN531 | PN532 | PN533), PNCMD(WriteGPIO, PN531 | PN532 | PN533), PNCMD(SetSerialBaudRate, PN531 | PN532 | PN533), PNCMD(SetParameters, PN531 | PN532 | PN533 | RCS360), PNCMD(SAMConfiguration, PN531 | PN532), PNCMD(PowerDown, PN531 | PN532), PNCMD(AlparCommandForTDA, PN533 | RCS360), // Has another usage on RC-S360... // RF communication PNCMD(RFConfiguration, PN531 | PN532 | PN533 | RCS360), PNCMD(RFRegulationTest, PN531 | PN532 | PN533), // Initiator PNCMD(InJumpForDEP, PN531 | PN532 | PN533 | RCS360), PNCMD(InJumpForPSL, PN531 | PN532 | PN533), PNCMD(InListPassiveTarget, PN531 | PN532 | PN533 | RCS360), PNCMD(InATR, PN531 | PN532 | PN533), PNCMD(InPSL, PN531 | PN532 | PN533), PNCMD(InDataExchange, PN531 | PN532 | PN533), PNCMD(InCommunicateThru, PN531 | PN532 | PN533 | RCS360), PNCMD(InQuartetByteExchange, PN533), PNCMD(InDeselect, PN531 | PN532 | PN533 | RCS360), PNCMD(InRelease, PN531 | PN532 | PN533 | RCS360), PNCMD(InSelect, PN531 | PN532 | PN533), PNCMD(InAutoPoll, PN532), PNCMD(InActivateDeactivatePaypass, PN533), // Target PNCMD(TgInitAsTarget, PN531 | PN532 | PN533), PNCMD(TgSetGeneralBytes, PN531 | PN532 | PN533), PNCMD(TgGetData, PN531 | PN532 | PN533), PNCMD(TgSetData, PN531 | PN532 | PN533), PNCMD(TgSetDataSecure, PN533), PNCMD(TgSetMetaData, PN531 | PN532 | PN533), PNCMD(TgSetMetaDataSecure, PN533), PNCMD(TgGetInitiatorCommand, PN531 | PN532 | PN533), PNCMD(TgResponseToInitiator, PN531 | PN532 | PN533), PNCMD(TgGetTargetStatus, PN531 | PN532 | PN533), }; // SFR part #define _BV( X ) (1 << X) #define P30 0 #define P31 1 #define P32 2 #define P33 3 #define P34 4 #define P35 5 // Registers part #ifdef LOG typedef struct { uint16_t ui16Address; const char *abtRegisterText; const char *abtRegisterDescription; } pn53x_register; # define PNREG( X, Y ) { X , #X, Y } #endif /* LOG */ #ifndef LOG # define PNREG_TRACE( X ) do { \ } while(0) #else # define PNREG_TRACE( X ) do { \ for (size_t i=0; i<(sizeof(pn53x_registers)/sizeof(pn53x_register)); i++) { \ if ( X == pn53x_registers[i].ui16Address ) { \ log_put( LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s (%s)", pn53x_registers[i].abtRegisterText, pn53x_registers[i].abtRegisterDescription ); \ break; \ } \ } \ } while(0) #endif // Register addresses #define PN53X_REG_Control_switch_rng 0x6106 #define PN53X_REG_CIU_Mode 0x6301 #define PN53X_REG_CIU_TxMode 0x6302 #define PN53X_REG_CIU_RxMode 0x6303 #define PN53X_REG_CIU_TxControl 0x6304 #define PN53X_REG_CIU_TxAuto 0x6305 #define PN53X_REG_CIU_TxSel 0x6306 #define PN53X_REG_CIU_RxSel 0x6307 #define PN53X_REG_CIU_RxThreshold 0x6308 #define PN53X_REG_CIU_Demod 0x6309 #define PN53X_REG_CIU_FelNFC1 0x630A #define PN53X_REG_CIU_FelNFC2 0x630B #define PN53X_REG_CIU_MifNFC 0x630C #define PN53X_REG_CIU_ManualRCV 0x630D #define PN53X_REG_CIU_TypeB 0x630E // #define PN53X_REG_- 0x630F // #define PN53X_REG_- 0x6310 #define PN53X_REG_CIU_CRCResultMSB 0x6311 #define PN53X_REG_CIU_CRCResultLSB 0x6312 #define PN53X_REG_CIU_GsNOFF 0x6313 #define PN53X_REG_CIU_ModWidth 0x6314 #define PN53X_REG_CIU_TxBitPhase 0x6315 #define PN53X_REG_CIU_RFCfg 0x6316 #define PN53X_REG_CIU_GsNOn 0x6317 #define PN53X_REG_CIU_CWGsP 0x6318 #define PN53X_REG_CIU_ModGsP 0x6319 #define PN53X_REG_CIU_TMode 0x631A #define PN53X_REG_CIU_TPrescaler 0x631B #define PN53X_REG_CIU_TReloadVal_hi 0x631C #define PN53X_REG_CIU_TReloadVal_lo 0x631D #define PN53X_REG_CIU_TCounterVal_hi 0x631E #define PN53X_REG_CIU_TCounterVal_lo 0x631F // #define PN53X_REG_- 0x6320 #define PN53X_REG_CIU_TestSel1 0x6321 #define PN53X_REG_CIU_TestSel2 0x6322 #define PN53X_REG_CIU_TestPinEn 0x6323 #define PN53X_REG_CIU_TestPinValue 0x6324 #define PN53X_REG_CIU_TestBus 0x6325 #define PN53X_REG_CIU_AutoTest 0x6326 #define PN53X_REG_CIU_Version 0x6327 #define PN53X_REG_CIU_AnalogTest 0x6328 #define PN53X_REG_CIU_TestDAC1 0x6329 #define PN53X_REG_CIU_TestDAC2 0x632A #define PN53X_REG_CIU_TestADC 0x632B // #define PN53X_REG_- 0x632C // #define PN53X_REG_- 0x632D // #define PN53X_REG_- 0x632E #define PN53X_REG_CIU_RFlevelDet 0x632F #define PN53X_REG_CIU_SIC_CLK_en 0x6330 #define PN53X_REG_CIU_Command 0x6331 #define PN53X_REG_CIU_CommIEn 0x6332 #define PN53X_REG_CIU_DivIEn 0x6333 #define PN53X_REG_CIU_CommIrq 0x6334 #define PN53X_REG_CIU_DivIrq 0x6335 #define PN53X_REG_CIU_Error 0x6336 #define PN53X_REG_CIU_Status1 0x6337 #define PN53X_REG_CIU_Status2 0x6338 #define PN53X_REG_CIU_FIFOData 0x6339 #define PN53X_REG_CIU_FIFOLevel 0x633A #define PN53X_REG_CIU_WaterLevel 0x633B #define PN53X_REG_CIU_Control 0x633C #define PN53X_REG_CIU_BitFraming 0x633D #define PN53X_REG_CIU_Coll 0x633E #define PN53X_SFR_P3 0xFFB0 #define PN53X_SFR_P3CFGA 0xFFFC #define PN53X_SFR_P3CFGB 0xFFFD #define PN53X_SFR_P7CFGA 0xFFF4 #define PN53X_SFR_P7CFGB 0xFFF5 #define PN53X_SFR_P7 0xFFF7 /* PN53x specific errors */ #define ETIMEOUT 0x01 #define ECRC 0x02 #define EPARITY 0x03 #define EBITCOUNT 0x04 #define EFRAMING 0x05 #define EBITCOLL 0x06 #define ESMALLBUF 0x07 #define EBUFOVF 0x09 #define ERFTIMEOUT 0x0a #define ERFPROTO 0x0b #define EOVHEAT 0x0d #define EINBUFOVF 0x0e #define EINVPARAM 0x10 #define EDEPUNKCMD 0x12 #define EINVRXFRAM 0x13 #define EMFAUTH 0x14 #define ENSECNOTSUPP 0x18 // PN533 only #define EBCC 0x23 #define EDEPINVSTATE 0x25 #define EOPNOTALL 0x26 #define ECMD 0x27 #define ETGREL 0x29 #define ECID 0x2a #define ECDISCARDED 0x2b #define ENFCID3 0x2c #define EOVCURRENT 0x2d #define ENAD 0x2e #ifdef LOG static const pn53x_register pn53x_registers[] = { PNREG(PN53X_REG_CIU_Mode, "Defines general modes for transmitting and receiving"), PNREG(PN53X_REG_CIU_TxMode, "Defines the transmission data rate and framing during transmission"), PNREG(PN53X_REG_CIU_RxMode, "Defines the transmission data rate and framing during receiving"), PNREG(PN53X_REG_CIU_TxControl, "Controls the logical behaviour of the antenna driver pins TX1 and TX2"), PNREG(PN53X_REG_CIU_TxAuto, "Controls the settings of the antenna driver"), PNREG(PN53X_REG_CIU_TxSel, "Selects the internal sources for the antenna driver"), PNREG(PN53X_REG_CIU_RxSel, "Selects internal receiver settings"), PNREG(PN53X_REG_CIU_RxThreshold, "Selects thresholds for the bit decoder"), PNREG(PN53X_REG_CIU_Demod, "Defines demodulator settings"), PNREG(PN53X_REG_CIU_FelNFC1, "Defines the length of the valid range for the received frame"), PNREG(PN53X_REG_CIU_FelNFC2, "Defines the length of the valid range for the received frame"), PNREG(PN53X_REG_CIU_MifNFC, "Controls the communication in ISO/IEC 14443/MIFARE and NFC target mode at 106 kbit/s"), PNREG(PN53X_REG_CIU_ManualRCV, "Allows manual fine tuning of the internal receiver"), PNREG(PN53X_REG_CIU_TypeB, "Configure the ISO/IEC 14443 type B"), // PNREG (PN53X_REG_-, "Reserved"), // PNREG (PN53X_REG_-, "Reserved"), PNREG(PN53X_REG_CIU_CRCResultMSB, "Shows the actual MSB values of the CRC calculation"), PNREG(PN53X_REG_CIU_CRCResultLSB, "Shows the actual LSB values of the CRC calculation"), PNREG(PN53X_REG_CIU_GsNOFF, "Selects the conductance of the antenna driver pins TX1 and TX2 for load modulation when own RF field is switched OFF"), PNREG(PN53X_REG_CIU_ModWidth, "Controls the setting of the width of the Miller pause"), PNREG(PN53X_REG_CIU_TxBitPhase, "Bit synchronization at 106 kbit/s"), PNREG(PN53X_REG_CIU_RFCfg, "Configures the receiver gain and RF level"), PNREG(PN53X_REG_CIU_GsNOn, "Selects the conductance of the antenna driver pins TX1 and TX2 for modulation, when own RF field is switched ON"), PNREG(PN53X_REG_CIU_CWGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when not in modulation phase"), PNREG(PN53X_REG_CIU_ModGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when in modulation phase"), PNREG(PN53X_REG_CIU_TMode, "Defines settings for the internal timer"), PNREG(PN53X_REG_CIU_TPrescaler, "Defines settings for the internal timer"), PNREG(PN53X_REG_CIU_TReloadVal_hi, "Describes the 16-bit long timer reload value (Higher 8 bits)"), PNREG(PN53X_REG_CIU_TReloadVal_lo, "Describes the 16-bit long timer reload value (Lower 8 bits)"), PNREG(PN53X_REG_CIU_TCounterVal_hi, "Describes the 16-bit long timer actual value (Higher 8 bits)"), PNREG(PN53X_REG_CIU_TCounterVal_lo, "Describes the 16-bit long timer actual value (Lower 8 bits)"), // PNREG (PN53X_REG_-, "Reserved"), PNREG(PN53X_REG_CIU_TestSel1, "General test signals configuration"), PNREG(PN53X_REG_CIU_TestSel2, "General test signals configuration and PRBS control"), PNREG(PN53X_REG_CIU_TestPinEn, "Enables test signals output on pins."), PNREG(PN53X_REG_CIU_TestPinValue, "Defines the values for the 8-bit parallel bus when it is used as I/O bus"), PNREG(PN53X_REG_CIU_TestBus, "Shows the status of the internal test bus"), PNREG(PN53X_REG_CIU_AutoTest, "Controls the digital self-test"), PNREG(PN53X_REG_CIU_Version, "Shows the CIU version"), PNREG(PN53X_REG_CIU_AnalogTest, "Controls the pins AUX1 and AUX2"), PNREG(PN53X_REG_CIU_TestDAC1, "Defines the test value for the TestDAC1"), PNREG(PN53X_REG_CIU_TestDAC2, "Defines the test value for the TestDAC2"), PNREG(PN53X_REG_CIU_TestADC, "Show the actual value of ADC I and Q"), // PNREG (PN53X_REG_-, "Reserved for tests"), // PNREG (PN53X_REG_-, "Reserved for tests"), // PNREG (PN53X_REG_-, "Reserved for tests"), PNREG(PN53X_REG_CIU_RFlevelDet, "Power down of the RF level detector"), PNREG(PN53X_REG_CIU_SIC_CLK_en, "Enables the use of secure IC clock on P34 / SIC_CLK"), PNREG(PN53X_REG_CIU_Command, "Starts and stops the command execution"), PNREG(PN53X_REG_CIU_CommIEn, "Control bits to enable and disable the passing of interrupt requests"), PNREG(PN53X_REG_CIU_DivIEn, "Controls bits to enable and disable the passing of interrupt requests"), PNREG(PN53X_REG_CIU_CommIrq, "Contains common CIU interrupt request flags"), PNREG(PN53X_REG_CIU_DivIrq, "Contains miscellaneous interrupt request flags"), PNREG(PN53X_REG_CIU_Error, "Error flags showing the error status of the last command executed"), PNREG(PN53X_REG_CIU_Status1, "Contains status flags of the CRC, Interrupt Request System and FIFO buffer"), PNREG(PN53X_REG_CIU_Status2, "Contain status flags of the receiver, transmitter and Data Mode Detector"), PNREG(PN53X_REG_CIU_FIFOData, "In- and output of 64 byte FIFO buffer"), PNREG(PN53X_REG_CIU_FIFOLevel, "Indicates the number of bytes stored in the FIFO"), PNREG(PN53X_REG_CIU_WaterLevel, "Defines the thresholds for FIFO under- and overflow warning"), PNREG(PN53X_REG_CIU_Control, "Contains miscellaneous control bits"), PNREG(PN53X_REG_CIU_BitFraming, "Adjustments for bit oriented frames"), PNREG(PN53X_REG_CIU_Coll, "Defines the first bit collision detected on the RF interface"), // SFR PNREG(PN53X_SFR_P3CFGA, "Port 3 configuration"), PNREG(PN53X_SFR_P3CFGB, "Port 3 configuration"), PNREG(PN53X_SFR_P3, "Port 3 value"), PNREG(PN53X_SFR_P7CFGA, "Port 7 configuration"), PNREG(PN53X_SFR_P7CFGB, "Port 7 configuration"), PNREG(PN53X_SFR_P7, "Port 7 value"), }; #endif #endif /* __PN53X_INTERNAL_H__ */
C
/*- * 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__
C
/*- * 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__
C
/*- * 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__
C
/* empty source code file */ #include <stdio.h>
C
/*- * 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; }
C
/*- * 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; }
C
/*- * 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__
C
/*- * 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; }
C
/*- * 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; }
C
/*- * 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__
C
/*- * 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); }
C
/*- * 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); }
C
/*- * 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; }
C
/*- * 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; }
C
/*- * 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); }
C
/*- * 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); }
C
/*- * 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_
C