• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*****************************************************************************
2  * Copyright (C) 2015 ST Microelectronics S.A.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *******************************************************************************/
16 
17 /******************************************************************************
18  *
19  *  This file contains the implementation for Mifare Classic tag in
20  *  Reader/Writer mode.
21  *
22  ******************************************************************************/
23 #include <android-base/stringprintf.h>
24 #include <base/logging.h>
25 #include <string.h>
26 #include "bt_types.h"
27 #include "nfc_target.h"
28 
29 #include "gki.h"
30 #include "nfc_api.h"
31 #include "nfc_int.h"
32 #include "rw_api.h"
33 #include "rw_int.h"
34 #include "tags_int.h"
35 
36 #define MFC_KeyA 0x60
37 #define MFC_KeyB 0x61
38 #define MFC_Read 0x30
39 #define MFC_Write 0xA0
40 
41 /* main state */
42 /* Mifare Classic is not activated */
43 #define RW_MFC_STATE_NOT_ACTIVATED 0x00
44 /* waiting for upper layer API */
45 #define RW_MFC_STATE_IDLE 0x01
46 /* performing NDEF detection precedure */
47 #define RW_MFC_STATE_DETECT_NDEF 0x02
48 /* performing read NDEF procedure */
49 #define RW_MFC_STATE_READ_NDEF 0x03
50 /* performing update NDEF procedure */
51 #define RW_MFC_STATE_UPDATE_NDEF 0x04
52 /* checking presence of tag */
53 #define RW_MFC_STATE_PRESENCE_CHECK 0x05
54 /* convert tag to read only */
55 #define RW_MFC_STATE_SET_READ_ONLY 0x06
56 /* detect tlv */
57 #define RW_MFC_STATE_DETECT_TLV 0x7
58 /* NDef Format */
59 #define RW_MFC_STATE_NDEF_FORMAT 0x8
60 
61 #define RW_MFC_SUBSTATE_NONE 0x00
62 #define RW_MFC_SUBSTATE_IDLE 0x01
63 #define RW_MFC_SUBSTATE_WAIT_ACK 0x02
64 #define RW_MFC_SUBSTATE_READ_BLOCK 0x03
65 #define RW_MFC_SUBSTATE_FORMAT_BLOCK 0x04
66 #define RW_MFC_SUBSTATE_WRITE_BLOCK 0x05
67 
68 #define RW_MFC_LONG_TLV_SIZE 4
69 #define RW_MFC_SHORT_TLV_SIZE 2
70 
71 #define RW_MFC_4K_Support 0x10
72 
73 #define RW_MFC_1K_BLOCK_SIZE 16
74 
75 uint8_t KeyNDEF[6] = {0xD3, 0XF7, 0xD3, 0XF7, 0xD3, 0XF7};
76 uint8_t KeyMAD[6] = {0xA0, 0XA1, 0xA2, 0XA3, 0xA4, 0XA5};
77 uint8_t KeyDefault[6] = {0xFF, 0XFF, 0xFF, 0XFF, 0xFF, 0XFF};
78 uint8_t access_permission_nfc[4] = {0x7F, 0x07, 0x88, 0x40};
79 uint8_t access_permission_mad[4] = {0x78, 0x77, 0x88, 0xC1};
80 uint8_t MAD_B1[16] = {0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1,
81                       0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1};
82 uint8_t MAD_B2[16] = {0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1,
83                       0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1};
84 uint8_t MAD_B64[16] = {0xE8, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1,
85                        0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1};
86 uint8_t NFC_B0[16] = {0x03, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
87                       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
88 
89 static bool rw_mfc_send_to_lower(NFC_HDR* p_c_apdu);
90 static bool rw_mfc_authenticate(int sector, bool KeyA);
91 static tNFC_STATUS rw_mfc_readBlock(int block);
92 static void rw_mfc_handle_tlv_detect_rsp(uint8_t* p_data);
93 static tNFC_STATUS rw_MfcLocateTlv(uint8_t tlv_type);
94 static void rw_mfc_conn_cback(uint8_t conn_id, tNFC_CONN_EVT event,
95                               tNFC_CONN* p_data);
96 static void rw_mfc_resume_op();
97 static bool rw_nfc_decodeTlv(uint8_t* p_data);
98 static void rw_mfc_ntf_tlv_detect_complete(tNFC_STATUS status);
99 static void rw_mfc_handle_read_op(uint8_t* data);
100 static void rw_mfc_handle_op_complete(void);
101 static void rw_mfc_handle_ndef_read_rsp(uint8_t* p_data);
102 static void rw_mfc_process_error();
103 
104 static tNFC_STATUS rw_mfc_formatBlock(int block);
105 static void rw_mfc_handle_format_rsp(uint8_t* p_data);
106 static void rw_mfc_handle_format_op();
107 static tNFC_STATUS rw_mfc_writeBlock(int block);
108 static void rw_mfc_handle_write_rsp(uint8_t* p_data);
109 static void rw_mfc_handle_write_op();
110 
111 using android::base::StringPrintf;
112 extern bool nfc_debug_enabled;
113 
114 /*****************************************************************************
115 **
116 ** Function         RW_MfcFormatNDef
117 **
118 ** Description
119 **      Format Tag content
120 **
121 ** Returns
122 **      NFC_STATUS_OK, Command sent to format Tag
123 **      NFC_STATUS_REJECTED: cannot format the tag
124 **      NFC_STATUS_FAILED: other error
125 **
126 *****************************************************************************/
RW_MfcFormatNDef(void)127 tNFC_STATUS RW_MfcFormatNDef(void) {
128   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
129   tNFC_STATUS status = NFC_STATUS_OK;
130 
131   if (p_mfc->state != RW_MFC_STATE_IDLE) {
132     LOG(ERROR) << __func__
133                << " Mifare Classic tag not activated or Busy - State:"
134                << p_mfc->state;
135     return NFC_STATUS_BUSY;
136   }
137 
138   p_mfc->state = RW_MFC_STATE_NDEF_FORMAT;
139   p_mfc->substate = RW_MFC_SUBSTATE_NONE;
140   p_mfc->last_block_accessed.block = 1;
141   p_mfc->next_block.block = 1;
142 
143   status = rw_mfc_formatBlock(p_mfc->next_block.block);
144   if (status == NFC_STATUS_OK) {
145     p_mfc->state = RW_MFC_STATE_NDEF_FORMAT;
146   } else {
147     p_mfc->substate = RW_MFC_SUBSTATE_NONE;
148   }
149 
150   return status;
151 }
152 
153 /*******************************************************************************
154  **
155  ** Function         rw_mfc_formatBlock
156  **
157  ** Description      This function format a given block.
158  **
159  ** Returns          true if success
160  **
161  *******************************************************************************/
rw_mfc_formatBlock(int block)162 static tNFC_STATUS rw_mfc_formatBlock(int block) {
163   NFC_HDR* mfcbuf;
164   uint8_t* p;
165   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
166   int sectorlength = block / 4;
167   tNFC_STATUS status = NFC_STATUS_OK;
168 
169   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": block : " << block;
170 
171   if (block > 128) {
172     sectorlength = (p_mfc->next_block.block - 128) / 16 + 32;
173   }
174 
175   if (sectorlength != p_mfc->sector_authentified) {
176     if (rw_mfc_authenticate(block, true) == true) {
177       return NFC_STATUS_OK;
178     }
179     return NFC_STATUS_FAILED;
180   }
181 
182   mfcbuf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
183 
184   if (!mfcbuf) {
185     LOG(ERROR) << __func__ << ": Cannot allocate buffer";
186     return NFC_STATUS_REJECTED;
187   }
188 
189   mfcbuf->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE;
190   p = (uint8_t*)(mfcbuf + 1) + mfcbuf->offset;
191 
192   UINT8_TO_BE_STREAM(p, MFC_Write);
193   UINT8_TO_BE_STREAM(p, block);
194 
195   if (block == 1) {
196     ARRAY_TO_BE_STREAM(p, MAD_B1, 16);
197   } else if (block == 2 || block == 65 || block == 66) {
198     ARRAY_TO_BE_STREAM(p, MAD_B2, 16);
199   } else if (block == 3 || block == 67) {
200     ARRAY_TO_BE_STREAM(p, KeyMAD, 6);
201     ARRAY_TO_BE_STREAM(p, access_permission_mad, 4);
202     ARRAY_TO_BE_STREAM(p, KeyDefault, 6);
203   } else if (block == 4) {
204     ARRAY_TO_BE_STREAM(p, NFC_B0, 16);
205   } else if (block == 64) {
206     ARRAY_TO_BE_STREAM(p, MAD_B64, 16);
207   } else {
208     ARRAY_TO_BE_STREAM(p, KeyNDEF, 6);
209     ARRAY_TO_BE_STREAM(p, access_permission_nfc, 4);
210     ARRAY_TO_BE_STREAM(p, KeyDefault, 6);
211   }
212   mfcbuf->len = 18;
213 
214   if (!rw_mfc_send_to_lower(mfcbuf)) {
215     return NFC_STATUS_REJECTED;
216   }
217   p_mfc->current_block = block;
218   p_mfc->substate = RW_MFC_SUBSTATE_FORMAT_BLOCK;
219 
220   return status;
221 }
222 
rw_mfc_handle_format_rsp(uint8_t * p_data)223 static void rw_mfc_handle_format_rsp(uint8_t* p_data) {
224   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
225   NFC_HDR* mfc_data;
226   uint8_t* p;
227 
228   mfc_data = (NFC_HDR*)p_data;
229   /* Assume the data is just the response byte sequence */
230   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
231 
232   switch (p_mfc->substate) {
233     case RW_MFC_SUBSTATE_WAIT_ACK:
234       p_mfc->last_block_accessed.block = p_mfc->current_block;
235 
236       if (p[0] == 0x0) {
237         p_mfc->next_block.auth = true;
238         p_mfc->last_block_accessed.auth = true;
239 
240         if (p_mfc->next_block.block < 128) {
241           p_mfc->sector_authentified = p_mfc->next_block.block / 4;
242         } else {
243           p_mfc->sector_authentified =
244               (p_mfc->next_block.block - 128) / 16 + 32;
245         }
246         rw_mfc_resume_op();
247       } else {
248         p_mfc->next_block.auth = false;
249         p_mfc->last_block_accessed.auth = false;
250         nfc_stop_quick_timer(&p_mfc->timer);
251         rw_mfc_process_error();
252       }
253       break;
254 
255     case RW_MFC_SUBSTATE_FORMAT_BLOCK:
256       if (p[0] == 0x0) {
257         rw_mfc_handle_format_op();
258       } else {
259         nfc_stop_quick_timer(&p_mfc->timer);
260         rw_mfc_process_error();
261       }
262       break;
263   }
264 }
265 
rw_mfc_handle_format_op()266 static void rw_mfc_handle_format_op() {
267   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
268   tRW_READ_DATA evt_data;
269   int num_of_blocks = 0;
270 
271   /* Total blockes of Mifare 1k/4K */
272   if (p_mfc->selres & RW_MFC_4K_Support)
273     num_of_blocks = 256;
274   else
275     num_of_blocks = 64;
276 
277   p_mfc->last_block_accessed.block = p_mfc->current_block;
278 
279   // Find next block needed to format
280   if (p_mfc->current_block < 4) {
281     p_mfc->next_block.block = p_mfc->current_block + 1;
282   } else if (p_mfc->current_block == 4) {
283     p_mfc->next_block.block = 7;
284   } else if (p_mfc->current_block >= 63 && p_mfc->current_block < 67) {
285     p_mfc->next_block.block = p_mfc->current_block + 1;
286   } else if (p_mfc->current_block < 127) {
287     p_mfc->next_block.block = p_mfc->current_block + 4;
288   } else {
289     p_mfc->next_block.block = p_mfc->current_block + 16;
290   }
291 
292   if (p_mfc->next_block.block < num_of_blocks) {
293     /* Format next blocks */
294     if (rw_mfc_formatBlock(p_mfc->next_block.block) != NFC_STATUS_OK) {
295       evt_data.status = NFC_STATUS_FAILED;
296       evt_data.p_data = NULL;
297       (*rw_cb.p_cback)(RW_MFC_NDEF_FORMAT_CPLT_EVT, (tRW_DATA*)&evt_data);
298     }
299   } else {
300     evt_data.status = NFC_STATUS_OK;
301     evt_data.p_data = NULL;
302     rw_mfc_handle_op_complete();
303     (*rw_cb.p_cback)(RW_MFC_NDEF_FORMAT_CPLT_EVT, (tRW_DATA*)&evt_data);
304   }
305 }
306 
307 /*******************************************************************************
308 **
309 ** Function         RW_MfcWriteNDef
310 **
311 ** Description      This function can be called to write an NDEF message to the
312 **                  tag.
313 **
314 ** Parameters:      buf_len:    The length of the buffer
315 **                  p_buffer:   The NDEF message to write
316 **
317 ** Returns          NCI_STATUS_OK, if write was started. Otherwise, error
318 **                  status.
319 **
320 *******************************************************************************/
RW_MfcWriteNDef(uint16_t buf_len,uint8_t * p_buffer)321 tNFC_STATUS RW_MfcWriteNDef(uint16_t buf_len, uint8_t* p_buffer) {
322   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
323   tNFC_STATUS status = NFC_STATUS_OK;
324 
325   if (p_mfc->state != RW_MFC_STATE_IDLE) {
326     return NFC_STATUS_BUSY;
327   }
328 
329   p_mfc->state = RW_MFC_STATE_UPDATE_NDEF;
330   p_mfc->substate = RW_MFC_SUBSTATE_NONE;
331   p_mfc->last_block_accessed.block = 4;
332   p_mfc->next_block.block = 4;
333 
334   p_mfc->p_ndef_buffer = p_buffer;
335   p_mfc->ndef_length = buf_len;
336   p_mfc->work_offset = 0;
337 
338   status = rw_mfc_writeBlock(p_mfc->next_block.block);
339   if (status == NFC_STATUS_OK) {
340     p_mfc->state = RW_MFC_STATE_UPDATE_NDEF;
341   } else {
342     p_mfc->substate = RW_MFC_SUBSTATE_NONE;
343   }
344 
345   return status;
346 }
347 
348 /*******************************************************************************
349  **
350  ** Function         rw_mfc_writeBlock
351  **
352  ** Description      This function write a given block.
353  **
354  ** Returns          true if success
355  **
356  *******************************************************************************/
rw_mfc_writeBlock(int block)357 static tNFC_STATUS rw_mfc_writeBlock(int block) {
358   NFC_HDR* mfcbuf;
359   uint8_t* p;
360   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
361   int sectorlength = block / 4;
362   tNFC_STATUS status = NFC_STATUS_OK;
363 
364   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": block : " << block;
365 
366   if (block > 128) {
367     sectorlength = (p_mfc->next_block.block - 128) / 16 + 32;
368   }
369 
370   if (sectorlength != p_mfc->sector_authentified) {
371     if (rw_mfc_authenticate(block, true) == true) {
372       return NFC_STATUS_OK;
373     }
374     return NFC_STATUS_FAILED;
375   }
376 
377   mfcbuf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
378 
379   if (!mfcbuf) {
380     LOG(ERROR) << __func__ << ": Cannot allocate buffer";
381     return NFC_STATUS_REJECTED;
382   }
383 
384   mfcbuf->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE;
385   p = (uint8_t*)(mfcbuf + 1) + mfcbuf->offset;
386 
387   UINT8_TO_BE_STREAM(p, MFC_Write);
388   UINT8_TO_BE_STREAM(p, block);
389   int index = 0;
390   while (index < RW_MFC_1K_BLOCK_SIZE) {
391     if (p_mfc->work_offset == 0) {
392       if (p_mfc->ndef_length < 0xFF) {
393         UINT8_TO_BE_STREAM(p, 0x03);
394         UINT8_TO_BE_STREAM(p, p_mfc->ndef_length);
395         index = index + 2;
396       } else {
397         UINT8_TO_BE_STREAM(p, 0x03);
398         UINT8_TO_BE_STREAM(p, 0xFF);
399         UINT8_TO_BE_STREAM(p, (uint8_t)(p_mfc->ndef_length >>8));
400         UINT8_TO_BE_STREAM(p, (uint8_t)(p_mfc->ndef_length & 0xFF));
401         index = index + 4;
402       }
403     }
404 
405     if (p_mfc->work_offset == p_mfc->ndef_length) {
406       UINT8_TO_BE_STREAM(p, 0xFE);
407       index = index + 1;
408     }
409 
410     if (p_mfc->work_offset > p_mfc->ndef_length) {
411       UINT8_TO_BE_STREAM(p, 0x00);
412     } else {
413       UINT8_TO_BE_STREAM(p, p_mfc->p_ndef_buffer[p_mfc->work_offset]);
414     }
415     p_mfc->work_offset++;
416     index++;
417   }
418   mfcbuf->len = 18;
419 
420   if (!rw_mfc_send_to_lower(mfcbuf)) {
421     return NFC_STATUS_REJECTED;
422   }
423   p_mfc->current_block = block;
424   p_mfc->substate = RW_MFC_SUBSTATE_WRITE_BLOCK;
425 
426   return status;
427 }
428 
rw_mfc_handle_write_rsp(uint8_t * p_data)429 static void rw_mfc_handle_write_rsp(uint8_t* p_data) {
430   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
431   NFC_HDR* mfc_data;
432   uint8_t* p;
433 
434   mfc_data = (NFC_HDR*)p_data;
435   /* Assume the data is just the response byte sequence */
436   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
437 
438   switch (p_mfc->substate) {
439     case RW_MFC_SUBSTATE_WAIT_ACK:
440       p_mfc->last_block_accessed.block = p_mfc->current_block;
441 
442       if (p[0] == 0x0) {
443         p_mfc->next_block.auth = true;
444         p_mfc->last_block_accessed.auth = true;
445 
446         if (p_mfc->next_block.block < 128) {
447           p_mfc->sector_authentified = p_mfc->next_block.block / 4;
448         } else {
449           p_mfc->sector_authentified =
450               (p_mfc->next_block.block - 128) / 16 + 32;
451         }
452         rw_mfc_resume_op();
453       } else {
454         p_mfc->next_block.auth = false;
455         p_mfc->last_block_accessed.auth = false;
456         nfc_stop_quick_timer(&p_mfc->timer);
457         rw_mfc_process_error();
458       }
459       break;
460 
461     case RW_MFC_SUBSTATE_WRITE_BLOCK:
462       if (p[0] == 0x0) {
463         rw_mfc_handle_write_op();
464       } else {
465         nfc_stop_quick_timer(&p_mfc->timer);
466         rw_mfc_process_error();
467       }
468       break;
469   }
470 }
471 
rw_mfc_handle_write_op()472 static void rw_mfc_handle_write_op() {
473   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
474   tRW_READ_DATA evt_data;
475 
476   if (p_mfc->work_offset >= p_mfc->ndef_length) {
477     evt_data.status = NFC_STATUS_OK;
478     evt_data.p_data = NULL;
479     (*rw_cb.p_cback)(RW_MFC_NDEF_WRITE_CPLT_EVT, (tRW_DATA*)&evt_data);
480   } else {
481     p_mfc->last_block_accessed.block = p_mfc->current_block;
482 
483     if (p_mfc->current_block % 4 == 2) {
484       p_mfc->next_block.block = p_mfc->current_block + 2;
485     } else {
486       p_mfc->next_block.block = p_mfc->current_block + 1;
487     }
488 
489     /* Do not read block 16 (MAD2) - Mifare Classic4 k */
490     if (p_mfc->next_block.block == 64) {
491       p_mfc->next_block.block += 4;
492     }
493 
494     if ((p_mfc->selres & RW_MFC_4K_Support) &&
495         (p_mfc->next_block.block >= 128)) {
496       if (p_mfc->current_block % 16 == 14) {
497         p_mfc->next_block.block = p_mfc->current_block + 2;
498       } else {
499         p_mfc->next_block.block = p_mfc->current_block + 1;
500       }
501     }
502 
503     /* Write next blocks */
504     if (rw_mfc_writeBlock(p_mfc->next_block.block) != NFC_STATUS_OK) {
505       evt_data.status = NFC_STATUS_FAILED;
506       evt_data.p_data = NULL;
507       (*rw_cb.p_cback)(RW_MFC_NDEF_WRITE_FAIL_EVT, (tRW_DATA*)&evt_data);
508     }
509   }
510 }
511 
512 /*****************************************************************************
513  **
514  ** Function         RW_MfcDetectNDef
515  **
516  ** Description
517  **      This function is used to perform NDEF detection on a Mifare Classic
518  **      tag, and retrieve the tag's NDEF attribute information.
519  **      Before using this API, the application must call RW_SelectTagType to
520  **      indicate that a Type 1 tag has been activated.
521  **
522  ** Returns
523  **      NFC_STATUS_OK: ndef detection procedure started
524  **      NFC_STATUS_WRONG_PROTOCOL: type 1 tag not activated
525  **      NFC_STATUS_BUSY: another command is already in progress
526  **      NFC_STATUS_FAILED: other error
527  **
528  *****************************************************************************/
RW_MfcDetectNDef(void)529 tNFC_STATUS RW_MfcDetectNDef(void) {
530   LOG(ERROR) << __func__;
531   return rw_MfcLocateTlv(TAG_NDEF_TLV);
532 }
533 
534 /*******************************************************************************
535  **
536  ** Function         rw_mfc_select
537  **
538  ** Description      This function will set the callback function to
539  **                  receive data from lower layers.
540  **
541  ** Returns          tNFC_STATUS
542  **
543  *******************************************************************************/
rw_mfc_select(uint8_t selres,uint8_t uid[MFC_UID_LEN])544 tNFC_STATUS rw_mfc_select(uint8_t selres, uint8_t uid[MFC_UID_LEN]) {
545   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
546 
547   p_mfc->state = RW_MFC_STATE_NOT_ACTIVATED;
548 
549   /* Alloc cmd buf for retransmissions */
550   if (p_mfc->p_cur_cmd_buf == NULL) {
551     DLOG_IF(INFO, nfc_debug_enabled) << __func__;
552     p_mfc->p_cur_cmd_buf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
553     if (p_mfc->p_cur_cmd_buf == NULL) {
554       LOG(ERROR) << __func__
555                  << ": unable to allocate buffer for retransmission";
556 
557       return NFC_STATUS_FAILED;
558     }
559   }
560   p_mfc->selres = selres;
561   memcpy(p_mfc->uid, uid, MFC_UID_LEN);
562 
563   NFC_SetStaticRfCback(rw_mfc_conn_cback);
564 
565   p_mfc->state = RW_MFC_STATE_IDLE;
566   p_mfc->substate = RW_MFC_SUBSTATE_IDLE;
567   p_mfc->last_block_accessed.block = -1;
568   p_mfc->last_block_accessed.auth = false;
569   p_mfc->next_block.block = 4;
570   p_mfc->next_block.auth = false;
571   p_mfc->sector_authentified = -1;
572 
573   return NFC_STATUS_OK;
574 }
575 
576 /*******************************************************************************
577  **
578  ** Function         rw_mfc_send_to_lower
579  **
580  ** Description      Send C-APDU to lower layer
581  **
582  ** Returns          true if success
583  **
584  *******************************************************************************/
rw_mfc_send_to_lower(NFC_HDR * p_data)585 static bool rw_mfc_send_to_lower(NFC_HDR* p_data) {
586   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
587   /* Indicate first attempt to send command, back up cmd buffer in case needed
588    * for retransmission */
589   rw_cb.cur_retry = 0;
590   memcpy(p_mfc->p_cur_cmd_buf, p_data,
591          sizeof(NFC_HDR) + p_data->offset + p_data->len);
592 
593   if (NFC_SendData(NFC_RF_CONN_ID, p_data) != NFC_STATUS_OK) {
594     LOG(ERROR) << __func__ << ": NFC_SendData () failed";
595     return false;
596   }
597 
598   nfc_start_quick_timer(&rw_cb.tcb.mfc.timer, NFC_TTYPE_RW_MFC_RESPONSE,
599                         (RW_MFC_TOUT_RESP * QUICK_TIMER_TICKS_PER_SEC) / 1000);
600 
601   return true;
602 }
603 
604 /*******************************************************************************
605  **
606  ** Function         rw_mfc_process_timeout
607  **
608  ** Description      handles timeout event
609  **
610  ** Returns          none
611  **
612  *******************************************************************************/
rw_mfc_process_timeout(TIMER_LIST_ENT * p_tle)613 void rw_mfc_process_timeout(TIMER_LIST_ENT* p_tle) {
614   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << " event=" << p_tle->event;
615 
616   if (p_tle->event == NFC_TTYPE_RW_MFC_RESPONSE) {
617     rw_mfc_process_error();
618   } else {
619     LOG(ERROR) << __func__ << " unknown event=" << p_tle->event;
620   }
621 }
622 
623 /*******************************************************************************
624  **
625  ** Function         rw_mfc_conn_cback
626  **
627  ** Description      This callback function receives the events/data from NFCC.
628  **
629  ** Returns          none
630  **
631  *******************************************************************************/
rw_mfc_conn_cback(uint8_t conn_id,tNFC_CONN_EVT event,tNFC_CONN * p_data)632 static void rw_mfc_conn_cback(uint8_t conn_id, tNFC_CONN_EVT event,
633                               tNFC_CONN* p_data) {
634   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
635   tRW_READ_DATA evt_data;
636   NFC_HDR* mfc_data = {};
637   uint8_t* p;
638   tRW_DATA rw_data;
639 
640   DLOG_IF(INFO, nfc_debug_enabled)
641       << StringPrintf("%s conn_id=%i, evt=0x%x", __func__, conn_id, event);
642   /* Only handle static conn_id */
643   if (conn_id != NFC_RF_CONN_ID) {
644     LOG(ERROR) << __func__ << " Not static connection id =" << conn_id;
645     return;
646   }
647 
648   switch (event) {
649     case NFC_CONN_CREATE_CEVT:
650     case NFC_CONN_CLOSE_CEVT:
651       break;
652 
653     case NFC_DEACTIVATE_CEVT:
654 
655       /* Stop mfc timer (if started) */
656       nfc_stop_quick_timer(&p_mfc->timer);
657       /* Free cmd buf for retransmissions */
658       if (p_mfc->p_cur_cmd_buf) {
659         GKI_freebuf(p_mfc->p_cur_cmd_buf);
660         p_mfc->p_cur_cmd_buf = NULL;
661       }
662 
663       p_mfc->state = RW_MFC_STATE_NOT_ACTIVATED;
664       NFC_SetStaticRfCback(NULL);
665       break;
666 
667     case NFC_DATA_CEVT:
668       if ((p_data != NULL) && (p_data->data.status == NFC_STATUS_OK)) {
669         mfc_data = (NFC_HDR*)p_data->data.p_data;
670         break;
671       }
672       /* Data event with error status...fall through to NFC_ERROR_CEVT case */
673       FALLTHROUGH_INTENDED;
674     case NFC_ERROR_CEVT:
675 
676       if ((p_mfc->state == RW_MFC_STATE_NOT_ACTIVATED) ||
677           (p_mfc->state == RW_MFC_STATE_IDLE)) {
678         if (event == NFC_ERROR_CEVT) {
679           evt_data.status = (tNFC_STATUS)(*(uint8_t*)p_data);
680         } else if (p_data) {
681           evt_data.status = p_data->status;
682         } else {
683           evt_data.status = NFC_STATUS_FAILED;
684         }
685 
686         evt_data.p_data = NULL;
687         (*rw_cb.p_cback)(RW_MFC_INTF_ERROR_EVT, (tRW_DATA*)&evt_data);
688         break;
689       }
690       nfc_stop_quick_timer(&p_mfc->timer);
691       break;
692 
693     default:
694       break;
695   }
696 
697   /* Assume the data is just the response byte sequence */
698   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
699 
700   switch (p_mfc->state) {
701     case RW_MFC_STATE_IDLE:
702       /* Unexpected R-APDU, it should be raw frame response */
703       /* forward to upper layer without parsing */
704       if (rw_cb.p_cback) {
705         rw_data.raw_frame.status = p_data->data.status;
706         rw_data.raw_frame.p_data = mfc_data;
707         (*(rw_cb.p_cback))(RW_MFC_RAW_FRAME_EVT, &rw_data);
708         mfc_data = NULL;
709       } else {
710         GKI_freebuf(mfc_data);
711       }
712       break;
713     case RW_MFC_STATE_DETECT_TLV:
714       rw_mfc_handle_tlv_detect_rsp((uint8_t*)mfc_data);
715       GKI_freebuf(mfc_data);
716       break;
717 
718     case RW_MFC_STATE_READ_NDEF:
719       rw_mfc_handle_ndef_read_rsp((uint8_t*)mfc_data);
720       GKI_freebuf(mfc_data);
721       break;
722     case RW_MFC_STATE_NOT_ACTIVATED:
723       DLOG_IF(INFO, nfc_debug_enabled)
724           << __func__ << " RW_MFC_STATE_NOT_ACTIVATED";
725       /* p_r_apdu may send upper layer */
726       break;
727     case RW_MFC_STATE_NDEF_FORMAT:
728       rw_mfc_handle_format_rsp((uint8_t*)mfc_data);
729       GKI_freebuf(mfc_data);
730       break;
731     case RW_MFC_STATE_UPDATE_NDEF:
732       rw_mfc_handle_write_rsp((uint8_t*)mfc_data);
733       GKI_freebuf(mfc_data);
734       break;
735     default:
736       LOG(ERROR) << __func__ << ": invalid state=" << p_mfc->state;
737       break;
738   }
739 }
740 
741 /*******************************************************************************
742  **
743  ** Function         rw_MfcLocateTlv
744  **
745  ** Description      This function performs NDEF detection procedure
746  **
747  **                  RW_MFC_NDEF_DETECT_EVT will be returned
748  **
749  ** Returns          NFC_STATUS_OK if success
750  **                  NFC_STATUS_FAILED if Mifare classic tag is busy or other
751  **                  error
752  **
753  *******************************************************************************/
rw_MfcLocateTlv(uint8_t tlv_type)754 static tNFC_STATUS rw_MfcLocateTlv(uint8_t tlv_type) {
755   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
756 
757   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
758   tNFC_STATUS success = NFC_STATUS_OK;
759 
760   if (p_mfc->state != RW_MFC_STATE_IDLE) {
761     LOG(ERROR) << __func__
762                << " Mifare Classic tag not activated or Busy - State:"
763                << p_mfc->state;
764     return NFC_STATUS_BUSY;
765   }
766 
767   if ((tlv_type != TAG_LOCK_CTRL_TLV) && (tlv_type != TAG_MEM_CTRL_TLV) &&
768       (tlv_type != TAG_NDEF_TLV) && (tlv_type != TAG_PROPRIETARY_TLV)) {
769     DLOG_IF(INFO, nfc_debug_enabled)
770         << StringPrintf("%s - Cannot search TLV: 0x%02x", __func__, tlv_type);
771     return NFC_STATUS_FAILED;
772   }
773   if (tlv_type == TAG_NDEF_TLV) {
774     p_mfc->ndef_length = 0;
775     p_mfc->ndef_start_pos = 0;
776     p_mfc->ndef_first_block = 0;
777     p_mfc->work_offset = 0;
778     p_mfc->ndef_status = MFC_NDEF_NOT_DETECTED;
779   }
780 
781   p_mfc->substate = RW_MFC_SUBSTATE_READ_BLOCK;
782   p_mfc->state = RW_MFC_STATE_DETECT_TLV;
783 
784   success = rw_mfc_readBlock(p_mfc->next_block.block);
785   if (success == NFC_STATUS_OK) {
786     p_mfc->state = RW_MFC_STATE_DETECT_TLV;
787     DLOG_IF(INFO, nfc_debug_enabled)
788         << __func__ << " RW_MFC_STATE_DETECT_TLV state=" << p_mfc->state;
789   } else {
790     p_mfc->substate = RW_MFC_SUBSTATE_NONE;
791     DLOG_IF(INFO, nfc_debug_enabled)
792         << __func__ << " rw_MfcLocateTlv state=" << p_mfc->state;
793   }
794 
795   return NFC_STATUS_OK;
796 }
797 
798 /*******************************************************************************
799  **
800  ** Function         rw_mfc_authenticate
801  **
802  ** Description      This function performs the authentication of a given
803  **                  block.
804  **
805  ** Returns          true if success
806  **
807  *******************************************************************************/
rw_mfc_authenticate(int block,bool KeyA)808 static bool rw_mfc_authenticate(int block, bool KeyA) {
809   NFC_HDR* mfcbuf;
810   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
811   uint8_t* p;
812 
813   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": block:" << block;
814 
815   uint8_t* KeyToUse;
816 
817   mfcbuf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
818 
819   if (!mfcbuf) {
820     LOG(ERROR) << __func__ << ": Cannot allocate buffer";
821     return false;
822   }
823 
824   mfcbuf->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE;
825   p = (uint8_t*)(mfcbuf + 1) + mfcbuf->offset;
826 
827   if (KeyA) {
828     UINT8_TO_BE_STREAM(p, MFC_KeyA);
829   } else {
830     UINT8_TO_BE_STREAM(p, MFC_KeyB);
831   }
832 
833   UINT8_TO_BE_STREAM(p, block);
834   ARRAY_TO_BE_STREAM(p, p_mfc->uid, 4);
835 
836   if (p_mfc->state == RW_MFC_STATE_NDEF_FORMAT)
837     KeyToUse = KeyDefault;
838   else {
839     if (block >= 0 && block < 4) {
840       KeyToUse = KeyMAD;
841     } else {
842       KeyToUse = KeyNDEF;
843     }
844   }
845   ARRAY_TO_BE_STREAM(p, KeyToUse, 6);
846 
847   mfcbuf->len = 12;
848 
849   if (!rw_mfc_send_to_lower(mfcbuf)) {
850     return false;
851   }
852   /* Backup the current substate to move back to this substate after changing
853    * sector */
854   p_mfc->prev_substate = p_mfc->substate;
855   p_mfc->substate = RW_MFC_SUBSTATE_WAIT_ACK;
856   return true;
857 }
858 
859 /*******************************************************************************
860  **
861  ** Function         rw_mfc_readBlock
862  **
863  ** Description      This function read a given block.
864  **
865  ** Returns          true if success
866  **
867  *******************************************************************************/
rw_mfc_readBlock(int block)868 static tNFC_STATUS rw_mfc_readBlock(int block) {
869   NFC_HDR* mfcbuf;
870   uint8_t* p;
871   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
872   int sectorlength = block / 4;
873   tNFC_STATUS status = NFC_STATUS_OK;
874 
875   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": block : " << block;
876 
877   if (block > 128) {
878     sectorlength = (p_mfc->next_block.block - 128) / 16 + 32;
879   }
880 
881   if (sectorlength != p_mfc->sector_authentified) {
882     if (rw_mfc_authenticate(block, true) == true) {
883       LOG(ERROR) << __func__ << ": RW_MFC_SUBSTATE_WAIT_ACK";
884       return NFC_STATUS_OK;
885     }
886     return NFC_STATUS_FAILED;
887   }
888 
889   mfcbuf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
890 
891   if (!mfcbuf) {
892     LOG(ERROR) << __func__ << ": Cannot allocate buffer";
893     return NFC_STATUS_REJECTED;
894   }
895 
896   mfcbuf->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE;
897   p = (uint8_t*)(mfcbuf + 1) + mfcbuf->offset;
898 
899   UINT8_TO_BE_STREAM(p, MFC_Read);
900   UINT8_TO_BE_STREAM(p, block);
901 
902   mfcbuf->len = 2;
903 
904   if (!rw_mfc_send_to_lower(mfcbuf)) {
905     return NFC_STATUS_REJECTED;
906   }
907   p_mfc->current_block = block;
908   p_mfc->substate = RW_MFC_SUBSTATE_READ_BLOCK;
909 
910   return status;
911 }
912 
913 /*******************************************************************************
914  **
915  ** Function         rw_mfc_handle_tlv_detect_rsp
916  **
917  ** Description      Handle TLV detection.
918  **
919  ** Returns          none
920  **
921  *******************************************************************************/
rw_mfc_handle_tlv_detect_rsp(uint8_t * p_data)922 static void rw_mfc_handle_tlv_detect_rsp(uint8_t* p_data) {
923   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
924   NFC_HDR* mfc_data;
925   uint8_t* p;
926 
927   mfc_data = (NFC_HDR*)p_data;
928   /* Assume the data is just the response byte sequence */
929   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
930 
931   p_mfc->last_block_accessed.block = p_mfc->next_block.block;
932   switch (p_mfc->substate) {
933     case RW_MFC_SUBSTATE_WAIT_ACK:
934       /* Search for the tlv */
935       if (p[0] == 0x0) {
936         p_mfc->next_block.auth = true;
937         p_mfc->last_block_accessed.auth = true;
938         p_mfc->sector_authentified = p_mfc->next_block.block / 4;
939 
940         rw_mfc_resume_op();
941       } else {
942         p_mfc->next_block.auth = false;
943         p_mfc->last_block_accessed.auth = false;
944         DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": status=" << p[0];
945         nfc_stop_quick_timer(&p_mfc->timer);
946         rw_mfc_process_error();
947       }
948       break;
949 
950     case RW_MFC_SUBSTATE_READ_BLOCK:
951       /* Search for the tlv */
952       if (mfc_data->len == 0x10) {
953         p_mfc->last_block_accessed.block = p_mfc->next_block.block;
954         p_mfc->next_block.block += 1;
955         p_mfc->next_block.auth = false;
956         rw_mfc_handle_read_op((uint8_t*)mfc_data);
957       }
958       break;
959   }
960 }
961 /*******************************************************************************
962  **
963  ** Function         rw_mfc_resume_op
964  **
965  ** Description      This function will continue operation after moving to new
966  **                  sector
967  **
968  ** Returns          none
969  **
970  *******************************************************************************/
rw_mfc_resume_op()971 static void rw_mfc_resume_op() {
972   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
973   bool status = true;
974 
975   switch (p_mfc->state) {
976     case RW_MFC_STATE_DETECT_TLV:
977       status = rw_mfc_readBlock(p_mfc->next_block.block);
978       break;
979     case RW_MFC_STATE_READ_NDEF:
980       status = rw_mfc_readBlock(p_mfc->next_block.block);
981       break;
982     case RW_MFC_STATE_NDEF_FORMAT:
983       status = rw_mfc_formatBlock(p_mfc->next_block.block);
984       break;
985     case RW_MFC_STATE_UPDATE_NDEF:
986       status = rw_mfc_writeBlock(p_mfc->next_block.block);
987       break;
988   }
989 }
990 
991 /*******************************************************************************
992  **
993  ** Function         rw_mfc_handle_read_op
994  **
995  ** Description      This function handles all the read operation.
996  **
997  ** Returns          none
998  **
999  *******************************************************************************/
rw_mfc_handle_read_op(uint8_t * data)1000 static void rw_mfc_handle_read_op(uint8_t* data) {
1001   uint8_t* p;
1002   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1003   bool tlv_found = false;
1004   NFC_HDR* mfc_data;
1005   uint16_t len;
1006   uint16_t offset;
1007   bool failed = false;
1008   bool done = false;
1009   tRW_READ_DATA evt_data;
1010 
1011   mfc_data = (NFC_HDR*)data;
1012   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
1013 
1014   switch (p_mfc->state) {
1015     case RW_MFC_STATE_DETECT_TLV:
1016       tlv_found = rw_nfc_decodeTlv(data);
1017       if (tlv_found) {
1018         p_mfc->ndef_status = MFC_NDEF_DETECTED;
1019         p_mfc->ndef_first_block = p_mfc->last_block_accessed.block;
1020         rw_mfc_ntf_tlv_detect_complete(tlv_found);
1021       }
1022       break;
1023 
1024     case RW_MFC_STATE_READ_NDEF:
1025       /* On the first read, adjust for any partial block offset */
1026       offset = 0;
1027       len = RW_MFC_1K_BLOCK_SIZE;
1028 
1029       if (p_mfc->work_offset == 0) {
1030         /* The Ndef Message offset may be present in the read 16 bytes */
1031         offset = p_mfc->ndef_start_pos;
1032 
1033         if (!rw_nfc_decodeTlv(data)) {
1034           failed = true;
1035           DLOG_IF(INFO, nfc_debug_enabled) << __func__ << " FAILED finding TLV";
1036         }
1037       }
1038 
1039       /* Skip all reserved and lock bytes */
1040       while ((offset < len) && (p_mfc->work_offset < p_mfc->ndef_length))
1041 
1042       {
1043         /* Collect the NDEF Message */
1044         p_mfc->p_ndef_buffer[p_mfc->work_offset] = p[offset];
1045         p_mfc->work_offset++;
1046         offset++;
1047       }
1048 
1049       if (p_mfc->work_offset >= p_mfc->ndef_length) {
1050         done = true;
1051         p_mfc->ndef_status = MFC_NDEF_READ;
1052       } else {
1053         /* Read next  blocks */
1054         if (rw_mfc_readBlock(p_mfc->next_block.block) != NFC_STATUS_OK) {
1055           failed = true;
1056           DLOG_IF(INFO, nfc_debug_enabled)
1057               << __func__ << " FAILED reading next";
1058         }
1059       }
1060 
1061       if (failed || done) {
1062         evt_data.status = failed ? NFC_STATUS_FAILED : NFC_STATUS_OK;
1063         evt_data.p_data = NULL;
1064         rw_mfc_handle_op_complete();
1065         (*rw_cb.p_cback)(RW_MFC_NDEF_READ_EVT, (tRW_DATA*)&evt_data);
1066       }
1067       break;
1068   }
1069 }
1070 /*******************************************************************************
1071  **
1072  ** Function         rw_nfc_decodeTlv
1073  **
1074  ** Description      Decode the NDEF data length from the Mifare TLV
1075  **                  Leading null TLVs (0x0) are skipped
1076  **
1077  ** Returns          true if success
1078  **
1079  *******************************************************************************/
rw_nfc_decodeTlv(uint8_t * data)1080 static bool rw_nfc_decodeTlv(uint8_t* data) {
1081   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1082   NFC_HDR* mfc_data;
1083   uint8_t* p;
1084 
1085   mfc_data = (NFC_HDR*)data;
1086   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
1087   int i = 0;
1088 
1089   do {
1090     if (p[i] == 0x0) {
1091       // do nothing, skip
1092     } else if (p[i] == 0x3) {
1093       p_mfc->tlv_detect = TAG_NDEF_TLV;
1094       break;
1095 
1096     } else {
1097       DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": Unknown TLV";
1098       p_mfc->tlv_detect = TAG_PROPRIETARY_TLV;
1099       break;
1100     }
1101     i++;
1102   } while (i < mfc_data->len);
1103 
1104   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": i=" << i;
1105 
1106   if (i < 0 || p[i] != 0x3) {
1107     LOG(ERROR) << __func__ << ": Can't decode message length";
1108     return false;
1109   } else {
1110     if (p[i + 1] == 0xFF) {
1111       p_mfc->ndef_length = (((uint16_t)p[i + 2]) << 8) | ((uint16_t)(p[i + 3]));
1112       p_mfc->ndef_start_pos = i + RW_MFC_LONG_TLV_SIZE;
1113       DLOG_IF(INFO, nfc_debug_enabled)
1114           << __func__ << " long NDEF SIZE=" << p_mfc->ndef_length;
1115     } else {
1116       p_mfc->ndef_length = p[i + 1];
1117       p_mfc->ndef_start_pos = i + RW_MFC_SHORT_TLV_SIZE;
1118       DLOG_IF(INFO, nfc_debug_enabled)
1119           << __func__ << " short NDEF SIZE=" << p_mfc->ndef_length;
1120     }
1121   }
1122   return true;
1123 }
1124 
1125 /*******************************************************************************
1126  **
1127  ** Function         rw_mfc_ntf_tlv_detect_complete
1128  **
1129  ** Description      Notify TLV detection complete to upper layer
1130  **
1131  ** Returns          none
1132  **
1133  *******************************************************************************/
rw_mfc_ntf_tlv_detect_complete(tNFC_STATUS status)1134 static void rw_mfc_ntf_tlv_detect_complete(tNFC_STATUS status) {
1135   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1136   tRW_DETECT_NDEF_DATA ndef_data = {};
1137 
1138   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
1139   if (p_mfc->tlv_detect == TAG_NDEF_TLV) {
1140     /* Notify upper layer the result of NDEF detect op */
1141     ndef_data.status = NFC_STATUS_OK;  // status;
1142     ndef_data.protocol = NFC_PROTOCOL_MIFARE;
1143     ndef_data.flags = 0;
1144     ndef_data.cur_size = p_mfc->ndef_length;
1145 
1146     if (status == NFC_STATUS_OK) {
1147       ndef_data.flags |= RW_NDEF_FL_FORMATED;
1148     }
1149 
1150     // TODO - calculate max size based on MAD sectr NFC_AID condition
1151     // Set max size as format condition
1152     if (p_mfc->selres & RW_MFC_4K_Support)
1153       ndef_data.max_size = 3356;
1154     else
1155       ndef_data.max_size = 716;
1156 
1157     rw_mfc_handle_op_complete();
1158     (*rw_cb.p_cback)(RW_MFC_NDEF_DETECT_EVT, (tRW_DATA*)&ndef_data);
1159   }
1160 }
1161 
1162 /*******************************************************************************
1163  **
1164  ** Function         RW_MfcReadNDef
1165  **
1166  ** Description      Retrieve NDEF contents from a Mifare Classic tag..
1167  **
1168  **                  The RW_MFC_NDEF_READ_EVT event is used to notify the
1169  **                  application after reading the NDEF message.
1170  **
1171  **                  Before using this API, the RW_MfcReadNDef function must
1172  **                  be called to verify that the tag contains NDEF data, and to
1173  **                  retrieve the NDEF attributes.
1174  **
1175  **                  Internally, this command will be separated into multiple
1176  **                  Mifare Classic Read commands (if necessary) - depending
1177  **                  on the NDEF Msg size.
1178  **
1179  ** Parameters:      p_buffer:   The buffer into which to read the NDEF message
1180  **                  buf_len:    The length of the buffer
1181  **
1182  ** Returns          NCI_STATUS_OK, if read was started. Otherwise, error
1183  **                  status.
1184  **
1185  *******************************************************************************/
RW_MfcReadNDef(uint8_t * p_buffer,uint16_t buf_len)1186 tNFC_STATUS RW_MfcReadNDef(uint8_t* p_buffer, uint16_t buf_len) {
1187   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1188   tNFC_STATUS status = NFC_STATUS_OK;
1189 
1190   if (p_mfc->state != RW_MFC_STATE_IDLE) {
1191     LOG(ERROR) << __func__
1192                << " Mifare Classic tag not activated or Busy - State="
1193                << p_mfc->state;
1194     return NFC_STATUS_FAILED;
1195   }
1196 
1197   if (p_mfc->ndef_status == MFC_NDEF_NOT_DETECTED) {
1198     LOG(ERROR) << __func__ << " NDEF detection not performed yet";
1199     return NFC_STATUS_FAILED;
1200   }
1201 
1202   if (buf_len < p_mfc->ndef_length) {
1203     LOG(ERROR) << __func__ << " buffer size=" << buf_len
1204                << "less than NDEF msg sise=" << p_mfc->ndef_length;
1205     return NFC_STATUS_FAILED;
1206   }
1207 
1208   if (!p_mfc->ndef_length) {
1209     LOG(ERROR) << __func__ << " NDEF Message length is zero ";
1210     return NFC_STATUS_NOT_INITIALIZED;
1211   }
1212 
1213   p_mfc->p_ndef_buffer = p_buffer;
1214   p_mfc->work_offset = 0;
1215 
1216   p_mfc->last_block_accessed.block = 0;
1217   p_mfc->next_block.block = p_mfc->ndef_first_block;
1218   p_mfc->substate = RW_MFC_SUBSTATE_NONE;
1219 
1220   /* Start reading NDEF Message */
1221   status = rw_mfc_readBlock(p_mfc->next_block.block);
1222   if (status == NFC_STATUS_OK) {
1223     p_mfc->state = RW_MFC_STATE_READ_NDEF;
1224   }
1225 
1226   return status;
1227 }
1228 
1229 /*****************************************************************************
1230  **
1231  ** Function         rw_mfc_handle_op_complete
1232  **
1233  ** Description      Reset to IDLE state
1234  **
1235  ** Returns          none
1236  **
1237  *****************************************************************************/
rw_mfc_handle_op_complete(void)1238 static void rw_mfc_handle_op_complete(void) {
1239   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1240 
1241   p_mfc->last_block_accessed.auth = false;
1242   p_mfc->next_block.auth = false;
1243   p_mfc->state = RW_MFC_STATE_IDLE;
1244   p_mfc->substate = RW_MFC_SUBSTATE_NONE;
1245   return;
1246 }
1247 
1248 /*******************************************************************************
1249  **
1250  ** Function         rw_mfc_handle_ndef_read_rsp
1251  **
1252  ** Description      Handle TLV detection.
1253  **
1254  ** Returns          none
1255  **
1256  *******************************************************************************/
rw_mfc_handle_ndef_read_rsp(uint8_t * p_data)1257 static void rw_mfc_handle_ndef_read_rsp(uint8_t* p_data) {
1258   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1259   NFC_HDR* mfc_data;
1260   uint8_t* p;
1261 
1262   mfc_data = (NFC_HDR*)p_data;
1263   /* Assume the data is just the response byte sequence */
1264   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
1265 
1266   switch (p_mfc->substate) {
1267     case RW_MFC_SUBSTATE_WAIT_ACK:
1268       /* Search for the tlv */
1269       p_mfc->last_block_accessed.block = p_mfc->current_block;
1270 
1271       if (p[0] == 0x0) {
1272         p_mfc->next_block.auth = true;
1273         p_mfc->last_block_accessed.auth = true;
1274 
1275         if (p_mfc->current_block < 128) {
1276           p_mfc->sector_authentified = p_mfc->next_block.block / 4;
1277         }
1278 
1279         else
1280           p_mfc->sector_authentified =
1281               (p_mfc->next_block.block - 128) / 16 + 32;
1282 
1283         rw_mfc_resume_op();
1284         DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
1285             "rw_mfc_handle_ndef_read_rsp () sector authentified: %d",
1286             p_mfc->sector_authentified);
1287       } else {
1288         p_mfc->next_block.auth = false;
1289         p_mfc->last_block_accessed.auth = false;
1290       }
1291       break;
1292 
1293     case RW_MFC_SUBSTATE_READ_BLOCK:
1294       /* Search for the tlv */
1295 
1296       if (mfc_data->len == 0x10) {
1297         p_mfc->last_block_accessed.block = p_mfc->current_block;
1298 
1299         if (p_mfc->current_block % 4 == 2) {
1300           p_mfc->next_block.block = p_mfc->current_block + 2;
1301         } else {
1302           p_mfc->next_block.block = p_mfc->current_block + 1;
1303         }
1304 
1305         /* Do not read block 16 (MAD2) - Mifare Classic4 k */
1306         if (p_mfc->next_block.block == 64) {
1307           p_mfc->next_block.block += 4;
1308         }
1309 
1310         if ((p_mfc->selres & RW_MFC_4K_Support) &&
1311             (p_mfc->next_block.block >= 128)) {
1312           if (p_mfc->current_block % 16 == 14) {
1313             p_mfc->next_block.block = p_mfc->current_block + 2;
1314           } else {
1315             p_mfc->next_block.block = p_mfc->current_block + 1;
1316           }
1317         }
1318 
1319         p_mfc->next_block.auth = false;
1320         rw_mfc_handle_read_op((uint8_t*)mfc_data);
1321       }
1322       break;
1323   }
1324 }
1325 
1326 /*******************************************************************************
1327  **
1328  ** Function         rw_mfc_process_error
1329  **
1330  ** Description      Process error including Timeout, Frame error. This function
1331  **                  will retry atleast till RW_MAX_RETRIES before give up and
1332  **                  sending negative notification to upper layer
1333  **
1334  ** Returns          none
1335  **
1336  *******************************************************************************/
rw_mfc_process_error()1337 static void rw_mfc_process_error() {
1338   tRW_READ_DATA evt_data;
1339   tRW_EVENT rw_event = RW_MFC_NDEF_DETECT_EVT;
1340   NFC_HDR* p_cmd_buf;
1341   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1342   tRW_DETECT_NDEF_DATA ndef_data;
1343 
1344   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << " State=" << p_mfc->state;
1345 
1346   /* Retry sending command if retry-count < max */
1347   if (rw_cb.cur_retry < RW_MAX_RETRIES) {
1348     /* retry sending the command */
1349     rw_cb.cur_retry++;
1350 
1351     DLOG_IF(INFO, nfc_debug_enabled)
1352         << __func__ << "Mifare Classic retransmission attempt "
1353         << rw_cb.cur_retry << " of " << RW_MAX_RETRIES;
1354 
1355     /* allocate a new buffer for message */
1356     p_cmd_buf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
1357     if (p_cmd_buf != NULL) {
1358       memcpy(p_cmd_buf, p_mfc->p_cur_cmd_buf,
1359              sizeof(NFC_HDR) + p_mfc->p_cur_cmd_buf->offset +
1360                  p_mfc->p_cur_cmd_buf->len);
1361 
1362       if (NFC_SendData(NFC_RF_CONN_ID, p_cmd_buf) == NFC_STATUS_OK) {
1363         /* Start timer for waiting for response */
1364         nfc_start_quick_timer(
1365             &p_mfc->timer, NFC_TTYPE_RW_MFC_RESPONSE,
1366             (RW_MFC_TOUT_RESP * QUICK_TIMER_TICKS_PER_SEC) / 1000);
1367 
1368         return;
1369       }
1370     }
1371   } else {
1372     DLOG_IF(INFO, nfc_debug_enabled)
1373         << __func__ << "MFC maximum retransmission attempts reached "
1374         << RW_MAX_RETRIES;
1375   }
1376 
1377   if (p_mfc->state == RW_MFC_STATE_DETECT_TLV) {
1378     rw_event = RW_MFC_NDEF_DETECT_EVT;
1379   } else if (p_mfc->state == RW_MFC_STATE_READ_NDEF) {
1380     rw_event = RW_MFC_NDEF_READ_EVT;
1381   } else if (p_mfc->state == RW_MFC_STATE_UPDATE_NDEF) {
1382     rw_event = RW_MFC_NDEF_WRITE_FAIL_EVT;
1383   } else if (p_mfc->state == RW_MFC_STATE_NDEF_FORMAT) {
1384     rw_event = RW_MFC_NDEF_FORMAT_CPLT_EVT;
1385   }
1386 
1387   if (rw_event == RW_MFC_NDEF_DETECT_EVT) {
1388     ndef_data.status = evt_data.status;
1389     ndef_data.protocol = NFC_PROTOCOL_MIFARE;
1390     ndef_data.flags = RW_NDEF_FL_UNKNOWN;
1391     ndef_data.max_size = 0;
1392     ndef_data.cur_size = 0;
1393     DLOG_IF(INFO, nfc_debug_enabled)
1394         << __func__ << " status=" << evt_data.status;
1395     /* If not Halt move to idle state */
1396     rw_mfc_handle_op_complete();
1397 
1398     (*rw_cb.p_cback)(rw_event, (tRW_DATA*)&ndef_data);
1399   } else {
1400     evt_data.p_data = NULL;
1401     /* If activated and not Halt move to idle state */
1402     if (p_mfc->state != RW_MFC_STATE_NOT_ACTIVATED) {
1403       rw_mfc_handle_op_complete();
1404     }
1405 
1406     DLOG_IF(INFO, nfc_debug_enabled)
1407         << __func__ << " status=" << evt_data.status;
1408     p_mfc->substate = RW_MFC_SUBSTATE_NONE;
1409     (*rw_cb.p_cback)(rw_event, (tRW_DATA*)&evt_data);
1410   }
1411 }
1412