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     } else if (p_mfc->work_offset > p_mfc->ndef_length) {
408       UINT8_TO_BE_STREAM(p, 0x00);
409     } else {
410       UINT8_TO_BE_STREAM(p, p_mfc->p_ndef_buffer[p_mfc->work_offset]);
411     }
412     p_mfc->work_offset++;
413     index++;
414   }
415   mfcbuf->len = 18;
416 
417   if (!rw_mfc_send_to_lower(mfcbuf)) {
418     return NFC_STATUS_REJECTED;
419   }
420   p_mfc->current_block = block;
421   p_mfc->substate = RW_MFC_SUBSTATE_WRITE_BLOCK;
422 
423   return status;
424 }
425 
rw_mfc_handle_write_rsp(uint8_t * p_data)426 static void rw_mfc_handle_write_rsp(uint8_t* p_data) {
427   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
428   NFC_HDR* mfc_data;
429   uint8_t* p;
430 
431   mfc_data = (NFC_HDR*)p_data;
432   /* Assume the data is just the response byte sequence */
433   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
434 
435   switch (p_mfc->substate) {
436     case RW_MFC_SUBSTATE_WAIT_ACK:
437       p_mfc->last_block_accessed.block = p_mfc->current_block;
438 
439       if (p[0] == 0x0) {
440         p_mfc->next_block.auth = true;
441         p_mfc->last_block_accessed.auth = true;
442 
443         if (p_mfc->next_block.block < 128) {
444           p_mfc->sector_authentified = p_mfc->next_block.block / 4;
445         } else {
446           p_mfc->sector_authentified =
447               (p_mfc->next_block.block - 128) / 16 + 32;
448         }
449         rw_mfc_resume_op();
450       } else {
451         p_mfc->next_block.auth = false;
452         p_mfc->last_block_accessed.auth = false;
453         nfc_stop_quick_timer(&p_mfc->timer);
454         rw_mfc_process_error();
455       }
456       break;
457 
458     case RW_MFC_SUBSTATE_WRITE_BLOCK:
459       if (p[0] == 0x0) {
460         rw_mfc_handle_write_op();
461       } else {
462         nfc_stop_quick_timer(&p_mfc->timer);
463         rw_mfc_process_error();
464       }
465       break;
466   }
467 }
468 
rw_mfc_handle_write_op()469 static void rw_mfc_handle_write_op() {
470   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
471   tRW_READ_DATA evt_data;
472 
473   if (p_mfc->work_offset >= p_mfc->ndef_length) {
474     evt_data.status = NFC_STATUS_OK;
475     evt_data.p_data = NULL;
476     (*rw_cb.p_cback)(RW_MFC_NDEF_WRITE_CPLT_EVT, (tRW_DATA*)&evt_data);
477   } else {
478     p_mfc->last_block_accessed.block = p_mfc->current_block;
479 
480     if (p_mfc->current_block % 4 == 2) {
481       p_mfc->next_block.block = p_mfc->current_block + 2;
482     } else {
483       p_mfc->next_block.block = p_mfc->current_block + 1;
484     }
485 
486     /* Do not read block 16 (MAD2) - Mifare Classic4 k */
487     if (p_mfc->next_block.block == 64) {
488       p_mfc->next_block.block += 4;
489     }
490 
491     if ((p_mfc->selres & RW_MFC_4K_Support) &&
492         (p_mfc->next_block.block >= 128)) {
493       if (p_mfc->current_block % 16 == 14) {
494         p_mfc->next_block.block = p_mfc->current_block + 2;
495       } else {
496         p_mfc->next_block.block = p_mfc->current_block + 1;
497       }
498     }
499 
500     /* Write next blocks */
501     if (rw_mfc_writeBlock(p_mfc->next_block.block) != NFC_STATUS_OK) {
502       evt_data.status = NFC_STATUS_FAILED;
503       evt_data.p_data = NULL;
504       (*rw_cb.p_cback)(RW_MFC_NDEF_WRITE_FAIL_EVT, (tRW_DATA*)&evt_data);
505     }
506   }
507 }
508 
509 /*****************************************************************************
510  **
511  ** Function         RW_MfcDetectNDef
512  **
513  ** Description
514  **      This function is used to perform NDEF detection on a Mifare Classic
515  **      tag, and retrieve the tag's NDEF attribute information.
516  **      Before using this API, the application must call RW_SelectTagType to
517  **      indicate that a Type 1 tag has been activated.
518  **
519  ** Returns
520  **      NFC_STATUS_OK: ndef detection procedure started
521  **      NFC_STATUS_WRONG_PROTOCOL: type 1 tag not activated
522  **      NFC_STATUS_BUSY: another command is already in progress
523  **      NFC_STATUS_FAILED: other error
524  **
525  *****************************************************************************/
RW_MfcDetectNDef(void)526 tNFC_STATUS RW_MfcDetectNDef(void) {
527   LOG(ERROR) << __func__;
528   return rw_MfcLocateTlv(TAG_NDEF_TLV);
529 }
530 
531 /*******************************************************************************
532  **
533  ** Function         rw_mfc_select
534  **
535  ** Description      This function will set the callback function to
536  **                  receive data from lower layers.
537  **
538  ** Returns          tNFC_STATUS
539  **
540  *******************************************************************************/
rw_mfc_select(uint8_t selres,uint8_t uid[MFC_UID_LEN])541 tNFC_STATUS rw_mfc_select(uint8_t selres, uint8_t uid[MFC_UID_LEN]) {
542   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
543 
544   p_mfc->state = RW_MFC_STATE_NOT_ACTIVATED;
545 
546   /* Alloc cmd buf for retransmissions */
547   if (p_mfc->p_cur_cmd_buf == NULL) {
548     DLOG_IF(INFO, nfc_debug_enabled) << __func__;
549     p_mfc->p_cur_cmd_buf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
550     if (p_mfc->p_cur_cmd_buf == NULL) {
551       LOG(ERROR) << __func__
552                  << ": unable to allocate buffer for retransmission";
553 
554       return NFC_STATUS_FAILED;
555     }
556   }
557   p_mfc->selres = selres;
558   memcpy(p_mfc->uid, uid, MFC_UID_LEN);
559 
560   NFC_SetStaticRfCback(rw_mfc_conn_cback);
561 
562   p_mfc->state = RW_MFC_STATE_IDLE;
563   p_mfc->substate = RW_MFC_SUBSTATE_IDLE;
564   p_mfc->last_block_accessed.block = -1;
565   p_mfc->last_block_accessed.auth = false;
566   p_mfc->next_block.block = 4;
567   p_mfc->next_block.auth = false;
568   p_mfc->sector_authentified = -1;
569 
570   return NFC_STATUS_OK;
571 }
572 
573 /*******************************************************************************
574  **
575  ** Function         rw_mfc_send_to_lower
576  **
577  ** Description      Send C-APDU to lower layer
578  **
579  ** Returns          true if success
580  **
581  *******************************************************************************/
rw_mfc_send_to_lower(NFC_HDR * p_data)582 static bool rw_mfc_send_to_lower(NFC_HDR* p_data) {
583   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
584   /* Indicate first attempt to send command, back up cmd buffer in case needed
585    * for retransmission */
586   rw_cb.cur_retry = 0;
587   memcpy(p_mfc->p_cur_cmd_buf, p_data,
588          sizeof(NFC_HDR) + p_data->offset + p_data->len);
589 
590   if (NFC_SendData(NFC_RF_CONN_ID, p_data) != NFC_STATUS_OK) {
591     LOG(ERROR) << __func__ << ": NFC_SendData () failed";
592     return false;
593   }
594 
595   nfc_start_quick_timer(&rw_cb.tcb.mfc.timer, NFC_TTYPE_RW_MFC_RESPONSE,
596                         (RW_MFC_TOUT_RESP * QUICK_TIMER_TICKS_PER_SEC) / 1000);
597 
598   return true;
599 }
600 
601 /*******************************************************************************
602  **
603  ** Function         rw_mfc_process_timeout
604  **
605  ** Description      handles timeout event
606  **
607  ** Returns          none
608  **
609  *******************************************************************************/
rw_mfc_process_timeout(TIMER_LIST_ENT * p_tle)610 void rw_mfc_process_timeout(TIMER_LIST_ENT* p_tle) {
611   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << " event=" << p_tle->event;
612 
613   if (p_tle->event == NFC_TTYPE_RW_MFC_RESPONSE) {
614     rw_mfc_process_error();
615   } else {
616     LOG(ERROR) << __func__ << " unknown event=" << p_tle->event;
617   }
618 }
619 
620 /*******************************************************************************
621  **
622  ** Function         rw_mfc_conn_cback
623  **
624  ** Description      This callback function receives the events/data from NFCC.
625  **
626  ** Returns          none
627  **
628  *******************************************************************************/
rw_mfc_conn_cback(uint8_t conn_id,tNFC_CONN_EVT event,tNFC_CONN * p_data)629 static void rw_mfc_conn_cback(uint8_t conn_id, tNFC_CONN_EVT event,
630                               tNFC_CONN* p_data) {
631   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
632   tRW_READ_DATA evt_data;
633   NFC_HDR* mfc_data = {};
634   uint8_t* p;
635   tRW_DATA rw_data;
636 
637   DLOG_IF(INFO, nfc_debug_enabled)
638       << StringPrintf("%s conn_id=%i, evt=0x%x", __func__, conn_id, event);
639   /* Only handle static conn_id */
640   if (conn_id != NFC_RF_CONN_ID) {
641     LOG(ERROR) << __func__ << " Not static connection id =" << conn_id;
642     return;
643   }
644 
645   switch (event) {
646     case NFC_CONN_CREATE_CEVT:
647     case NFC_CONN_CLOSE_CEVT:
648       break;
649 
650     case NFC_DEACTIVATE_CEVT:
651 
652       /* Stop mfc timer (if started) */
653       nfc_stop_quick_timer(&p_mfc->timer);
654       /* Free cmd buf for retransmissions */
655       if (p_mfc->p_cur_cmd_buf) {
656         GKI_freebuf(p_mfc->p_cur_cmd_buf);
657         p_mfc->p_cur_cmd_buf = NULL;
658       }
659 
660       p_mfc->state = RW_MFC_STATE_NOT_ACTIVATED;
661       NFC_SetStaticRfCback(NULL);
662       break;
663 
664     case NFC_DATA_CEVT:
665       if ((p_data != NULL) && (p_data->data.status == NFC_STATUS_OK)) {
666         mfc_data = (NFC_HDR*)p_data->data.p_data;
667         break;
668       }
669       /* Data event with error status...fall through to NFC_ERROR_CEVT case */
670       FALLTHROUGH_INTENDED;
671     case NFC_ERROR_CEVT:
672 
673       if ((p_mfc->state == RW_MFC_STATE_NOT_ACTIVATED) ||
674           (p_mfc->state == RW_MFC_STATE_IDLE)) {
675         if (event == NFC_ERROR_CEVT) {
676           evt_data.status = (tNFC_STATUS)(*(uint8_t*)p_data);
677         } else if (p_data) {
678           evt_data.status = p_data->status;
679         } else {
680           evt_data.status = NFC_STATUS_FAILED;
681         }
682 
683         evt_data.p_data = NULL;
684         (*rw_cb.p_cback)(RW_MFC_INTF_ERROR_EVT, (tRW_DATA*)&evt_data);
685         break;
686       }
687       nfc_stop_quick_timer(&p_mfc->timer);
688       break;
689 
690     default:
691       break;
692   }
693 
694   /* Assume the data is just the response byte sequence */
695   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
696 
697   switch (p_mfc->state) {
698     case RW_MFC_STATE_IDLE:
699       /* Unexpected R-APDU, it should be raw frame response */
700       /* forward to upper layer without parsing */
701       if (rw_cb.p_cback) {
702         rw_data.raw_frame.status = p_data->data.status;
703         rw_data.raw_frame.p_data = mfc_data;
704         (*(rw_cb.p_cback))(RW_MFC_RAW_FRAME_EVT, &rw_data);
705         mfc_data = NULL;
706       } else {
707         GKI_freebuf(mfc_data);
708       }
709       break;
710     case RW_MFC_STATE_DETECT_TLV:
711       rw_mfc_handle_tlv_detect_rsp((uint8_t*)mfc_data);
712       GKI_freebuf(mfc_data);
713       break;
714 
715     case RW_MFC_STATE_READ_NDEF:
716       rw_mfc_handle_ndef_read_rsp((uint8_t*)mfc_data);
717       GKI_freebuf(mfc_data);
718       break;
719     case RW_MFC_STATE_NOT_ACTIVATED:
720       DLOG_IF(INFO, nfc_debug_enabled)
721           << __func__ << " RW_MFC_STATE_NOT_ACTIVATED";
722       /* p_r_apdu may send upper layer */
723       break;
724     case RW_MFC_STATE_NDEF_FORMAT:
725       rw_mfc_handle_format_rsp((uint8_t*)mfc_data);
726       GKI_freebuf(mfc_data);
727       break;
728     case RW_MFC_STATE_UPDATE_NDEF:
729       rw_mfc_handle_write_rsp((uint8_t*)mfc_data);
730       GKI_freebuf(mfc_data);
731       break;
732     default:
733       LOG(ERROR) << __func__ << ": invalid state=" << p_mfc->state;
734       break;
735   }
736 }
737 
738 /*******************************************************************************
739  **
740  ** Function         rw_MfcLocateTlv
741  **
742  ** Description      This function performs NDEF detection procedure
743  **
744  **                  RW_MFC_NDEF_DETECT_EVT will be returned
745  **
746  ** Returns          NFC_STATUS_OK if success
747  **                  NFC_STATUS_FAILED if Mifare classic tag is busy or other
748  **                  error
749  **
750  *******************************************************************************/
rw_MfcLocateTlv(uint8_t tlv_type)751 static tNFC_STATUS rw_MfcLocateTlv(uint8_t tlv_type) {
752   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
753 
754   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
755   tNFC_STATUS success = NFC_STATUS_OK;
756 
757   if (p_mfc->state != RW_MFC_STATE_IDLE) {
758     LOG(ERROR) << __func__
759                << " Mifare Classic tag not activated or Busy - State:"
760                << p_mfc->state;
761     return NFC_STATUS_BUSY;
762   }
763 
764   if ((tlv_type != TAG_LOCK_CTRL_TLV) && (tlv_type != TAG_MEM_CTRL_TLV) &&
765       (tlv_type != TAG_NDEF_TLV) && (tlv_type != TAG_PROPRIETARY_TLV)) {
766     DLOG_IF(INFO, nfc_debug_enabled)
767         << StringPrintf("%s - Cannot search TLV: 0x%02x", __func__, tlv_type);
768     return NFC_STATUS_FAILED;
769   }
770   if (tlv_type == TAG_NDEF_TLV) {
771     p_mfc->ndef_length = 0;
772     p_mfc->ndef_start_pos = 0;
773     p_mfc->ndef_first_block = 0;
774     p_mfc->work_offset = 0;
775     p_mfc->ndef_status = MFC_NDEF_NOT_DETECTED;
776   }
777 
778   p_mfc->substate = RW_MFC_SUBSTATE_READ_BLOCK;
779   p_mfc->state = RW_MFC_STATE_DETECT_TLV;
780 
781   success = rw_mfc_readBlock(p_mfc->next_block.block);
782   if (success == NFC_STATUS_OK) {
783     p_mfc->state = RW_MFC_STATE_DETECT_TLV;
784     DLOG_IF(INFO, nfc_debug_enabled)
785         << __func__ << " RW_MFC_STATE_DETECT_TLV state=" << p_mfc->state;
786   } else {
787     p_mfc->substate = RW_MFC_SUBSTATE_NONE;
788     DLOG_IF(INFO, nfc_debug_enabled)
789         << __func__ << " rw_MfcLocateTlv state=" << p_mfc->state;
790   }
791 
792   return NFC_STATUS_OK;
793 }
794 
795 /*******************************************************************************
796  **
797  ** Function         rw_mfc_authenticate
798  **
799  ** Description      This function performs the authentication of a given
800  **                  block.
801  **
802  ** Returns          true if success
803  **
804  *******************************************************************************/
rw_mfc_authenticate(int block,bool KeyA)805 static bool rw_mfc_authenticate(int block, bool KeyA) {
806   NFC_HDR* mfcbuf;
807   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
808   uint8_t* p;
809 
810   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": block:" << block;
811 
812   uint8_t* KeyToUse;
813 
814   mfcbuf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
815 
816   if (!mfcbuf) {
817     LOG(ERROR) << __func__ << ": Cannot allocate buffer";
818     return false;
819   }
820 
821   mfcbuf->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE;
822   p = (uint8_t*)(mfcbuf + 1) + mfcbuf->offset;
823 
824   if (KeyA) {
825     UINT8_TO_BE_STREAM(p, MFC_KeyA);
826   } else {
827     UINT8_TO_BE_STREAM(p, MFC_KeyB);
828   }
829 
830   UINT8_TO_BE_STREAM(p, block);
831   ARRAY_TO_BE_STREAM(p, p_mfc->uid, 4);
832 
833   if (p_mfc->state == RW_MFC_STATE_NDEF_FORMAT)
834     KeyToUse = KeyDefault;
835   else {
836     if (block >= 0 && block < 4) {
837       KeyToUse = KeyMAD;
838     } else {
839       KeyToUse = KeyNDEF;
840     }
841   }
842   ARRAY_TO_BE_STREAM(p, KeyToUse, 6);
843 
844   mfcbuf->len = 12;
845 
846   if (!rw_mfc_send_to_lower(mfcbuf)) {
847     return false;
848   }
849   /* Backup the current substate to move back to this substate after changing
850    * sector */
851   p_mfc->prev_substate = p_mfc->substate;
852   p_mfc->substate = RW_MFC_SUBSTATE_WAIT_ACK;
853   return true;
854 }
855 
856 /*******************************************************************************
857  **
858  ** Function         rw_mfc_readBlock
859  **
860  ** Description      This function read a given block.
861  **
862  ** Returns          true if success
863  **
864  *******************************************************************************/
rw_mfc_readBlock(int block)865 static tNFC_STATUS rw_mfc_readBlock(int block) {
866   NFC_HDR* mfcbuf;
867   uint8_t* p;
868   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
869   int sectorlength = block / 4;
870   tNFC_STATUS status = NFC_STATUS_OK;
871 
872   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": block : " << block;
873 
874   if (block > 128) {
875     sectorlength = (p_mfc->next_block.block - 128) / 16 + 32;
876   }
877 
878   if (sectorlength != p_mfc->sector_authentified) {
879     if (rw_mfc_authenticate(block, true) == true) {
880       LOG(ERROR) << __func__ << ": RW_MFC_SUBSTATE_WAIT_ACK";
881       return NFC_STATUS_OK;
882     }
883     return NFC_STATUS_FAILED;
884   }
885 
886   mfcbuf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
887 
888   if (!mfcbuf) {
889     LOG(ERROR) << __func__ << ": Cannot allocate buffer";
890     return NFC_STATUS_REJECTED;
891   }
892 
893   mfcbuf->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE;
894   p = (uint8_t*)(mfcbuf + 1) + mfcbuf->offset;
895 
896   UINT8_TO_BE_STREAM(p, MFC_Read);
897   UINT8_TO_BE_STREAM(p, block);
898 
899   mfcbuf->len = 2;
900 
901   if (!rw_mfc_send_to_lower(mfcbuf)) {
902     return NFC_STATUS_REJECTED;
903   }
904   p_mfc->current_block = block;
905   p_mfc->substate = RW_MFC_SUBSTATE_READ_BLOCK;
906 
907   return status;
908 }
909 
910 /*******************************************************************************
911  **
912  ** Function         rw_mfc_handle_tlv_detect_rsp
913  **
914  ** Description      Handle TLV detection.
915  **
916  ** Returns          none
917  **
918  *******************************************************************************/
rw_mfc_handle_tlv_detect_rsp(uint8_t * p_data)919 static void rw_mfc_handle_tlv_detect_rsp(uint8_t* p_data) {
920   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
921   NFC_HDR* mfc_data;
922   uint8_t* p;
923 
924   mfc_data = (NFC_HDR*)p_data;
925   /* Assume the data is just the response byte sequence */
926   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
927 
928   p_mfc->last_block_accessed.block = p_mfc->next_block.block;
929   switch (p_mfc->substate) {
930     case RW_MFC_SUBSTATE_WAIT_ACK:
931       /* Search for the tlv */
932       if (p[0] == 0x0) {
933         p_mfc->next_block.auth = true;
934         p_mfc->last_block_accessed.auth = true;
935         p_mfc->sector_authentified = p_mfc->next_block.block / 4;
936 
937         rw_mfc_resume_op();
938       } else {
939         p_mfc->next_block.auth = false;
940         p_mfc->last_block_accessed.auth = false;
941         DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": status=" << p[0];
942         nfc_stop_quick_timer(&p_mfc->timer);
943         rw_mfc_process_error();
944       }
945       break;
946 
947     case RW_MFC_SUBSTATE_READ_BLOCK:
948       /* Search for the tlv */
949       if (mfc_data->len == 0x10) {
950         p_mfc->last_block_accessed.block = p_mfc->next_block.block;
951         p_mfc->next_block.block += 1;
952         p_mfc->next_block.auth = false;
953         rw_mfc_handle_read_op((uint8_t*)mfc_data);
954       }
955       break;
956   }
957 }
958 /*******************************************************************************
959  **
960  ** Function         rw_mfc_resume_op
961  **
962  ** Description      This function will continue operation after moving to new
963  **                  sector
964  **
965  ** Returns          none
966  **
967  *******************************************************************************/
rw_mfc_resume_op()968 static void rw_mfc_resume_op() {
969   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
970   bool status = true;
971 
972   switch (p_mfc->state) {
973     case RW_MFC_STATE_DETECT_TLV:
974       status = rw_mfc_readBlock(p_mfc->next_block.block);
975       break;
976     case RW_MFC_STATE_READ_NDEF:
977       status = rw_mfc_readBlock(p_mfc->next_block.block);
978       break;
979     case RW_MFC_STATE_NDEF_FORMAT:
980       status = rw_mfc_formatBlock(p_mfc->next_block.block);
981       break;
982     case RW_MFC_STATE_UPDATE_NDEF:
983       status = rw_mfc_writeBlock(p_mfc->next_block.block);
984       break;
985   }
986 }
987 
988 /*******************************************************************************
989  **
990  ** Function         rw_mfc_handle_read_op
991  **
992  ** Description      This function handles all the read operation.
993  **
994  ** Returns          none
995  **
996  *******************************************************************************/
rw_mfc_handle_read_op(uint8_t * data)997 static void rw_mfc_handle_read_op(uint8_t* data) {
998   uint8_t* p;
999   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1000   bool tlv_found = false;
1001   NFC_HDR* mfc_data;
1002   uint16_t len;
1003   uint16_t offset;
1004   bool failed = false;
1005   bool done = false;
1006   tRW_READ_DATA evt_data;
1007 
1008   mfc_data = (NFC_HDR*)data;
1009   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
1010 
1011   switch (p_mfc->state) {
1012     case RW_MFC_STATE_DETECT_TLV:
1013       tlv_found = rw_nfc_decodeTlv(data);
1014       if (tlv_found) {
1015         p_mfc->ndef_status = MFC_NDEF_DETECTED;
1016         p_mfc->ndef_first_block = p_mfc->last_block_accessed.block;
1017         rw_mfc_ntf_tlv_detect_complete(tlv_found);
1018       }
1019       break;
1020 
1021     case RW_MFC_STATE_READ_NDEF:
1022       /* On the first read, adjust for any partial block offset */
1023       offset = 0;
1024       len = RW_MFC_1K_BLOCK_SIZE;
1025 
1026       if (p_mfc->work_offset == 0) {
1027         /* The Ndef Message offset may be present in the read 16 bytes */
1028         offset = p_mfc->ndef_start_pos;
1029 
1030         if (!rw_nfc_decodeTlv(data)) {
1031           failed = true;
1032           DLOG_IF(INFO, nfc_debug_enabled) << __func__ << " FAILED finding TLV";
1033         }
1034       }
1035 
1036       /* Skip all reserved and lock bytes */
1037       while ((offset < len) && (p_mfc->work_offset < p_mfc->ndef_length))
1038 
1039       {
1040         /* Collect the NDEF Message */
1041         p_mfc->p_ndef_buffer[p_mfc->work_offset] = p[offset];
1042         p_mfc->work_offset++;
1043         offset++;
1044       }
1045 
1046       if (p_mfc->work_offset >= p_mfc->ndef_length) {
1047         done = true;
1048         p_mfc->ndef_status = MFC_NDEF_READ;
1049       } else {
1050         /* Read next  blocks */
1051         if (rw_mfc_readBlock(p_mfc->next_block.block) != NFC_STATUS_OK) {
1052           failed = true;
1053           DLOG_IF(INFO, nfc_debug_enabled)
1054               << __func__ << " FAILED reading next";
1055         }
1056       }
1057 
1058       if (failed || done) {
1059         evt_data.status = failed ? NFC_STATUS_FAILED : NFC_STATUS_OK;
1060         evt_data.p_data = NULL;
1061         rw_mfc_handle_op_complete();
1062         (*rw_cb.p_cback)(RW_MFC_NDEF_READ_EVT, (tRW_DATA*)&evt_data);
1063       }
1064       break;
1065   }
1066 }
1067 /*******************************************************************************
1068  **
1069  ** Function         rw_nfc_decodeTlv
1070  **
1071  ** Description      Decode the NDEF data length from the Mifare TLV
1072  **                  Leading null TLVs (0x0) are skipped
1073  **
1074  ** Returns          true if success
1075  **
1076  *******************************************************************************/
rw_nfc_decodeTlv(uint8_t * data)1077 static bool rw_nfc_decodeTlv(uint8_t* data) {
1078   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1079   NFC_HDR* mfc_data;
1080   uint8_t* p;
1081 
1082   mfc_data = (NFC_HDR*)data;
1083   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
1084   int i = 0;
1085 
1086   do {
1087     if (p[i] == 0x0) {
1088       // do nothing, skip
1089     } else if (p[i] == 0x3) {
1090       p_mfc->tlv_detect = TAG_NDEF_TLV;
1091       break;
1092 
1093     } else {
1094       DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": Unknown TLV";
1095       p_mfc->tlv_detect = TAG_PROPRIETARY_TLV;
1096       break;
1097     }
1098     i++;
1099   } while (i < mfc_data->len);
1100 
1101   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << ": i=" << i;
1102 
1103   if (i < 0 || p[i] != 0x3) {
1104     LOG(ERROR) << __func__ << ": Can't decode message length";
1105     return false;
1106   } else {
1107     if (p[i + 1] == 0xFF) {
1108       p_mfc->ndef_length = (((uint16_t)p[i + 2]) << 8) | ((uint16_t)(p[i + 3]));
1109       p_mfc->ndef_start_pos = i + RW_MFC_LONG_TLV_SIZE;
1110       DLOG_IF(INFO, nfc_debug_enabled)
1111           << __func__ << " long NDEF SIZE=" << p_mfc->ndef_length;
1112     } else {
1113       p_mfc->ndef_length = p[i + 1];
1114       p_mfc->ndef_start_pos = i + RW_MFC_SHORT_TLV_SIZE;
1115       DLOG_IF(INFO, nfc_debug_enabled)
1116           << __func__ << " short NDEF SIZE=" << p_mfc->ndef_length;
1117     }
1118   }
1119   return true;
1120 }
1121 
1122 /*******************************************************************************
1123  **
1124  ** Function         rw_mfc_ntf_tlv_detect_complete
1125  **
1126  ** Description      Notify TLV detection complete to upper layer
1127  **
1128  ** Returns          none
1129  **
1130  *******************************************************************************/
rw_mfc_ntf_tlv_detect_complete(tNFC_STATUS status)1131 static void rw_mfc_ntf_tlv_detect_complete(tNFC_STATUS status) {
1132   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1133   tRW_DETECT_NDEF_DATA ndef_data = {};
1134 
1135   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
1136   if (p_mfc->tlv_detect == TAG_NDEF_TLV) {
1137     /* Notify upper layer the result of NDEF detect op */
1138     ndef_data.status = NFC_STATUS_OK;  // status;
1139     ndef_data.protocol = NFC_PROTOCOL_MIFARE;
1140     ndef_data.flags = 0;
1141     ndef_data.cur_size = p_mfc->ndef_length;
1142 
1143     if (status == NFC_STATUS_OK) {
1144       ndef_data.flags |= RW_NDEF_FL_FORMATED;
1145     }
1146 
1147     // TODO - calculate max size based on MAD sectr NFC_AID condition
1148     // Set max size as format condition
1149     if (p_mfc->selres & RW_MFC_4K_Support)
1150       ndef_data.max_size = 3356;
1151     else
1152       ndef_data.max_size = 716;
1153 
1154     rw_mfc_handle_op_complete();
1155     (*rw_cb.p_cback)(RW_MFC_NDEF_DETECT_EVT, (tRW_DATA*)&ndef_data);
1156   }
1157 }
1158 
1159 /*******************************************************************************
1160  **
1161  ** Function         RW_MfcReadNDef
1162  **
1163  ** Description      Retrieve NDEF contents from a Mifare Classic tag..
1164  **
1165  **                  The RW_MFC_NDEF_READ_EVT event is used to notify the
1166  **                  application after reading the NDEF message.
1167  **
1168  **                  Before using this API, the RW_MfcReadNDef function must
1169  **                  be called to verify that the tag contains NDEF data, and to
1170  **                  retrieve the NDEF attributes.
1171  **
1172  **                  Internally, this command will be separated into multiple
1173  **                  Mifare Classic Read commands (if necessary) - depending
1174  **                  on the NDEF Msg size.
1175  **
1176  ** Parameters:      p_buffer:   The buffer into which to read the NDEF message
1177  **                  buf_len:    The length of the buffer
1178  **
1179  ** Returns          NCI_STATUS_OK, if read was started. Otherwise, error
1180  **                  status.
1181  **
1182  *******************************************************************************/
RW_MfcReadNDef(uint8_t * p_buffer,uint16_t buf_len)1183 tNFC_STATUS RW_MfcReadNDef(uint8_t* p_buffer, uint16_t buf_len) {
1184   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1185   tNFC_STATUS status = NFC_STATUS_OK;
1186 
1187   if (p_mfc->state != RW_MFC_STATE_IDLE) {
1188     LOG(ERROR) << __func__
1189                << " Mifare Classic tag not activated or Busy - State="
1190                << p_mfc->state;
1191     return NFC_STATUS_FAILED;
1192   }
1193 
1194   if (p_mfc->ndef_status == MFC_NDEF_NOT_DETECTED) {
1195     LOG(ERROR) << __func__ << " NDEF detection not performed yet";
1196     return NFC_STATUS_FAILED;
1197   }
1198 
1199   if (buf_len < p_mfc->ndef_length) {
1200     LOG(ERROR) << __func__ << " buffer size=" << buf_len
1201                << "less than NDEF msg sise=" << p_mfc->ndef_length;
1202     return NFC_STATUS_FAILED;
1203   }
1204 
1205   if (!p_mfc->ndef_length) {
1206     LOG(ERROR) << __func__ << " NDEF Message length is zero ";
1207     return NFC_STATUS_NOT_INITIALIZED;
1208   }
1209 
1210   p_mfc->p_ndef_buffer = p_buffer;
1211   p_mfc->work_offset = 0;
1212 
1213   p_mfc->last_block_accessed.block = 0;
1214   p_mfc->next_block.block = p_mfc->ndef_first_block;
1215   p_mfc->substate = RW_MFC_SUBSTATE_NONE;
1216 
1217   /* Start reading NDEF Message */
1218   status = rw_mfc_readBlock(p_mfc->next_block.block);
1219   if (status == NFC_STATUS_OK) {
1220     p_mfc->state = RW_MFC_STATE_READ_NDEF;
1221   }
1222 
1223   return status;
1224 }
1225 
1226 /*****************************************************************************
1227  **
1228  ** Function         rw_mfc_handle_op_complete
1229  **
1230  ** Description      Reset to IDLE state
1231  **
1232  ** Returns          none
1233  **
1234  *****************************************************************************/
rw_mfc_handle_op_complete(void)1235 static void rw_mfc_handle_op_complete(void) {
1236   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1237 
1238   p_mfc->last_block_accessed.auth = false;
1239   p_mfc->next_block.auth = false;
1240   p_mfc->state = RW_MFC_STATE_IDLE;
1241   p_mfc->substate = RW_MFC_SUBSTATE_NONE;
1242   return;
1243 }
1244 
1245 /*******************************************************************************
1246  **
1247  ** Function         rw_mfc_handle_ndef_read_rsp
1248  **
1249  ** Description      Handle TLV detection.
1250  **
1251  ** Returns          none
1252  **
1253  *******************************************************************************/
rw_mfc_handle_ndef_read_rsp(uint8_t * p_data)1254 static void rw_mfc_handle_ndef_read_rsp(uint8_t* p_data) {
1255   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1256   NFC_HDR* mfc_data;
1257   uint8_t* p;
1258 
1259   mfc_data = (NFC_HDR*)p_data;
1260   /* Assume the data is just the response byte sequence */
1261   p = (uint8_t*)(mfc_data + 1) + mfc_data->offset;
1262 
1263   switch (p_mfc->substate) {
1264     case RW_MFC_SUBSTATE_WAIT_ACK:
1265       /* Search for the tlv */
1266       p_mfc->last_block_accessed.block = p_mfc->current_block;
1267 
1268       if (p[0] == 0x0) {
1269         p_mfc->next_block.auth = true;
1270         p_mfc->last_block_accessed.auth = true;
1271 
1272         if (p_mfc->current_block < 128) {
1273           p_mfc->sector_authentified = p_mfc->next_block.block / 4;
1274         }
1275 
1276         else
1277           p_mfc->sector_authentified =
1278               (p_mfc->next_block.block - 128) / 16 + 32;
1279 
1280         rw_mfc_resume_op();
1281         DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
1282             "rw_mfc_handle_ndef_read_rsp () sector authentified: %d",
1283             p_mfc->sector_authentified);
1284       } else {
1285         p_mfc->next_block.auth = false;
1286         p_mfc->last_block_accessed.auth = false;
1287       }
1288       break;
1289 
1290     case RW_MFC_SUBSTATE_READ_BLOCK:
1291       /* Search for the tlv */
1292 
1293       if (mfc_data->len == 0x10) {
1294         p_mfc->last_block_accessed.block = p_mfc->current_block;
1295 
1296         if (p_mfc->current_block % 4 == 2) {
1297           p_mfc->next_block.block = p_mfc->current_block + 2;
1298         } else {
1299           p_mfc->next_block.block = p_mfc->current_block + 1;
1300         }
1301 
1302         /* Do not read block 16 (MAD2) - Mifare Classic4 k */
1303         if (p_mfc->next_block.block == 64) {
1304           p_mfc->next_block.block += 4;
1305         }
1306 
1307         if ((p_mfc->selres & RW_MFC_4K_Support) &&
1308             (p_mfc->next_block.block >= 128)) {
1309           if (p_mfc->current_block % 16 == 14) {
1310             p_mfc->next_block.block = p_mfc->current_block + 2;
1311           } else {
1312             p_mfc->next_block.block = p_mfc->current_block + 1;
1313           }
1314         }
1315 
1316         p_mfc->next_block.auth = false;
1317         rw_mfc_handle_read_op((uint8_t*)mfc_data);
1318       }
1319       break;
1320   }
1321 }
1322 
1323 /*******************************************************************************
1324  **
1325  ** Function         rw_mfc_process_error
1326  **
1327  ** Description      Process error including Timeout, Frame error. This function
1328  **                  will retry atleast till RW_MAX_RETRIES before give up and
1329  **                  sending negative notification to upper layer
1330  **
1331  ** Returns          none
1332  **
1333  *******************************************************************************/
rw_mfc_process_error()1334 static void rw_mfc_process_error() {
1335   tRW_READ_DATA evt_data = tRW_READ_DATA();
1336   tRW_EVENT rw_event = RW_MFC_NDEF_DETECT_EVT;
1337   NFC_HDR* p_cmd_buf;
1338   tRW_MFC_CB* p_mfc = &rw_cb.tcb.mfc;
1339   tRW_DETECT_NDEF_DATA ndef_data;
1340 
1341   DLOG_IF(INFO, nfc_debug_enabled) << __func__ << " State=" << p_mfc->state;
1342   evt_data.status = NFC_STATUS_FAILED;
1343 
1344   /* Retry sending command if retry-count < max */
1345   if (rw_cb.cur_retry < RW_MAX_RETRIES) {
1346     /* retry sending the command */
1347     rw_cb.cur_retry++;
1348 
1349     DLOG_IF(INFO, nfc_debug_enabled)
1350         << __func__ << "Mifare Classic retransmission attempt "
1351         << rw_cb.cur_retry << " of " << RW_MAX_RETRIES;
1352 
1353     /* allocate a new buffer for message */
1354     p_cmd_buf = (NFC_HDR*)GKI_getpoolbuf(NFC_RW_POOL_ID);
1355     if (p_cmd_buf != NULL) {
1356       memcpy(p_cmd_buf, p_mfc->p_cur_cmd_buf,
1357              sizeof(NFC_HDR) + p_mfc->p_cur_cmd_buf->offset +
1358                  p_mfc->p_cur_cmd_buf->len);
1359 
1360       if (NFC_SendData(NFC_RF_CONN_ID, p_cmd_buf) == NFC_STATUS_OK) {
1361         /* Start timer for waiting for response */
1362         nfc_start_quick_timer(
1363             &p_mfc->timer, NFC_TTYPE_RW_MFC_RESPONSE,
1364             (RW_MFC_TOUT_RESP * QUICK_TIMER_TICKS_PER_SEC) / 1000);
1365 
1366         return;
1367       }
1368     }
1369   } else {
1370     DLOG_IF(INFO, nfc_debug_enabled)
1371         << __func__ << "MFC maximum retransmission attempts reached "
1372         << RW_MAX_RETRIES;
1373   }
1374 
1375   if (p_mfc->state == RW_MFC_STATE_DETECT_TLV) {
1376     rw_event = RW_MFC_NDEF_DETECT_EVT;
1377   } else if (p_mfc->state == RW_MFC_STATE_READ_NDEF) {
1378     rw_event = RW_MFC_NDEF_READ_EVT;
1379   } else if (p_mfc->state == RW_MFC_STATE_UPDATE_NDEF) {
1380     rw_event = RW_MFC_NDEF_WRITE_FAIL_EVT;
1381   } else if (p_mfc->state == RW_MFC_STATE_NDEF_FORMAT) {
1382     rw_event = RW_MFC_NDEF_FORMAT_CPLT_EVT;
1383   }
1384 
1385   if (rw_event == RW_MFC_NDEF_DETECT_EVT) {
1386     ndef_data.status = evt_data.status;
1387     ndef_data.protocol = NFC_PROTOCOL_MIFARE;
1388     ndef_data.flags = RW_NDEF_FL_UNKNOWN;
1389     ndef_data.max_size = 0;
1390     ndef_data.cur_size = 0;
1391     DLOG_IF(INFO, nfc_debug_enabled)
1392         << __func__ << " status=" << evt_data.status;
1393     /* If not Halt move to idle state */
1394     rw_mfc_handle_op_complete();
1395 
1396     (*rw_cb.p_cback)(rw_event, (tRW_DATA*)&ndef_data);
1397   } else {
1398     evt_data.p_data = NULL;
1399     /* If activated and not Halt move to idle state */
1400     if (p_mfc->state != RW_MFC_STATE_NOT_ACTIVATED) {
1401       rw_mfc_handle_op_complete();
1402     }
1403 
1404     DLOG_IF(INFO, nfc_debug_enabled)
1405         << __func__ << " status=" << evt_data.status;
1406     p_mfc->substate = RW_MFC_SUBSTATE_NONE;
1407     (*rw_cb.p_cback)(rw_event, (tRW_DATA*)&evt_data);
1408   }
1409 }
1410