1 /*-
2  * Free/Libre Near Field Communication (NFC) library
3  *
4  * Libnfc historical contributors:
5  * Copyright (C) 2009      Roel Verdult
6  * Copyright (C) 2009-2013 Romuald Conty
7  * Copyright (C) 2010-2012 Romain Tartière
8  * Copyright (C) 2010-2013 Philippe Teuwen
9  * Copyright (C) 2012-2013 Ludovic Rousseau
10  * See AUTHORS file for a more comprehensive list of contributors.
11  * Additional contributors of this file:
12  *
13  * This program is free software: you can redistribute it and/or modify it
14  * under the terms of the GNU Lesser General Public License as published by the
15  * Free Software Foundation, either version 3 of the License, or (at your
16  * option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful, but WITHOUT
19  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
21  * more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>
25  */
26 
27 /**
28  * @file pn53x_usb.c
29  * @brief Driver for PN53x using USB
30  */
31 
32 #ifdef HAVE_CONFIG_H
33 #  include "config.h"
34 #endif // HAVE_CONFIG_H
35 
36 /*
37 Thanks to d18c7db and Okko for example code
38 */
39 
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <inttypes.h>
43 #include <sys/select.h>
44 #include <errno.h>
45 #include <string.h>
46 
47 #include <nfc/nfc.h>
48 
49 #include "nfc-internal.h"
50 #include "buses/usbbus.h"
51 #include "chips/pn53x.h"
52 #include "chips/pn53x-internal.h"
53 #include "drivers/pn53x_usb.h"
54 
55 #define PN53X_USB_DRIVER_NAME "pn53x_usb"
56 #define LOG_CATEGORY "libnfc.driver.pn53x_usb"
57 #define LOG_GROUP    NFC_LOG_GROUP_DRIVER
58 
59 #define USB_INFINITE_TIMEOUT   0
60 
61 #define DRIVER_DATA(pnd) ((struct pn53x_usb_data*)(pnd->driver_data))
62 
63 typedef enum {
64   UNKNOWN,
65   NXP_PN531,
66   SONY_PN531,
67   NXP_PN533,
68   ASK_LOGO,
69   SCM_SCL3711,
70   SONY_RCS360
71 } pn53x_usb_model;
72 
73 // Internal data struct
74 struct pn53x_usb_data {
75   usb_dev_handle *pudh;
76   pn53x_usb_model model;
77   uint32_t uiEndPointIn;
78   uint32_t uiEndPointOut;
79   uint32_t uiMaxPacketSize;
80   volatile bool abort_flag;
81 };
82 
83 // Internal io struct
84 const struct pn53x_io pn53x_usb_io;
85 
86 // Prototypes
87 bool pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len);
88 int pn53x_usb_init(nfc_device *pnd);
89 
90 static int
pn53x_usb_bulk_read(struct pn53x_usb_data * data,uint8_t abtRx[],const size_t szRx,const int timeout)91 pn53x_usb_bulk_read(struct pn53x_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout)
92 {
93   int res = usb_bulk_read(data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout);
94   if (res > 0) {
95     LOG_HEX(NFC_LOG_GROUP_COM, "RX", abtRx, res);
96   } else if (res < 0) {
97     if (res != -USB_TIMEDOUT)
98       log_put(NFC_LOG_GROUP_COM, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror(res));
99   }
100   return res;
101 }
102 
103 static int
pn53x_usb_bulk_write(struct pn53x_usb_data * data,uint8_t abtTx[],const size_t szTx,const int timeout)104 pn53x_usb_bulk_write(struct pn53x_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout)
105 {
106   LOG_HEX(NFC_LOG_GROUP_COM, "TX", abtTx, szTx);
107   int res = usb_bulk_write(data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout);
108   if (res > 0) {
109     // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details
110     if ((res % data->uiMaxPacketSize) == 0) {
111       usb_bulk_write(data->pudh, data->uiEndPointOut, "\0", 0, timeout);
112     }
113   } else {
114     log_put(NFC_LOG_GROUP_COM, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror(res));
115   }
116   return res;
117 }
118 
119 struct pn53x_usb_supported_device {
120   uint16_t vendor_id;
121   uint16_t product_id;
122   pn53x_usb_model model;
123   const char *name;
124 };
125 
126 const struct pn53x_usb_supported_device pn53x_usb_supported_devices[] = {
127   { 0x04CC, 0x0531, NXP_PN531,   "Philips / PN531" },
128   { 0x04CC, 0x2533, NXP_PN533,   "NXP / PN533" },
129   { 0x04E6, 0x5591, SCM_SCL3711, "SCM Micro / SCL3711-NFC&RW" },
130   { 0x054c, 0x0193, SONY_PN531,  "Sony / PN531" },
131   { 0x1FD3, 0x0608, ASK_LOGO,    "ASK / LoGO" },
132   { 0x054C, 0x02E1, SONY_RCS360, "Sony / FeliCa S360 [PaSoRi]" }
133 };
134 
135 static pn53x_usb_model
pn53x_usb_get_device_model(uint16_t vendor_id,uint16_t product_id)136 pn53x_usb_get_device_model(uint16_t vendor_id, uint16_t product_id)
137 {
138   for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) {
139     if ((vendor_id == pn53x_usb_supported_devices[n].vendor_id) &&
140         (product_id == pn53x_usb_supported_devices[n].product_id))
141       return pn53x_usb_supported_devices[n].model;
142   }
143 
144   return UNKNOWN;
145 }
146 
147 int  pn53x_usb_ack(nfc_device *pnd);
148 
149 // Find transfer endpoints for bulk transfers
150 static void
pn53x_usb_get_end_points(struct usb_device * dev,struct pn53x_usb_data * data)151 pn53x_usb_get_end_points(struct usb_device *dev, struct pn53x_usb_data *data)
152 {
153   uint32_t uiIndex;
154   uint32_t uiEndPoint;
155   struct usb_interface_descriptor *puid = dev->config->interface->altsetting;
156 
157   // 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out
158   for (uiIndex = 0; uiIndex < puid->bNumEndpoints; uiIndex++) {
159     // Only accept bulk transfer endpoints (ignore interrupt endpoints)
160     if (puid->endpoint[uiIndex].bmAttributes != USB_ENDPOINT_TYPE_BULK)
161       continue;
162 
163     // Copy the endpoint to a local var, makes it more readable code
164     uiEndPoint = puid->endpoint[uiIndex].bEndpointAddress;
165 
166     // Test if we dealing with a bulk IN endpoint
167     if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_IN) {
168       data->uiEndPointIn = uiEndPoint;
169       data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize;
170     }
171     // Test if we dealing with a bulk OUT endpoint
172     if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_OUT) {
173       data->uiEndPointOut = uiEndPoint;
174       data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize;
175     }
176   }
177 }
178 
179 static size_t
pn53x_usb_scan(const nfc_context * context,nfc_connstring connstrings[],const size_t connstrings_len)180 pn53x_usb_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len)
181 {
182   (void)context;
183 
184   usb_prepare();
185 
186   size_t device_found = 0;
187   uint32_t uiBusIndex = 0;
188   struct usb_bus *bus;
189   for (bus = usb_get_busses(); bus; bus = bus->next) {
190     struct usb_device *dev;
191 
192     for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) {
193       for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) {
194         if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) &&
195             (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) {
196           // Make sure there are 2 endpoints available
197           // with libusb-win32 we got some null pointers so be robust before looking at endpoints:
198           if (dev->config == NULL || dev->config->interface == NULL || dev->config->interface->altsetting == NULL) {
199             // Nope, we maybe want the next one, let's try to find another
200             continue;
201           }
202           if (dev->config->interface->altsetting->bNumEndpoints < 2) {
203             // Nope, we maybe want the next one, let's try to find another
204             continue;
205           }
206 
207           usb_dev_handle *udev = usb_open(dev);
208           if (udev == NULL)
209             continue;
210 
211           // Set configuration
212           int res = usb_set_configuration(udev, 1);
213           if (res < 0) {
214             log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res));
215             usb_close(udev);
216             // we failed to use the device
217             continue;
218           }
219 
220           // pn53x_usb_get_usb_device_name (dev, udev, pnddDevices[device_found].acDevice, sizeof (pnddDevices[device_found].acDevice));
221           log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "device found: Bus %s Device %s", bus->dirname, dev->filename);
222           usb_close(udev);
223           snprintf(connstrings[device_found], sizeof(nfc_connstring), "%s:%s:%s", PN53X_USB_DRIVER_NAME, bus->dirname, dev->filename);
224           device_found++;
225           // Test if we reach the maximum "wanted" devices
226           if (device_found == connstrings_len) {
227             return device_found;
228           }
229         }
230       }
231     }
232   }
233 
234   return device_found;
235 }
236 
237 struct pn53x_usb_descriptor {
238   char *dirname;
239   char *filename;
240 };
241 
242 bool
pn53x_usb_get_usb_device_name(struct usb_device * dev,usb_dev_handle * udev,char * buffer,size_t len)243 pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len)
244 {
245   *buffer = '\0';
246 
247   if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) {
248     if (udev) {
249       usb_get_string_simple(udev, dev->descriptor.iManufacturer, buffer, len);
250       if (strlen(buffer) > 0)
251         strcpy(buffer + strlen(buffer), " / ");
252       usb_get_string_simple(udev, dev->descriptor.iProduct, buffer + strlen(buffer), len - strlen(buffer));
253     }
254   }
255 
256   if (!*buffer) {
257     for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) {
258       if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) &&
259           (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) {
260         strncpy(buffer, pn53x_usb_supported_devices[n].name, len);
261         buffer[len - 1] = '\0';
262         return true;
263       }
264     }
265   }
266 
267   return false;
268 }
269 
270 static nfc_device *
pn53x_usb_open(const nfc_context * context,const nfc_connstring connstring)271 pn53x_usb_open(const nfc_context *context, const nfc_connstring connstring)
272 {
273   nfc_device *pnd = NULL;
274   struct pn53x_usb_descriptor desc = { NULL, NULL };
275   int connstring_decode_level = connstring_decode(connstring, PN53X_USB_DRIVER_NAME, "usb", &desc.dirname, &desc.filename);
276   log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring);
277   if (connstring_decode_level < 1) {
278     goto free_mem;
279   }
280 
281   struct pn53x_usb_data data = {
282     .pudh = NULL,
283     .uiEndPointIn = 0,
284     .uiEndPointOut = 0,
285   };
286   struct usb_bus *bus;
287   struct usb_device *dev;
288 
289   usb_prepare();
290 
291   for (bus = usb_get_busses(); bus; bus = bus->next) {
292     if (connstring_decode_level > 1)  {
293       // A specific bus have been specified
294       if (0 != strcmp(bus->dirname, desc.dirname))
295         continue;
296     }
297     for (dev = bus->devices; dev; dev = dev->next) {
298       if (connstring_decode_level > 2)  {
299         // A specific dev have been specified
300         if (0 != strcmp(dev->filename, desc.filename))
301           continue;
302       }
303       // Open the USB device
304       if ((data.pudh = usb_open(dev)) == NULL)
305         continue;
306       // Retrieve end points
307       pn53x_usb_get_end_points(dev, &data);
308       // Set configuration
309       int res = usb_set_configuration(data.pudh, 1);
310       if (res < 0) {
311         log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res));
312         if (EPERM == -res) {
313           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);
314         }
315         usb_close(data.pudh);
316         // we failed to use the specified device
317         goto free_mem;
318       }
319 
320       res = usb_claim_interface(data.pudh, 0);
321       if (res < 0) {
322         log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror(res));
323         usb_close(data.pudh);
324         // we failed to use the specified device
325         goto free_mem;
326       }
327       data.model = pn53x_usb_get_device_model(dev->descriptor.idVendor, dev->descriptor.idProduct);
328       // Allocate memory for the device info and specification, fill it and return the info
329       pnd = nfc_device_new(context, connstring);
330       if (!pnd) {
331         perror("malloc");
332         goto error;
333       }
334       pn53x_usb_get_usb_device_name(dev, data.pudh, pnd->name, sizeof(pnd->name));
335 
336       pnd->driver_data = malloc(sizeof(struct pn53x_usb_data));
337       if (!pnd->driver_data) {
338         perror("malloc");
339         goto error;
340       }
341       *DRIVER_DATA(pnd) = data;
342 
343       // Alloc and init chip's data
344       if (pn53x_data_new(pnd, &pn53x_usb_io) == NULL) {
345         perror("malloc");
346         goto error;
347       }
348 
349       switch (DRIVER_DATA(pnd)->model) {
350           // empirical tuning
351         case ASK_LOGO:
352           CHIP_DATA(pnd)->timer_correction = 50;
353           break;
354         case SCM_SCL3711:
355         case NXP_PN533:
356           CHIP_DATA(pnd)->timer_correction = 46;
357           break;
358         case NXP_PN531:
359           CHIP_DATA(pnd)->timer_correction = 50;
360           break;
361         case SONY_PN531:
362           CHIP_DATA(pnd)->timer_correction = 54;
363           break;
364         case SONY_RCS360:
365         case UNKNOWN:
366           CHIP_DATA(pnd)->timer_correction = 0;   // TODO: allow user to know if timed functions are available
367           break;
368       }
369       pnd->driver = &pn53x_usb_driver;
370 
371       // HACK1: Send first an ACK as Abort command, to reset chip before talking to it:
372       pn53x_usb_ack(pnd);
373 
374       // HACK2: Then send a GetFirmware command to resync USB toggle bit between host & device
375       // in case host used set_configuration and expects the device to have reset its toggle bit, which PN53x doesn't do
376       if (pn53x_usb_init(pnd) < 0) {
377         usb_close(data.pudh);
378         goto error;
379       }
380       DRIVER_DATA(pnd)->abort_flag = false;
381       goto free_mem;
382     }
383   }
384   // We ran out of devices before the index required
385   goto free_mem;
386 
387 error:
388   // Free allocated structure on error.
389   nfc_device_free(pnd);
390   pnd = NULL;
391 free_mem:
392   free(desc.dirname);
393   free(desc.filename);
394   return pnd;
395 }
396 
397 static void
pn53x_usb_close(nfc_device * pnd)398 pn53x_usb_close(nfc_device *pnd)
399 {
400   pn53x_usb_ack(pnd);
401 
402   if (DRIVER_DATA(pnd)->model == ASK_LOGO) {
403     /* Set P30, P31, P32, P33, P35 to logic 1 and P34 to 0 logic */
404     /* ie. Switch all LEDs off and turn off progressive field */
405     pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P32) | _BV(P33) | _BV(P35));
406   }
407 
408   pn53x_idle(pnd);
409 
410   int res;
411   if ((res = usb_release_interface(DRIVER_DATA(pnd)->pudh, 0)) < 0) {
412     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror(res));
413   }
414 
415   if ((res = usb_close(DRIVER_DATA(pnd)->pudh)) < 0) {
416     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror(res));
417   }
418   pn53x_data_free(pnd);
419   nfc_device_free(pnd);
420 }
421 
422 #define PN53X_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD)
423 
424 static int
pn53x_usb_send(nfc_device * pnd,const uint8_t * pbtData,const size_t szData,const int timeout)425 pn53x_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout)
426 {
427   uint8_t  abtFrame[PN53X_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff };  // Every packet must start with "00 00 ff"
428   size_t szFrame = 0;
429   int res = 0;
430 
431   if ((res = pn53x_build_frame(abtFrame, &szFrame, pbtData, szData)) < 0) {
432     pnd->last_error = res;
433     return pnd->last_error;
434   }
435 
436   if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), abtFrame, szFrame, timeout)) < 0) {
437     pnd->last_error = res;
438     return pnd->last_error;
439   }
440 
441   uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN];
442   if ((res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), timeout)) < 0) {
443     // try to interrupt current device state
444     pn53x_usb_ack(pnd);
445     pnd->last_error = res;
446     return pnd->last_error;
447   }
448 
449   if (pn53x_check_ack_frame(pnd, abtRxBuf, res) == 0) {
450     // The PN53x is running the sent command
451   } else {
452     // For some reasons (eg. send another command while a previous one is
453     // running), the PN533 sometimes directly replies the response packet
454     // instead of ACK frame, so we send a NACK frame to force PN533 to resend
455     // response packet. With this hack, the nextly executed function (ie.
456     // pn53x_usb_receive()) will be able to retreive the correct response
457     // packet.
458     // FIXME Sony reader is also affected by this bug but NACK is not supported
459     if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout)) < 0) {
460       pnd->last_error = res;
461       // try to interrupt current device state
462       pn53x_usb_ack(pnd);
463       return pnd->last_error;
464     }
465   }
466 
467   return NFC_SUCCESS;
468 }
469 
470 #define USB_TIMEOUT_PER_PASS 200
471 static int
pn53x_usb_receive(nfc_device * pnd,uint8_t * pbtData,const size_t szDataLen,const int timeout)472 pn53x_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout)
473 {
474   size_t len;
475   off_t offset = 0;
476 
477   uint8_t  abtRxBuf[PN53X_USB_BUFFER_LEN];
478   int res;
479 
480   /*
481    * If no timeout is specified but the command is blocking, force a 200ms (USB_TIMEOUT_PER_PASS)
482    * timeout to allow breaking the loop if the user wants to stop it.
483    */
484   int usb_timeout;
485   int remaining_time = timeout;
486 read:
487   if (timeout == USB_INFINITE_TIMEOUT) {
488     usb_timeout = USB_TIMEOUT_PER_PASS;
489   } else {
490     // A user-provided timeout is set, we have to cut it in multiple chunk to be able to keep an nfc_abort_command() mecanism
491     remaining_time -= USB_TIMEOUT_PER_PASS;
492     if (remaining_time <= 0) {
493       pnd->last_error = NFC_ETIMEOUT;
494       return pnd->last_error;
495     } else {
496       usb_timeout = MIN(remaining_time, USB_TIMEOUT_PER_PASS);
497     }
498   }
499 
500   res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), usb_timeout);
501 
502   if (res == -USB_TIMEDOUT) {
503     if (DRIVER_DATA(pnd)->abort_flag) {
504       DRIVER_DATA(pnd)->abort_flag = false;
505       pn53x_usb_ack(pnd);
506       pnd->last_error = NFC_EOPABORTED;
507       return pnd->last_error;
508     } else {
509       goto read;
510     }
511   }
512 
513   if (res < 0) {
514     // try to interrupt current device state
515     pn53x_usb_ack(pnd);
516     pnd->last_error = res;
517     return pnd->last_error;
518   }
519 
520   const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff };
521   if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) {
522     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch");
523     pnd->last_error = NFC_EIO;
524     return pnd->last_error;
525   }
526   offset += 3;
527 
528   if ((0x01 == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) {
529     // Error frame
530     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected");
531     pnd->last_error = NFC_EIO;
532     return pnd->last_error;
533   } else if ((0xff == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) {
534     // Extended frame
535     offset += 2;
536 
537     // (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] (LEN) include TFI + (CC+1)
538     len = (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] - 2;
539     if (((abtRxBuf[offset] + abtRxBuf[offset + 1] + abtRxBuf[offset + 2]) % 256) != 0) {
540       // TODO: Retry
541       log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch");
542       pnd->last_error = NFC_EIO;
543       return pnd->last_error;
544     }
545     offset += 3;
546   } else {
547     // Normal frame
548     if (256 != (abtRxBuf[offset] + abtRxBuf[offset + 1])) {
549       // TODO: Retry
550       log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch");
551       pnd->last_error = NFC_EIO;
552       return pnd->last_error;
553     }
554 
555     // abtRxBuf[3] (LEN) include TFI + (CC+1)
556     len = abtRxBuf[offset] - 2;
557     offset += 2;
558   }
559 
560   if (len > szDataLen) {
561     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len);
562     pnd->last_error = NFC_EIO;
563     return pnd->last_error;
564   }
565 
566   // TFI + PD0 (CC+1)
567   if (abtRxBuf[offset] != 0xD5) {
568     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch");
569     pnd->last_error = NFC_EIO;
570     return pnd->last_error;
571   }
572   offset += 1;
573 
574   if (abtRxBuf[offset] != CHIP_DATA(pnd)->last_command + 1) {
575     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed");
576     pnd->last_error = NFC_EIO;
577     return pnd->last_error;
578   }
579   offset += 1;
580 
581   memcpy(pbtData, abtRxBuf + offset, len);
582   offset += len;
583 
584   uint8_t btDCS = (256 - 0xD5);
585   btDCS -= CHIP_DATA(pnd)->last_command + 1;
586   for (size_t szPos = 0; szPos < len; szPos++) {
587     btDCS -= pbtData[szPos];
588   }
589 
590   if (btDCS != abtRxBuf[offset]) {
591     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch");
592     pnd->last_error = NFC_EIO;
593     return pnd->last_error;
594   }
595   offset += 1;
596 
597   if (0x00 != abtRxBuf[offset]) {
598     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch");
599     pnd->last_error = NFC_EIO;
600     return pnd->last_error;
601   }
602   // The PN53x command is done and we successfully received the reply
603   pnd->last_error = 0;
604   return len;
605 }
606 
607 int
pn53x_usb_ack(nfc_device * pnd)608 pn53x_usb_ack(nfc_device *pnd)
609 {
610   return pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *) pn53x_ack_frame, sizeof(pn53x_ack_frame), 1000);
611 }
612 
613 int
pn53x_usb_init(nfc_device * pnd)614 pn53x_usb_init(nfc_device *pnd)
615 {
616   int res = 0;
617   // Sometimes PN53x USB doesn't reply ACK one the first frame, so we need to send a dummy one...
618   //pn53x_check_communication (pnd); // Sony RC-S360 doesn't support this command for now so let's use a get_firmware_version instead:
619   const uint8_t abtCmd[] = { GetFirmwareVersion };
620   pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1);
621   // ...and we don't care about error
622   pnd->last_error = 0;
623   if (SONY_RCS360 == DRIVER_DATA(pnd)->model) {
624     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "SONY RC-S360 initialization.");
625     const uint8_t abtCmd2[] = { 0x18, 0x01 };
626     pn53x_transceive(pnd, abtCmd2, sizeof(abtCmd2), NULL, 0, -1);
627     pn53x_usb_ack(pnd);
628   }
629 
630   if ((res = pn53x_init(pnd)) < 0)
631     return res;
632 
633   if (ASK_LOGO == DRIVER_DATA(pnd)->model) {
634     log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ASK LoGO initialization.");
635     /* Internal registers */
636     /* Disable 100mA current limit, Power on Secure IC (SVDD) */
637     pn53x_write_register(pnd, PN53X_REG_Control_switch_rng, 0xFF, SYMBOL_CURLIMOFF | SYMBOL_SIC_SWITCH_EN | SYMBOL_RANDOM_DATAREADY);
638     /* Select the signal to be output on SIGOUT: Modulation signal (envelope) from the internal coder */
639     pn53x_write_register(pnd, PN53X_REG_CIU_TxSel, 0xFF, 0x14);
640 
641     /* SFR Registers */
642     /* Setup push-pulls for pins from P30 to P35 */
643     pn53x_write_register(pnd, PN53X_SFR_P3CFGB, 0xFF, 0x37);
644 
645     /*
646     On ASK LoGO hardware:
647       LEDs port bits definition:
648        * LED 1: bit 2 (P32)
649        * LED 2: bit 1 (P31)
650        * LED 3: bit 0 or 3 (depending of hardware revision) (P30 or P33)
651        * LED 4: bit 5 (P35)
652       Notes:
653        * Set logical 0 to switch LED on; logical 1 to switch LED off.
654        * Bit 4 should be maintained at 1 to keep RF field on.
655 
656       Progressive field activation:
657        The ASK LoGO hardware can progressively power-up the antenna.
658        To use this feature we have to switch on the field by switching on
659        the field on PN533 (RFConfiguration) then set P34 to '1', and cut-off the
660        field by switching off the field on PN533 then set P34 to '0'.
661     */
662 
663     /* Set P30, P31, P33, P35 to logic 1 and P32, P34 to 0 logic */
664     /* ie. Switch LED1 on and turn off progressive field */
665     pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P33) | _BV(P35));
666   }
667 
668   return NFC_SUCCESS;
669 }
670 
671 static int
pn53x_usb_set_property_bool(nfc_device * pnd,const nfc_property property,const bool bEnable)672 pn53x_usb_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable)
673 {
674   int res = 0;
675   if ((res = pn53x_set_property_bool(pnd, property, bEnable)) < 0)
676     return res;
677 
678   switch (DRIVER_DATA(pnd)->model) {
679     case ASK_LOGO:
680       if (NP_ACTIVATE_FIELD == property) {
681         /* Switch on/off LED2 and Progressive Field GPIO according to ACTIVATE_FIELD option */
682         log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Switch progressive field %s", bEnable ? "On" : "Off");
683         if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P31) | _BV(P34), bEnable ? _BV(P34) : _BV(P31))) < 0)
684           return NFC_ECHIP;
685       }
686       break;
687     case SCM_SCL3711:
688       if (NP_ACTIVATE_FIELD == property) {
689         // Switch on/off LED according to ACTIVATE_FIELD option
690         if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P32), bEnable ? 0 : _BV(P32))) < 0)
691           return res;
692       }
693       break;
694     case NXP_PN531:
695     case NXP_PN533:
696     case SONY_PN531:
697     case SONY_RCS360:
698     case UNKNOWN:
699       // Nothing to do.
700       break;
701   }
702   return NFC_SUCCESS;
703 }
704 
705 static int
pn53x_usb_abort_command(nfc_device * pnd)706 pn53x_usb_abort_command(nfc_device *pnd)
707 {
708   DRIVER_DATA(pnd)->abort_flag = true;
709   return NFC_SUCCESS;
710 }
711 
712 const struct pn53x_io pn53x_usb_io = {
713   .send       = pn53x_usb_send,
714   .receive    = pn53x_usb_receive,
715 };
716 
717 const struct nfc_driver pn53x_usb_driver = {
718   .name                             = PN53X_USB_DRIVER_NAME,
719   .scan_type                        = NOT_INTRUSIVE,
720   .scan                             = pn53x_usb_scan,
721   .open                             = pn53x_usb_open,
722   .close                            = pn53x_usb_close,
723   .strerror                         = pn53x_strerror,
724 
725   .initiator_init                   = pn53x_initiator_init,
726   .initiator_init_secure_element    = NULL, // No secure-element support
727   .initiator_select_passive_target  = pn53x_initiator_select_passive_target,
728   .initiator_poll_target            = pn53x_initiator_poll_target,
729   .initiator_select_dep_target      = pn53x_initiator_select_dep_target,
730   .initiator_deselect_target        = pn53x_initiator_deselect_target,
731   .initiator_transceive_bytes       = pn53x_initiator_transceive_bytes,
732   .initiator_transceive_bits        = pn53x_initiator_transceive_bits,
733   .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed,
734   .initiator_transceive_bits_timed  = pn53x_initiator_transceive_bits_timed,
735   .initiator_target_is_present      = pn53x_initiator_target_is_present,
736 
737   .target_init           = pn53x_target_init,
738   .target_send_bytes     = pn53x_target_send_bytes,
739   .target_receive_bytes  = pn53x_target_receive_bytes,
740   .target_send_bits      = pn53x_target_send_bits,
741   .target_receive_bits   = pn53x_target_receive_bits,
742 
743   .device_set_property_bool     = pn53x_usb_set_property_bool,
744   .device_set_property_int      = pn53x_set_property_int,
745   .get_supported_modulation     = pn53x_get_supported_modulation,
746   .get_supported_baud_rate      = pn53x_get_supported_baud_rate,
747   .device_get_information_about = pn53x_get_information_about,
748 
749   .abort_command  = pn53x_usb_abort_command,
750   .idle           = pn53x_idle,
751   .powerdown      = pn53x_PowerDown,
752 };
753