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